Safe Terraform auto-apply with conftest

Open original

This article shows how to export Terraform plans to JSON and evaluate them with conftest policies written in Rego, enabling deterministic auto-apply of safe changes. It walks through examples for allowed actions, resource types, field diffs, blast radius limits, and environment gating to keep control while boosting velocity.

  • Terraform plans can be exported to JSON (`terraform show -json`) and tested against Rego policies via conftest to auto-apply only compliant changes.
  • AI review tools like Overmind are non-deterministic and fail audit requirements for human sign-off, whereas codified policy checks give repeatable, versioned decisions.
  • Policies can be as granular as needed: restrict to no-op/create/read actions, gate specific resource types (RDS, IAM), limit changes to certain fields (tags), cap the number of modified resources, or vary rules by environment tag (staging vs. production).

Terraform reviews slow down when teams scale up. Human approval catches mistakes but becomes a choke point as plans pile up. AI tools like Overmind can flag issues but they’re non-deterministic, don’t satisfy audit rules demanding human sign-off, and muddy accountability when something breaks. A better route is policy-as-code: export your Terraform plan as JSON, run it through conftest (built on Open Policy Agent), and auto-apply only when it meets your own rules. You start by converting the plan into JSON: terraform plan -out=plan.tfplan terraform show -json plan.tfplan > plan.json Then run `conftest test plan.json`. If it passes your Rego policies, you auto-apply; if it fails, a human steps in. A simple policy might allow only “no-op”, “create” or “read” actions and reject any update or delete. That way you get a clear, versioned decision boundary instead of vague judgments about safety. You can get more granular too. Deny changes to specific resource types (for example, always gate deletes or updates to RDS or IAM), or allow updates only to certain fields like tags. You can even count the number of modified resources and block a plan if it touches more than, say, ten items. Tag values let you auto-apply in staging but require review in production. All rules live in code, can be tested, versioned, and expanded as your policies evolve. This approach keeps velocity high without sacrificing audit trails or accountability. Every decision is repeatable and transparent. You build confidence by coding your own safety net, and you stay in control even if AI agents start proposing infrastructure changes.

Ask about this article