8

我目前正在学习 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}}

这里是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 %}

所以目前我的输出看起来像这样,因为我无法访问 yaml 哈希的第二维。

石墨.acme.com eth0.1

eth0

4

1 回答 1

22

变量hosts是一个dict。访问值的正确方法dict是使用[]运算符。

{{ fqdn }}
{% for interface in hosts[fqdn] %}
    {{ interface }}
    {{ hosts[fqdn][interface]['ip'] }}
{% endfor %}

.运算符用于访问对象的属性。

于 2012-06-05T09:42:58.290 回答