sorin
sorin

Reputation: 170478

Check if all elements from a list are present in another list with Ansible

I am looking for the easiest way to check if all elements from a list are present in another bigger list, in Ansible.

Example checking that ['pkg_mgr', 'python'] are both present in ansible_facts.

Upvotes: 2

Views: 3619

Answers (3)

matt_s
matt_s

Reputation: 1075

How about using is subset?

Test:

- name: "Check lists"
  hosts: localhost
  connection: local 
  tasks:
  - debug:
      msg: "{{ ['pkg_mgr', 'python'] is subset(ansible_facts.keys()) }}"
  - debug:
      msg: "{{ ['pkg_mgr', 'python', 'foo'] is subset(ansible_facts.keys()) }}"

Output:

PLAY [Check lists] *****************************************************************************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************************************************************************************
ok: [localhost]

TASK [debug] ***********************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": true
}

TASK [debug] ***********************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": false
}

Upvotes: 1

Vladimir Botka
Vladimir Botka

Reputation: 68064

when: "{{ ['pkg_mgr', 'python'] | difference(ansible_facts.keys()) | length == 0 }}"

Q: "I am far from being pleased regarding how ugly it looks. I would be more than happy to see cleaner solutions."

A: An empty list evaluates to False in Ansible. It's not necessary to test the length of the list. Ansible condition when expands the expression by default. It's not necessary to close it in braces. The equivalent condition is

when: not ['pkg_mgr', 'python']|difference(ansible_facts.keys())


Python3 returns a dictionary view object instead of a list for methods dict.keys(), dict.values(), and dict.items(). Add list filter to make the code portable. See Dictionary Views.

when: not ['pkg_mgr', 'python']|difference(ansible_facts.keys()|list)

Upvotes: 2

sorin
sorin

Reputation: 170478

I was able to find a solution that works but I am far from being pleased regarding how ugly it looks.

- when: "{{ ['pkg_mgr', 'python'] | difference(ansible_facts.keys()) | length == 0 }}"
  ...

I would be more than happy to see cleaner solutions.

Upvotes: 2

Related Questions