Nexus Void Research

Terraform, Terraform State, Infrastructure as Code, IaC Security, AWS S3, Secrets, CWE-312, How-to

How to Secure Terraform State Files (S3, GCS, Azure)

How to secure a Terraform state file: remote encrypted backend, state locking, least-privilege access, and keeping secrets out of state entirely.

To secure a Terraform state file, never commit it to git and never leave it on a laptop. Store it in a remote backend (an encrypted, versioned, non-public S3 bucket, a Google Cloud Storage bucket, Azure Storage or HCP Terraform) with state locking, restrict access to the few identities that run Terraform, and keep secrets out of state where you can with ephemeral values and write-only arguments, because state stores resource attributes, including secrets, in plain text.

Terraform state maps your configuration to real infrastructure. It is also one of the most sensitive files in your company: it can contain database passwords, private keys, access tokens and the full shape of your cloud estate. HashiCorp's own documentation on sensitive data in state is clear that state should be treated as sensitive. Storing it in clear text in the wrong place is CWE-312: Cleartext Storage of Sensitive Information. This guide shows how to lock it down on AWS, Google Cloud and Azure.

What sensitive data is in Terraform state?

State records the attributes of every resource Terraform manages, as returned by the provider. Depending on your resources that includes:

  • Database master passwords and connection strings

  • Generated private keys and TLS certificates (for example from the tls provider)

  • Access keys for IAM users or service accounts created by Terraform

  • Values from data sources, such as secrets read from a secret manager

  • Internal hostnames, IP ranges and security group rules

Marking a variable or output sensitive = true hides it from CLI output and plans, but it is still stored in state in plain text. That surprises many teams.

Step 1: Never commit state or local secrets

Add these to .gitignore in every Terraform repository:

*.tfstate
*.tfstate.*
.terraform/
crash.log
*.tfvars
*.tfstate
*.tfstate.*
.terraform/
crash.log
*.tfvars
*.tfstate
*.tfstate.*
.terraform/
crash.log
*.tfvars

Commit .terraform.lock.hcl (the provider lock file), but never state. If state has ever been committed, treat every secret in it as exposed: rotate them, then remove the file from git history.

Step 2: Use a remote backend with encryption and locking

AWS S3, with native locking (Terraform 1.10 and later):

terraform {
  backend "s3" {
    bucket       = "acme-terraform-state"
    key          = "prod/network/terraform.tfstate"
    region       = "eu-west-1"
    encrypt      = true
    kms_key_id   = "arn:aws:kms:eu-west-1:111122223333:key/abcd-1234"
    use_lockfile = true
  }
}
terraform {
  backend "s3" {
    bucket       = "acme-terraform-state"
    key          = "prod/network/terraform.tfstate"
    region       = "eu-west-1"
    encrypt      = true
    kms_key_id   = "arn:aws:kms:eu-west-1:111122223333:key/abcd-1234"
    use_lockfile = true
  }
}
terraform {
  backend "s3" {
    bucket       = "acme-terraform-state"
    key          = "prod/network/terraform.tfstate"
    region       = "eu-west-1"
    encrypt      = true
    kms_key_id   = "arn:aws:kms:eu-west-1:111122223333:key/abcd-1234"
    use_lockfile = true
  }
}

Older setups use a DynamoDB table for locking; S3-native locking with use_lockfile replaces it in current versions.

Google Cloud Storage:

terraform {
  backend "gcs" {
    bucket = "acme-terraform-state"
    prefix = "prod/network"
  }
}
terraform {
  backend "gcs" {
    bucket = "acme-terraform-state"
    prefix = "prod/network"
  }
}
terraform {
  backend "gcs" {
    bucket = "acme-terraform-state"
    prefix = "prod/network"
  }
}

GCS locks state automatically. Use a customer-managed encryption key if your policy requires one.

Azure Storage:

terraform {
  backend "azurerm" {
    resource_group_name  = "rg-terraform-state"
    storage_account_name = "acmetfstate"
    container_name       = "tfstate"
    key                  = "prod/network.tfstate"
    use_azuread_auth     = true
  }
}
terraform {
  backend "azurerm" {
    resource_group_name  = "rg-terraform-state"
    storage_account_name = "acmetfstate"
    container_name       = "tfstate"
    key                  = "prod/network.tfstate"
    use_azuread_auth     = true
  }
}
terraform {
  backend "azurerm" {
    resource_group_name  = "rg-terraform-state"
    storage_account_name = "acmetfstate"
    container_name       = "tfstate"
    key                  = "prod/network.tfstate"
    use_azuread_auth     = true
  }
}

Azure uses blob leases for locking. use_azuread_auth avoids storage account keys. HCP Terraform and Terraform Enterprise also store, encrypt and lock state for you.

Locking matters for security as well as reliability: two concurrent applies can corrupt state, and a corrupted state file can lead someone to "fix" things by hand with broad permissions.

Step 3: Harden the state bucket

On S3 (with equivalent settings on GCS and Azure):

  • Block all public access on the bucket and account.

  • Enable versioning, so you can recover from a bad apply or a deleted state file.

  • Encrypt with a KMS key whose key policy allows only the Terraform roles, which adds a second layer of access control beyond the bucket policy.

  • Require TLS in the bucket policy (deny requests where aws:SecureTransport is false).

  • Enable access logging or data events in CloudTrail so every read of state is recorded.

  • Keep the bucket in a separate, locked-down account from the workloads it describes, where your organisation allows it.

