Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to check if a certain key/value pair exists in a list of dictionaries in Ansible.

I found this question, however I am not sure if the syntax differs from python to ansible (I have never seen an if statement in ansible!) Check if value already exists within list of dictionaries?

I have already tried the when condition:

  when: '"value" not in list'

however I have not had any luck with that.

For example, list looks something like:

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

And I am trying to find out, for example, whether the pair "key2":"value5" exists within any of the dictionaries in the list. Hopefully there is a way to do this that just gives true if the pair exists, false if not?

Any tips would be greatly appreciated! Thanks.

like image 325
astrade Avatar asked Jul 06 '17 18:07

astrade


People also ask

How do you see if a value is in a list of dictionaries?

Use any() & List comprehension to check if a value exists in a list of dictionaries.

How do you check if a key value exists in a list of dictionary python?

Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

What is With_dict in Ansible?

with_dict: - "{{ zones_hash }}" declares a list with a dict as the first index, and Ansible rightfully complains since it expects a dict. The solution kfreezy mentioned works since it actually gives a dictionary to with_dict and not a list: with_dict: "{{ zones_hash }}" Follow this answer to receive notifications.

How do you check if a key has a value in Python?

Checking if key exists using the get() method The get() method is a dictionary method that returns the value of the associated key. If the key is not present it returns either a default value (if passed) or it returns None.


1 Answers

Here you go:

- 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
like image 194
Konstantin Suvorov Avatar answered Oct 09 '22 18:10

Konstantin Suvorov