Invite a friend, get 1 month of Pro freeHow it works

Claude Code for Terraform: A Practical Field Guide

Learn how to use Claude Code on Terraform projects: CLAUDE.md setup, plan-review loops, testing, module pitfalls, and running multiple agents in worktrees.

Solviera Teknoloji 6 min read

Claude Code is a terminal-native coding agent that works well on Terraform repositories. Start it with claude in the project folder, give it clear project instructions, and it can generate modules, refactor resources, run terraform commands, and explain plan diffs. The practical workflow below keeps the agent productive while protecting state and infrastructure.

What makes Claude Code a good fit for Terraform

Terraform work is mostly editing declarative HCL, wiring variables and outputs, and checking plans. Claude Code handles these well because it can read the whole module tree, run terraform fmt, terraform validate, and terraform plan, and iterate on errors. The agent is also good at mechanical refactors that would otherwise be tedious: renaming variables across many files, extracting repeated resources into modules, and updating provider arguments. Because infrastructure changes are high-risk, use plan-first discipline: have the agent propose a change, show the diff, and stop before apply. This matches the workflow in Claude Code plan mode: plan first, then let it build. Since HCL is declarative, Claude Code can reason about resource graphs and avoid many syntax errors, but it still needs human review for resource lifecycles and state effects.

Preparing a Terraform repository for Claude Code with CLAUDE.md

Claude Code reads project instructions from CLAUDE.md at the repo root. For Terraform, that file should not be generic. Spell out the environment layout, required tool versions, commands for each workflow step, and rules that prevent dangerous changes. A strong CLAUDE.md follows the Claude Code best practices checklist and removes guesswork about which directory holds which state.

Here is a compact example for a multi-environment AWS repository:

# CLAUDE.md

## Project overview
- Repository: multi-environment Terraform for AWS.
- Environments: dev, staging, prod under `environments/`.
- Reusable modules under `modules/`.

## Commands
- Initialize: `terraform init -backend-config=environments/<env>/backend.hcl`
- Format check: `terraform fmt -check -recursive`
- Validate: `terraform validate`
- Plan: `terraform plan -var-file=environments/<env>/terraform.tfvars`
- Apply: `terraform apply -var-file=environments/<env>/terraform.tfvars`
- Tests: `terraform test`

## Conventions
- Use Terraform >= 1.6, AWS provider >= 5.0.
- Never edit `.tfstate` files or backend configuration directly.
- Always run `terraform fmt` before committing.
- Variables are snake_case; outputs are lowercase with underscores.
- Modules must not declare provider blocks; inherit from root.
- One resource per logical change in a commit.
- Before apply, show the full plan diff and wait for confirmation.

A short file-to-purpose map helps the agent use the repo correctly:

File or pathPurpose for Claude Code
CLAUDE.mdProject rules and commands the agent must follow
environments/<env>/terraform.tfvarsPer-environment variable values, never hardcode
modules/Reusable Terraform modules, keep provider blocks out
.terraform.lock.hclProvider version lock file, commit it

The most important rules are: never edit state or backend files directly, always run terraform fmt before committing, and always show the full plan before apply. If you use wrappers like Terragrunt or Terraform Cloud, document those commands too, because the agent will otherwise try raw terraform commands against the wrong backend.

A practical Terraform change loop with Claude Code

Treat Claude Code like a junior engineer who can move fast but must not apply without review. For each request, ask for a specific change. Let the agent edit files, run terraform fmt, terraform validate, and terraform plan, then stop. Read the diff and the plan output. If resources are being replaced or deleted, ask why before continuing. Commit each logical change separately so it is easy to revert.

Good prompts for Terraform tasks:

  • Add a versioning variable to the S3 module and wire it through the root module. Run terraform fmt and terraform validate, then show the plan.
  • Refactor the duplicated security group rules in environments/dev and environments/staging into modules/baseline-sg. Keep the module dependency-free and show the resulting plan diff.
  • Find any hardcoded AWS region across modules/ and replace it with var.region. Do not edit provider.tf or backend.tf.
  • Write terraform test cases for the VPC module that check the public and private subnet counts and no CIDR overlap. Run the tests until they pass.
  • Review the current git diff against main and list every resource that will be added, destroyed, or replaced. Quote the plan lines.

