Restore or Download a Previous Version of Terraform State
Updated: Jul 15
Introduction
In the event of accidental destruction of resources, it may be necessary to restore a previous version of the Terraform state. If the backend bucket that stores the Terraform state has versioning enabled, you can easily download and restore an earlier version of the state file. This document assumes that you are storing your Terraform state in an S3 bucket with versioning enabled.
Steps to download a Previous Version of Terraform State
Follow the steps below to restore a previous version of Terraform state from a backend bucket with versioning enabled:
Identify the version of the state file that you want to restore by navigating to the version history in your backend bucket. The version history will display a list of all the previous versions of the state file that have been uploaded to the bucket. aws s3api list-object-versions --bucket my-tf-state-bucket --prefix my-state-file.tfstate
Download the desired version of the state file from the bucket to your local machine. You can do this by clicking on the version number in the version history and selecting "Download". aws s3api get-object --bucket my-tf-state-bucket --key my-state-file.tfstate --version-id ABC1234 --output my-state-file.tfstate
Replace the current state file with the downloaded version. Open the backend configuration file, usually named backend.tf, and find the section that specifies the path to the state file. Replace the name of the file in the specified path with the name of the downloaded file. terraform { backend "s3" { bucket = "my-tf-state-bucket" key = "my-state-file.tfstate" region = "my-region" # replace the state file name with the name of the downloaded file key = "my-downloaded-state-file.tfstate" } }
Verify the restored state by running terraform plan. This command will show you the differences between the restored state and the current state. terraform plan
Apply the restored state by running terraform apply. This command will apply the restored state to the infrastructure and restore any previously destroyed resources. terraform apply
By following these steps, you can easily restore a previous version of Terraform state from a backend bucket with versioning enabled.
Conclusion
Restoring a previous version of Terraform state can save you from the pain of rebuilding an entire infrastructure from scratch. With the versioning feature of Terraform backend buckets, this process is simple and straightforward.
Martín Carletti
Cloud Engineer
Teracloud
If you want to know more about our Tips, we suggest checking Two tools for handling obsolete APIs in k8s
To learn more about cloud computing, visit our blog for first-hand insights from our team. If you need an AWS-certified team to deploy, scale, or provision your IT resources to the cloud seamlessly, send us a message here.