【问题标题】:Ansible - Extract record from dict on valueAnsible - 从值的字典中提取记录
【发布时间】:2018-12-20 21:13:37
【问题描述】:

在 ansible 中,我有一个 dict 列表,例如:

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

我想在 cond 未定义或为假 (1) 时提取名称列表,以及当 cond 为真或未定义 (2) 时的列表:

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

如何做到这一点?没找到。

谢谢

【问题讨论】:

    标签: ansible


    【解决方案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   
    

    【讨论】:

    • 谢谢,这正是我想要的!
    猜你喜欢
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    相关资源
    最近更新 更多