Lesson 4 of 9 · 26m
Validating and Testing Terraform Modules
Move beyond fmt and validate: static checks, terraform test, contract tests, and the failure modes worth testing.
terraform validate proves syntax and basic consistency. It does not prove your module creates the right thing, preserves an important invariant, or fails correctly on bad input. At scale, modules are shared code libraries. They need tests the same way application libraries do — perhaps more, because the cost of a bad release is infrastructure replacement.
Start with the cheap mechanical gates
terraform fmt -check -recursive
terraform validate
tflint --recursive
checkov -d .These catch formatting, malformed references, provider-rule violations, and obvious security mistakes. They are necessary but not sufficient. A completely valid security group can still open 0.0.0.0/0 to port 22.
Input validation is part of the interface
Fail fast with explicit messages:
variable "backup_retention_days" {
type = number
validation {
condition = var.backup_retention_days >= 7
error_message = "Production data stores must retain backups for at least 7 days."
}
}Do not write validations that merely restate type constraints. Test business or operational invariants: minimum retention, disallowed public exposure, naming length limits, required tag keys.
terraform test exercises behavior
Native Terraform tests can run plan or apply operations against test configuration:
# tests/service.tftest.hcl
run "rejects_public_database" {
command = plan
variables {
publicly_accessible = true
}
expect_failures = [
var.publicly_accessible,
]
}
Run them with terraform test. Use plan-level tests for interface contracts and inexpensive assertions. Reserve apply tests for ephemeral test accounts because they create real infrastructure and cost real money.
The failures worth testing are operational
Do not test that AWS behaves like AWS. Test what your module promises: rejection of insecure inputs, stable output shape, no accidental public exposure by default, tagging conventions, and replacement behavior when risky inputs change. A suite that creates full production-shaped infrastructure every time will become slow and then ignored; prefer focused fixtures and a smaller number of end-to-end soak tests.
Field notes
- Pin provider versions in module tests; otherwise a provider release can break a module that did not change.
- Isolate apply-test credentials and clean up resources even when tests fail — an untested module is copy-paste with extra steps.
Was this lesson helpful?