Cloud Technology

How to resolve Terraform state locking issues when using Amazon S3 and DynamoDB backends?

AM Asked by Amanda Roberts · 14-11-2025
0 upvotes 12,500 views 0 comments
The question

We recently migrated our AWS infrastructure management to Terraform. We are using an S3 bucket for the state file and a DynamoDB table for state locking to prevent concurrent writes. However, we keep encountering 'Error: Error acquiring the state lock' even when no other pipeline is running. Has anyone found a reliable way to force-unlock or prevent these stale locks in a CI/CD environment?

3 answers

0
JE
Answered on 12-01-2025

Stale locks usually happen if a CodeBuild project is interrupted or times out before Terraform can finish its cleanup. To fix this manually, you can use the command 'terraform force-unlock <LOCK_ID>', but you must ensure nobody else is actually running a plan. To prevent this in the future, I suggest wrapping your Terraform commands in a script that checks for existing locks or setting a shorter timeout in your DynamoDB configuration. We also found that increasing the 'retry_lock' parameter in the backend configuration helps the pipeline wait out transient issues without failing immediately.

0
RO
Answered on 15-02-2025

Are you sure the IAM role used by your CI/CD pipeline has the 'dynamodb:DeleteItem' permission on the specific lock table? If it can create the lock but lacks permission to delete it after completion, you'll be stuck with a permanent stale lock every single time.

AM 18-02-2025

That was exactly it, Robert! I checked our IAM policy and we only had PutItem and GetItem allowed for the DynamoDB table. After adding DeleteItem to the policy, the locks started clearing automatically after every 'terraform apply'. It’s a subtle permission that’s easy to miss when you're setting up a new environment from scratch.

0
ST
Answered on 10-04-2025

Always use versioning on your S3 bucket. If a lock failure leads to state corruption, you can revert to a previous version of the .tfstate file quickly.

JE 15-04-2025

I agree with Steven. S3 versioning is your ultimate safety net. It’s saved us more than once when a pipeline crash corrupted the state file during a complex resource migration.

Share your thoughts

Your email address will not be published. Required fields are marked (*)

Professional Counselling Session

Still have questions?
Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Request a Call Back

Search Online

We Accept

We Accept

Follow Us

"PMI®", "PMBOK®", "PMP®", "CAPM®" and "PMI-ACP®" are registered marks of the Project Management Institute, Inc. | "CSM", "CST" are Registered Trade Marks of The Scrum Alliance, USA. | COBIT® is a trademark of ISACA® registered in the United States and other countries.

World globe icon Country: India

Book Free Session