Terraform Advanced — Stuck State Lock
What to do when state is locked and won’t unlock.
The Error
Error: Error acquiring the state lock
Lock Info:
ID: a1b2c3d4-e5f6-7890-abcd-ef1234567890
Path: s3://my-state/prod/terraform.tfstate
Operation: OperationTypeApply
Who: user@hostname
Created: 2024-01-15 10:30:00 UTC
Why It Happens
1. CI/CD pipeline crashed mid-apply
2. Someone Ctrl+C'd during apply
3. Network timeout during state write
4. Two people ran apply simultaneously
Force Unlock
# Copy the Lock ID from the error message
terraform force-unlock a1b2c3d4-e5f6-7890-abcd-ef1234567890
⚠️ Warning: Only force-unlock if you’re sure no other apply is running. Unlocking during an active apply can corrupt state.
Check DynamoDB Directly
# See what's in the lock table
aws dynamodb scan --table-name tf-locks --region us-east-1
# Delete the lock manually (last resort)
aws dynamodb delete-item \
--table-name tf-locks \
--key '{"LockID": {"S": "my-state/prod/terraform.tfstate-md5"}}'
Prevention
# Use DynamoDB with TTL for automatic lock expiry
resource "aws_dynamodb_table" "locks" {
name = "tf-locks"
billing_mode = "PAY_PER_REQUEST"
hash_key = "LockID"
attribute {
name = "LockID"
type = "S"
}
}
What’s Next?
Force resource recreation with taint and replace.