DevOpsil
TerraformHigh

Fix: Terraform State Lock Error

Terraform plan/apply fails with 'Error acquiring the state lock'

!Symptoms

  • Terraform plan/apply fails with 'Error acquiring the state lock'
  • Message shows another process is holding the lock
  • Terraform operations hang indefinitely waiting for lock

?Root Causes

  • Previous Terraform run was interrupted (Ctrl+C, CI timeout, network failure)
  • Another team member is running Terraform on the same state at the same time
  • Stale lock left in DynamoDB (AWS) or storage backend after a crash
  • CI/CD pipeline running multiple Terraform jobs in parallel against the same state

#Diagnosis Steps

  1. 1Read the lock error message for the Lock ID and who holds it
  2. 2Check if another terraform process is running: `ps aux | grep terraform`
  3. 3For S3+DynamoDB backend, check the lock table: `aws dynamodb scan --table-name <lock-table>`
  4. 4Ask team members if anyone is running terraform right now
  5. 5Check CI/CD for in-progress terraform jobs

>Fix

  1. 1Wait for the other process to finish if one is legitimately running
  2. 2Force unlock the state: `terraform force-unlock <LOCK_ID>` (use with caution)
  3. 3For DynamoDB, manually delete the lock item if the process that held it is gone
  4. 4Kill the orphaned terraform process if it is stuck: `kill <pid>`
  5. 5If state is corrupted, restore from a backup and re-run

*Prevention

  • Never interrupt terraform apply with Ctrl+C unless absolutely necessary
  • Use CI/CD with queued/serialized terraform runs (Terraform Cloud, Atlantis)
  • Set appropriate lock timeouts in your backend configuration
  • Implement a locking mechanism in CI/CD to prevent parallel runs
  • Enable state versioning in your backend (S3 versioning) for rollback

Related Error Messages

Error acquiring the state lockError locking stateLock Info: ID:ConditionalCheckFailedExceptionstate is already locked