我更深入地研究Ansible功能,我希望以优美的方式实现VIP的概念。
为此,我在我的广告资源的group_vars
中实施了此变量:
group_vars / firstcluster:
vips:
- name: cluster1_vip
ip: 1.2.3.4
- name: cluster1.othervip
ip: 1.2.3.5
group_vars / secondcluster:
vips:
- name: cluster2_vip
ip: 1.2.4.4
- name: cluster2.othervip
ip: 1.2.4.5
并在清单中:
[firstcluster]
node10
node11
[secondcluster]
node20
node21
我的问题:如果我想设置一个DNS服务器,收集所有VIP和相关名称(没有美学冗余),我该如何处理?简而言之:尽管主机位于下方,是否可以获得所有组变量?
像:
{% for group in <THEMAGICVAR> %}
{% for vip in group.vips %}
{{ vip.name }} IN A {{ vip.ip }}
{% end for %}
{% end for %}
答案 0 :(得分:3)
我认为你无法直接访问任何组的变量,但是你可以访问组主机,也可以从主机访问变量。因此,循环遍历所有组,然后只选择每个组的第一个主机应该这样做。
您正在寻找的神奇变量是groups
。同样重要的是hostvars
。
{%- for group in groups -%}
{%- for host in groups[group] -%}
{%- if loop.first -%}
{%- if "vips" in hostvars[host] -%}
{%- for vip in hostvars[host].vips %}
{{ vip.name }} IN A {{ vip.ip }}
{%- endfor -%}
{%- endif -%}
{%- endif -%}
{%- endfor -%}
{%- endfor -%}
文档:Magic Variables, and How To Access Information About Other Hosts
如果主机属于多个组,您可能希望过滤重复的条目。在这种情况下,您需要先收集dict中的所有值,然后将其输出到一个单独的循环中,如下所示:
{% set vips = {} %} {# we store all unique vips in this dict #}
{%- for group in groups -%}
{%- for host in groups[group] -%}
{%- if loop.first -%}
{%- if "vips" in hostvars[host] -%}
{%- for vip in hostvars[host].vips -%}
{%- set _dummy = vips.update({vip.name:vip.ip}) -%} {# we abuse 'set' to actually add new values to the original vips dict. you can not add elements to a dict with jinja - this trick was found at http://stackoverflow.com/a/18048884/2753241#}
{%- endfor -%}
{%- endif -%}
{%- endif -%}
{%- endfor -%}
{%- endfor -%}
{% for name, ip in vips.iteritems() %}
{{ name }} IN A {{ ip }}
{% endfor %}
答案 1 :(得分:0)
所有ansible组都存储在全局变量groups
中,因此如果要迭代所有内容,可以执行以下操作:
All groups:
{% for g in groups %}
{{ g }}
{% endfor %}
Hosts in group "all":
{% for h in groups['all'] %}
{{ h }}
{% endfor %}
等