Problem
When using Terraform, you may encounter irreconcilable configuration errors or a corrupted state file. Because the Terraform state is the source of truth that maps your configuration to real-world resources, resolving these issues often requires restoring the state to a previously valid version.
Solutions
There are three primary approaches to restoring a Terraform state file.
Solution 1: Restore from a Backup
Restoring from a backup is often the most direct method.
If you use a backend that supports versioning, you can restore the last known good version of the state file from before the issue occurred.
If you are running Terraform locally, Terraform automatically creates a backup file named terraform.tfstate.backup before writing to the main terraform.tfstate file. You can use this backup to restore the previous state.
To use a backup file as your new state:
- Move the current, problematic
terraform.tfstatefile to a safe location for archival purposes. - Rename the backup state file to
terraform.tfstate. - Run
terraform planto verify that the restored state aligns with your expectations.
Note that a restored state file may not include recently created resources. You may need to use terraform import or re-apply your configuration to account for any infrastructure drift.
Solution 2: Remove and Re-import the Problematic Resource
If a suitable backup is unavailable, you can surgically remove the problematic resource from the state and re-import it from your infrastructure.
- Use the
terraform state rmcommand to remove the resource from Terraform's state management. You must provide the resource address. For detailed usage, refer to theterraform state rmdocumentation. - After removing the resource, re-import it to bring it back under Terraform's management. Consult your provider's documentation for the specific import command for that resource type. For general guidance, see the
terraform importdocumentation.
Solution 3: Push a Local State File (Advanced)
This advanced option is only available when using a remote backend. It involves pulling the remote state, modifying it locally, and pushing it back to overwrite the remote version. This procedure carries risk and you should perform it with caution.
You can use the terraform state pull and terraform state push commands to manage this process. For a detailed recovery guide using this method, refer to the documentation on recovering state when a push fails.
Link References
[a] https://www.terraform.io/docs/cli/commands/state/rm.html