原文链接:http://networkbit.ch/python-jinja-template/
template.txt如下:
hostname {{ name }} interface Loopback1 ip address 10.1.1.{{ id }} 255.255.255.255 {% for vlan, name in vlans.items() %} vlan {{ vlan }} name {{ name }} {% endfor -%} router bgp {{ id }} {% for neighbor in bgp %} neighbor {{ neighbor.neighbor }} remote-as {{ neighbor.remote-as }} {% endfor %}
data.yml 如下:
name: R1 id: 1 vlans: 11: User 22: Voice 33: Video bgp: - neighbor: 10.1.1.1 remote-as: 1 - neighbor: 10.1.2.2 remote-as: 2 - neighbor: 10.1.3.3 remote-as: 3
Create Python script:
#Imports from Jinja2 from jinja2 import Environment, FileSystemLoader #Import YAML from PyYAML import yaml #Load data from YAML file into Python dictionary config = yaml.load(open('./data.yml')) #Load Jinja2 template env = Environment(loader = FileSystemLoader('./'), trim_blocks=True, lstrip_blocks=True) template = env.get_template('template.txt') #Render template using data and print the output print(template.render(config))