# Codex Terraform: Practical Guide for Infrastructure as Code

URL: https://agentvera.dev/en/blog/codex-for-terraform/ · Published: 2026-11-01

Learn how to use Codex for Terraform projects: AGENTS.md setup, working loops, prompts, pitfalls, and verification for reliable infrastructure changes.

**In short:**

- Set up AGENTS.md with format, validate, plan, lint, and test commands so Codex follows your Terraform workflow.
- Keep changes small, always review terraform plan output before apply, and use git diffs to catch unintended resource changes.
- Watch state, backends, provider upgrades, and for_each/count logic closely; Codex handles module and variable refactors well.

Codex is a practical fit for Terraform work when you give it clear repository conventions and keep every change small and reviewable. This guide shows how to set up AGENTS.md, run a safe plan-review-apply loop, avoid common state and provider pitfalls, and verify changes before they reach production.

## Where Codex earns its keep in Terraform

Terraform changes are rarely one-line edits. Adding a variable touches variables.tf, the module implementation, and every root module call. Codex can hold those connected edits in context and update them consistently, including output descriptions and README snippets if you ask. It also runs terraform fmt, validate, and plan quickly, so the feedback loop is short. The risk is not missing HCL syntax; it is making plausible but destructive changes to resources or state. Treat Codex as a pair programmer that drafts and lints, while you own the plan and apply decision. For a baseline on the CLI itself, see [Codex](/en/agents/codex/).

## Teaching Codex your project with AGENTS.md

Start by putting an AGENTS.md at the repository root. Codex loads project instructions from that file on every turn, so keep it specific and stable. For Terraform, the most useful content is the exact command sequence, folder layout, backend and state rules, and a small set of inviolable constraints. If you have not used the CLI before, see [how to use Codex CLI: a step-by-step guide](/en/blog/how-to-use-codex-cli/).

```markdown
# AGENTS.md

## Commands
- Format: `terraform fmt -check -recursive`
- Validate: `terraform validate`
- Lint: `tflint --recursive`
- Plan: `terraform plan -out=plan.tfplan`
- Apply: `terraform apply plan.tfplan`
- Module tests: `terraform test`

## Repository layout
- `modules/<name>/` contains reusable modules; each must have `variables.tf`, `outputs.tf`, and `versions.tf`
- `environments/<env>/` contains root modules; never edit `*.tfstate` files
- Providers and backend configuration live only in root modules

## Terraform rules
- Never run apply without showing plan output first.
- Do not remove or rename state resources without checking migration.
- Pin provider versions in `versions.tf`.
- Every input variable must have a type and description.
- Outputs must be documented with `description`.
- Use remote state backends for shared environments.
```

Keep the file short. Anything that changes per environment belongs in a root module, not in AGENTS.md. The goal is to reduce the agent’s degrees of freedom around state and apply, not to document every provider option.

## A safe change loop: plan, verify, review

Use a loop that produces a diff you can reason about. Ask Codex for one small change, have it run formatting and validation, then generate a terraform plan. Review the plan output yourself, especially for replacements, deletions, or changes to security-sensitive attributes. Commit only after the plan is clean.

Example prompts:

- Add an enable_versioning variable to modules/s3, default it to false, and pass it from the production root module.
- Create a staging environment under environments/staging by copying production, then change the backend state key and reduce the instance size to t3.small.
- Replace the repeated IAM policy document blocks in main.tf with a local value named common_policy and update all references.
- Add a terraform test that creates a plan for the VPC module and asserts that public subnets have map_public_ip_on_launch set to true.
- Update provider and module version constraints in versions.tf to the latest compatible minor versions, then run terraform init -upgrade and show the lockfile diff.

After each change, ask Codex to run terraform fmt, terraform validate, and a plan. If the plan shows unexpected replacements, stop and ask for an explanation before applying. Use git diff to review the HCL changes alongside the plan output, because a clean plan can still hide a bad variable default or a missing output description.

## What Codex does well, and what to double-check

