Losing a Terraform state file (terraform.tfstate
) can be a nightmare, but recovery is possible using backups, remote storage, or importing existing resources.
🔹 Steps to Recover Terraform State
1️⃣ Check for a local backup: Terraform automatically creates a .tfstate.backup
file. Restore it with:
mv terraform.tfstate.backup terraform.tfstate
2️⃣ Restore from an S3 remote backend: If you stored the state in AWS S3, retrieve it:
aws s3 cp s3://my-terraform-state-bucket/terraform.tfstate .
- To recover an older version (if S3 versioning is enabled):
aws s3api list-object-versions --bucket my-terraform-state-bucket --prefix terraform.tfstate
aws s3 cp s3://my-terraform-state-bucket/terraform.tfstate --version-id <version_id> terraform.tfstate
3️⃣ Use terraform import
if no backups exist:
- If no state file is found, manually import resources:
terraform import aws_instance.my_instance i-0abc123456def
terraform import aws_s3_bucket.my_bucket my-terraform-bucket
4️⃣ Prevent Future Loss:
✔ Store state in remote backends (S3, Terraform Cloud).
✔ Enable S3 versioning to track changes.
✔ Regularly backup terraform.tfstate
manually.
✅ With these steps, you can quickly recover lost Terraform state files!