我有一个包含YAML文档的文件,其中包含有关vlan的信息:
#yaml_file.yaml
- vlan: 123
name: DATEN-VLAN
- vlan: 124
name: PRINTER-VLAN
- vlan: 125
name: WLAN-VLAN
然后我创建了一个Jinja2Template来遍历vlan:
{% for vlan in vlans %}
interface {{INTERFACE}}.{{vlan['vlan']}}
description {{vlan['name']}}
ip address {{'V_VLAN_IP_' ~ vlan['vlan']}}
{% endfor %}
我在Python中使用以下代码呈现模板:
template = template.render(
vlans=vlans,
INTERFACE="Gi0/1",
V_LAN_IP_123="192.168.100.1",
V_LAN_IP_124="192.168.200.1",
V_LAN_IP_125="192.168.300.1"
)
在循环中,我试图动态地为每个循环创建一个新的变量,如下所示:ip address {{'V_VLAN_IP_' ~ vlan['vlan']}}
输出如下所示:
interface Gi0/1.123
description DATEN-VLAN
ip address V_VLAN_IP_123
interface Gi0/1.124
description PRINTER-VLAN
ip address V_VLAN_IP_124
interface Gi0/1.125
description WLAN-VLAN
ip address V_VLAN_IP_125
但那不是我想要的。我希望使用创建的变量,并将其值替换为python脚本中渲染调用中的给定信息。所以"V_VLAN_IP_123"替换为"192.168.100.1", "V_VLAN_IP_124"通过"192.168.200.1"one_answers";V_VLAN_IP_125"通过"192.168.300.1".
我的输出应该是这样的:
interface Gi0/1.123
description DATEN-VLAN
ip address 192.168.100.1
interface Gi0/1.124
description PRINTER-VLAN
ip address 192.168.200.1
interface Gi0/1.125
description WLAN-VLAN
ip address 192.168.300.1
我尝试了几种方法来连接变量。
将ip作为字典传递,这样您就不需要考虑变量"变量";
import jinja2
import yaml
vlans = yaml.safe_load(
"""
- vlan: 123
name: DATEN-VLAN
- vlan: 124
name: PRINTER-VLAN
- vlan: 125
name: WLAN-VLAN
"""
)
templ = jinja2.Template(
"""
{% for vlan in vlans %}
interface {{INTERFACE}}.{{vlan['vlan']}}
description {{vlan['name']}}
ip address {{ips[vlan['vlan']]}}
{% endfor %}
""".strip()
)
print(
templ.render(
INTERFACE="Gi0/1",
vlans=vlans,
ips={
123: "192.168.100.1",
124: "192.168.200.1",
125: "192.168.300.1",
},
)
)
输出
interface Gi0/1.123
description DATEN-VLAN
ip address 192.168.100.1
interface Gi0/1.124
description PRINTER-VLAN
ip address 192.168.200.1
interface Gi0/1.125
description WLAN-VLAN
ip address 192.168.300.1