Ansible 获取其他组变量

mou*_*njr 3 variables jinja2 ansible

我正在进一步挖掘 Ansible 功能,并且希望以一种漂亮的方式实现 VIP 的概念。为此,我在group_vars库存中实现了此变量:

group_vars/firstcluster:

vips:
  - name: cluster1_vip
    ip: 1.2.3.4
  - name: cluster1.othervip
    ip: 1.2.3.5
Run Code Online (Sandbox Code Playgroud)

group_vars/第二个集群:

vips:
  - name: cluster2_vip
    ip: 1.2.4.4
  - name: cluster2.othervip
    ip: 1.2.4.5
Run Code Online (Sandbox Code Playgroud)

并在库存中:

[firstcluster]
node10
node11

[secondcluster]
node20
node21
Run Code Online (Sandbox Code Playgroud)

我的问题:如果我想设置一个 DNS 服务器来收集所有 VIP 和相关名称(没有美观的冗余),我该如何进行?简而言之:是否有可能获取所有组变量,尽管有下面的主机?

喜欢:

{% for group in <THEMAGICVAR> %}
{% for vip in group.vips %}
{{ vip.name }}      IN A     {{ vip.ip }}
{% end for %}
{% end for %}
Run Code Online (Sandbox Code Playgroud)

udo*_*dan 5

我认为您不能直接访问任何组的变量,但您可以访问组主机,并且可以从主机访问变量。因此,循环遍历所有组,然后只选择每个组的第一个主机就可以了。

您正在寻找的神奇变量是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 -%}
Run Code Online (Sandbox Code Playgroud)

文档:神奇变量以及如何访问有关其他主机的信息


如果主机属于多个组,您可能需要过滤重复的条目。在这种情况下,您需要首先收集字典中的所有值,然后在单独的循环中输出它,如下所示:

{% 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 %}
Run Code Online (Sandbox Code Playgroud)