在Ansible中,我有一个字典列表,例如:
- { name: "a" }
- { name: "b", cond: true }
当cond未定义或为false时,我想提取名称列表(1);当cond为true或未定义时,我也想提取名称列表:
1 => [ 'a' ]
2 => [ 'a', 'b' ]
该怎么做?我没找到。
谢谢
答案 0 :(得分:1)
您可以使用json_query
过滤器来做到这一点:
---
- hosts: localhost
gather_facts: false
vars:
mylist:
- name: a
- name: b
cond: true
tasks:
- set_fact:
true_or_unset: "{{ mylist|json_query('[?cond == null || cond].[name]') }}"
false_or_unset: "{{ mylist|json_query('[?cond == null || !cond].[name]') }}"
- debug:
msg:
true_or_unset: "{{ true_or_unset }}"
false_or_unset: "{{ false_or_unset }}"
哪个会产生:
PLAY [localhost] ******************************************************************************
TASK [set_fact] *******************************************************************************
ok: [localhost]
TASK [debug] **********************************************************************************
ok: [localhost] => {
"msg": {
"false_or_unset": [
[
"a"
]
],
"true_or_unset": [
[
"a"
],
[
"b"
]
]
}
}
PLAY RECAP ************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0