【问题标题】:Ansible get other group varsAnsible 获取其他组变量
【发布时间】:2016-04-09 10:25:27
【问题描述】:

我正在进一步研究 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 %}

【问题讨论】:

    标签: variables ansible jinja2


    【解决方案1】:

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

    您正在寻找的魔法变量是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 %}
    

    【讨论】:

    • 太棒了!但是如果一个主机在两个组中,那么你就有冗余......(我肯定会选择这个解决方案,它只是一个 DNS 条目,它可以容忍冗余)
    • 即使您可能不需要它,我还是添加了一个过滤重复项的示例。
    • 谢谢你,很棒的答案!
    【解决方案2】:

    所有 ansible 组都存储在全局变量 groups 中,因此如果您想遍历所有内容,可以执行以下操作:

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

    等等

    【讨论】:

      猜你喜欢
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 2016-02-21
      • 1970-01-01
      相关资源
      最近更新 更多