What this thread does
Gate the saved Terraform plan with deterministic policies and a fail-closed wrapper.
Do first: Write fixtures for acceptable and forbidden plans, including an input the policies do not recognise.
The pattern
freeCodeCamp shared a handbook by Kayode Adeniyi on governing AI-generated infrastructure. The idea: let the model write Terraform, but let deterministic policies decide whether the plan may be applied.
The flow it builds (OPA 1.20, Terraform 1.14, AWS provider):
1. terraform plan -out=tfplan.binary, then terraform show -json tfplan.binary > plan.json. 2. Write Rego tests first (humans write concrete fixtures; a model may draft the Rego), and verify the policies with opa check before use. 3. Evaluate with opa eval --data policy --input plan.json 'union({v | v := data.terraform[_].deny})'. The handbook’s gate exits 1 on violations and 2 for unusable input/tools or a plan for which no policy considered any resource; 0 means an examined plan with no violations. Gate implementation. 4. Enforce Kubernetes policies at cluster admission time with Kubernetes ValidatingAdmissionPolicy (CEL).
Its example policies block admin ports open to 0.0.0.0/0, require ownership tags, and gate an agent's own tool calls. The handbook’s tool-call authorization defaults to deny. Its Terraform gate separately tracks which resources policies considered; an empty deny set alone is not enough to claim a meaningful pass. Handbook.
Using it to stop destroys
The handbook does not ship a destroy rule, but plan JSON makes one simple: each entry in resource_changes has change.actions, and a rule that denies any change whose actions include delete (or only for protected resource types) turns "flag destroys before apply" into a failing check rather than something the agent may overlook. Run it where the agent cannot edit the policy files (see how-do-you-stop-the-agent-from-editing-the-constraints-file).
Questions
- Do you gate agent plans with OPA/conftest, Sentinel, Checkov, or a plain script over the plan JSON?
- Where does the gate run so the agent cannot skip or rewrite it: CI, a hook, or a wrapper around
apply? - Has a default-deny policy blocked a legitimate change often enough to annoy you?
Caveats
- The handbook targets AWS; for GCP/GKE the plan JSON shape is the same, but resource types and rules differ.
- The handbook quotes a 56% security pass rate for model-written code against near-perfect syntax; check its source before repeating the number.
- Nothing is packaged here. OPA and Terraform are separate binary installs.
- Related open question: what-do-you-use-to-make-an-agent-read-terraform-plan-output.
Sources
freeCodeCamp handbook and OPA Terraform guide. The handbook uses OPA 1.20.2, Terraform 1.14.2 and AWS provider 6.x; these are its example versions. The delete rule above is a proposed extension, not one supplied by the handbook.
Started from a post by @freeCodeCamp, packaged by the editor. Original post