On this page#
What changes when an agent does this#
A Terraform MCP server does not remove infrastructure risk; it moves the bottleneck from writing configuration to reviewing proposed state transitions. The agent can discover resources, inspect repository context, and draft changes quickly. Your job becomes proving that its plan respects the repository’s invariants before any credentials can turn that proposal into infrastructure.
Model Context Protocol is the interface through which an AI application can call external tools and consume structured context. That interface is useful, but it creates a dangerous illusion: a well-formed tool call can still encode the wrong infrastructure decision.
The acceptance artifact should therefore be the Terraform plan, not the generated .tf file and certainly not the agent’s explanation. Review these separately:
- Intent: Does the change solve the requested problem?
- Scope: Are only expected modules, resources, and environments affected?
- State transition: What will be created, updated, replaced, or destroyed?
- Repository fit: Does the change preserve naming, provider, tagging, dependency, and ownership conventions?
- Operational authority: Can the server plan, apply, import, modify state, or reach unrelated directories?
MCP separates the host, client, and server roles, as described in its architecture documentation. That boundary is not a security policy by itself. If the server process inherits broad cloud credentials and unrestricted filesystem access, a narrow-looking prompt still reaches a broad execution surface.
For a real repository, configure the server through a wrapper you control:
{
"mcpServers": {
"terraform-review": {
"command": "/absolute/path/to/approved-terraform-wrapper",
"args": ["--repository", "/absolute/path/to/infrastructure"],
"env": {
"TF_IN_AUTOMATION": "true",
"TF_INPUT": "false"
}
}
}
}The wrapper should allow formatting, validation, planning, and read-only inspection. It should reject apply, state mutation, imports, credential discovery, shell passthrough, and paths outside the approved repository. Client configuration syntax varies, but that permission boundary should not.
Photo by Christina Morillo on Pexels.
The prompt chain#
Do not ask the agent to “fix the Terraform” in one turn. Split discovery, proposal, implementation, and verification into distinct prompts, each with an explicit stopping condition. The separation makes hidden assumptions visible and prevents the agent from treating successful command execution as permission to continue into a materially different operation.
1. Establish repository invariants#
Start by forcing the agent to describe the repository before editing it:
Inspect the Terraform repository without modifying files or state.
Identify:
- the module and environment affected by this request;
- naming, tagging, provider, and variable conventions;
- validation and plan commands already used by the repository;
- files that must not change;
- any ambiguity that could change resource identity or lifecycle.
Return an evidence-backed change boundary. Stop before proposing code.This prompt makes the agent earn its scope. A server can expose tools cleanly while the model still chooses the wrong directory or module; the official reference servers demonstrate server patterns, not the invariants of your repository.
2. Produce a constrained proposal#
Next, request a plan for the edit rather than the edit itself:
Propose the smallest change that satisfies the request while preserving the
identified invariants.
List:
1. files to modify;
2. resources or data sources affected;
3. expected Terraform plan actions;
4. assumptions requiring human confirmation;
5. rollback steps.
Do not edit files. Do not run apply, import, or any state command.The expected plan actions are important. If the proposal predicts one in-place update but the eventual plan contains replacement or deletion, the mismatch is a review signal—not an invitation for the agent to rationalize the difference.
3. Implement only the approved boundary#
After a human accepts the proposal, constrain implementation:
Implement only the approved proposal.
Rules:
- change only the approved files;
- preserve existing repository conventions;
- do not broaden provider permissions or module scope;
- do not edit state, lock files, generated files, or unrelated formatting;
- do not apply infrastructure.
After editing, show a concise diff summary and stop.“Only” matters. Agents often notice adjacent cleanup opportunities, but mixing them into an infrastructure change makes the plan harder to attribute and rollback.
4. Generate review artifacts#
Finally, ask for deterministic evidence:
Run the repository's existing formatting and validation checks, then create a
saved Terraform plan for the approved target.
Report:
- commands executed;
- validation failures without attempting unrelated fixes;
- counts of create, update, replace, and destroy actions;
- resource addresses for every non-no-op action;
- any difference between the approved proposal and the actual plan.
Do not apply. Stop after presenting the review artifacts.This chain treats the agent as a fast operator inside a controlled workflow. If your team needs a ready-made review discipline, Review & Repair is the relevant PairFoundry path; the broader options are listed in the packs overview.
The gate#
The mandatory gate is a human review of both the repository diff and the saved Terraform plan before any apply-capable identity becomes available. If the reviewer cannot explain every replacement and destruction, the change does not pass. An agent-generated summary is navigation help, not evidence, and must never substitute for the plan.
Use a short, repeatable checklist:
- The diff touches only approved files.
- Every plan action maps to a requested outcome.
- Resource addresses match the intended environment and module.
- No unexpected replacement, deletion, or dependency cascade appears.
- Provider, backend, lifecycle, and ownership boundaries remain intact.
- Sensitive values are not exposed in prompts, logs, or review artifacts.
- A rollback commit and an infrastructure recovery path are both understood.
- The apply identity remains unavailable to the MCP process.
Code review is a systematic examination of source changes by someone other than the author. Here, the author may be an agent, but the principle becomes more important: reviewing syntax alone misses the externally visible state transition.
The person approving the plan should not merely ask whether Terraform accepts it. They should compare the actual actions against the proposal produced earlier. A discrepancy resets the chain at proposal, even when the new plan looks plausible.
For engineers still establishing this discipline, PairFoundry Foundations provides a lower-commitment next step. Related operating patterns live in the workflows collection.
Photo by Christina Morillo on Pexels.
What it gets wrong#
The most dangerous failures are usually coherent, valid, and reviewable only if you know where to look. A Terraform MCP server may execute exactly the requested command while the agent selects the wrong module, changes resource identity, or “fixes” a plan by weakening an invariant. Correct tool execution does not imply correct infrastructure intent.
Watch for these concrete patterns:
| Failure mode | Recognition signal | |---|---| | Wrong environment | Resource addresses, variable files, backend context, or paths name an unintended environment | | Accidental replacement | The plan shows destroy-and-create where the proposal predicted an update | | Scope creep | Unrelated files or resources appear in the diff or plan | | Convention drift | New naming, tagging, provider, or module patterns appear without repository precedent | | Symptom suppression | The agent removes lifecycle protection, validation, or constraints to make checks pass | | State confusion | The agent proposes import, state removal, or address movement as routine cleanup | | Secret exposure | Credentials or sensitive outputs appear in prompts, logs, command arguments, or summaries | | Summary mismatch | The prose says “no destructive changes,” but the plan contains replacement or destroy actions |
Do not let the agent self-approve after detecting one of these. Its explanation may be internally consistent because it is based on the same mistaken assumption that created the change.
The official MCP architecture explains how components exchange context and invoke tools. It cannot tell you whether changing a resource address violates your migration policy or whether a replacement is acceptable during business hours. Those are repository and team invariants, so encode them in prompts, wrappers, and review checklists.
Rollback#
Rollback has two separate meanings: reverting repository changes and recovering infrastructure after an apply. Keep them separate. Before the gate, rollback should be a clean source-control revert plus deletion of disposable plan artifacts. After an apply, blindly reverting code and applying again can create another destructive transition.
Before apply:
- Preserve the reviewed diff as one isolated change.
- Discard the saved plan when code, variables, credentials, or relevant remote state changes.
- Revert only the approved files if the proposal is rejected.
- Re-run validation and produce a fresh plan from the restored repository.
- Confirm that no state-mutating command was executed.
After apply, stop the agent and assess the actual state before issuing another command. Restore the prior configuration only when a new plan proves that doing so produces the intended recovery. Some operations are not logically reversible: destroyed data, rotated values, recreated identities, and external side effects may require service-specific recovery rather than Terraform reversal.
Never “repair” rollback by granting the server broader state access. MCP’s official specification defines interoperability, not authorization for emergency infrastructure changes. Recovery should use the team’s established operator identity, audit path, and incident process outside the agent’s routine tool boundary.
Photo by Lukas Blazek on Pexels.
Related reading#
- Claude Code Python, with the guardrails that keep it honest
- How to upgrade Claude Code: making the output reviewable, not just correct
FAQ#
Should the Terraform MCP server ever have permission to run apply?#
For the review workflow described here, no. Planning and applying should use different authority boundaries, with the MCP process limited to inspection, editing, validation, and plan generation. Giving the same agent apply access collapses the only meaningful human gate and turns a mistaken interpretation into an infrastructure event.
How is this different from following the official MCP examples?#
Official examples explain protocol roles and server implementation patterns; they do not define your repository’s invariants, cloud authorization model, or review policy. Use them to understand the interface, then add a repository-specific wrapper, narrow credentials, explicit command allowlists, path restrictions, staged prompts, and a human plan gate.
What breaks when a second engineer takes over this setup?#
Hidden local assumptions break first: absolute paths, inherited credentials, unrecorded environment variables, client-specific configuration, and a wrapper that exists only on one machine. Commit the non-secret policy and wrapper logic where appropriate, document prerequisites, and make missing configuration fail closed rather than silently selecting defaults.
When should a team avoid this workflow entirely?#
Avoid it when the repository cannot produce a reliable plan, state ownership is unclear, credentials cannot be narrowed, or reviewers cannot identify intended resource actions. Also avoid it during emergency recovery where agent-generated edits would add uncertainty. Fix the operating boundary first; faster generation is worthless without reviewable evidence.
What is the cleanest response to an unexpected destroy action?#
Stop immediately, withhold apply authority, and compare the resource address against the approved proposal, diff, variables, and target environment. Do not ask the agent to “make the destroy disappear.” Identify the assumption that changed identity or ownership, revert the unapproved edit, and generate a completely fresh plan.