Ask Your Question
4

How can you verify if a certain value is present in a dictionary using Ansible?

asked 2022-10-05 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-07-01 16:00:00 +0000

woof gravatar image

There are several ways to verify if a certain value is present in a dictionary using Ansible:

  1. 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`)")
    
  2. 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"
    
  3. 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()
    
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-05 11:00:00 +0000

Seen: 12 times

Last updated: Jul 01 '21