patternbashterraformMajor
Terraform state locking prevents concurrent apply corruption
Viewed 0 times
state lockingdynamodbforce-unlockconcurrent applyrace conditionlock id
Error Messages
Problem
Two simultaneous
terraform apply runs on the same workspace can read the same state, make conflicting changes, and write back conflicting state files, corrupting the state and leaving infrastructure in an unknown configuration.Solution
Enable state locking via the backend configuration. For S3, add a
To break a stuck lock (e.g., after a crashed apply):
Find the lock ID from the error message or the DynamoDB table:
dynamodb_table argument. Terraform acquires a lock before any operation that modifies state and releases it after. If a lock exists, Terraform waits or fails with an informative error.To break a stuck lock (e.g., after a crashed apply):
terraform force-unlock <LOCK_ID>Find the lock ID from the error message or the DynamoDB table:
aws dynamodb get-item \
--table-name terraform-state-lock \
--key '{"LockID": {"S": "my-bucket/path/to/terraform.tfstate"}}'Why
Terraform state is not an append-only log — it is a single JSON document overwritten on each apply. Without locking, a race condition between two applies produces a corrupted state that reflects neither the first nor the second apply correctly.
Gotchas
- Terraform Cloud and Terraform Enterprise have built-in state locking — no DynamoDB required
- A force-unlock should only be used when you are certain no apply is actually running
- Local backend has file-based locking that only works on a single machine
- Network interruptions during apply can leave a lock in place — always check DynamoDB after CI failures
Context
Any multi-developer or CI/CD Terraform workflow with shared remote state
Revisions (0)
No revisions yet.