Ninja Docs Help

How-to: Restore Terraform state to a previous version

Sometimes there are situations that require restoring a Terraform state file to a previous version (for example, overwriting the file with another project). The operation itself is not complicated, but requires turning on versioning on AWS S3 Bucket.

To perform the procedure, the following is necessary:

  • Access to the AWS Common account:

    • Ability to view and edit objects and their versions in AWS S3 Bucket for Terraform State.

    • Ability to view and edit the DynamoDB table with Terraform Locks.

  • Access to the AWS API (Terraform).

Instructions

To restore Terraform state file to a previous version, you need to:

  1. Log in to the AWS Common account.

  2. Go to the S3 console and find the terraform state bucket.

  3. Locate the Terraform state file you are interested in (its path is defined in the backend configuration of the project).

  4. In the file details, navigate to the Versions tab.

    terraform_restore_state_1.png
  5. Find the version of the file you want to revert to (after selecting the desired version, you can open the file in a new tab using the Open button).

  6. Once you've found the appropriate version, select all other versions newer than it (your preferred version should not be selected) and click Delete.

  7. Confirm the deletion.

    terraform_restore_state_2.png
  8. In the project directory, delete the .terraform directory.

  9. Initialize the project. An error about an incorrect checksum should appear.

  10. In the AWS console, navigate to the DynamoDB console. From the menu, select Explore items.

  11. Select the table with Terraform Locks.

  12. Expand the Scan or query items tab, then click Filters.

  13. In the Attribute name field, select LockID. In the Condition field, choose Contains, and in the Value field, enter the name of the Terraform state file. Confirm with the Run button.

    terraform_restore_state_3.png
  14. From the results list, select the appropriate entry. Choose Actions, then Edit item.

  15. Change the value of the Digest attribute to the one provided in the error message after initializing the Terraform project (checksum for the current Terraform state file, different from the one currently in DynamoDB).

    terraform-restore-state-4.png
  16. Save the changes.

  17. Reinitialize the project in the console. If the procedure was successful, the error should no longer appear.

Last modified: 17 February 2025