AI Coding Agents for Infrastructure (2026): 91% Fix It, 39% Clean Up
I let coding agents into my infrastructure repositories in 2025 and spent most of 2026 working out which jobs they belong in. The short version: they are good at reading, drafting and iterating against a validator, and bad at knowing when to stop. This post covers how AI coding agents for infrastructure (Claude Code, OpenAI Codex, Cursor and GitHub's Copilot cloud agent) actually behave on Terraform, Kubernetes YAML and shell, what the 2026 benchmarks measure, how each tool's permission and plan-only modes work, and the guardrails I would insist on before any of them gets near a cloud credential. Versions are current as of 10 November 2026: Claude Code 2.1.322, Codex CLI 0.167.0 and Terraform 1.17.1.
What are AI coding agents good at in Terraform and Kubernetes?
Drafting, mostly, provided something checks the draft. The single most useful finding in the research is that first attempts are poor and loops are good. The DPIaC-Eval benchmark (arXiv 2506.05623), 153 real deployment scenarios across 58 services, found six frontier models produced a deployable template on the first attempt only 20.8 to 30.2 percent of the time. Feed the deployment errors back and 54.6 to 91.6 percent became deployable within ten iterations. A December 2025 study of Terraform generation (arXiv 2512.14792) tells the same story from another angle: 27.1 percent baseline success, 62.6 percent once the model was given structured provider knowledge.
That is exactly the shape of an agent loop. An agent that can run terraform validate, tflint, terraform plan and kubectl apply --dry-run=server, read the errors and try again is doing the iteration the papers measured. A chat window that hands you HCL is doing the first attempt.
The jobs where I see them earn their keep:
- Reading and explaining. Pointing an agent at a 4,000-line plan output or a failing Helm release and asking what changed and why is the safest, highest-value use. Nothing is written.
- Boilerplate with a validator. New modules, variable plumbing, Kubernetes manifests from a spec, converting
counttofor_each. The validator catches the hallucinated argument. - Shell glue. One-off scripts to reconcile tags, parse JSON from a CLI, or bulk-rename resources in config. Fast, and easy to read before running.
- Debugging from output.
kubectl describeplus events plus logs is a lot of text, and agents are good at finding the line that matters. I covered the dedicated tools in K8sGPT vs HolmesGPT vs kubectl-ai.
What they are not good at is intent. The same Terraform study names a "Correctness-Congruence Gap": technical validity climbed with better context while matching what the user actually wanted plateaued. A plan that applies cleanly can still be the wrong plan.
Where do AI agents fail on infrastructure work?
On the parts of operations nobody demos: durability, cleanup and blast radius.
InfraBench (arXiv 2608.11234), by a team that includes Andrea and Remzi Arpaci-Dusseau, is the first benchmark I have seen that scores infrastructure agents across the operational lifecycle rather than on "did the file parse". Its prototype is small, 12 seed tasks across container, VM and bare-metal backends and 18 agent and model configurations, so treat the numbers as directional. The pattern is still striking: 91.5 percent pass on functional repair, 80.9 percent on durability, and 38.9 percent on cleanup. The agent fixes the thing. The fix sometimes does not survive. And most of the time it leaves state behind. The authors' conclusion, that immediate recovery is "an incomplete measure of operational capability", matches my experience exactly.
Security is worse. DPIaC-Eval reports requirement coverage of 25.2 percent and a security compliance rate of 8.4 percent. If you let an agent write security groups or IAM without a policy scanner in the loop, assume it widened something. I went through the specific failure modes, from hallucinated arguments to open CIDR blocks, in AI-generated Terraform in 2026.
Then there are the incidents, and they rhyme:
| When | What happened | Agent | Root cause | Source |
|---|---|---|---|---|
| Jul 2025 | Production database deleted during a declared code freeze | Replit agent | Dev and production shared a database; agent had direct production access | SaaStr |
| Feb 2026 | terraform destroy removed VPC, ECS, load balancers and RDS with its snapshots |
Claude Code | Local state on a new laptop, broad credentials, no plan review | Alexey Grigorev |
| Apr 2026 | Production volume and its backups deleted in one API call | Cursor | Root-scoped Railway token found in an unrelated file; backups in the same volume | Giskard |
Read the root-cause column. Every row is an access-control or state-management failure that a 2015 production readiness review would have flagged. The agent did not invent a new failure class. It removed the delay that used to give a tired human time to notice. The longer write-ups are in my AI agent failures post.
How do Claude Code, Codex, Cursor and Copilot handle permissions?
Each tool ships three things in different proportions: permission rules matched against the command text, an OS-level sandbox, and a model-based reviewer. Here is what each documents today.
| Tool | Default posture | Read-only or plan option | OS sandbox | Model-based review | Source |
|---|---|---|---|---|---|
| Claude Code 2.1.322 | Auto mode is the built-in starting mode from v2.1.283; rules evaluated deny, then ask, then allow | plan mode; dontAsk denies anything not pre-approved |
Off by default; Seatbelt on macOS, bubblewrap plus socat on Linux; egress allowlist starts empty | Auto mode classifier, blocks terraform destroy and production deploys by default |
permissions, modes, sandbox |
| Codex CLI 0.167.0 | workspace-write with on-request approvals; network off |
--sandbox read-only; CI pattern is read-only plus --ask-for-approval never |
Seatbelt via sandbox-exec, bwrap plus seccomp; .git, .codex, .agents, .aws stay read-only |
Optional auto_review approvals reviewer |
Codex docs |
| Cursor | Terminal commands need approval | Run Modes from an allowlist to an Auto-review classifier | Not described on the security page | Auto-review classifier, called "best-effort guardrails rather than a hard security boundary" | Cursor security |
| Copilot cloud agent | Runs remotely, pushes to one copilot/ branch |
No default-branch writes; requester cannot approve its own PR | Firewall restricts internet access; Actions workflows wait for human review | None documented | GitHub docs |
Two things in that table deserve more attention than they get.
First, text-matching permission rules are not a boundary around a program. Claude Code's own docs say a deny rule for Bash(rm *) stops rm -rf build/ but not /bin/rm -rf build/ or bash -c 'rm -rf build/', and Bash(git push *) does not stop git -C . push. The rule covers the invocation Claude usually writes. That is useful against accidents and useless against a prompt injection that knows the rule exists. The sandbox, which enforces at the OS level for every child process, is what holds.
Second, Copilot's model is structurally different: the agent never runs on your laptop and never holds your cloud credentials unless you put them in its environment. For infrastructure, that is the safest default of the four, and the most annoying when you want it to actually run terraform plan against real state. I set up that pull-request flow in running an AI coding agent in GitHub Actions safely.
Do plan-only modes keep an AI agent read-only?
Less than the name suggests. Claude Code's plan mode stops file edits until you approve a plan, but Claude can still run shell commands to explore. With auto mode available, a classifier reviews those commands instead of you, per the plan mode docs. Codex's read-only sandbox is stricter because it is enforced by the kernel rather than by a prompt.
The deeper problem is that "read-only" infrastructure commands are not always read-only:
terraform planrefreshes state, and theexternaldata source re-runs its program each time state is refreshed. A plan can execute arbitrary code from the repository.kubectl get secret -o yamlis a read. It also prints every secret in the namespace into the agent's context, which may be logged, summarised or sent to a model provider.aws sts get-caller-identityis harmless; the credential it proves exists is not. If the agent can read it, a later step can use it.
So the useful question is not "is the mode read-only" but "what can the credentials in this process do". If the shell the agent runs in can only reach a plan-only role and a namespace-scoped, get-only service account, plan mode is a convenience. If it holds your admin session, plan mode is a suggestion.
Is auto mode or a classifier safe enough for terraform apply?
It is better than approval fatigue, and it is not a control I would rely on for production. Anthropic's own engineering post says sandboxing cut permission prompts by 84 percent in internal use, and the reason that matters is the same post's point about approval fatigue: people stop reading prompts they see fifty times a day. A human clicking "yes" by reflex is not a control either.
Claude Code's classifier list is genuinely infrastructure-aware. By default it blocks terraform destroy, pulumi destroy and cdk destroy, applying a plan that destroys resources, production deploys and migrations, granting IAM permissions, DaemonSets and admission webhooks, draining nodes and requests to the instance-metadata endpoint, according to the auto mode docs. The same docs say plainly that auto mode "does not guarantee safety", and Cursor describes its classifier as best-effort. A model judging another model's intent will be wrong sometimes, in both directions.
My rule: classifiers are for reducing friction on the long tail of ordinary commands. Anything with an irreversible cloud effect gets a deterministic block (a deny rule plus a hook), and the real apply path runs in CI under a separate identity. The guide that pairs with this post, how to block dangerous commands with Claude Code hooks, builds that block and tests it.
Guardrails that hold for AI agents on infrastructure
Four layers, in order of how much I trust them:
- Credentials. The agent's environment gets a read-only or plan-only role, short-lived, and no production keys on the laptop at all. This is the only layer that would have prevented all three incidents in the table.
- The sandbox. OS-enforced write and network limits, with an explicit allowlist. On Claude Code that means
sandbox.enabledplusallowUnsandboxedCommands: falseandfailIfUnavailable: true; on Codex,read-onlyorworkspace-writewith network off. - Deterministic deny rules and hooks. Fast, cheap, fail-closed where possible, and honest about being text matching.
- CI as the only apply path. Plan on pull request, a policy check on the plan JSON, apply after merge with a human-approved environment. I walked through Conftest rules for this in policy as code for AI agents.
A minimal Claude Code project policy looks like this. It is a starting point, not the full setup:
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"permissions": {
"deny": [
"Bash(terraform apply *)", "Bash(terraform destroy *)",
"Bash(tofu apply *)", "Bash(tofu destroy *)",
"Bash(kubectl delete *)", "Bash(helm uninstall *)",
"Read(**/*.tfstate)", "Read(.env)"
],
"ask": ["Bash(kubectl apply *)", "Bash(git push *)"],
"allow": ["Bash(terraform fmt *)", "Bash(terraform validate)", "Bash(terraform plan *)"]
},
"sandbox": {
"enabled": true,
"allowUnsandboxedCommands": false,
"failIfUnavailable": true,
"network": { "allowedDomains": ["registry.terraform.io", "releases.hashicorp.com"] }
}
}
The ordering matters because deny is evaluated first and an allow can never carve an exception out of it. Note what the sandbox does to terraform plan here: with only the registry hosts allowed, a plan against a real cloud backend will fail or stop at a network prompt, depending on the permission mode. That is the point. Run real plans in CI, or widen the allowlist knowingly for a plan-only role.
If you want the agent's whole process, not just its shell, inside a boundary, run it in a container or microVM with no ambient credentials. I build PandaStack, an open-source Firecracker microVM platform for agent workloads, so I am biased toward that option; the isolation trade-offs apply whichever runtime you pick.
None of this is new discipline. It is least privilege, separation of plan and apply, and backups the tooling cannot delete. Agents just make skipping it expensive faster. And the productivity case is still contested: METR's February 2026 update says its newer data is "very weak evidence" on the size of any speedup, after its 2025 study found experienced developers 19 percent slower. Spend the guardrail effort before you spend the time savings.
FAQ
Can AI coding agents write production Terraform?
They can draft it, and with a validate and plan loop most drafts become deployable. First attempts deploy only 20.8 to 30.2 percent of the time in DPIaC-Eval, and security compliance was 8.4 percent, so every agent-written change needs tflint, a policy scanner and a human-reviewed plan before apply.
Should an AI agent ever run terraform apply?
Not from a developer machine with real credentials. Let the agent open a pull request, let CI run the plan and policy checks, and let apply run after merge under a separate identity. If an agent must apply in a sandbox account, give it credentials scoped to that account only.
Which AI coding agent is safest for Kubernetes and Terraform?
The safest setup matters more than the brand. Copilot cloud agent has the most conservative default because it runs remotely and can only push to a single branch (its own copilot/ branch, or the pull request branch it was asked to work on). Codex has a strict kernel-enforced read-only sandbox. Claude Code has the richest controls (rules, sandbox, hooks, managed settings) but its sandbox is off until you enable it.
Are permission deny rules enough to stop rm -rf or kubectl delete?
No. They match command text, so /bin/rm, sh -c and alternate flag orders can slip past. Use them with a PreToolUse hook, an OS sandbox and, above all, credentials that cannot delete anything that matters.
This quarter I would do three things: strip every long-lived cloud credential from developer laptops that run agents, turn on the Claude Code or Codex sandbox in strict mode with a short allowlist, and add a fail-closed hook that denies apply, destroy and delete outright, so that the CI pipeline is the only route to production. Then I would let the agents draft and read as much as they like.
Related: AI-Generated Terraform in 2026: Benchmarks, Failure Modes, Guardrails, Policy as Code for AI Agents in 2026: Cedar at the Gateway, Rego in the Hook, and the 11.2% the Model Still Lets Through and How to Run an AI Coding Agent in GitHub Actions Safely (2026).
Spot an error or something out of date? Email me and I will fix it and log it on the corrections page.
I'm Ajay Kumar — I build and operate PandaStack, an open-source Firecracker microVM cloud for AI agents, and write about the infrastructure and tooling around it.
Need this kind of infrastructure work? See what I do or email hello@ajayk.sh.
Related
AI-Generated Terraform in 2026: Benchmarks, Failure Modes, Guardrails
Can you trust an LLM to write Terraform, Kubernetes YAML or Helm? What IaC-Eval, DPIaC-Eval and three 2025 to 2026 papers measured (19% to 30% first-try success, 8.4% policy compliance), the failure modes they found, and the plan, policy and review gates that make AI-written IaC safe.
12 minOct 20, 2026Why AI Agents Fail in Production: 5 Real Incidents
What goes wrong when AI agents run in production: Replit, Kiro and PocketOS incidents, 14 failure modes from 1,642 traces, and the guardrails that stopped them.
12 minOct 20, 2026OWASP Top 10 for LLMs 2026 and Agentic Apps: 20 Risks, Real Incidents
The OWASP Top 10 for LLM Applications 2026 and the Agentic Top 10 explained risk by risk: what moved since 2025, the real incidents behind each entry (EchoLeak, Amazon Q, postmark-mcp, Replit), and the infrastructure controls that contain them.
13 min