Ansible filter list based on attributes

Suppose we want to find only users who have a middle name from this:

users:
  - name: John
    surname: Johnson
  - name: Alice
    surname: Wonderland
  - name: Bob
    surname: Rabbit
    middlename: Bebop

Old, verbose way would be:

- debug: msg=""
  loop: ""
  when: item.middlename is defined

This results in “skipping” lines polluting the output, however. To avoid this, use

- debug: msg="{{ item.middlename }}"
  loop: "{{ users | selectattr('middlename','defined') | list }}"

This, however, grows unwieldy when you need to chain many conditions. But remember that you can break lines, that’ll work just as well:

- debug: msg="{{ item.middlename }}"
  loop: "{{ users
    | selectattr('middlename','defined')
    | list }}"

Comments