Join our Newsletter — 33% off our NHI Course
Home› Guides› Terraform State Security Guide: Protect the File That…
Guide Cloud Security

Terraform State Security Guide: Protect the File That Knows Every Secret

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 18 November 2026 13 min read
On this page

Terraform state is a complete, machine-readable map of your infrastructure that routinely contains passwords, keys and tokens in plaintext, so whoever can read or write it can read your secrets and quietly change what Terraform believes exists. This guide covers how to secure state as a system: where it is stored, who and what can read and write it, how it is locked and encrypted, how it is versioned and recovered, and how to keep new secrets out of it.

If you need to find secrets already sitting in state files and copies, follow How to find secrets in Terraform state first. This page does not repeat that search; it covers the controls that stop the problem recurring. Credentials used by pipelines to run Terraform are covered in the Terraform and IaC Pipeline Credential Security Guide.

Key takeaways

  • HashiCorp's guidance on sensitive data in state is explicit: Terraform stores secret values from configuration in plaintext in state and plan files. Treat state as a secret, store it remotely, encrypt it at rest, restrict access and audit reads.
  • The sensitive flag only redacts values from CLI and UI output. It does not keep them out of state. Ephemeral values (Terraform 1.10 and later) and write-only arguments (Terraform 1.11 and later) do.
  • Read access to state is a privileged permission. Write access is more dangerous still, because a modified state file changes what the next apply creates, updates or destroys.
  • Locking prevents concurrent corruption. On Amazon S3 the native lock file (use_lockfile) replaces DynamoDB locking, which HashiCorp has deprecated.
  • Versioning is your recovery plan. HashiCorp strongly recommends bucket or object versioning for the S3 and GCS backends so state can be restored after deletion or error.
  • The identities that read and write state are non-human identities with some of the widest reach in your estate. Use federated, short-lived credentials and scope them per state file.

What state holds and why it is a target

A state file records every managed resource, its identifiers and the attribute values the provider returned. That includes database master passwords, generated private keys, access keys created for service accounts, connection strings and any value passed through a variable into a resource argument. Plan files contain much the same data.

For an attacker, state offers three things. It is a credential store: one read can yield dozens of working secrets, which maps to MITRE ATT&CK T1552.001 Credentials In Files and, for cloud buckets, T1530 Data from Cloud Storage. It is a reconnaissance map: account IDs, network ranges, role names and endpoints for the whole environment. And it is a control point: if an attacker can write state, they can remove a resource from Terraform's view so it is never managed again, or alter attributes so the next apply makes changes a reviewer does not expect.

Security for state therefore needs confidentiality, integrity and availability controls, not just encryption.

Choosing and hardening a backend

Local state on a laptop or a CI runner disk is plaintext, unaudited and easily copied. HashiCorp recommends remote state. Whichever backend you choose, apply the same baseline:

  • A dedicated storage location for state, in an account or project reserved for infrastructure management, not shared with application data. The S3 backend documentation describes a multi-account pattern that keeps Terraform's own infrastructure in an administrative account to limit blast radius.
  • No public access, no anonymous access and no broad cross-account read grants.
  • Encryption at rest with a customer-managed key where the backend supports it.
  • Versioning, plus protection against deletion of old versions.
  • Access logging for reads as well as writes.
  • One state file per environment and per component, so a single credential or a single corrupted file does not expose or break everything.

Managed platforms such as HCP Terraform store state for you; HashiCorp states that HCP Terraform encrypts state at rest, supports customer-supplied keys and uses TLS in transit. Its workspace permissions and run controls are covered in the Terraform Cloud and HCP Security Guide. The sections below cover the three most common cloud storage backends, in alphabetical order by provider.

Amazon S3 backend

The S3 backend documentation lists the settings that matter:

  • encrypt = true enables server-side encryption of the state and lock files. kms_key_id sets a KMS key, which requires the Terraform identity to have kms:Encrypt, kms:Decrypt and kms:GenerateDataKey on that key.
  • If you use customer-provided keys (sse_customer_key), HashiCorp recommends the AWS_SSE_CUSTOMER_KEY environment variable, because a key written in a Terraform file is persisted to state.
  • Minimum permissions without workspaces are s3:ListBucket on the bucket, limited to the state path, and s3:GetObject and s3:PutObject on the state key. s3:DeleteObject is not needed on the state file itself; it is needed on the .tflock lock file when native locking is on.
  • HashiCorp recommends per-object IAM policies to restrict reading as well as writing, including the lock file.
  • Bucket Versioning is strongly recommended for recovery.
  • HashiCorp tests the backend only against Amazon S3; S3-compatible stores are best effort.

