Skip to content

Instantly share code, notes, and snippets.

@jim80net
Last active February 25, 2022 10:21
Show Gist options
  • Save jim80net/1a81ebfd687c36283046d34113dbe96e to your computer and use it in GitHub Desktop.
Save jim80net/1a81ebfd687c36283046d34113dbe96e to your computer and use it in GitHub Desktop.
Move terraform state between projects.
#!/usr/bin/env bash
##
# Usage: tf_move_state.sh source_directory target_directory source_resource_name <target_resource_name (uses source_resource_name if not provided)>
# Provide source and target directories using relative paths.
# WARNING: TEST ON AN INCONSPICUOUS AREA AS STAINING MAY OCCUR
# Credit to https://github.com/mcalhoun
set -e
SOURCEDIR=${1:?}
TARGETDIR=${2:?}
SOURCERESOURCE=${3:?}
TARGETRESOURCE=${4:-$SOURCERESOURCE}
TODAY=$(date +%Y%m%d)
BASEDIR=$(pwd)
cd ${BASEDIR}/${TARGETDIR}
terraform state pull > ${TODAY}.tfstate
cd ${BASEDIR}/${SOURCEDIR}
terraform state mv -state-out=${BASEDIR}/${TARGETDIR}/${TODAY}.tfstate ${SOURCERESOURCE} ${TARGETRESOURCE}
cd ${BASEDIR}/${TARGETDIR}
terraform state push ${TODAY}.tfstate;
cd ${BASEDIR}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment