Terraform · Infrastructure as code
How do you test Terraform code?
Short answer
Test Terraform at several levels: fmt and validate, static analysis, plan assertions, native terraform test runs, and ephemeral integration environments. Assert behaviour and policy, not just exit codes.
Terraform testing is layered. Syntax and formatting checks are fast and catch little. Plan tests catch wiring and policy issues without creating resources. Integration tests create real infrastructure in an isolated account and verify behaviour, which is slower and costs money.
run "creates_bucket" {
command = plan
assert {
condition = aws_s3_bucket.logs.bucket == "acme-logs-test"
error_message = "Bucket name did not match."
}
}The testing stack
- terraform fmt -check and terraform validate in every pull request
- tflint, Checkov or tfsec for provider and security rules
- terraform test or Terratest for module behaviour
- Plan JSON assertions for policy and blast-radius checks
- Ephemeral integration environments with automatic destroy
Test the module interface, not every provider attribute. Assert the outputs and invariants callers depend on, such as encryption enabled, private access and expected CIDRs. Use unique names and a dedicated test account so parallel runs do not collide, and always clean up with a destroy step even on failure.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What can a plan-only test catch and what can it miss?
- 2How do you keep integration tests from colliding?
- 3When would you use Terratest instead of terraform test?
- 4How do you test a module's contract?
Say it in the interview
I test Terraform in layers: fmt and validate plus static analysis on every pull request, plan assertions for wiring and policy, and native terraform test or Terratest for module behaviour. Real integration tests run in an isolated account with unique names and guaranteed cleanup. I assert the invariants callers depend on rather than every provider attribute, and I remember that a plan cannot prove runtime health.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Terraform mock interview and get scored feedback on depth, clarity and confidence.