How do you test infrastructure as code?
IntermediateConceptTesting in DevOps
Answer
In one line: You test infrastructure code in layers, just like application code: formatting and validation, static and security analysis, plan review, and then real deployment tests in a sandbox — all automated in the pipeline.
The layers (Terraform example):
- Formatting and syntax
terraform fmt -check -recursive terraform validate - Linting —
tflintcatches mistakes like invalid instance types or deprecated syntax. - Security and policy scanning — Checkov, tfsec/Trivy, KICS: public S3 buckets, open security groups (
0.0.0.0/0on port 22), unencrypted databases. - Policy as code — OPA/Conftest or Sentinel rules such as "every resource must have an
ownertag" or "only approved instance types". - Plan review —
terraform planin the PR, posted as a comment. Reviewers check exactly what will be created, changed or destroyed. Some teams fail the pipeline if a plan would destroy critical resources. - Unit-style tests — Terraform's built-in
terraform testwith mocked providers, to check module logic and outputs. - Integration tests — Terratest (Go) or
terraform testagainst a real sandbox account: apply the module, check the resources work (for example the web server returns 200), then destroy. - Drift detection — scheduled
terraform planin production to detect manual changes. - Cost checks — Infracost shows the monthly cost change in the PR.
For other tools: Ansible has ansible-lint and Molecule (test roles in containers); Kubernetes YAML has kubeconform, kube-linter and policy tools like Kyverno or Gatekeeper.
Example pipeline: PR → fmt, validate, tflint, Checkov, plan comment, Infracost → review → merge → apply to dev → Terratest smoke check → apply to prod after approval.
Tip for interviews: layer the answer from cheap and fast to slow and real, and mention plan review — interviewers always want to hear it.
More on Testing in DevOps
What is the testing pyramid?BeginnerWhat is the difference between unit, integration and end-to-end tests?BeginnerWhat are smoke tests and sanity tests?BeginnerWhat is regression testing?BeginnerWhat is test automation, and what should (and shouldn't) be automated?BeginnerWhat is shift-left testing, and how do you apply it in a pipeline?Intermediate