Files
config_builder/config_builder_yaml.py
T
2026-04-27 16:31:00 -04:00

74 lines
2.2 KiB
Python

from jinja2 import Environment, FileSystemLoader
import pprint
import os
from yaml import safe_load
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
def main(args: list) -> None:
template_filepath = args.template
input_filepath = args.input
output_filepath = args.output
with open(input_filepath, 'r') as file:
devices = safe_load(file)
template_path = os.path.dirname(os.path.abspath(template_filepath))
template_filename = os.path.basename(template_filepath)
env = Environment(loader=FileSystemLoader(template_path))
template = env.get_template(template_filename)
#Path("./output").mkdir(parents=True, exist_ok=True)
### Specify output file - current write to script working directory
#filename = "./output/bdr_output.config"
### open output file mode="w" for create/truncate
output = open(output_filepath, mode="w", encoding="utf-8")
for host, keys in devices.items():
device = "{"
for key, value in keys.items():
device += "'{}':'{}', ".format(key,value)
device += "'hostname':'{}' }}".format(host)
#pprint.pprint(device)
device_dict = eval(device)
#pprint.pprint(device_dict)
content = template.render( device_dict )
#print('{}\n'.format(content))
output.write('{}\n'.format(content))
return 0
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Arguments for '
'Config_builder.py')
parser.add_argument('-template',
help='Template config with JINJA markup',
required=True
)
parser.add_argument('-input',
help='YAML file with devices and config variables',
required=True
)
parser.add_argument('-output',
help='Output File',
required=True
)
custom_args = parser.parse_known_args()[0]
main(custom_args)