For safer applies, ask the agent to capture a plan: terraform plan -out=plan.tfplan, then review the saved plan and apply with terraform apply plan.tfplan. This prevents drift between review and apply. For larger refactors, use plan mode so the agent explains before editing.

Where Claude Code shines vs. Terraform-specific pitfalls

It handles resource generation well: ask for an S3 bucket, IAM policy, or security group following existing naming patterns, and it will usually produce valid HCL. Module extraction and variable/output rewiring are also strong, especially if the existing code has clear conventions. Updating provider argument names and deprecations across many files is another good fit.

The risky areas are state and backends. If you ask Claude Code to migrate state or change a backend, it may edit .tfstate files or duplicate backend blocks. Lock that down in CLAUDE.md and review those changes manually. Provider configuration is another trap: the agent can add provider blocks to modules, which breaks the common pattern of inheriting providers from the root. Dependencies are also a weak point when refactoring; a resource may end up missing an implicit dependency because the agent created separate files or modules. Always inspect terraform plan output for replacement markers and unexpected deletions. The agent can also be too eager to bump required_version or provider versions in versions.tf; require a plan after any version change. Watch for duplicate resource names if you ask for several similar resources in one session.

Terraform testing and verification alongside Claude Code

Use the agent to keep the verification loop tight. After any change, run terraform fmt -check -recursive, terraform validate, and terraform plan -detailed-exitcode so a non-empty plan is not silently ignored. For shared modules, add terraform test suites that use ephemeral resources or mocks where possible. Claude Code can write these tests, but verify they do not create real infrastructure that costs money. If you use static analysis, add tflint and checkov commands to CLAUDE.md and have the agent run them after validate. If you run checks in CI, Claude Code headless mode lets you invoke the same agent with claude -p in scripts, so the review comments match the local workflow.

Running multiple Claude Code agents on one Terraform repo

AgentVera is useful when several agents need to touch the same repo. For Terraform, the most important parts are git worktrees for each agent, so parallel Claude Code sessions do not overwrite modules or lock files; automatic code review after each turn, with findings linked to file:line, catches provider and state mistakes early; checkpoints let you undo a bad refactor before it reaches terraform apply; and token budgets stop a long plan-review loop from consuming the whole day while keeping the conversation intact.

Final recommendations for Terraform teams

Terraform rewards small, reviewable changes, and Claude Code fits that pattern when you constrain it with a good CLAUDE.md, a plan-first loop, and explicit verification. The agent is not a replacement for reviewing plans, but it can remove most of the repetitive HCL work and surface risky diffs early.

Questions

Can Claude Code run terraform apply automatically?

Claude Code can run terraform commands when you ask it to, but you should keep applies behind explicit approval and review the plan first. Configure the agent to stop after terraform plan and ask for confirmation before changing infrastructure.

What should I put in CLAUDE.md for a Terraform project?

Include required Terraform version, provider versions, backend configuration, module layout, naming conventions, and the exact commands for fmt, validate, plan, and test. Also tell it never to edit state files directly and to run plan before apply.

Is Claude Code good at refactoring Terraform modules?

It handles mechanical refactors well, such as extracting resources into modules, renaming variables, and aligning provider arguments, but it can introduce duplicate resources or miss dependency changes. Review every diff and run terraform plan to catch issues.

Can I run multiple Claude Code agents on one Terraform repo safely?

Yes, if each agent works in its own git worktree or targets separate module directories. Avoid parallel edits to shared files like backend.tf, provider.tf, and variables.tf, and serialize applies with locking.

Bring your agents to one desk.

Download AgentVera for free; your installed CLIs are ready to go.

More Claude Code guides

Other agents for Terraform