Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Terraform/Terragrunt wrapper module state move
#!/bin/bash
# Lets say we have all resources under state /A using module A
# We decide to wrap all the resources of the module into a inner module B
# So now all resources that were orignally top level in A are now top level in B
# Normally if we try to plan our changes, terraform will want to delete all resources originally under A and create new ones under B
# However, we may not want that (what if our resources are vpc level resources that we cant afford to delete)
# Terraform provides a state move command
# We can list all the resources in a module via `terraform state list`
# We can pipe this list to xargs and for each resource we can move it to the new prefix, ie. under inner module B.
# Note: Below we use terragrunt instead of terraform but the command is the same
# Note on Xargs, it will process each line with the -n1 flag. The -I{} defines our placeholder as {}
# we can then specify which command to run and where the substitution should take place
terragrunt state list 2>/dev/null | xargs -n1 -I{} terragrunt state mv {} module.b.{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment