Merge Terraform State

last modified: | 1 min read #terraform

Refactoring Terraform code can be quite painful. This guide describes how you easily can merge two Terraform state files.

Get the current state files

Pull the current state files from both projects:

# Pull the state of two projects 'left' and 'right'
terraform state pull > left.tfstate
terraform state pull > right.tfstate

Make sure you create a backup of these files.

View the resources

To view the resources in a state file use: terraform state list -state=left.tfstate. Create resources files from all state files:

find -maxdepth 1 -type f -name '*.tfstate' \
    | xargs -I{} sh -c 'terraform state list -state="$1" > "$1.resources"' -- {}

Make sure all keys are unique:

cat *.resources | sort | uniq -d

Merge state

This example merges left into right:

cat left.tfstate.resources \
    | xargs -I{} terraform state mv -state=left.tfstate -state-out=right.tfstate {} {}

Verify that all resources from left are moved to right by checking left.tfstate. This file should be empty. Resources that couldn’t be moved will still be in here. If you want to repeat this step don’t forget to re-generate the resources files.

Increment the serial number of the state

jq '.serial +=1' right.tfstate | sponge right.tfstate

Install the newly created state

terraform state push right.tfstate