如何在Ansible中获取子组列表?

时间:2016-09-23 07:46:35

标签: loops ansible inventory

我有一个如下所示的库存文件:

[master]
host01

[nl]
host02

[us]
host03

[satellites:children]
nl
us

如何获得以satellites为父母的群组列表?

我正在寻找与此类似的解决方案:

- debug: msg="{{ item }}"
  with_items: "{{ groups['satellites:children'] }}"

更新

我能够提供的唯一解决方案是:

- debug: {{ item }}
  with_items: "{{ groups }}"
  when: item != "master" and item != "satellites" and item != "all" and item != "ungrouped"

但这不是很灵活。

1 个答案:

答案 0 :(得分:5)

<击> 您可以尝试以下方法:

  vars:
    parent: 'satellites'
  tasks:
      # functional style
    - debug: msg="{{hostvars[item].group_names | select('ne', parent) | first}}"
      with_items: "{{groups[parent]}}"
      # set style
    - debug: msg="{{hostvars[item].group_names | difference(parent) | first}}"
      with_items: "{{groups[parent]}}"

同样select('ne', parent)可与reject('equalto', parent)互换,具体取决于您的可读性。

链接:
set theory operator
select and reject filters

根据评论更新了答案。来自this thread的灵感。

vars:
    parent: 'satellites'
tasks:
    - name: build a subgroups list
      set_fact: subgroups="{{ ((subgroups | default([])) + hostvars[item].group_names) | difference(parent) }}"
      with_items: "{{groups[parent]}}"

    - debug: var=subgroups

输出:

 "subgroups": [
        "nl",
        "us"
    ]