ansible json_query 将包含键值的字典作为列表

ansible json_query to with dicts containing key values as list

我在变量 allcsv 中有一个低于值的值

"msg": [
    {
        "added_bundle_images": [
            "locuz.qe.pnq.local/eng-build/lzfirewallmod:v4.8.3-10"
        ],
        "index_image": "locuz.qe.pnq.local/eng-build/iib:297699",
        "locuz_version": "v4.8"
    },
    {
        "added_bundle_images": [
            "locuz.qe.pnq.local/eng-build/lzfirewallmod:v4.10.0-57"
        ],
        "index_image": "locuz.qe.pnq.local/eng-build/iib:297697",
        "locuz_version": "v4.9"
    },
    {
        "added_bundle_images": [
            "locuz.qe.pnq.local/eng-build/lzfirewallmod:v4.7.7-14"
        ],
        "index_image": "locuz.qe.pnq.local/eng-build/iib:297497",
        "locuz_version": "v4.7"
    },
    {
        "added_bundle_images": [
            "locuz.qe.pnq.local/eng-build/lzfirewallmod:v4.9.2-3"
        ],
        "index_image": "locuz.qe.pnq.local/eng-build/iib:297495",
        "locuz_version": "v4.9"
    }
]

我有一个 ansible 变量,其中包含 added_bundle_images 中的值之一。例如,我有一个名为 lastcsv 的变量,其中包含值“locuz.qe.pnq.local/eng-build/lzfirewallmod:v4.7.7-14”

我正在尝试编写一个 json_query,如果我的键值与“locuz.qe.pnq.local/eng-build/lzfirewallmod:v4.7.7-14 匹配,我还尝试使用 selectattr 获取 index_image “

- name: set my variable
  set_fact:
     lastcsv: "locuz.qe.pnq.local/eng-build/lzfirewallmod:v4.7.7-14"

- name: my debug2                                                                                                                                                        
  debug: msg="{{ allcsv | selectattr('added_bundle_images','equalto', [lastcsv])  | list }}"

我看到的输出是:

TASK [common : my debug2] ***************************************************************************************************************************************************
ok: [foo.example.com] => {
    "msg": []
}

在构建查询时需要帮助,以便在 added_bundle_image 键的值为“locuz.qe.pnq.local/eng-build/lzfirewallmod:v4.7.7-14 时获得 index_image 值“

allcsv中,added_bundle_images是一个列表(用[]表示),所以我们可以用contains匹配而不是equalto看是否lastcsv 元素在该列表中。如下所示:

- name: set my variable
  set_fact:
     lastcsv: "locuz.qe.pnq.local/eng-build/lzfirewallmod:v4.7.7-14"

- name: my debug2                                                                                                                                                        
  debug:
    msg: "{{ allcsv | selectattr('added_bundle_images', 'contains', lastcsv) | map(attribute='index_image') | list }}"

产生:

TASK [my debug2] ********************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        "locuz.qe.pnq.local/eng-build/iib:297497"
    ]
}