Step 4: Restrict who can read state

Reading state is close to reading every secret it contains, so treat it like production admin access:

  • Give read and write access only to the CI role that runs terraform apply and a small break-glass group.

  • Split state per environment and per component (separate keys, buckets or workspaces for prod and dev), so a dev role cannot read production state.

  • Run Terraform in CI with short-lived credentials via OIDC rather than long-lived keys on laptops; see how to secure a GitHub repository for the Actions setup.

  • Be careful with terraform_remote_state data sources: any configuration that reads another state can see all of its outputs.

Step 5: Keep secrets out of state

The best protection is not putting secrets in state at all:

  • Let the cloud generate and manage secrets. For example, use managed master passwords for databases where the provider supports them, so Terraform never sees the password.

  • Use ephemeral values (Terraform 1.10 and later): ephemeral resources and variables are available during a run but are not written to plan or state files.

  • Use write-only arguments (Terraform 1.11 and later) where providers support them, to pass a secret to a resource without storing it in state.

  • Reference secrets by name from a secret manager at runtime in your application, rather than reading the secret value into Terraform.

  • Avoid creating long-lived access keys with Terraform; prefer roles and workload identity.

If you use OpenTofu, it also supports client-side state encryption, so state is encrypted before it reaches the backend.

Step 6: Scan your Terraform code

Misconfigurations in the code that manages state, and everywhere else, are easier to catch before apply:

trivy config
trivy config
trivy config

IaC scanners flag public buckets, missing encryption, open security groups and overly broad IAM policies in Terraform, CloudFormation and Kubernetes manifests. Run them in pull requests so findings block merge, not deploys.

Terraform state security checklist

Check

Done when

Not in git

.gitignore covers state and tfvars; history is clean

Remote backend

S3, GCS, Azure or HCP Terraform; no local state in shared use

Locking

use_lockfile, GCS or Azure native locking, or HCP Terraform

Encryption

KMS or customer-managed key; TLS required

Bucket hardened

Public access blocked, versioning on, access logged

Least privilege

Only the CI role and break-glass group can read state

Separated

State split per environment and component

Secrets minimised

Managed passwords, ephemeral values, write-only arguments

IaC scanned

Terraform misconfiguration scan on every pull request

How does ARGUS help secure Terraform?

  1. IaC misconfiguration scanning checks Terraform, Terraform plans, CloudFormation, Azure ARM templates and Dockerfiles, plus a second pass for Kubernetes manifests and Helm charts, on every repository scan, flagging issues such as public buckets, missing encryption and open network rules.

  2. Secret scanning catches credentials in committed .tfvars files, provider blocks and state files, and marks them Live, Rotated or Test when AI scanning is on.

  3. Infrastructure bill of materials. ARGUS builds an HBOM from your Terraform resources, Docker Compose files, Dockerfile base images and Kubernetes workloads, so you can see what your code deploys.

  4. Pull request review and fix pull requests keep new misconfigurations from merging, and Assign to Agent proposes the change as a pull request for you to review and merge.

Limits: ARGUS analyses the code in your repository; it does not read your remote state or audit your live cloud account. See how ARGUS works, or scan a repository free. For storing the secrets themselves, see how to store API keys securely.

Frequently asked questions

How do I secure a Terraform state file?

Keep it out of git, store it in a remote backend such as an encrypted, versioned, non-public S3, GCS or Azure Storage bucket or HCP Terraform, enable state locking, restrict read access to the CI role and a small break-glass group, split state per environment, and keep secrets out of state with managed passwords, ephemeral values and write-only arguments.

Does Terraform state contain secrets?

Yes. State stores the attributes of every managed resource as returned by the provider, which can include database passwords, private keys, access keys and values read from data sources. Marking values sensitive hides them from CLI output but not from the state file.

Is it safe to store Terraform state in S3?

Yes, if the bucket is configured securely: block public access, enable versioning, encrypt with a KMS key restricted to Terraform roles, require TLS, log access, enable state locking, and allow only the identities that run Terraform to read and write it.

Do I still need DynamoDB for Terraform state locking?

Not with Terraform 1.10 and later. The S3 backend supports native locking with use_lockfile = true, which stores a lock file in the bucket. DynamoDB-based locking still works for older configurations but is being phased out in favour of the native option.

Does sensitive = true encrypt values in Terraform state?

No. sensitive = true only redacts the value in plan and apply output and in some UI displays. The value is still written to state in plain text, which is why state needs encryption at rest and strict access control.

How do I keep secrets out of Terraform state?

Let cloud services generate and manage secrets where possible, use ephemeral resources and variables (Terraform 1.10+) and write-only arguments (Terraform 1.11+) so values are not persisted, reference secrets by name at runtime instead of reading values into Terraform, and avoid creating long-lived access keys.

Should Terraform state be committed to git?

Never. Git has no access control at the file level, keeps every version forever, and is copied to every clone and CI cache, so any secret in state is exposed to everyone with repository access. Use a remote backend, and add state files to .gitignore.

What happens if my Terraform state file is leaked?

Treat every secret it contains as compromised: rotate database passwords, keys and tokens it includes, review access logs for misuse, and check what the infrastructure details reveal. Then fix how state is stored and who can access it so it cannot happen again.

DATA SOURCES

HashiCorp sensitive data in state: https://developer.hashicorp.com/terraform/language/state/sensitive-data ; CWE-312: https://cwe.mitre.org/data/definitions/312.html

Liked this post? Share it: