Recover a Lost Terraform State File

Saurabh AdhauSaurabh Adhau
1 min read

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!

10
Subscribe to my newsletter

Read articles from Saurabh Adhau directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Saurabh Adhau
Saurabh Adhau

As a DevOps Engineer, I thrive in the cloud and command a vast arsenal of tools and technologies: ☁️ AWS and Azure Cloud: Where the sky is the limit, I ensure applications soar. 🔨 DevOps Toolbelt: Git, GitHub, GitLab – I master them all for smooth development workflows. 🧱 Infrastructure as Code: Terraform and Ansible sculpt infrastructure like a masterpiece. 🐳 Containerization: With Docker, I package applications for effortless deployment. 🚀 Orchestration: Kubernetes conducts my application symphonies. 🌐 Web Servers: Nginx and Apache, my trusted gatekeepers of the web.