Skip to content

Instantly share code, notes, and snippets.

@ludoo
Created June 12, 2025 05:56
Show Gist options
  • Select an option

  • Save ludoo/5a99b5934e2ad444a8f6ebc0d96ef51b to your computer and use it in GitHub Desktop.

Select an option

Save ludoo/5a99b5934e2ad444a8f6ebc0d96ef51b to your computer and use it in GitHub Desktop.

Revisions

  1. ludoo created this gist Jun 12, 2025.
    56 changes: 56 additions & 0 deletions state-moved.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    #!/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()