Change the Terraform  Remote state which was stored in S3

Change the Terraform Remote state which was stored in S3

Senario

Imagine we have configured terraform where its remote store is stored in an S3 bucket.

Prerequisites for this bucket are that version control is enabled. Please find the below image.

version.png

While upgrading the terraform versions consider we had messed up the current state of terraforming and this state is stored in the S3 bucket. In this scenario, we can fix the terraform by rolling back to the previous version of the state.

Steps to rollback remote state

  1. Identify the version
  2. Download the file from the s3 bucket locally
  3. Upload this file to the S3 bucket.

Identify the version

First of all, we need to identify which version of the file we need to replace.

In order to do this go to the s3 bucket click on a particular state file

  1. check for Entity Tag as shown in the below diagram
  2. make a note for the entity tag.

new state fiel.png

Download the file from the s3 bucket locally

The below command will download the file from the S3 bucket locally

aws s3api get-object --bucket [backname] --key [filename] --version-id [entitytagid] [localfoldername]

example



 aws s3api get-object --bucket test --key  test.tfstate --version-id [d769284e56ae3434426436f533] [local_copy_name]

Upload this file to the S3 bucket

The below command, will upload the file to the S3 bucket aws s3 cp ./[localfoldername] s3://[bucketname]/[filename]

example

  aws s3 cp ./[local_copy_name] s3://test/test.tfstate