Skip to content

Instantly share code, notes, and snippets.

@inversion
Last active August 31, 2022 20:08
Show Gist options
  • Save inversion/9da3ecdb02a59876ebaa6edf2a678e20 to your computer and use it in GitHub Desktop.
Save inversion/9da3ecdb02a59876ebaa6edf2a678e20 to your computer and use it in GitHub Desktop.
Update state after moving existing terraform resources to a module
#!/bin/bash
# 1. Fill in your module name
# 2. Run the terraform state mv commands from the output
# Pipeline steps:
# Generate plan
# Remove ANSI colour codes
# Generate state mv commands
# Strip any moves of numbered instances of a resource (i.e. from using count)
# Caveats:
# - Resources that use count will need to be moved manually (welcome improvements to oneliner to trim the indexes and generate a unique list of top-level resources :)
terraform plan 2>&1 | \
perl -pe 's/\e\[?.*?[\@-~]//g' | \
perl -ne 's/^\+ (module\.NEW_MODULE_NAME\.(.+))/terraform state mv \2 \1/ and print' | \
perl -ne '!/\.\d+$/ && print'
@afeld
Copy link

afeld commented Nov 19, 2017

Nice! FYI that terraform plan has a -no-color option that should allow you to skip that second step.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment