[Terraform] Predict cloud infrastructure cost changes on Terraform using infracost
"Cloud costs are a shared responsibility", we all know that stuff very well..
But from a devops/cloud operator prospective, how can we deal with that?
One of the strategies I usually use is absolutely Infracost.
This tool has really saved me a lot of time because it has also a VS Code integration as well as CLI APIs (so we are free to integrate Infracost in any custom CI/CD process).
How it works?
Infracost CLI (or VSCode extension) basically calls a public infracost cloud API which aggregates updated costs of most cloud provider resources (it is a GET API, no sensitive information goes outside).
After that, Infracost makes a diff, like the usual terraform plan
, but print out instead the cost changes... really useful before a terraform apply
!
CLI usage
Going directly to the more useful and real world usage...
# To be run on the terraform folder
# It generates a point in time cost of the infrastructure described by the terraform code
# --usage-file is optional and enrich the cost calculation by infracost (for example adding how many api calls will be done)
# --out-file generates output file
$ infracost breakdown --path . --format json --usage-file usage.yml --out-file baseline.json
# The following command than compare the current terraform local configuration (ex. after a lambda resource configuration change) compared to the latest infracost run (previous step) thanks to the --compare-to option
$ infracost diff --path . --compare-to baseline.json --usage-file usage.yml
~ aws_lambda_function.my_lambda
+$4.17 ($26.00 → $30.17)
~ Duration
+$4.17 ($25.00 → $29.17)
Monthly cost change for TomFern/infracost-demo/dev
Amount: +$4.17 ($26.00 → $30.17)
Percent: +16%
VS Code Integration 😍😍😍
CI/CD integration
While we are free to use the infracost CLI as we want (for example in a Jenkins pipeline),
the most recommended way is using native integration with GitHub/GitLab, see the example below.