Codex handles many Terraform tasks well: adding variables with types and descriptions across a module and its callers; generating consistent tags, locals, and data sources; refactoring duplicate resources into for_each or child modules; and updating references after a rename or move. It is also good at writing IAM policies, S3 bucket policies, and module README updates from variable descriptions.

Watch it closely in a few areas specific to Terraform. State and backend changes are the highest risk: never let an agent edit .tfstate files, run state mv, or change a backend block without showing you the exact plan and waiting for approval. Provider and module version bumps can introduce deprecations or breaking arguments, so require a provider changelog note or terraform providers output. Dynamic blocks with count and for_each are easy to get subtly wrong; check for index mistakes and unintended destroy-recreate behavior. Sensitive values can leak through outputs or local files, so tell Codex to mark sensitive variables and outputs and never print them in plan or error logs.

## Commands that catch Terraform mistakes

For Terraform, the agent’s changes should pass the same checks you run locally before any apply. Use this table as a baseline; run the cheap checks first and let Codex fix mechanical issues.

| Check | Command | What it catches |
| --- | --- | --- |
| Formatting | `terraform fmt -check -recursive` | HCL style drift and inconsistent alignment |
| Static validation | `terraform validate` | Missing arguments, invalid references, type mismatches |
| Lint | `tflint --recursive` | Provider-specific issues, deprecated arguments, best-practice violations |
| Security static analysis | `tfsec .` | Misconfigured security groups, public S3 buckets, IAM issues |
| Plan review | `terraform plan -out=plan.tfplan` | Resource additions, changes, replacements before apply |
| Module docs | `terraform-docs markdown table --output-file README.md ./modules/...` | Missing variable or output descriptions |

Keep plan review manual. terraform plan shows the exact resource diff, but the agent may not always interpret a replacement as a danger. In CI, the same checks plus a plan gate catch regressions before merge.

## Parallel agents on one Terraform repo

AgentVera lets multiple agents work on a Terraform project without stepping on each other: each agent runs in its own [git worktree](/en/blog/ai-agent-workflow-pipeline/), so one can refactor a module while another updates an environment without file conflicts. Automatic [code review](/en/blog/ai-code-review/) sends the finished diff to a second model, with findings linked to file:line, which catches mistakes like a missing for_each key or an output that exposes a secret. Checkpoints let you undo a risky provider upgrade or state-related refactor in one click, and token budgets stop a long plan/validate loop from consuming the whole day.

## Keep the apply button yours

Codex is not a replacement for Terraform expertise; it is a force multiplier when you encode your standards in AGENTS.md, keep changes small, and always inspect plan output. Use it for module plumbing, variable wiring, and repetitive HCL, but stay hands-on for state, backends, and anything that shows a replacement in the plan. With the right guardrails, you get faster, more consistent infrastructure changes without handing over the apply button.

## Frequently asked questions

**Can Codex run terraform apply automatically?** Codex can run shell commands in your project when you allow it. For Terraform, instruct it in AGENTS.md to generate a plan, show the output, and wait for approval before applying. Review the plan carefully to avoid destructive changes.

**What should I include in AGENTS.md for a Terraform project?** Include the exact commands for formatting, validation, linting, planning, and testing. Also specify folder conventions, backend and state rules, provider version pinning, and a rule that apply only happens after plan review.

**How do I prevent Codex from changing Terraform state directly?** Tell the agent never to edit .tfstate files or run state-modifying commands without explicit confirmation. Keep state files remote and use read-only plan operations during code generation.

**Can Codex work with existing Terraform modules?** Yes, it can read module inputs, outputs, and resources to add variables, refactor repeated blocks, or wire modules together. It does best when you point it to the specific module and ask for a small, testable change.

---

**About AgentVera.** AgentVera is a desktop app for macOS, Windows and Linux, built by Solviera Teknoloji. It runs 18 AI coding agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor, Antigravity, opencode, Hermes, Qwen Code, Kimi Code, Kiro, Amp, Droid, Goose, Vibe, Crush, Aider, Cline) side by side, per project, in real terminals with the user's own CLI installs and logins. The free plan has unlimited agents. Download: https://agentvera.dev/en/download/ · Pricing: https://agentvera.dev/en/pricing/
