There are several ways to verify if a certain value is present in a dictionary using Ansible:
Using the json_query
filter: This filter allows you to extract specific values from a JSON object using JMESPath expressions. You can use this filter to check if a certain value is present in a dictionary. For example:
- hosts: localhost
vars:
my_dict:
key1: value1
key2: value2
key3: value3
tasks:
- name: Check if value exists in dict
assert:
that: my_dict | json_query("[*].value | contains(`value2`)")
Using the default
filter: This filter returns a default value if the original value is undefined or false. You can use this filter to check if a certain value is present in a dictionary. For example:
- hosts: localhost
vars:
my_dict:
key1: value1
key2: value2
key3: value3
tasks:
- name: Check if value exists in dict
assert:
that: my_dict.key2 is defined and my_dict.key2 | default("") == "value2"
Using the contains
method: This method is available in Jinja2 and allows you to check if a certain value is present in a dictionary. For example:
- hosts: localhost
vars:
my_dict:
key1: value1
key2: value2
key3: value3
tasks:
- name: Check if value exists in dict
assert:
that: "value2" in my_dict.values()
Asked: 2022-10-05 11:00:00 +0000
Seen: 12 times
Last updated: Jul 01 '21