Interview Prep/Terraform/State Locking and Backend Errors

With the S3 backend and `use_lockfile = true`, you get `Error acquiring the state lock` with `StatusCode: 412` and `PreconditionFailed`.

IntermediateTroubleshootingState Locking and Backend Errors
Answer

Likely causes → Terraform 1.10+ S3-native locking writes a <key>.tflock object with a conditional If-None-Match PUT. A 412 means that lock object already exists: another run holds it or a dead run left it behind.

Diagnose →

aws s3api head-object --bucket acme-tfstate --key prod/network/terraform.tfstate.tflock
aws s3 cp s3://acme-tfstate/prod/network/terraform.tfstate.tflock -   # shows Who / Created

Fix → Confirm no run is active, then terraform force-unlock <ID>. Deleting the .tflock object by hand works too but is the last resort.

Prevent → Same as DynamoDB locking: one pipeline per state key at a time, graceful job cancellation. Make sure the bucket policy allows s3:PutObject and s3:DeleteObject on *.tflock, otherwise unlocks silently fail.

All Terraform questions Roadmap: Terraform in production

More on State Locking and Backend Errors