Created
August 27, 2019 10:03
-
-
Save prog893/191348182d0ff1712f2ee973683c67c2 to your computer and use it in GitHub Desktop.
Filter tfstate resources with regex by resource path
This file contains 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/local/bin/python3 | |
import json | |
import argparse | |
import re | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser(description='Filter tfstate resources by resource path') | |
parser.add_argument('tfstate', type=str, help="tfstate file to parse") | |
pattern_group = parser.add_mutually_exclusive_group(required=True) | |
pattern_group.add_argument('--filter', type=str, help="Pattern used to filter resources by path") | |
pattern_group.add_argument('--regex', type=str, help="Regex pattern used to filter resources by path") | |
parser.add_argument('--save', action="store_true", help="Save results to file") | |
args = parser.parse_args() | |
with open(args.tfstate) as f: | |
state = json.load(f) | |
for module in state['modules']: | |
resources = module['resources'] | |
delete_list = list() | |
for path_key in resources: | |
if args.regex: | |
if not re.search(args.regex, path_key): | |
delete_list.append(path_key) | |
else: | |
if args.filter not in path_key: | |
delete_list.append(path_key) | |
for item in delete_list: | |
resources.pop(item) | |
print(json.dumps(state, indent=4, sort_keys=False)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment