76 lines
2.3 KiB
Python
76 lines
2.3 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(template_filepath,yaml_filepath,output_filepath):
|
|
|
|
with open(yaml_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(filename, mode="w", encoding="utf-8")
|
|
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('-yaml',
|
|
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]
|
|
|
|
template = custom_args.template
|
|
yaml = custom_args.yaml
|
|
output = custom_args.output
|
|
|
|
main(template,yaml,output)
|
|
|