A Terraform module can deploy successfully and still produce the wrong infrastructure. Terraform's built-in testing framework lets you define checks in HCL and run them with `terraform test`. Unlike Terratest, it does not require Go; tests can also inspect resource attributes and local values directly rather than exposing everything as module outputs. section 9.4 section 9.1.3
Put test definitions in files ending `.tftest.hcl`. A `variables` block supplies inputs, while each `run` block performs a Terraform action and contains `assert` blocks with a condition and failure message. Runs apply by default; set `command = plan` when the assertion needs only values available during planning. section 9.4.1
Check a module output
For a module that passes `test_input` through a `terraform_data` resource to `test_output`, set `test_input = "test"` in `variables` and assert `output.test_output == "test"` in a run. This is a useful first test of the mechanics, but routine input-to-output pass-through checks offer less value than checks of module-specific logic. section 9.4.1 section 9.1.1
Choose assertions around behavior you own: transformed values, generated names, regular expressions, dynamic blocks, or a service endpoint. For example, a DNS record whose name combines an input, the current region, and a domain has meaningful string-building logic to check. Do not spend the suite merely retesting provider behavior. section 9.1.1
Keep infrastructure tests practical:
- Use working examples as test configurations, especially when a module must integrate with other resources. Native tests run against the current folder, so place example tests alongside each example and run `terraform test` from each initialized folder. section 9.2.2 section 9.4.4
- Expect real infrastructure to be launched and torn down. Give concurrently created resources distinct names, such as names incorporating a random string. section 9.2.1 section 9.2.3
- In CI, use a strategy matrix and `terraform test -filter` to distribute tests. Check engine versions: the framework is tied more closely to Terraform and OpenTofu releases than Terratest is. section 9.4.6 section 9.1.3
A plan-time assertion cannot read a value that is unknown until apply. If `terraform test` reports an unknown condition for an output, assert against plan-known values instead or let that run apply. Tests that preserve expected behavior provide a safety net when refactoring modules. section 9.4.1 section 9.5
