Ansible 检查字典列表中是否存在 key/value 对

Ansible check if key/value pair exists in list of dictionaries

我正在尝试检查某个 key/value 对是否存在于 Ansible 的词典列表中。

我发现了这个问题,但是我不确定 python 和 ansible 的语法是否不同(我从来没有在 ansible 中看到过 if 语句!) Check if value already exists within list of dictionaries?

when条件我已经试过了:

  when: '"value" not in list'

然而我没有任何运气。

例如,列表类似于:

list: [
   {
   "key1" : "value1",
   "key2" : "value2",
   "key3" : "value3"
   },
   {
   "key1" : "value4",
   "key2" : "value5",
   "key3" : "value6"
   },
   and so on

我试图找出,例如,"key2":"value5" 对是否存在于列表中的任何词典中。希望有一种方法可以做到这一点,如果该对存在则给出 true,如果不存在则给出 false?

如有任何提示,我们将不胜感激!谢谢。

给你:

- hosts: localhost
  gather_facts: no
  vars:
    list_of_dicts: [
     {
     "key1" : "value1",
     "key2" : "value2",
     "key3" : "value3"
     },
     {
     "key1" : "value4",
     "key2" : "value5",
     "key3" : "value3"
     }]
  tasks:
    - debug:
        msg: found
      when: list_of_dicts | selectattr(search_key,'equalto',search_val) | list | count > 0
      vars:
        search_key: key3
        search_val: value3