Skip to content

Instantly share code, notes, and snippets.

@joerx
Last active April 11, 2019 03:33
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 joerx/218f47c80798f1e2c65520db3f2250f6 to your computer and use it in GitHub Desktop.
Save joerx/218f47c80798f1e2c65520db3f2250f6 to your computer and use it in GitHub Desktop.
Terraform batch rename
#!/bin/sh
SOURCE=module.foo
TARGET=module.bar
tf state list $SOURCE | sed "s/$SOURCE\(.*\)/$SOURCE\1 $TARGET\1/" | xargs -n2 echo terraform state mv
@joerx
Copy link
Author

joerx commented Apr 11, 2019

Append | sh to the last line to actually run

@joerx
Copy link
Author

joerx commented Apr 11, 2019

Might get missing provider config errors. E.g. * module.foo.github_team.owner: configuration for module.bar.provider.github.gh is not present; a provider configuration block is required for all operations - requires manual state editing:

terraform state dump > state.json
sed -i 'bak' 's/module.foo.provider.github.gh/module.bar.provider.github.gh/' > state.json
terraform state push state.json
terraform plan

@joerx
Copy link
Author

joerx commented Apr 11, 2019

State mangling doesn't go well with data sources - the 'data' prefix will be skipped. Leads to problems when these resources cannot be found or will be marked for removal. To fix, multiple options:

  • Edit statefile, add the data. prefix to the affected resources, push state
  • Remove the resources from state using terraform state rm, then terraform refresh

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