Skip to navigation

Claude Code Terraform State: Locking and Access Controls

In short: Protect Terraform state before Claude Code can plan or apply, with remote backends, locking and narrow operator access.

Published 16 min read
On this page

Direct answer

Terraform state is the most privileged artifact in an infrastructure repository. It holds the mapping between configuration and real resources, it can contain secret values, and whoever can write it can redirect every future apply. Before Claude Code plans or applies anything, state needs a remote backend, verified locking, and a separate identity for reading state from changing it. Give the agent a planning identity with read access, keep apply behind a human-approved execution identity, and never put state in version control.

The concrete win is that a compromised or confused agent session cannot silently rewrite what Terraform believes exists. The concrete loss is that remote state moves the problem rather than deleting it: the backend now holds the secrets, so backend access, encryption and recovery become part of the control set. The practical step is a permission split that treats state access as its own reviewable surface, separate from the application permissions the infrastructure manages.

Why the gate earns its cost

State decides what Terraform thinks is true. When an apply runs, Terraform reconciles real infrastructure against state and configuration. Corrupt state, concurrent writes, or a leaked state file each produce a different failure, and all three are expensive to unwind.

Three ordinary accidents account for most state incidents. Two applies run at once because nothing serialized them, and one overwrites the other’s changes. State lands in a commit because the working directory was never configured for a backend, and every contributor now has a copy. An agent session with broad cloud credentials reads state contents it did not need, because planning was never separated from applying.

None of these are exotic. They are the default outcome of a local state file plus shared credentials, which is the configuration most teams start with. The fix is structural, and it is cheaper to install before an agent has write access than after.

Why State Is a Privileged Artifact

Official, F004: Terraform warns that local state risks loss of workspace state and recommends storing state remotely.

The artifact is privileged for three reasons that compound. It maps configuration addresses to real resource IDs, so a wrong entry can cause Terraform to modify or destroy the wrong thing. It often contains values that configuration marks sensitive, because the provider returns them during refresh and Terraform stores them. It is a coordination point, so concurrent writes without locking produce lost updates.

Terraform documents state as its own topic rather than a configuration footnote, which reflects how much depends on it. A planning identity that can read state can see every attribute the provider stored, including values the configuration never printed. That alone justifies treating state reads as a governed action.

State property What it enables Risk if uncontrolled
Resource ID mapping Terraform reconciles configuration to real resources Wrong mapping redirects apply at the wrong target
Stored attribute values Plan can compare desired to current Cleartext secret exposure on read
Single coordination point One source of truth per workspace Concurrent writes lose updates
Backend credentials Access to the storage location Whoever holds them controls every apply

Read the fourth row as the boundary this post is really about. Backend credentials are the effective key to the whole environment, so they belong to an identity review, not a shared config file.

Local State Failure Modes

Local state is the file Terraform writes when no backend is configured. It is convenient for a first experiment and unsuitable for anything shared.

Official, F005: Terraform advises against putting state in version control because version control lacks state locking and secure access control.

The failure modes are concrete. No locking means two engineers or two agent sessions can apply against the same file concurrently, and the last writer wins while the other’s changes vanish from record. Version control storage means every clone carries a copy of every secret value the state captured, indefinitely, in the repository history. No access control means anyone who can read the repository can read the state.

bash
  # local state has no serialization and no access boundary
# terraform applies in two terminals race on the same file
terraform apply -auto-approve  # terminal A
terraform apply -auto-approve  # terminal B, concurrent

Local state remains appropriate for throwaway experimentation and local-only learning. Once more than one identity can reach the workspace, or once an agent can run applies, the local file is the wrong default.

Evidence map showing Terraform state as a privileged artifact with local, remote and version-control locations, each with different locking and exposure risk.
Editorial evidence map based on F004 and F005. If state exposure is acceptable, the access-control design is not finished. Labels are the post author’s.

Remote Backend Selection

A remote backend stores state outside the working directory and, for most production choices, outside the repository entirely. Terraform documents backend configuration as a settings topic, and the backend configuration reference covers how a backend is declared.

Selection criteria that matter for an agent-assisted workflow:

Locking support. The backend must serialize writes so two applies cannot corrupt the same state. Not every backend behaves identically here, so verify the specific backend rather than assuming a shared feature.

Access control. The storage location needs its own permission model, separate from the repository and separate from the cloud resources Terraform manages. AWS IAM policies define permissions for AWS resources, which is how state access gets governed independently of the infrastructure being built.

Recovery. A backup and a tested restore path are part of the state design, because a backend that cannot be restored is a single point of failure for the whole environment.

State location Locking support Exposure risk
Local file in the working directory None Low barrier to copy; secrets on every clone
Committed to version control None from Terraform’s view High; secrets persist in history
Remote backend object storage Depends on backend configuration Depends on storage permissions and encryption
Managed remote state service Provided by the service Governed by the service’s access model

Treat the second row as the one to eliminate first. Committing state is the failure mode Terraform explicitly warns against.

Locking Verification

Locking is a backend property that has to be observed, not assumed. A backend can store state remotely and still not serialize concurrent writes.

