is there any filter in ansible can mimic all() and any()?

Viewed 163

It is surprising there is no such filter in jinja2 or ansible. What is the canonical way to mimic this in ansible? I expect to have [True, False] | all return False, [True, False] | any return True. So far for any I can use sum then check if it is greater than 0. But all is trickier I have to do select('false') | length ==0 which looks quite stupid. Is there better way to do this?

1 Answers

This is exactly what all and any tests do e.g.

    - debug:
        msg: "{{ [True, False] is all }}"
    - debug:
        msg: "{{ [True, False] is any }}"

give

  msg: false
  msg: true

There are no such filters in Ansible but you can write them e.g.

shell> cat filter_plugins/list2bool.py

def fall(l):
        return all(l)

def fany(l):
        return any(l)

class FilterModule(object):
    ''' Ansible filters for operating on Boolean '''

    def filters(self):
        return {
            'fall': fall,
            'fany': fany,
            }

(see other plugins)

These custom filters are useful in pipes, e.g. to map lists

    - debug:
        msg: "{{ l|map('fall')|list }}"
      vars:
        l:
          - [True, True]
          - [True, False]
          - [False, True]
          - [False, False]

gives

  msg:
  - true
  - false
  - false
  - false

and

    - debug:
        msg: "{{ l|map('fany')|list }}"
      vars:
        l:
          - [True, True]
          - [True, False]
          - [False, True]
          - [False, False]

gives

  msg:
  - true
  - true
  - true
  - false
Related