What to do if you lost the Terraform state file?
sobes.tech AI
Answer from AI
Losing the Terraform state file can lead to a mismatch between the current infrastructure state and what Terraform considers managed. Here's what you can do:
-
Restore from backup — if you're using remote storage (like S3, Terraform Cloud), try to find the latest version of the state file.
-
Import existing resources — use the
terraform importcommand to manually add resources to a new state file, synchronizing Terraform with the actual state. -
Recreate the infrastructure — if restoring the state is impossible and importing is too complex, you can delete the resources and recreate them using Terraform.
-
Use
terraform refresh— this updates the state, but without a state file, it won't help since Terraform doesn't know what it manages.
Example of importing a resource:
terraform import aws_instance.example i-1234567890abcdef0
It is recommended to always store the state file in a reliable remote backend with versioning and to make regular backups.