9

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.

astrade
  • 222
  • 1
  • 3
  • 10

1 Answers1

14

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
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • [equalto](http://jinja.pocoo.org/docs/2.9/templates/#equalto) is available since Jinja2 2.8, so I guess there's a bit of package chaos on your system. Check pip/system packages, ensure that Ansible uses Jinja2>=2.8. – Konstantin Suvorov Jul 06 '17 at 19:41
  • It's working now, thanks! I suppose the jinja upgrade was recent and the server just needed a restart. Thanks for your help. – astrade Jul 06 '17 at 19:47
  • How can I get the index of dictionary in which that pair exists? – Bhavneet sharma Jun 25 '20 at 11:25