Verify three behaviors before trusting a backend for agent-assisted applies. A second apply started while the first holds the lock should fail rather than proceed. The lock should be released when the apply completes or fails, including on an interrupted session. There should be a documented, safe procedure for removing a stale lock held by a dead process, and that procedure should be restricted to operators who understand the consequence.

bash
  # observe locking behavior before agent access
# start apply A, then attempt apply B while A holds the lock
terraform apply   # A acquires lock
terraform apply   # B should fail while lock is held

Locking interacts with the plan gate described in Terraform plan review gates. A saved plan from a locked backend binds an approval to reviewed bytes; a backend that is not locked undermines that binding because the state can change underneath it. The drift triage workflow in the Terraform drift triage guide also assumes refresh sees a coherent state, which locking protects.

Workflow from selecting a remote backend through verifying locking, splitting identities, and reviewing state access evidence before agent plan or apply.
Editorial workflow based on F004 and F006. Locking is verified against the actual backend, not assumed from documentation.

Identity and Permission Split

The central design move is separating the identity that plans from the identity that applies. AWS IAM policies define permissions for AWS resources, so state access can be governed as its own set of actions, distinct from the permissions the infrastructure grants to applications.

Official, F006: IAM policies define permissions for AWS resources, meaning state access can be governed separately from other cloud actions. The caveat is that exact state-backend permissions depend on the chosen backend and the AWS services involved.

A workable split uses three identities.

A read identity for planning. It can read state and the cloud resources a plan refreshes, and it cannot write state or run applies.

An execution identity for applying. It can write state and mutate infrastructure, and it is used only after a human approval.

A break-glass identity for recovery. It exists for incidents, is time-boxed, and is reviewed after use. The Claude Code Break Glass: Incident Access Controls guide covers that path in detail.

Operator role Required Terraform actions Cloud permissions
Planning identity (agent) Read state, refresh, produce a plan Read-only across in-scope resources
Execution identity (human-approved) Apply the reviewed plan, write state Write across in-scope resources, gated
Recovery identity Restore or rewrite state during incidents Broad, time-boxed, reviewed after use

Keep the agent off the third row. An agent that can restore or rewrite state during an incident is an agent that can rewrite history, which defeats every other control in this post.

Cloud guardrails sit on top of this split. Cloud IAM permission boundaries set the maximum any single identity can grant, and policy as code audit before deny adds automated checks that report before they block. Reviewing the whole identity surface, not only the newest binding, is covered by access recertification for agent identities, the accountability question of who owns a change is covered by RACI ownership for infrastructure changes, and what an agent can reach when its output is wrong is modeled in infrastructure threat model boundaries.

AWS Cost Management IAM controls describe how IAM governs access to cost and billing capabilities, a reminder that permission design applies to every AWS surface the workflow touches, not only the compute and storage the configuration creates.

State Exposure Checklist

Run this list against every workspace an agent can reach. Each row is a pass condition.

Backend check Evidence to retain Stop condition
State stored remotely Backend configuration and storage location Local state in a shared workspace
State absent from version control Repository history shows no state files Any state file in git history
Locking verified Recorded test of concurrent apply failure Backend cannot serialize writes
Backend access restricted Permission policy naming allowed identities Shared backend credentials
Encryption at rest Backend storage configuration Unencrypted state storage
Read separated from write Planning identity cannot write state Agent holds apply credentials
Recovery path tested Documented restore run No tested restore procedure

The version control row deserves emphasis because it is the most common violation and the easiest to check. State in git history is state disclosed to everyone who ever cloned the repository, and removing it means rewriting history, not just deleting a file. Credential handling for the agent session itself is a separate surface, covered by API key security for AI apps.

Tradeoff between a locked remote backend that serializes applies and the operational cost of managing backend credentials, encryption and recovery separately.
Editorial tradeoff diagram based on F004. Remote state removes local exposure; the trade is owning backend access, locking and recovery as first-class controls.

Recovery Ownership

State recovery is a decision about who is allowed to rewrite what Terraform believes exists. That authority is broader than an apply, because a restored state file changes the baseline for every future plan.

Name a recovery owner per workspace. Keep the recovery identity separate from the agent and from routine execution. Test the restore path on a schedule, because an untested backup is a hypothesis rather than a control. Record every recovery action with the reason, the approver and the state version restored.

Recovery also has a detection side. When state and reality disagree, something changed outside Terraform, and that is a drift event rather than a routine apply. The Terraform drift triage guide covers classifying those differences before anything reconciles them. Judging whether your evidence is complete enough to trust is covered by audit evidence integrity checks.

Evidence for Reviewers

A reviewer evaluating state controls should ask for evidence, not assurances. Four artifacts answer most of the review.

The backend configuration showing where state lives. A permission policy naming which identities can read and write state. A record of the locking test, including the concurrent-apply failure. The restore runbook with a date from the last successful test.

Packaging this evidence for an auditor is covered by SOC 2 change evidence packets, and deciding how much review a state change deserves is covered by risk-tiered infrastructure approvals. Judging telemetry before treating it as evidence is covered by audit evidence integrity checks.

