Created
June 12, 2025 05:56
-
-
Save ludoo/5a99b5934e2ad444a8f6ebc0d96ef51b to your computer and use it in GitHub Desktop.
Simple script to remove prefixes from module resources
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
#!/usr/bin/env python3 | |
'Simple script used to remove prefixes, pipe `terraform state list` to it.' | |
import click | |
import logging | |
import os | |
import re | |
import stat | |
import sys | |
R = re.compile(r'^(module(?:\.[a-z0-9_-]+)+\["(.*?)"\])') | |
def stdin_is_piped(): | |
fileno = sys.stdin.fileno() | |
mode = os.fstat(fileno).st_mode | |
return not os.isatty(fileno) and stat.S_ISFIFO(mode) | |
@click.command() | |
@click.argument('prefix', nargs=-1) | |
def main(prefix): | |
print(prefix) | |
modules = dict() | |
ignored = set() | |
if not stdin_is_piped(): | |
raise SystemExit(0) | |
for line in sys.stdin.read().splitlines(): | |
m = R.search(line) | |
if m: | |
module, key = m.groups() | |
if module not in modules and module not in ignored: | |
for p in prefix: | |
if key.startswith(f'{p}/'): | |
logging.debug(f'adding module {module} (key: {key}, prefix: {p})') | |
modules[module] = module.replace(f'["{p}/', '["') | |
break | |
if module not in modules: | |
logging.debug(f'ignoring module {module} (key: {key})') | |
ignored.add(module) | |
else: | |
logging.debug(f'skipping {line}') | |
logging.debug('opening file') | |
with open('state-moved.tf', 'w') as f: | |
for k, v in modules.items(): | |
logging.debug(f'writing moved block for {k}') | |
f.write('moved {\n') | |
f.write(f' from = {k}\n') | |
f.write(f' to = {v}\n') | |
f.write('}\n') | |
if __name__ == '__main__': | |
logging.basicConfig(level=logging.DEBUG) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment