如何获得Ansible中的子组列表? [英] How can I get a list of child groups in Ansible?
本文介绍了如何获得Ansible中的子组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个库存文件,如下所示:
I have an inventory file that looks like this:
[master]
host01
[nl]
host02
[us]
host03
[satellites:children]
nl
us
如何获取以卫星
作为其父级的组的列表?
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屋!
查看全文