State Locking
When multiple people work on the same Terraform configuration, two users might run
terraform apply at the same time. This can corrupt the state file. State locking prevents this by allowing only one operation at a time.What Is State Locking?
State locking ensures that when a user runs a Terraform command that modifies state (apply, destroy, etc.), the state is locked for the duration of the operation. Other users will receive an error until the lock is released.
Locking prevents concurrent state modifications that could lead to corruption or inconsistent infrastructure.
Backends That Support Locking
- AWS S3 – requires a DynamoDB table for locking
- Azure Storage – built‑in locking (blob leases)
- Google Cloud Storage – built‑in locking (if bucket has object versioning)
- Terraform Cloud/Enterprise – native locking
- Local backend – no locking (not safe for teams)
Setting Up Locking for AWS S3 Backend
Create a DynamoDB table (name can be anything) with partition key
LockID (string). Then configure the backend:terraform {
backend "s3" {
bucket = "my-tfstate-bucket"
key = "terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks"
encrypt = true
}
}What Happens When Locked?
If a user tries to apply while another apply is in progress, they will see:
Acquiring state lock. This may take a few moments...
Error: Error acquiring the state lockThe error message includes the lock info (who, when, operation).Releasing a Stale Lock
If a lock is stuck (e.g., Terraform crashed), you can release it manually:
terraform force-unlock LOCK_IDUse this only after verifying that no operation is actually running.Best Practices
- Always use state locking for team environments.
- Set up remote state and locking from the first day of a project.
- Use CI/CD pipelines that run Terraform sequentially (or with locking) to avoid conflicts.
- Do not disable locking unless you have a good reason.
Two Minute Drill
- State locking prevents concurrent modifications.
- Supported by many backends (S3+DynamoDB, Azure, GCS, Terraform Cloud).
- If lock is stuck, use
terraform force-unlockwith caution. - Locking is essential for team workflows.
Need more clarification?
Drop us an email at career@quipoinfotech.com
