我希望获得有关以下代码的一些指导,其中涉及 Ansible 中的嵌套变量。这是剧本:
---
- name: Testing
hosts: localhost
connection: local
gather_facts: false
vars:
hostname: HOST1
VLAN_DEFS: [
{
"TAG": "1001",
"HOST1_DATA_IP": "10.10.0.1",
"HOST2_DATA_IP": "10.20.0.1",
"DATA_NETMASK": "24"
},
{
"TAG": "1002",
"HOST1_DATA_IP": "10.10.0.2",
"HOST2_DATA_IP": "10.20.0.2",
"DATA_NETMASK": "24"
},
{
"TAG": "1003",
"HOST1_DATA_IP": "10.10.0.3",
"HOST2_DATA_IP": "10.20.0.3",
"DATA_NETMASK": "24"
}
]
tasks:
- template:
src: ./test.j2
dest: ./output.json
这是 test.j2 Jinja 模板:
[
{% for VLAN in VLAN_DEFS %}
{
"VLAN": "VLAN{{ VLAN.TAG }}",
"ADDRESS": "{{ lookup('vars', 'VLAN.' ~ hostname ~ '_DATA_IP') }}/{{ VLAN.DATA_NETMASK }}"
}{% if not loop.last %},{% endif %}
{% endfor %}
]
我使用的查找行似乎给了我我想要的 VLAN.HOST1_DATA_IP,但它没有被解释为有效变量。我的剧本的结果是错误“找不到具有此名称的变量:VLAN.HOST1_DATA_IP”。但是,如果我将 ADDRESS 行替换为如下所示的确切值,则它可以正常工作:
"ADDRESS": "{{ VLAN.HOST1_DATA_IP }}/{{ VLAN.DATA_NETMASK }}"
有人偶然了解为什么会发生此错误吗?
您不需要使用
vars
查找。使用 var.attribute
代替 var[attribute]
,它允许使用表达式构建属性名称,如下所示:
[
{% for VLAN in VLAN_DEFS %}
{
"VLAN": "VLAN{{ VLAN.TAG }}",
"ADDRESS": "{{ VLAN[hostname ~ '_DATA_IP'] }}/{{ VLAN.DATA_NETMASK }}"
}{% if not loop.last %},{% endif %}
{% endfor %}
]
产生:
[
{
"VLAN": "VLAN1001",
"ADDRESS": "10.10.0.1/24"
}, {
"VLAN": "VLAN1002",
"ADDRESS": "10.10.0.2/24"
}, {
"VLAN": "VLAN1003",
"ADDRESS": "10.10.0.3/24"
}
]