Last active
June 15, 2020 13:13
-
-
Save jcPOLO/e210f35086d3d09dd966f18cd291ec25 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
# script to get the configuration file based on a jinja2 template. | |
# Usage python do_config.py template_file.j2 | |
# it will generate a cfg.txt file with the output shown | |
# Example j2 template file: | |
# | |
# {{ vlan_tag }} | |
# {{ vlan_description }} | |
# {{ int_out_to_peer }} | |
# {{ vpn_instance }} | |
# {{ ip_vlan_svi }} | |
# {{ mask_vlan_svi }} | |
# {{ ip_vlan_svi_peer }} | |
# | |
# sys | |
# # | |
# vlan {{ vlan_tag }} | |
# name {{ vlan_description }} | |
# description {{ vlan_description }} | |
# # | |
# interface {{ int_out_to_peer }} | |
# port trunk allow-pass vlan {{ vlan_tag }} | |
# # | |
# int vlan {{ vlan_tag }} | |
# description {{ vlan_description }} | |
# ip binding vpn-instance {{ vpn_instance }} | |
# ip address {{ ip_vlan_svi }} {{ mask_vlan_svi }} | |
# undo icmp host-unreachable send | |
# undo icmp redirect send | |
# # | |
# bgp 65500 | |
# ipv4-family vpn-instance {{ vpn_instance }} | |
# peer {{ ip_vlan_svi_peer }} as-number 65000 | |
# peer {{ ip_vlan_svi_peer }} fake-as 65556 | |
# # | |
# quit | |
# save all | |
from jinja2 import Template, Environment, meta | |
import os | |
from typing import Set | |
import argparse | |
def get_variables(file: str) -> Set: | |
path = os.getcwd() | |
filename = f'{path}/{file}' | |
with open(filename) as f: | |
template = f.read() | |
env = Environment() | |
ast = env.parse(template) | |
r = meta.find_undeclared_variables(ast) | |
return r | |
def load_template(file: str, d) -> str: | |
path = os.getcwd() | |
filename = f'{path}/{file}' | |
with open(filename) as f: | |
template = Template(f.read()) | |
r = template.render(d) | |
return r | |
def main() -> None: | |
parser = argparse.ArgumentParser(description='Process template...') | |
parser.add_argument('jinja2_template') | |
args = parser.parse_args() | |
var_d = get_variables(args.jinja2_template) | |
r = {} | |
for n in var_d: | |
r[n] = input(f'{n}: ') | |
cfg = load_template(args.jinja2_template, r) | |
with open('config.txt', 'w') as f: | |
f.write(cfg) | |
print(cfg) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment