Last active
August 6, 2024 14:46
-
-
Save gyoza/a17356300b46dedbdd1ebdf29b88128e to your computer and use it in GitHub Desktop.
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/bin/env python3.11 | |
from pathlib import Path | |
import argparse | |
import json | |
import sys | |
import pprint | |
from difflib import * | |
pp = pprint.PrettyPrinter(indent=4, width=120) | |
class SmartFormatter(argparse.HelpFormatter): | |
""" allow 'smart' formatting in help examples in argparse """ | |
def _split_lines(self, text, width): | |
if text.startswith("R|"): | |
return text[2:].splitlines() | |
# this is the RawTextHelpFormatter._split_lines | |
return argparse.HelpFormatter._split_lines(self, text, width) | |
def config_parser(): | |
"""argparse""" | |
parser = argparse.ArgumentParser( | |
description="Show diff on terraform sensitive values from a json formatted terraform plan file.", | |
formatter_class=SmartFormatter, | |
epilog="example: terraform-show-sensitive --plan-file plan.json --address 'kubectl_manifest.thing[\"example\"]'", | |
) | |
parser.add_argument( | |
"--address", | |
help="address of item you'd like to show sensitive data for.", | |
default="default", | |
required=True | |
) | |
parser.add_argument( | |
"--plan-file", | |
default="plan.out.json", | |
help="R|\nTo create plan json file do:\n\tterraform plan -out plan.out\n\tterraform show -no-color -json plan.out > plan.json", | |
required=True | |
) | |
parser.add_argument( | |
"--target", | |
default="undefined", | |
help="R|Look for this value -- for instance if you sensitive data is under 'yaml_body' your target would be --target yaml_body", | |
required=True | |
) | |
parser.add_argument( | |
"--print", | |
default="undefined", | |
help="print the target yamls", | |
action="store_true", | |
required=False | |
) | |
return parser | |
if __name__ == "__main__": | |
parser = config_parser() | |
args = parser.parse_args() | |
if Path(args.plan_file).is_file: | |
plan_file = json.loads(open(args.plan_file, "r").read())["resource_changes"] | |
for address in plan_file: | |
if address["address"] == args.address: | |
before = address["change"]["before"][args.target] | |
after = address["change"]["after"][args.target] | |
sys.stdout.writelines(unified_diff(str(before), str(after), fromfile="before", tofile="after")) | |
if args.print: | |
print(f"------ {args.address} BEFORE ------") | |
pp.pprint(before) | |
print(f"------ {args.address} AFTER ------") | |
pp.pprint(after) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment