【问题标题】:Ansible: Intersection of two host groups using yaml inventoryAnsible:使用 yaml 库存的两个主机组的交集
【发布时间】:2020-11-16 23:30:48
【问题描述】:

我有 2 个组,每个组都有名为 devtest 的子组。我正在尝试使用group2:&test 模式定位group2 (four.example.com) 中的test 主机。

鉴于 yaml 库存:

all:
  children:
    group1:
      children:
        dev:
          hosts:
            one.example.com:
        test:
          hosts:
            two.example.com:
    group2:
      children:
        dev:
          hosts:
            three.example.com:
        test:
          hosts:
            four.example.com:
                  

还有剧本:

- name: health check
  hosts: group2:&test
  tasks:
    - name: Ping hosts
      ping:

我收到了来自twofour 的回复。

我希望 four 发送 ping。

虽然two 确实是名为test 的组的一部分,但它属于名为group2 的组,因此我不希望将其视为一部分相交。

就好像它在做一个逻辑或 (||),而不是一个逻辑与 (&&)

在使用具有非唯一子名称的嵌套组时,这是 Ansible 的限制吗?

【问题讨论】:

    标签: ansible yaml


    【解决方案1】:

    问:在使用具有非唯一子名称的嵌套组时,这是 Ansible 的限制吗?

    答:Ansible by design 不存储库存树。这似乎是一个限制。引用自How variables are merged

    默认情况下,变量会在播放运行之前合并/展平到特定主机。这让 Ansible 专注于主机和任务,因此组在清单和主机匹配之外无法真正生存。

    引用Inheriting variable values: group variables for groups of groups

    任何属于子组成员的主机都会自动成为父组的成员。

    有两个含义

    1. patern 'group2:&test' 是自相矛盾的。 test 组包含主机:twofour。通过尝试过交叉点,您同意这一点。否则,交叉点就没有意义了。但是引用的声明说 test 的成员自动成为 group1group2 的成员。换句话说,Ansible 无法区分 1)组 test 保留所有主机和 2)​​组 test 作为 group1 的子组em> 或 group2。例如,以下清单与问题中的清单相同
    all:
      children:
        group1:
          children:
            dev:
              hosts:
                one.example.com:
                three.example.com:
            test:
              hosts:
                two.example.com:
                four.example.com:
        group2:
          children:
            dev:
            test:
    
    all:
      children:
        dev:
          hosts:
            one.example.com:
            three.example.com:
        test:
          hosts:
            two.example.com:
            four.example.com:
        group1:
          children:
            dev:
            test:
        group2:
          children:
            dev:
            test:
    
    1. 具有非唯一子名称的嵌套组不符合此用例的目的。试试下面的库存
    all:
      children:
        group1:
          hosts:
            one.example.com:
            two.example.com:
        group2:
          hosts:
            three.example.com:
            four.example.com:
        dev:
          hosts:
            one.example.com:
            three.example.com:
        test:
          hosts:
            two.example.com:
            four.example.com:
    

    注意事项

    【讨论】:

    • 如果我为子组使用唯一名称(group1_dev、group2_test 等),它会按预期工作,所以如果我理解正确,展平会产生一个名为 test 的单个组,它属于两个 group1和组2。感谢您的回答
    • 不客气。正确的。让我补充一下。如果您使用唯一名称,则不需要相交。
    • 是的。也许是非常规的,但我的想法是,如果需要,我仍然可以定位所有“group1”节点,同时还可以以一种清晰传达信息的方式存储组,这可能是环境管理员可能关心的。 (例如,我在 jenkins 中使用这个 yml 来为每个环境创建目标主机的下拉列表)
    猜你喜欢
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 2020-09-02
    • 2016-06-12
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多