json_query 使用包含在另一个列表中搜索项目失败

json_query uses contains to search item within another list failed

我有样本列表,我想 select 类型在 wanted_list 中的项目。

- name: Get item based on anther list
  vars: 
    samples:
      - { item: 10, type: sample-1 },
      - { item: 20, type: sample-11 },
      - { item: 30, type: sample-2 }
    wanted_list: [ sample-11, sample-2 ]
    query: "[?contains('{{wanted_list|to_json}}', type)]"
  debug:
    var: samples | json_query(query)

结果:

TASK: Get item based on anther list
ok: [localhost] => {
    "samples|json_query(query)": [
        {
            "item": 10,
            "type": "sample-1"
        },
        {
            "item": 20,
            "type": "sample-11"
        },
        {
            "item": 30,
            "type": "sample-2"
        }
    ]
}

我期望它只会 return 项目 20 和 30。但它实际上 return 所有 3。看起来 sample-1 匹配列表项目 sample-11 的一部分。

但基于 JMESPath 文档 contains:

boolean contains(array|string $subject, any $search)

If $subject is an array, this function returns true if one of the elements in the array is equal to the provided $search value.

因此 sample-1 不等于 sample-11,因此不应 selected。

您将要使用 the backtick in order to quote literal JSON like that, since the single quote is just for strings

  - name: Get item based on anther list
    vars: 
      samples:
        - { item: 10, type: sample-1 }
        - { item: 20, type: sample-11 }
        - { item: 30, type: sample-2 }
      wanted_list: [ sample-11, sample-2 ]
      query: "[?contains(`{{ wanted_list | to_json }}`, type)]"
    debug:
      msg: '{{ samples | json_query(query) }}'

过滤器 selectattrmap 完成工作

- debug:
    msg: "{{ samples|
             selectattr('type', 'in', wanted_list)|
             map(attribute='item')|
             list }}"

给予

    "msg": [
        20,
        30
    ]

备注

  • 修复列表的语法samples并删除行尾的逗号
  vars: 
    samples:
      - {item: 10, type: sample-1}
      - {item: 20, type: sample-11}
      - {item: 30, type: sample-2}