Official: Claude Code security documentation describes permission modes, sandboxing and managed settings as safeguards. These govern what an agent session can do on the workstation. They do not replace backend access control, because the backend holds the authority regardless of what the agent is permitted to run locally.

Review question Evidence Weak answer
Where is state stored? Backend configuration “In the cloud somewhere”
Who can write state? Permission policy with named identities “Only the team”
Do concurrent applies serialize? Locking test record “The backend handles it”
Can we restore? Tested restore run “We have backups”

Read the weak-answer column as the pattern to reject in review. Each entry sounds reasonable and none of them is evidence.

Control checklist covering remote storage, absence from version control, verified locking, restricted backend access, encryption, read-write separation and a tested recovery path.
Editorial control checklist derived from F004 through F006. Passing the checklist shows state access was reviewed honestly; it does not certify the backend for every failure mode.

Safe default for a new team

A team adopting Claude Code for infrastructure should start from a configuration that fails safe. Remote backend with locking enabled. Planning identity read-only, used by the agent. Execution identity held by a human approver. State excluded from version control from the first commit. Restore path documented and tested once before the first production apply. A record of who approves what is covered by RACI ownership for infrastructure changes.

Verdict that state must sit behind a locked remote backend with a read-only planning identity and a separate human-approved execution identity.
Editorial verdict based on F004 and F005. Treat state as a privileged dependency; a plan gate cannot compensate for an unlocked or exposed backend.

The concrete win, loss, and implication

The concrete win is containment. A read-only planning identity means an agent session can produce a complete, reviewable plan without holding the authority to change state or infrastructure. A bad suggestion stays a suggestion.

The concrete loss is a new operational surface. The backend now stores the secrets state carries, so backend permissions, encryption and recovery become responsibilities the team owns and reviews. Moving to remote state does not delete the risk; it relocates it to a place where it can be controlled.

The practical implication is that state access is an identity problem before it is a Terraform problem. Teams that split planning from execution can let an agent propose changes confidently, because the agent never held apply authority. Teams that share one set of credentials cannot audit who did what, and the plan gate degrades into a formality.

State control is the foundation under the Terraform posts. To turn plans into bound approvals, read Terraform plan review gates. Differences between state and reality are covered by the Terraform drift triage guide.

Kubernetes has an equivalent boundary. The additive permission union you grant before agent access is covered by Kubernetes RBAC least privilege reviews. Field ownership on shared objects is covered by server-side apply ownership checks. Traffic policy enforcement is covered by NetworkPolicy blast radius reviews. Workload admission controls are covered by Pod Security admission gate reviews.

Cloud and governance context appears in cloud IAM permission boundaries and access recertification for agent identities. Change accountability is covered by RACI ownership for infrastructure changes and SOC 2 change evidence packets. The reporting-versus-prevention tradeoff in automated guardrails is covered by policy as code audit before deny, and incident recovery paths are covered by break glass incident access controls, and running a change freeze with an emergency path is covered by change freeze emergency rules.

Data gap and future update

The Terraform state page supports the remote-storage and version-control warnings in F004 and F005. Backend-specific locking semantics, encryption behavior and permission requirements vary by backend and were not verified against each backend’s documentation in the research pass behind this post. The backend configuration reference was identified as a canonical source but not full-page fetched, so exact fields should be rechecked before relying on a detail.

No measurement of state-corruption frequency, apply race incidents or recovery success rates is reported here, because none was collected. The AWS permission examples are structural rather than a copyable policy for a specific backend, because exact state-backend permissions depend on the backend and services involved.

One AI API Key option for OpenAI-format agents

Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The packet records Claude IDs as unavailable on 2026-11-27.

OpenAI-format agents have a separate route: One AI API Key provides https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. That is a different client and request format, not a workaround for Claude Code authentication. Check the free model list for eligibility, read the quickstart for request shape, or compare hosted options with the cost calculator.

FAQ

Why is Terraform state sensitive?

State maps configuration to real resources and stores attribute values the provider returns, which can include secrets marked sensitive in configuration. Reading state can therefore disclose values that were never meant to be printed, and writing it can redirect every future apply.

Can state stay in version control if the repository is private?

Terraform advises against it because version control lacks state locking and secure access control. A private repository reduces who can see the file, but it still publishes every secret value to everyone with clone access and keeps them in history indefinitely.

What does a planning identity need?

Read access to state and read access to the cloud resources a plan refreshes. It does not need permission to write state or to mutate infrastructure. Keeping apply behind a separate execution identity is what makes the plan gate meaningful.

How do I verify a backend actually locks?

Attempt a second apply while the first holds the lock and confirm it fails rather than proceeding. Documentation describes capability; the concurrent-apply test shows the backend serializing writes for your configuration.

Does remote state remove the risk of leaking secrets?

It removes the local copy and the version-control copy, which are the most common leaks. The backend now holds those values, so backend access control, encryption at rest and recovery ownership become the controls that matter.

More Claude Code troubleshooting

Sources

More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
Claim $10 credit →