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):

  1. Formatting and syntax
    terraform fmt -check -recursive
    terraform validate
    
  2. Linting — tflint catches mistakes like invalid instance types or deprecated syntax.
  3. Security and policy scanning — Checkov, tfsec/Trivy, KICS: public S3 buckets, open security groups (0.0.0.0/0 on port 22), unencrypted databases.
  4. Policy as code — OPA/Conftest or Sentinel rules such as "every resource must have an owner tag" or "only approved instance types".
  5. Plan review — terraform plan in 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.
  6. Unit-style tests — Terraform's built-in terraform test with mocked providers, to check module logic and outputs.
  7. Integration tests — Terratest (Go) or terraform test against a real sandbox account: apply the module, check the resources work (for example the web server returns 200), then destroy.
  8. Drift detection — scheduled terraform plan in production to detect manual changes.
  9. 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.

All DevOps Fundamentals questions

More on Testing in DevOps