038 Project 38: Terraform Cost Estimator

038 Build a Terraform Cost Estimator (Simple)

Estimate monthly change by resource action counts.

Full main.go

package main

import (
    "encoding/json"
    "fmt"
    "os"
)

type Plan struct {
    ResourceChanges []struct {
        Type   string `json:"type"`
        Change struct {
            Actions []string `json:"actions"`
        } `json:"change"`
    } `json:"resource_changes"`
}

var cost = map[string]float64{
    "aws_instance": 15.0,
    "aws_db_instance": 120.0,
    "aws_lb": 25.0,
}

func main() {
    if len(os.Args) != 2 {
        fmt.Println("usage: tf-cost <plan.json>")
        os.Exit(2)
    }
    b, err := os.ReadFile(os.Args[1])
    if err != nil {
        panic(err)
    }
    var p Plan
    if err := json.Unmarshal(b, &p); err != nil {
        panic(err)
    }

    var delta float64
    for _, rc := range p.ResourceChanges {
        c := cost[rc.Type]
        if c == 0 {
            continue
        }
        for _, a := range rc.Change.Actions {
            if a == "create" {
                delta += c
            }
            if a == "delete" {
                delta -= c
            }
        }
    }
    fmt.Printf("estimated monthly delta: $%.2f\n", delta)
}

Step-by-Step Explanation

  1. Export Terraform plan in JSON form.
  2. Parse resource_changes into typed structs.
  3. Classify actions such as create/update/delete/replace.
  4. Compute risk, policy, or cost summaries.
  5. Gate CI based on explicit thresholds.

Code Anatomy

  • Decoder layer parses JSON file.
  • Analysis layer converts raw actions into signals.
  • Reporting layer prints summary and sets exit status.

Learning Goals

  • Build deterministic IaC review tools.
  • Enforce infrastructure policy as code.
  • Reduce risky deploys with automated checks.