Moving Terraform Resources’ States from One Remote State to Another

Lynn Lin
Lynn Lin
Nov 8, 2018 · 2 min read

Terraform state can be managed in local file or remote file such as in AWS S3. As the resources go more and more, the state file becomes larger and the time will be longer when executing terraform apply. To make changes can be applied more quickly, we can use terraform apply —-target=. Or, we could separate the state into small pieces. Move states between local files is easy. But move states between remote states needs a little bit more steps.

Move to an empty state

Assume we are in the directory global/ now (terraform state is set to AWS s3 of course) and want to move one of the resources, module.backend_parameter_store to a complete new folder deployment/.

1. Add terraform code in deployment/, including provider, state settings of AWS S3 and the resource

2. Move the state of module.backend_paramter_store from global/ to a local state file under deployment/

$ pwd
global
$ terraform state mv -state-out=../deployment/terraform.tfstate module.backend_parameter_store module.backend_parameter_store

3. Initialize terraform under deployment/ and just enter yes in the prompt

$ pwd 
deployment
$ terraform init

After that, terraform.tfstate is empty and all the content is pushed to remote state.

Move to a non-empty state

Assume that we are going to move another resource, module.frontend_parameter_store to deployment/ and the state already contains module.backend_parameter_store.

1. Add terraform code of the resource in deployment/

2. Pull the latest state of deployment/ into local file

$ pwd
deployment
$ terraform state pull > terraform.tfstate

3. Move the state of module.frontend_parameter_store from global/ to deployment/ local state file

$ pwd 
global
$ terraform state mv -state-out=../deployment/terraform.tfstate module.frontend_parameter_store module.frontend_parameter_store

4. Push the local state file of deployment/ to remote

$ pwd
deployment
$ terraform state push terraform.tfstate
  • terraform state mv -state=terraform.tfstate module.frontend_parameter_store module.frontend_parameter_store in the destination folder deployment/ is not working for me, so I just push all the content
  • Be careful when using state push since it will overwrite the current state

Lynn Lin

Written by

Lynn Lin

Backend Developer