Terraform Tutorial — State Locking
State locking prevents two people (or CI pipelines) from modifying the state file at the same time, which could corrupt it.
The Problem
Without locking:
Developer A: terraform apply (reads state)
Developer B: terraform apply (reads same state)
Developer A: writes new state (adds EC2)
Developer B: writes new state (adds S3) → overwrites A's changes!
Developer A’s EC2 instance is now missing from state — it exists in AWS but Terraform doesn’t know about it.
How Locking Works
- Before modifying state, Terraform acquires a lock
- If someone else already has the lock, Terraform waits (or fails)
- After the operation completes, Terraform releases the lock
terraform apply
├─ 1. Acquire lock ← blocks others
├─ 2. Read state
├─ 3. Create resources
├─ 4. Write new state
└─ 5. Release lock ← unblocks others
DynamoDB Locking with S3 Backend
The most common setup for AWS:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks"
encrypt = true
}
}
Create the DynamoDB table:
resource "aws_dynamodb_table" "terraform_locks" {
name = "terraform-locks"
billing_mode = "PAY_PER_REQUEST"
hash_key = "LockID"
attribute {
name = "LockID"
type = "S"
}
}
Lock Timeout and Force Unlock
If a lock is held (e.g., a CI pipeline crashed):
# See who holds the lock
$ terraform plan
Error: Error acquiring the state lock
Lock Info:
ID: abc123-def456
Path: my-terraform-state/prod/terraform.tfstate
Operation: OperationTypeApply
Who: runner@github-actions
Created: 2024-01-15 10:30:00 UTC
# Force unlock (use with caution!)
$ terraform force-unlock abc123-def456
⚠️ Warning: Only use
force-unlockwhen you are certain no other operation is running. Forcing the unlock while someone else is applying can corrupt the state.
Backends That Support Locking
| Backend | Locking Support | Lock Mechanism |
|---|---|---|
| S3 | ✅ Yes | DynamoDB table |
| Terraform Cloud | ✅ Yes | Built-in |
| Azure Blob | ✅ Yes | Blob leases |
| GCS | ✅ Yes | Built-in |
| Local | ✅ Yes | File lock (.lock.info) |
| Consul | ✅ Yes | Consul sessions |
What’s Next?
You understand locking. Let’s learn the commands for inspecting and modifying state.