Terraform – Renaming The Statefile

Sometimes you might need to rename the statefile for whatever reason. Heres a quick and dirty way to get that done assuming you are using the S3 backend. Let’s change the name to reflect the environment this statefile is for.

VERY IMPORTANT!!!! Make a copy of the current statefile in the S3 bucket:

aws s3 --profile staging-sfloyd cp s3://bucket-devops/Terraform/statefile.tfstate s3://bucket-devops/Terraform/statefile-staging.tfstate

Make a branch locally and change the key name in the local copy of backend-state.tf

From:

terraform {
  backend "s3" {
    bucket = "tb-staging-devops"
    key    = "Terraform/ds-infrastructure.tfstate" . <---NOTICE THE CHANGE HERE
    region = "us-east-1"
  }
}

To:

terraform {
  backend "s3" {
    bucket = "tb-staging-devops"
    key = "Terraform/ds-infrastructure-staging.tfstate" . <---NOTICE THE CHANGE HERE
    region = "us-east-1"
  }
}

 

Locally run init and plan to make sure there are no changes expected for apply.

Push your change and run through your CI/CD pipeline to merge into master with no changes for apply to worry about.

Once you are done you can delete the older copy of the state file from your bucket:

aws s3 --profile staging-sfloyd rm --dryrun s3://bucket-devops/Terraform/statefile.tfstate

Then once again without the --dryrun

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s