Q: How do you test Terraform modules?
To test Terraform modules, layer cheap static checks first, then plan-level assertions, then real apply tests in a disposable account.
Want to master this scenario in a live sandbox? KodeKloud's HashiCorp Certified Terraform Associate (003) Interactive Labs covers this exact problem with hands-on terminal drills.
🛠️ Production Runbook & Step-by-Step Resolution
Direct Answer: To <strong>test Terraform modules</strong>, layer cheap static checks first, then plan-level assertions, then real apply tests in a disposable account. Use <code>terraform fmt</code>, <code>validate</code> and linters, then the native <code>terraform test</code> framework (Terraform 1.6 and later) with <code>.tftest.hcl</code> files, and reserve Terratest or full integration runs for behaviour you cannot assert from a plan. Interviewers ask this to see whether you treat infrastructure code like software: a test pyramid, safe cleanup, cost control and automation in CI. A strong answer explains what each layer catches and what it cannot.
Mental model: a test pyramid for Terraform modules
Cost and speed rise as you go from static checks to real infrastructure, so push most checks to the cheap layers.
- Static:
terraform fmt -check,terraform validate, TFLint rules and policy scanners such as Checkov or Trivy run in seconds without credentials. - Plan-level:
terraform testwithcommand = planasserts planned values, conditions and variable validation without creating anything. - Apply-level: real
applyin a sandbox account proves provider and API behaviour, outputs and idempotence, at the cost of time and money. - Consumer examples: keep an
examples/directory that uses the module like a caller would; tests and docs both use it. - Speed matters: static and plan tests finish in seconds to minutes, so developers actually run them locally before pushing.
Hands-on: test Terraform modules with terraform test
Native tests live next to the module and need no extra language or framework.
# tests/bucket.tftest.hcl
variables {
name = "my-test-bucket"
}
run "plan_sets_expected_name" {
command = plan
assert {
condition = aws_s3_bucket.this.bucket == var.name
error_message = "Bucket name must match input."
}
}
run "rejects_uppercase_name" {
command = plan
variables { name = "BadName" }
expect_failures = [var.name]
}
run "apply_creates_versioned_bucket" {
command = apply
assert {
condition = aws_s3_bucket_versioning.this.versioning_configuration[0].status == "Enabled"
error_message = "Versioning must be enabled."
}
}
# Run
# terraform init && terraform test
- File layout: put
*.tftest.hclfiles in the module root or atests/directory and runterraform test. - run blocks: each
runsetscommand(planorapply), optionalvariablesand one or moreassertblocks. - Negative tests: use
expect_failuresto prove that variable validation rejects bad input. - Mocking:
mock_provider(Terraform 1.7 and later) lets plan-style tests run without cloud credentials. - Run selectively:
terraform test -filter=tests/bucket.tftest.hclruns one file while you iterate, and-verboseprints plan output for debugging.
Integration testing with Terratest and CI
For multi-step scenarios and probing deployed endpoints, Go based Terratest is a common choice.
// test/vpc_test.go
func TestVpc(t *testing.T) {
t.Parallel()
opts := &terraform.Options{
TerraformDir: "../examples/basic",
Vars: map[string]interface{}{"name": "tt-" + random.UniqueId()},
}
defer terraform.Destroy(t, opts)
terraform.InitAndApply(t, opts)
vpcID := terraform.Output(t, opts, "vpc_id")
assert.NotEmpty(t, vpcID)
}
- Terratest: a Go test calls
terraform.InitAndApply, reads outputs, makes real checks (HTTP, SDK calls) and destroys withdefer. - Isolation: use unique name suffixes and a dedicated sandbox account so parallel CI runs do not collide.
- CI tiers: run static and plan tests on every pull request; run apply-based tests on merge or nightly to control cost.
- Cleanup guard: add a scheduled job that deletes leftover resources by tag, because failed runs can skip destroy.
Failure modes and what to verify
Tests can give false confidence if they only exercise the happy path or leave debris behind.
- Plan cannot see runtime behaviour: values known only after apply cannot be asserted at plan stage; use an apply run for those.
- Idempotence: follow an apply with
plan -detailed-exitcode; exit code 2 means the module produces a perpetual diff. - Version matrix: test against the minimum and latest supported provider versions declared in the module
required_providers. - Cost and secrets: keep sandbox accounts with budgets, short-lived OIDC credentials and no production data.
- Cleanup behaviour:
terraform testdestroys infrastructure created by apply runs at the end, but a crashed job can still leave resources, so tag them. - Flaky tests: retry only known transient API errors; blindly retrying hides genuine ordering bugs in the module.
Policy and security testing for modules
Functional tests do not prove a module is safe, so add policy checks to the same pipeline.
- Scanners: Checkov, Trivy or tfsec flag public buckets, open security groups and missing encryption directly in HCL.
- Policy as code: run OPA/Conftest or Sentinel against
terraform show -json tfplanto enforce organisation rules on planned changes. - Secure defaults: write tests that assert encryption, logging and versioning are on by default, so a refactor cannot quietly remove them.
- Documentation tests: run
terraform-docsin CI and fail if the README is stale, keeping the module contract visible.
- I test Terraform modules in layers: fmt, validate and linting, plan-based terraform test assertions, then apply tests in a sandbox.
- I verify idempotence with a second plan using detailed-exitcode and verify outputs and behaviour with run assertions or Terratest.
- I automate fast checks on every pull request, run apply tests on merge or nightly with OIDC credentials, and schedule tag-based cleanup.
Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:
- Only running terraform validate Validate checks syntax and types, not provider behaviour or logic, so broken conditions and wrong defaults still pass.
- Running apply tests in a shared or production account Failed tests can leave or modify real resources and cost money; use a dedicated sandbox with budgets.
- Skipping the second plan after apply Without it you miss perpetual diffs caused by computed or normalised attributes.
- Testing against a single provider version Constraints allow a range, and a module can break on the minimum or newest version it claims to support.