Ansible-从dict提取值记录

时间:2018-12-20 21:13:38

标签: ansible

在Ansible中,我有一个字典列表,例如:

- { name: "a" }
- { name: "b", cond: true }

当cond未定义或为false时,我想提取名称列表(1);当cond为true或未定义时,我也想提取名称列表:

1 => [ 'a' ]
2 => [ 'a', 'b' ]

该怎么做?我没找到。

谢谢

1 个答案:

答案 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