Skip to content
IT // Adventures

Splitting Terraform Deployments

A short guide to moving Terraform modules from one deployment to another.

2 min read

Recently I had to split an “organically grown” Terraform deployment into several new deployments, “extract” existing resources and modules from the Terraform state and move them, without changing the real Azure resources.

Note: it is of course possible (and recommended) to “move” resources between deployments with remove and import blocks - see Removing Resources and Import. For modules that consist of several or even several hundred resources, however, the method described below is considerably faster.

Preparation

First we have to prepare two deployments:

  • A source deployment as the origin of the modules and resources to be migrated.
  • A destination deployment as the target of the migration.

Ideally, the destination deployment should already be runnable and can optionally contain resources of its own.

Download remote states

Since my deployments use remote state, I first have to download the “state” files. First download the source state…

cd /deployments/source-deployment
terraform state pull > source.tfstate

… and then the destination state:

cd /deployments/destination-deployment
terraform state pull > destination.tfstate

Move modules and resources in the Terraform STATE

We can now use the terraform state mv command to move resources and entire modules from the source state to the destination state. In the same step, objects can optionally be renamed as well:

cd /deployments

terraform state mv -state=".\source-deployment\source.tfstate" -state-out=".\destination-deployment\destination.tfstate" module.some_module module.some_module

terraform state mv -state=".\source-deployment\source.tfstate" -state-out=".\destination-deployment\destination.tfstate" module.old_name module.new_name

Move modules and resources in the Terraform CODE

Of course we also have to apply the changes in the Terraform code and remove the code of all moved modules/resources from the .tf files in the source deployment. In the code of the destination deployment, the same resources of course have to be created. In my case, we could simply move the affected .tf files to the destination directory.

Please note that references to the resources and modules moved this way are of course not updated or corrected automatically in the source deployment.

Upload remote states

Finally, we have to upload our “state” files again:

cd /deployments/source-deployment
terraform state push ./source.tfstate

cd /deployments/destination-deployment
terraform state push ./destination.tfstate

Sources