Skip to content

Instantly share code, notes, and snippets.

@jkulton
Last active August 24, 2022 02:45
Show Gist options
  • Save jkulton/7cd7077309fa97f431efc4fc8a98923b to your computer and use it in GitHub Desktop.
Save jkulton/7cd7077309fa97f431efc4fc8a98923b to your computer and use it in GitHub Desktop.
Terraform Import/Export

Terraform Import/Export

If you need to move resources between Terraform projects but they aren't configured in such a way you can directly run tf state move to move them between modules you can follow this process for migrating resources between terraform projects.

Commands Used

Overview

Imagine you need to move some resources from Terraform project a into project b without disturbing the remote resources themselves.

The basic process for moving state would work like the following:

  1. In Terraform project a figure out what pieces of state you'd like to move (terraform state list along with grep can be useful here)
  2. Create a local file in project a called transfer.tfstate
  3. Run terraform state mv -state-out=transfer.tfstate RESOURCE_NAME RESOURCE_NAME for each resource to move
  4. Move transfer.tfstate into project b
  5. Run terraform state pull > ./destination.tfstate to pull the project's remote state into a file
  6. Run terraform state mv -state=transfer.tfstate -state-out=destination.tfstate RESOURCE_NAME RESOURCE_NAME for each resource to move
  7. Run terraform state push ./destination.tfstate to overwrite the remote state with what is in the local file

If the transfer was successful running terraform plan in either project should show a noop of changes.

Helper Scripts

If you have a lot of resources to move see the attached helper scripts. These help automate steps 3 and 6 if you need to run for multiple resources.

Just replace the resources array in the bash script with an array of resources to export or import and run the script to automate the mv commands.

#!/bin/bash
resources=(
"module.my_piece_of_state"
"module.another_piece.of.state"
)
for i in "${resources[@]}"
do
:
terraform state mv -state-out=transfer.tfstate $i $i
done
#!/bin/bash
resources=(
"module.my_piece_of_state"
"module.another_piece.of.state"
)
for i in "${resources[@]}"
do
:
terraform state mv -state=transfer.tfstate -state-out=destination.tfstate $i $i
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment