问题描述
我有一个这样的列表:
host_depends:
- host: abc
depends:
- name: item1
- name: item4
type: asdf
- name: item6
- host: def
depends:
- name: item2
- name: item4
- name: item6
我需要遍历 depends
元素的唯一名称,所以在这个例子中我想遍历
I need to loop over the unique name of the depends
elemnents, so in this example I want to loop over
- item1
- item2
- item4
- item6
基本上是什么
debug: var=item.1.name
with_subelements:
- "{{ host_depends }}"
- depends
可以,但只有独特的元素.
does, but with unique elements only.
如何获取所有 host_depends
项的 depends
以便我可以对它们运行 unique
过滤器并将它们与 一起使用with_items
?
How can I get the depends
of all host_depends
items so I can run a unique
filter over them and use them with with_items
?
我设法得到所有 depends
项目的列表,如下所示:
I manage to get a list of all depends
items like this:
host_depends|map(attribute='depends')|list
但从那里开始,我无法将此列表缩减为 name
项目.
But from there, I fail to reduce this list to the name
items.
推荐答案
host_depends|map(attribute='depends')|list
返回一个列表列表,因为depends 是一个列表.要将这个列表列表扁平化/合并成一个列表,请使用内置的扁平化查找:
returns a list of lists, as depends is a list. To flatten/combine this list of lists into one list, use the builtin flatten lookup:
lookup('flattened', host_depends|map(attribute='depends')) |map(attribute='name')|unique|list
这篇关于ansible/jinja2 获取唯一的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!