Last active
August 31, 2022 20:08
-
-
Save inversion/9da3ecdb02a59876ebaa6edf2a678e20 to your computer and use it in GitHub Desktop.
Update state after moving existing terraform resources to a module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! FYI that
terraform plan
has a-no-color
option that should allow you to skip that second step.