Azure Blob Storage backend (azurerm)

The azurerm backend documentation supports locking through Azure Blob Storage native capabilities and ranks authentication methods:

  • Recommended: Microsoft Entra ID with OpenID Connect workload identity federation, or managed identity. Azure CLI authentication is listed for local development.
  • Not recommended for new workloads: storage access keys, SAS tokens and access key lookup.
  • Backwards compatibility only: client secrets and client certificates, which require you to manage and rotate a secret.
  • Least privilege: the Storage Blob Data Contributor role scoped to the container, with Reader on the storage account only if blob endpoint lookup is enabled.

Access keys deserve particular attention. A storage account key grants full access to every container in the account, so a key used for Terraform state is a key to every other blob in that account too.

Google Cloud Storage backend (gcs)

The GCS backend documentation notes that the backend supports locking and provides two encryption options: encryption_key for a customer-supplied key and kms_encryption_key for a Cloud KMS customer-managed key, in which case the project's Cloud Storage service agent needs the CryptoKey Encrypter/Decrypter role. Backend credentials need the Storage Object Admin role on the bucket, and service account impersonation requires the Service Account Token Creator role on the target account. Object Versioning is highly recommended. HashiCorp warns that state encrypted with a lost or deleted key cannot be recovered.

Access control for people and pipelines

Treat state access as a privileged entitlement with separate read and write tiers.

  • Write: only the pipeline identity that runs applies for that state file. Humans should not hold standing write access to production state. Use a break-glass role, logged and time-limited, for recovery work.
  • Read: the plan identity, and the apply identity. Developers who need outputs from another stack should get them through a published output or a parameter store, not by reading the other stack's full state.
  • Cross-stack reads: the terraform_remote_state data source exposes only the other stack's root-level outputs, but HashiCorp states its user must have access to the entire state snapshot, which often includes sensitive data. Every consumer therefore gains read access to every secret in that state. Prefer publishing the specific values a consumer needs.
  • Scope per file: grant access to a specific key or prefix, not to the whole bucket or container. Use separate roles for separate environments.
  • Short-lived credentials: use workload identity federation from your CI system rather than long-lived keys. The How to federate Terraform Cloud to AWS walkthrough shows the pattern for one combination.

Keep backend credentials out of configuration. All three backend pages warn that values passed with -backend-config or hardcoded in configuration are written to the .terraform directory and to plan files, and recommend environment variables instead. A CI cache that keeps .terraform between runs can otherwise become a second copy of your backend credentials.

Map these controls to NIST SP 800-53 Rev. 5 AC-6 Least Privilege for scoping, AU-2 Event Logging for read and write logging, SC-28 Protection of Information at Rest for encryption and SC-12 Cryptographic Key Establishment and Management for key handling.

Locking and integrity

State locking prevents two runs writing the same state at once, which can corrupt it or silently lose changes. On S3, use_lockfile = true enables S3 native locking; it defaults to false. The DynamoDB table option is deprecated and will be removed in a future minor version, and both can be set together during migration. The azurerm and gcs backends lock natively.

Locking is not an integrity control against a malicious writer. For that you need:

  • Write access limited to the apply pipeline, as above.
  • Version history you can compare. Diff the latest state against the previous version when an apply produces unexpected changes.
  • Alerts on state writes outside the pipeline's identity, and on lock files that are force-removed. terraform force-unlock is a legitimate recovery command, but it should be rare and should be explained.
  • Review of terraform state rm, state mv, import and state push operations. Each changes state without a normal plan, so record who ran them and why.

Encryption beyond the storage layer

Backend encryption protects state from someone with access to the storage media. It does not protect state from anyone who can read the object through the storage API, because the service decrypts it for them. Two further options exist.

