【发布时间】:2018-12-20 21:13:37
【问题描述】:
在 ansible 中,我有一个 dict 列表,例如:
- { name: "a" }
- { name: "b", cond: true }
我想在 cond 未定义或为假 (1) 时提取名称列表,以及当 cond 为真或未定义 (2) 时的列表:
1 => [ 'a' ]
2 => [ 'a', 'b' ]
如何做到这一点?没找到。
谢谢
【问题讨论】:
标签: ansible
在 ansible 中,我有一个 dict 列表,例如:
- { name: "a" }
- { name: "b", cond: true }
我想在 cond 未定义或为假 (1) 时提取名称列表,以及当 cond 为真或未定义 (2) 时的列表:
1 => [ 'a' ]
2 => [ 'a', 'b' ]
如何做到这一点?没找到。
谢谢
【问题讨论】:
标签: ansible
您可以使用 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
【讨论】: