Skip to content

Instantly share code, notes, and snippets.

@hpcsc
Created April 19, 2020 09:58
Show Gist options
  • Save hpcsc/8550e6dff49798d0c0e2ea786c7722b0 to your computer and use it in GitHub Desktop.
Save hpcsc/8550e6dff49798d0c0e2ea786c7722b0 to your computer and use it in GitHub Desktop.
Script to merge source terraform state into destination state
#!/bin/bash
SOURCE=$1
DESTINATION=$2
if [ -z "${SOURCE}" ] || [ -z "${DESTINATION}" ]; then
echo "=== source and destination are required"
echo "Usage: $0 source destination"
exit 1
fi;
pushd "${DESTINATION}" > /dev/null
DESTINATION_ABSOLUTE_PATH=$(pwd)
rm -f ./state.tfstate && terraform state pull > state.tfstate
popd > /dev/null
pushd "${SOURCE}" > /dev/null
SOURCE_ABSOLUTE_PATH=$(pwd)
rm -f ./state.tfstate && terraform state pull > state.tfstate
RESOURCES=( $(cat state.tfstate | jq -r '.resources[] | "\(.type).\(.name)"') )
for resource in "${RESOURCES[@]}"
do
terraform state mv -state-out=${DESTINATION_ABSOLUTE_PATH}/state.tfstate $resource $resource
done;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment