Interview Prep/Terraform/State Locking and Backend Errors

`terraform init -migrate-state` asks `Do you want to copy existing state to the new backend?` and the new backend already has a state. What is the danger?

IntermediateTroubleshootingState Locking and Backend Errors
Answer

Likely causes → The target key already contains state, often because someone already migrated, or two stacks were pointed at the same key by mistake.

Diagnose →

terraform state pull > local-copy.json
aws s3 cp s3://acme-tfstate/prod/app/terraform.tfstate remote.json
jq '.lineage, .serial, (.resources|length)' local-copy.json remote.json

Different lineage means they are unrelated states.

Fix → Answer no until you know which state is authoritative. If both are real, use different keys. If one is a stale copy, keep the newer/complete one.

Prevent → Use one unique key per stack (<env>/<component>/terraform.tfstate) and enable bucket versioning so an overwrite is recoverable.

All Terraform questions Roadmap: Terraform in production

More on State Locking and Backend Errors