原文链接: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))

 

相关文章:

  • 2022-12-23
  • 2021-12-16
  • 2022-12-23
  • 2021-08-21
  • 2021-08-04
  • 2021-05-25
  • 2022-12-23
  • 2022-01-16
猜你喜欢
  • 2022-12-23
  • 2021-08-22
  • 2022-12-23
  • 2021-06-22
  • 2021-06-03
  • 2021-08-17
  • 2022-03-06
相关资源
相似解决方案