簡體   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