Skip to content

Instantly share code, notes, and snippets.

@mrgarymartin
Created July 10, 2023 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrgarymartin/b3d9c4670bc12b30d5d6180c4a035150 to your computer and use it in GitHub Desktop.
Save mrgarymartin/b3d9c4670bc12b30d5d6180c4a035150 to your computer and use it in GitHub Desktop.
This script will capture current terraform states then output a ps1 script to run and import them
# Extract the identifying URLs using terraform plan
terraform plan | grep "Refreshing state" > terraform-current-states.txt
# Extract the states we know from the configuration
terraform state list > terraform-state-list.txt
# Subscription strings
OLD_SUBSCRIPTION=00000000-0000-0000-0000-000000000000
NEW_SUBSCRIPTION=11111111-1111-1111-1111-111111111111
# Resource group strings (other name)
OLD_RG='Rg-appname-TST'
NEW_RG='Rg-appname-TST'
# Iterate over state list
cat terraform-state-list.txt | while read RESOURCE; do
AZURE_ID=$(grep "${RESOURCE}" terraform-current-states.txt | cut -d"=" -f2 | tr -d ']')
# null resources etc can be filtered out - no AZURE_ID
if [ -z "$AZURE_ID" ]; then
continue
fi
# print out the current resource and azure id mapping as a comment
echo "# ${RESOURCE} ${AZURE_ID}"
# replace the subscription and resource group strings (and remove weird characters from terraform
NEW_AZURE_ID=$(echo ${AZURE_ID} | sed "s/${OLD_SUBSCRIPTION}/${NEW_SUBSCRIPTION}/" | sed "s/${OLD_RG}/${NEW_RG}/g" | sed "s/\x1b\[[0-9;]*m//g")
# replace the current terraform state with a "state rm" and then "import" command
echo "terraform state rm ${RESOURCE}; terraform import ${RESOURCE} ${NEW_AZURE_ID}
"
# You can update this script name to even be a sh script instead of ps1
done > terraform-migration-generated-script-TST.ps1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment