繁体   English   中英

Ansible获得其他组变速器

[英]Ansible get other group vars

我正在深入研究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 %}

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

你正在寻找的神奇变种是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 -%}

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


如果主机属于多个组,您可能希望过滤重复的条目。 在这种情况下,您需要先收集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 %}

所有ansible组都存储在全局变量groups ,因此如果要迭代所有内容,可以执行以下操作:

All groups:
{% for g in groups %}
{{ g }}
{% endfor %}

Hosts in group "all":
{% for h in groups['all'] %}
{{ h }}
{% endfor %}

等等

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM