How to migrate Terraform remote tfstates

1 minute read

Terraform


In Terraform you can rename and move resources and modules in the same state, whether it is local or remote. But when you want to migrate resources or modules between remote states, you have to take other considerations.

To solve this, you have to bring the remote configuration, then move the resource locally, and once it has been moved, upload the change to the remote tftstate.

Let’s see how to do this:

1) Pull the destination remote tfstate:   

To move the resources from one tstate to another, you need to have the tfstate destination locally

$ terraform state pull > dev.tfstate

2) Move the resource or module to this local tfstate

In this example we want to move the module.lambda.module.your_funtion resource to module.your_function

$ terraform state mv -state-out=dev.tfstate module.lambda.module.your_function module.your_function

3) Upload the change to the remote tftstate

The resource was moved from one state to another, but it was done locally. To persist in the destination remote tftstate it must be uploadedr:

$ terraform state push dev.tfstate

In some cases the use of the -force option may be required, for example when there were problems with the initialization of the module, so the previous command would be as follows:

$ terraform state push -force dev.tfstate

Finally, and once you have verified that everything is correct, you can delete the local tftstate :

$ rm dev.tfstate*

References:

Leave a Comment