Easily estimate infrastructure costs with terraform
1 min read

Easily estimate infrastructure costs with terraform

A simple shell script to help with planning and estimating infrastructure costs with terraform.
Easily estimate infrastructure costs with terraform
Photo by Scott Graham / Unsplash

A simple shell script to help with planning and estimating infrastructure costs with terraform.

The following script uses this third party pricing calculator cost.modules.tf to generate an estimate of costs based on a provided terraform plan output.

WARNING: In order for this to work, you are required to submit a terraform plan output in json format. Please ensure you have sanitised the plan file before uploading it as it could potentially contain sensitive values.

The first thing you want to do is generate a planned output for your infrastructure, this can be achieved by running the following command against your terraform configuration:

terraform plan -out=plan.tfplan

Then convert this plan to json format:

terraform show -json plan.tfplan > plan.json

This command will save the output to a file named plan.json in json format.

Next we want to POST our plan to cost.modules.tf:

curl -s -X POST -H "Content-Type: application/json" -d "@plan.json" https://cost.modules.tg | jq

You will recieve an output similar to this: (note I used jq to format the returned json)

{
  "currency": "USD",
  "hourly": 0.03,
  "monthly": 18.14,
  "diff_hourly": 0,
  "diff_monthly": 0,
  "messages": [
    "It is sometimes impossible to extract all information required for cost estimations from the Terraform plan provided, and it is more accurate to get estimates from the Terraform state file after the infrastructure is created."
  ]
}

The following is a shell function that when sourced will give you access to tfcost directly from your command line:

tfcost() {
        echo "Calulating cost estimate..."
        terraform plan -var-file=environment/"$1"/variables.tfvars -out=plan.tfplan > /dev/null
        terraform show -json plan.tfplan | curl -s -X POST -H "Content-Type: application/json" -d @- https://cost.modules.tf | jq
}

once sourced you can then call this from within your terraform configuration path by typing tfcost into your terminal