我很难找到列表的基本过滤器:'any'(如果列表中的任何值可以转换为
true
,则返回true
),'all'(仅返回列表中的所有值true
)可以投射到true
)。
我可以使用
any
来模拟 my_list|map()|bool
,但它看起来像是一个 hack,而且我在使用 all
功能时遇到了麻烦。
更新:
我发现了这个(又一个奇怪的)黑客。
my_list|map('bool')|max
my_list|map('bool')|min
有更好的(惯用的)方法吗?
2022年答案和ansible.core版本2.12(我不知道过去版本的答案):
使用
is any
和 is all
语法而不是非工作的 | any
/ | all
或您建议的任何其他 hack
示例复制自 https://docs.ansible.com/ansible/latest/user_guide/playbooks_tests.html
vars:
mylist:
- 1
- "{{ 3 == 3 }}"
- True
myotherlist:
- False
- True
tasks:
- debug:
msg: "all are true!"
when: mylist is all
- debug:
msg: "at least one is true"
when: myotherlist is any
是的,您可以只使用
all
和 any
。
这是使用它们的示例手册。 (这对我的 Ansible 2.5.1 有效。)
---
- hosts: localhost
tasks:
- assert:
that:
- mixed | any
- not (mixed | all)
- all_true | any
- all_true | all
- not (all_false | any)
- not (all_false | all)
vars:
mixed:
- false
- true
- false
all_true:
- true
- true
- true
all_false:
- false
- false
- false
事实上,当涉及到布尔值列表时,您不需要
any
或 all
。我很高兴使用 max
和 min
来代替,因为 True > False
:)
any([False, False, False]): {{ [False, False, False] | max }}
any([False, True, False]): {{ [False, True, False] | max }}
all([True, True, False]): {{ [True, True, False ] | min }}
all([True, True, True]): {{ [True, True, True] | min }}
渲染至
any([False, False, False]): False
any([False, True, False]): True
all([True, True, False]): False
all([True, True, True]): True
Ansible 不实现
any
和 all
过滤器。