← All writing

Terraform State in Production: Locking, Remote Backends & Disaster Recovery

· Sourabh G Kulkarni

Mastering Terraform state in enterprise environments: S3 and DynamoDB locking, state manipulation commands, and recovering from corruption.

Terraform State in Production: Locking, Remote Backends & Disaster Recovery

The .tfstate file is the brain of your infrastructure. It maps declarative HCL resources to real-world cloud IDs, metadata, and dependencies. If you lose or corrupt your state file, Terraform has no idea what exists in your cloud, leading to accidental recreations or catastrophic deletions.

In enterprise production environments, managing state requires strict remote backends, distributed locking, and disciplined recovery playbooks.

sequenceDiagram
    autonumber
    actor CI as CI Runner / Engineer
    participant Dynamo as DynamoDB (Lock Table)
    participant S3 as S3 Bucket (Encrypted State)
    participant Cloud as AWS Cloud Resources

    CI->>Dynamo: Acquire State Lock (PutItem with MD5)
    alt Lock Already Held by Another Run
        Dynamo-->>CI: Error: State Locked by LockID xyz
        CI-->>CI: Halt Execution & Prevent Collision
    else Lock Successfully Acquired
        Dynamo-->>CI: Lock Granted
        CI->>S3: Download Latest State JSON
        CI->>Cloud: Refresh Cloud Resources & Calculate Diff
        CI->>Cloud: Apply Changes
        CI->>S3: Upload New State Version (Encrypted)
        CI->>Dynamo: Release Lock (DeleteItem)
    end

1. The Standard Remote Backend Architecture

Never store state in Git. State files contain plain-text database passwords, private keys, and sensitive resource attributes.

The industry gold standard for AWS combines S3 with DynamoDB:

terraform {
  required_version = ">= 1.5.0"

  backend "s3" {
    bucket         = "prod-terraform-state-company-us-east-1"
    key            = "platform/eks-cluster/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "prod-terraform-locks"
  }
}

Essential S3 Bucket Security Settings:

  • Versioning Enabled: Every apply creates a new version in S3. If an apply goes wrong, you can roll back to the exact previous state file in seconds.
  • Server-Side Encryption with KMS: Enforces customer-managed KMS keys.
  • Block Public Access (All 4 settings): Strict bucket policy preventing accidental exposure.

2. Essential State Manipulation Commands

Production engineers must know how to surgical modify state without deleting real cloud infrastructure:

terraform state list

Inspect every resource tracked in the current state:

terraform state list
# module.vpc.aws_subnet.private[0]
# module.eks.aws_eks_cluster.this

terraform state rm (Disown Without Destroying)

If a resource needs to be decoupled from Terraform management without destroying the cloud asset:

terraform state rm aws_s3_bucket.customer_uploads

terraform import (Bring Existing Cloud Resources into IaC)

Adopt resources provisioned via the web console into code:

terraform import aws_iam_role.app_role app-production-execution-role

terraform state mv (Refactoring Code Without Recreation)

When you move a resource into a module, Terraform will try to destroy and recreate it because its address changed. Use state mv to update the pointer:

terraform state mv aws_security_group.web module.networking.aws_security_group.web

3. Disaster Recovery Playbook: Stuck Locks & Corruption

Scenario A: The Process Died and Left State Locked

When a CI job cancels abruptly, DynamoDB still holds the lock entry:

Error: Error acquiring the state lock: ConditionalCheckFailedException
Lock Info:
  ID:        5f3a12b4-789a-4c2d-98e1-abcdef123456
  Who:       runner@github-actions

Resolution:

# Force unlock using the exact Lock ID provided in the error message
terraform force-unlock 5f3a12b4-789a-4c2d-98e1-abcdef123456

Scenario B: State Corruption or Accidental Truncation

  1. Open the AWS S3 Console (or use aws s3api list-object-versions).
  2. Identify the last healthy version before the botched apply.
  3. Download the healthy .tfstate JSON file.
  4. Run terraform state push healthy_state.json to restore consistency.

Treat Terraform state like a mission-critical database: isolate it by environment (dev/, staging/, prod/), enable versioning, and practice lock recovery before emergencies strike.