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.

0

1 Answer 1

15

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
3
  • 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. Jul 6, 2017 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 6, 2017 at 19:47
  • How can I get the index of dictionary in which that pair exists? Jun 25, 2020 at 11:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.