Created
May 20, 2022 16:12
-
-
Save zxpower/d6695ed884181cd5baeb71e9a35f6251 to your computer and use it in GitHub Desktop.
Little Python script to split one big YAML manifest into multiple documents
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
| import yaml | |
| from yaml.loader import SafeLoader | |
| import argparse | |
| dry_run = False | |
| zeros = '000' | |
| output_dir = '' | |
| def yaml_as_python(val): | |
| """Convert YAML to dict""" | |
| try: | |
| return yaml.load_all(val, Loader=SafeLoader) | |
| except yaml.YAMLError as exc: | |
| return exc | |
| if __name__ == '__main__': | |
| argparser = argparse.ArgumentParser() | |
| argparser.add_argument('--dry_run', help='Dry-run - no changes are done, defaults to False.', type=bool, default=False) | |
| argparser.add_argument('-i', '--input_file', help='Input file name, defaults to empty.', type=str, default='') | |
| argparser.add_argument('-o', '--output_dir', help='Output directory, defaults to current directory.', type=str, default='.') | |
| args = argparser.parse_args() | |
| dry_run = args.dry_run | |
| if args.input_file == '': | |
| print("You need to specify input file!") | |
| quit() | |
| if len(args.output_dir) > 0: | |
| output_dir = args.output_dir | |
| if not output_dir[-1] == '/': | |
| output_dir = output_dir + '/' | |
| try: | |
| with open(args.input_file, 'r') as input_file: | |
| i = 1 | |
| results = yaml_as_python(input_file) | |
| for value in results: | |
| if dry_run: | |
| print(value) | |
| else: | |
| index = zeros + str(i) | |
| i += 1 | |
| kind = value['kind'].lower() | |
| name = value['metadata']['name'] | |
| filename = f'{index[-2:]}-{kind}-{name}.yaml' | |
| output_file = open(output_dir + filename, "w") | |
| output_file.write('---\n') | |
| output_file.write(yaml.dump(value, indent=2, default_flow_style=False)) | |
| output_file.close() | |
| if not dry_run: | |
| print(f'{i-1} files writen to {output_dir}') | |
| except Exception as e: | |
| print(f"Something went wrong! {e}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment