dam*_*aex 8 python yaml jinja2
我目前正在学习jinja2,我不确定如何以正确的方式处理变量:
这是我在yaml中的变量:
---
hosts:
app201.acme.com: {eth0: {ip: 46.0.0.1, netmask: 255.255.255.255}}
graphite.acme.com: {eth0: {ip: 46.0.0.2, netmask: 255.255.255.255},
eth0.1: {ip: 10.2.90.1, netmask: 255.255.255.255}}
Run Code Online (Sandbox Code Playgroud)
这里是jinja2模板:
{{ fqdn }}
{% for interface in hosts[fqdn] %}
{{ interface }}
{{ hosts[fqdn].interface.ip }} << doesn't work
{{ hosts[fqdn].{{ interface }}.ip }} << doesn't work
{{ interface.ip }} << doesn't work
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
所以目前我的输出看起来像这样,因为我无法访问yaml哈希的第二维.
graphite.acme.com eth0.1
为eth0
Vik*_*kas 21
变量hosts
是a dict
.访问值的正确方法dict
是使用[]
运算符.
{{ fqdn }}
{% for interface in hosts[fqdn] %}
{{ interface }}
{{ hosts[fqdn][interface]['ip'] }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
.
operator用于访问对象的属性.