Docker fun
Docker fun

Reputation: 143

Ansible - how to check if all elements on list are the same?

We have list, like:
['A', 'A']
How to check if list contains only elements A? (Yes, it is exactly string).

For example, for ['A'], ['A','A','A','A'] True should be returned, however for
[], ['A','A', 'B'] False should be returned.

Is there exists any elegant way to express it?

Upvotes: 3

Views: 2116

Answers (1)

clockworknet
clockworknet

Reputation: 3056

This should do it:

- set_fact:
    sample:
      - A
      - A
- set_fact:
    has_unique_val: "{{ sample | unique | length == 1 }}"
- debug:
    var: has_unique_val
  • sample | unique | length this reduces the list to only unique values, then counts how many values are returned. If there is only one value, 1 will be returned, otherwise 0 or >1
  • == 1 returns true if the count is 1, otherwise false

Upvotes: 4

Related Questions