Skip to content

Terraform state backends — remote storage with locking

Move Terraform state off the laptop and into a remote backend with locking — S3+DynamoDB on AWS, GCS on GCP, plus workspace and isolation patterns.

You have a working Terraform configuration, but the state file lives next to the HCL in someone’s Git checkout. Two operators cannot run apply at the same time without trashing each other; an apply on a laptop that crashes leaves state in limbo; a state file accidentally committed to a public repo is a credential leak. The fix is a remote backend with locking — state in object storage, a lock in a strongly-consistent KV store, and state versions retained for rollback. This article walks the AWS S3+DynamoDB backend in detail and notes the equivalent on GCP and Azure.

How to verify

terraform init will tell you what backend is configured and whether it’s healthy:

terraform init -reconfigure
terraform state list
aws s3 ls s3://<state-bucket>/ --recursive
aws s3api get-bucket-versioning --bucket <state-bucket>
aws dynamodb describe-table --table-name <lock-table>
terraform state pull > /tmp/state.json && jq '.serial, .version' /tmp/state.json

The S3 bucket should report Status: Enabled for versioning. The DynamoDB table should have LockID as its hash key and on-demand billing. terraform state pull should succeed without prompting for credentials.

What’s happening

A Terraform backend is the storage layer for state plus the locking mechanism. The local backend writes to terraform.tfstate in the working directory; everything else is a remote backend. The S3 backend writes the state file to an S3 object, optionally encrypted with KMS, and uses a DynamoDB table to hold a row per state key when an apply is in progress. The row is the lock; any other apply against the same state key waits or fails.

State isolation has two dimensions: per-environment (production, staging, dev) and per-component (network, data, app). The combination is the state key, and the right pattern is one state file per (environment, component) — small blast radius, faster plans, fewer locks held for fewer minutes. Workspaces give you per-environment isolation within a single configuration but share the backend bucket and key prefix; for anything serious, separate root modules per environment beat workspaces.

The procedure

  1. Pre-create the backend resources in a bootstrap config. A chicken-and-egg problem — Terraform cannot create its own backend on the first apply. Bootstrap with a tiny local-state config, then terraform init -migrate-state once.

    # bootstrap/main.tf — runs once with local state
    resource "aws_s3_bucket" "tf_state" {
      bucket = "acme-tf-state-${data.aws_caller_identity.current.account_id}"
    }
    resource "aws_s3_bucket_versioning" "tf_state" {
      bucket = aws_s3_bucket.tf_state.id
      versioning_configuration { status = "Enabled" }
    }
    resource "aws_s3_bucket_server_side_encryption_configuration" "tf_state" {
      bucket = aws_s3_bucket.tf_state.id
      rule {
        apply_server_side_encryption_by_default { sse_algorithm = "AES256" }
      }
    }
    resource "aws_s3_bucket_public_access_block" "tf_state" {
      bucket                  = aws_s3_bucket.tf_state.id
      block_public_acls       = true
      block_public_policy     = true
      ignore_public_acls      = true
      restrict_public_buckets = true
    }
    resource "aws_dynamodb_table" "tf_lock" {
      name         = "acme-tf-lock"
      billing_mode = "PAY_PER_REQUEST"
      hash_key     = "LockID"
      attribute {
        name = "LockID"
        type = "S"
      }
    }
  2. Configure the backend in every root module. The key per environment + component makes blast radius explicit.

    terraform {
      backend "s3" {
        bucket         = "acme-tf-state-123456789012"
        key            = "production/network/terraform.tfstate"
        region         = "us-east-1"
        dynamodb_table = "acme-tf-lock"
        encrypt        = true
      }
    }
  3. Migrate the existing local state. Done once per project; copies local state into the backend and writes an empty local file.

    terraform init -migrate-state
    terraform state list   # confirm everything moved
  4. Lock the backend with IAM. The state file contains plaintext secrets that resources hold (DB passwords, generated keys). Restrict who can read the bucket; restrict who can take a lock on the DynamoDB table. CI roles need read+write; operators get read for plan, write for apply only after a review.

    data "aws_iam_policy_document" "tf_state_read" {
      statement {
        actions   = ["s3:GetObject", "s3:ListBucket"]
        resources = [
          aws_s3_bucket.tf_state.arn,
          "${aws_s3_bucket.tf_state.arn}/*"
        ]
      }
    }
  5. Use terraform_remote_state to share outputs across components. The network root publishes the VPC ID; the app root reads it back without re-deriving.

    data "terraform_remote_state" "network" {
      backend = "s3"
      config = {
        bucket = "acme-tf-state-123456789012"
        key    = "production/network/terraform.tfstate"
        region = "us-east-1"
      }
    }
    resource "aws_security_group" "app" {
      vpc_id = data.terraform_remote_state.network.outputs.vpc_id
    }
  6. Force-unlock with the lock ID, never with a tag. If an apply crashes and leaves a lock behind, terraform force-unlock takes a single argument — the lock ID printed in the error. Do not blindly delete the DynamoDB row.

    terraform force-unlock <LOCK_ID>
  7. Adopt Terraform Cloud / OpenTofu / Spacelift only when justified. Hosted state with run history, policy-as-code, and audit logs is the next step up — pay for it when the team grows past three operators or when SOC 2 evidence is needed. S3+DynamoDB is the right baseline.

Common pitfalls

  • A bucket without versioning means a botched apply can corrupt state and there is no undo — enable versioning before the first migration.
  • Two configurations with the same key field overwrite each other’s state every apply — choose unique keys, do not assume environment differences in vars are enough.
  • A state file leaked to a public S3 prefix is a credential incident — assume every secret in state has rotated.
  • Workspaces store state under the same backend with env:/<workspace>/<key> prefixes — useful for ephemeral environments, not a substitute for per-environment root modules.
  • terraform import does not export the resulting HCL — you still have to write the resource block by hand, and forgetting argument fields causes a destroy/create on the next apply.

In the engagements we run, every customer Terraform workspace has an encrypted S3 backend with DynamoDB locking and per-environment per-component keys — and the lock table is alarmed when a lock has been held longer than the slowest legitimate apply. State is treated as sensitive at the same tier as the secrets it contains. See /en/solutions/aws-management/.