Skip to content

Instantly share code, notes, and snippets.

@innyso
Last active May 9, 2020 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save innyso/aa676100df3372503bf0048866ca0d08 to your computer and use it in GitHub Desktop.
Save innyso/aa676100df3372503bf0048866ca0d08 to your computer and use it in GitHub Desktop.
#terraform #tfstate #move

Moving and renaming a resource out of terraform state file

One of my rule of thumb is never touch terraform state file if I want to live a happy life but recently I found myself having to separate a state file into 2. At first I was very irritated because I should've done this in the beginning but what happened, happened so lets deal with it.

With some quick online searching, to my surprised there are some terraform built-in command that can make my life easier.

Let says all the current terraform code are in foo/ and I would like to move module.bar out of foo/ to bar/ and also rename the module to module.balloon

Let's get an understand what we currently have

I want to know

  • what do we current have
  • get a backup copy of the current tfstate file just in case if things goes horribly wrong

NOTE another thing that I do to make sure I can save myself from disaster is to have versioning on for whatever backend storage I am using

cd foo

terraform init
terraform state list > tf_resource_list
terrafor state pull > ../bar/tf_state_$(date +%s).tfstate

Move the state to my local state file

terraform mv -state-out=../bar/bar.tfstate 'module.bar' 'module.balloon'

Prepare terraform code

Add all the required terraform code to bar/ that match the bar.tfstate file

Push the state to the backend storage

cd bar

terraform push bar.tfstate

Final Check

To make sure the migration is sucessful

cd bar

terraform init
terraform plan # should see no changes

And to make sure the original state correspond to the current terraform state

cd foo

terraform init
terraform plan # should see no changes

References

https://www.terraform.io/docs/commands/state/mv.html

https://www.terraform.io/docs/commands/state/push.html

https://medium.com/@lynnlin827/moving-terraform-resources-states-from-one-remote-state-to-another-c76f8b76a996

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment