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.
Use any() & List comprehension to check if a value exists in a list of dictionaries.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With