Testing Terraform
terraform test, Terratest, validate.
Infrastructure code deserves testing like any other code, and Terraform has a ladder of techniques from cheap-and-fast to thorough-and-slow. The cheap end runs on every change and catches most mistakes; the expensive end actually provisions real resources to prove they work. A good pipeline uses several rungs, heaviest sparingly.
The cheap rungs: fmt and validate
terraform fmt canonicalizes formatting (run it in CI as a check so diffs stay clean), and terraform validate checks that the configuration is internally consistent — valid HCL, correct argument types, references that resolve — without touching any cloud. These run in seconds, need no credentials, and belong on every commit as the first gate. They will not catch a logic error, but they catch the typos and type mismatches instantly.
$ terraform fmt -check -recursive # fail CI if anything is unformatted$ terraform validateSuccess! The configuration is valid.
The native test framework
terraform test (built in since 1.6) runs .tftest.hcl files that set variables, run a plan or apply, and assert on the results — including spinning up real resources in a run block and checking their attributes, then cleaning up automatically. It is the sweet spot for module authors: real assertions without a separate language. For the heaviest end, Terratest (a Go library) deploys infrastructure, hits it with real checks (make an HTTP request, query the API), and tears it down — true integration testing, run before releasing a module.
run "sets_correct_size" {command = planvariables { environment = "prod" }assert {condition = aws_instance.web.instance_type == "t3.large"error_message = "prod must use t3.large"}}