Ansible.com上的这篇文章展示了如何在模板文件中迭代一个组:https://support.ansible.com/hc/en-us/articles/201957887-How-to-loop-over-a-list-of-hosts-in-a-group-inside-of-a-template-
它显示以下代码:
{% for host in groups['db_servers'] %}
{{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}
它运行得很漂亮,但是我要迭代的服务器是通过多个组来定义的。所以想象一下,我想迭代db_servers和qa组中的所有服务器。我怎么能这样做?
我尝试以与我在剧本中相同的方式指定组的交集,但这不起作用。所以,当我尝试:
{% for host in groups['db_servers:&qa'] %}
{{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}
我收到以下错误:
fatal: [54.173.247.115] => {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict object' has no attribute 'db_servers:&qa'", 'failed': True}
有关如何在模板文件中迭代多个组的任何建议吗?
答案 0 :(得分:4)
Ansible有intersect
过滤器。请参阅Set Theory Filters。
{% for host in groups['db_servers'] | intersect(groups['qa']) %}
{{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}
答案 1 :(得分:0)
您可以将循环包装在另一个服务器组中:
{% for svrs in ['db_servers', 'qa'] %}
{% for host in groups[svrs] %}
{{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}
{% endfor %}