Terraform: Move Resources from One State to Another

Overview

Terraform has the command terraform state mv that allows moving resources like so:

terraform state mv aws_instance.src aws_instance.dst

The above example’s scope is a single Terraform state file. If you need to move resources between different state files, you use the same command, but with extra flags:

terraform state mv -state=src.tfstate -state-out=dst.tfstate \
  aws_instance.src aws_instance.dst

Here you specify the source state file with -state flag and the destination state file with -state-out flag. These flags work only with local state files. If your state files are stored remotely, e.g. in S3, you need to first pull them, make changes locally, and then push back. Below is a detailed breakdown.

Step-by-step

Pull remote state files:

cd srcDir
terraform state pull > src.tfstate

cd dstDir
terraform state pull > dst.tfstate
Tip
It doesn’t matter how you name a state file when pulling. When you push it back, it’ll replace the remote state file regardless of the name.

Move your resources:

terraform state mv -state=srcDir/src.tfstate -state-out=dstDir/dst.tfstate \
  aws_instance.src aws_instance.dst

Push the changes:

cd srcDir
terraform state push

cd dstDir
terraform state push

You can verify your changes by running terraform state list.


That’s it. Once you do this a couple of times it becomes really trivial.