Client-side state encryption in OpenTofu. The OpenTofu state encryption documentation describes encrypting state and plan files before they are written, locally or to any backend, including data read through terraform_remote_state. Key providers include a passphrase-derived key (pbkdf2), AWS KMS, Google Cloud KMS, Azure Key Vault, OpenBao Transit and an external program, with aes_gcm as the built-in method. Points to note from that documentation:

  • Set enforced = true so plaintext state cannot be written when the key configuration is missing.
  • Migration from plaintext uses a fallback to the unencrypted method, removed once all state is re-encrypted.
  • Back up keys and an unencrypted copy of state before enabling encryption; without the key, state cannot be read.
  • Use a separate KMS key per state file, and do not rename key providers or methods after encrypting.
  • Encryption does not protect against data loss, replay or the person running the tool.

Keeping secrets out of state. In Terraform, the sensitive argument redacts output, but values are still stored, and terraform output -json or -raw shows them in plain text. Ephemeral variables, ephemeral outputs from child modules and ephemeral resource blocks (Terraform 1.10 and later) exist only during a run and are omitted from state and plan files. Write-only arguments (Terraform 1.11 and later), usually ending in _wo with a matching _wo_version, pass a value to the provider without storing it. Combined with a secrets manager that generates and holds the actual secret, these features shrink what a state leak exposes.

Versioning, backup and recovery

  • Enable versioning on the state bucket or container, as HashiCorp recommends for S3 and GCS, and protect old versions from deletion by the same identities that write state.
  • Remember that every old version is another copy of every historic secret. Apply a retention period that balances recovery against exposure, and rotate any secret found in state rather than relying on version expiry to remove it.
  • Back up encryption keys separately from state, and test that you can decrypt a restored version.
  • Document the recovery steps: identify the last good version, take a lock, restore, run a plan to confirm no unexpected changes, release the lock. Rehearse them.
  • Include state storage in your incident response plan. A suspected read of state means rotating every secret in it, not just revoking the reader.

Where identity fits

State security is an identity problem in both directions. The identities that run Terraform usually hold some of the broadest cloud permissions in the organisation, and their access to state is what turns a pipeline compromise into a credential harvest. At the same time, state is where many other non-human identities' secrets end up: service account keys, database users, API tokens and certificates created by Terraform.

  • Inventory the identities that can read each state file, including CI runners, policy tools, drift detectors and any automation using terraform_remote_state.
  • Replace long-lived backend keys with federated identities, as the azurerm guidance recommends.
  • Track the secrets in state as identities with owners. When state is exposed, you need a list of what to rotate and who owns it.
  • Where Terraform runs through a pull request automation tool, its server identity has the same reach; see the Atlantis Security guide for that case.

Common failure patterns

  • Relying on sensitive. Output is redacted but the value sits in state in plaintext.
  • One bucket, one role, every environment. A development pipeline credential reads production state.
  • Broad terraform_remote_state use. Consumers read every secret in another stack to get a single output.
  • Storage account keys for state. The key also opens every other container in the account.
  • Backend credentials in -backend-config. They are written to .terraform and plan files, then cached by CI.
  • No versioning, or versioning with unlimited retention. Either no recovery, or every historic secret kept indefinitely.
  • Standing human write access. Manual state edits bypass review and leave little trace.
  • Plan files treated as harmless. Saved plans carry the same sensitive values and are often uploaded as CI artefacts.
  • Encryption keys without backup. Client-side encryption locks the organisation out of its own state.

Practitioner checklist

  • Move all state to a remote backend in a dedicated infrastructure account or project.
  • Enable encryption at rest with a customer-managed key, and consider client-side state encryption where your tooling supports it.
  • Split state per environment and component, and scope read and write access per state key.
  • Limit write access to the apply pipeline identity; give humans break-glass access only.
  • Use federated, short-lived credentials for backends; remove storage account keys, SAS tokens and static keys.
  • Pass backend credentials through environment variables, never -backend-config files or code.
  • Enable native locking (use_lockfile on S3) and plan removal of DynamoDB locking.
  • Enable versioning with a defined retention period and protection against deletion.
  • Log and alert on state reads, writes outside the pipeline, force-unlocks and manual state commands.
  • Replace terraform_remote_state with published outputs where possible.
  • Adopt ephemeral values and write-only arguments for new secrets, and rotate any secret already found in state.
  • Treat saved plan files as sensitive and avoid keeping them as long-lived CI artefacts.

Standards and references

Related NHI Mgmt Group resources: How to find secrets in Terraform state · Terraform and IaC Pipeline Credential Security Guide · Terraform Cloud and HCP Security Guide · Atlantis Security

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.