如何在 Ansible 中获取子组列表? [英] How can I get a list of child groups in Ansible?

查看:37
本文介绍了如何在 Ansible 中获取子组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的清单文件:

I have an inventory file that looks like this:

[master]
host01

[nl]
host02

[us]
host03

[satellites:children]
nl
us

如何获取以 satellites 作为父级的组的列表?

How can I get a list of groups that have satellites as their parent?

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

I am looking for a solution that works similar to this:

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

更新:

我能想到的唯一解决方案是:

The only solution I was able to come with is this:

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

但这不是很灵活.

推荐答案

您可以尝试以下方法:

You can try the following approaches:

  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) 互换,具体取决于您的可读性.

Also select('ne', parent) is interchangeable with reject('equalto', parent) depending on what is more readable to you.

链接:
集合论算子
选择和拒绝过滤器

根据评论更新答案.灵感来自这个主题.

Updated answer based on comments. inspiration from 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"
    ]

这篇关于如何在 Ansible 中获取子组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