`Error: Failed to persist state to backend` and Terraform says it wrote `errored.tfstate`. The CI job ended. What now?
AdvancedTroubleshootingState Locking and Backend Errors
Answer
Likely causes → Network drop, expired credentials or a permission issue at the moment of writing state. The cloud resources were changed, but the remote state was not updated.
Diagnose → Find the errored.tfstate file. In CI it is lost unless you upload the working directory on failure. Check what the run created from the apply log.
Fix →
- If you have the file: fix credentials, then
terraform state push errored.tfstate. - If the file is gone: the state is behind reality. Use the apply log to list created resource IDs and
terraform importthem (or useimportblocks), then re-plan.
Prevent → In pipelines, upload errored.tfstate as an artifact on failure (if: failure()), and use credentials whose session lasts longer than the longest apply.
More on State Locking and Backend Errors
`terraform plan` fails with `Error acquiring the state lock` and `ConditionalCheckFailedException: The conditional request failed`.BeginnerWith the S3 backend and `use_lockfile = true`, you get `Error acquiring the state lock` with `StatusCode: 412` and `PreconditionFailed`.Intermediate`terraform force-unlock` returns `Failed to unlock state: lock ID "..." does not match existing lock`.BeginnerA teammate ran `terraform apply -lock=false` "because the lock was stuck". Now the plan shows resources you never touched being recreated.Advanced`terraform init` fails with `Error: Backend configuration changed`.Beginner`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?Intermediate