我是Ansible的新手,只是在库存中遇到了变量问题。在清单中,我有不同的变量,其中包含MAC或IP地址。我想循环浏览它们,如果它们存在,则在jinjar2模板中处理它们。
我的库存(缩短(:
net6_prd:
children:
net6_prd_test:
hosts:
net6-tst-01:
eth1_mac: "001 eth1 mac"
eth1_ip: "001 eth1 ip"
eth2_mac: "001 eth2 mac"
eth2_ip: "001 eth2 ip"
net6-tst-02:
eth1_mac: "002 eth1 mac"
eth1_ip: "002 eth1 ip"
eth2_mac: "002 eth2 mac"
eth2_ip: "002 eth2 ip"
在jinjar2模板中,我使用以下循环:
{% for ihost in hostvars -%}
# example={{ hostvars[items]['eth1_mac'] }}
{% endfor %}
不幸的是,这不起作用。Ansible报告变量不存在。
失败=>{"changed":false,"msg":"AnsibleUndefinedVariable":"ansible.vars.hostvars.HostVarsVars object"没有属性"eth1_mac"}
我也尝试过通过groups[net6_prd]
在net6_prd
中的所有主机上运行,但这也不起作用。其他人知道我的循环出了什么问题吗?
变量hostvars
实际上包含所有主机,无论它们是否是游戏的目标。这就是为什么你可能会遇到这个问题,你可能有主机在你的库存中没有定义这些变量。
根据您想要循环的主机,您可以使用:
ansible_play_hosts
特殊变量当前播放运行中的主机列表,不受序列号限制。失败/无法访问的主机从此列表中排除。
groups['net6_prd_test']
,它将列出名为net6_prd_test
的组中的所有主机- 根据您的需求,还有更多的选择
所以你最终在你的模板中:
{% for _host in ansible_play_hosts %}
# example={{ hostvars[_host].eth1_mac }}
{% endfor %}
如果你真的无法避免使用那些未定义的变量来定位主机,你也可以在循环中进行过滤:
{% for _host in hostvars if hostvars[_host].eth1_mac is defined %}
# example={{ hostvars[_host].eth1_mac }}
{% endfor %}