97 lines
2.9 KiB
Python
97 lines
2.9 KiB
Python
from jinja2 import Environment, FileSystemLoader
|
|
import pprint
|
|
import os
|
|
import json
|
|
|
|
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
|
|
|
|
with open(input_filepath, 'r') as file:
|
|
input_devices = file.read()
|
|
|
|
device_info = dict()
|
|
|
|
if os.path.splitext(input_filepath)[1] == ".json":
|
|
device_info = json.loads(input_devices)
|
|
# elif os.path.splitext(input_filepath) == ".yaml":
|
|
# devices = safe_load(input_devices)
|
|
else:
|
|
print(os.path.splitext(input_filepath))
|
|
print('{} is not a valid JSON format!\n'.format(input_filepath))
|
|
return 406
|
|
|
|
if args.output is not None:
|
|
output_filepath = args.output
|
|
else:
|
|
output_filepath = './output/{}.nso.config'.format(device_info["device"])
|
|
|
|
|
|
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")
|
|
|
|
content = template.render(device_info)
|
|
|
|
output.write('{}\n'.format(content))
|
|
|
|
# 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))
|
|
|
|
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='Input file with devices and config variables',
|
|
required=True
|
|
)
|
|
|
|
parser.add_argument('-output',
|
|
help='Output File',
|
|
required=False
|
|
)
|
|
|
|
custom_args = parser.parse_known_args()[0]
|
|
|
|
#template = custom_args.template
|
|
#input = custom_args.input
|
|
#output = custom_args.output
|
|
|
|
main(custom_args)
|
|
|