Search code examples
ansible

Removing empty values from a list and assigning it to a new list


I have a list generated in Ansible using values gathered by a task.
In that list, there are empty strings as some of the keys don't have values assigned to them.
So, what I am trying to achieve is to assign that list to a new list but without those empty values.

list1: [
   "a",
   "b",
   "",
   "7",
   ""
]

I have tried the following and it doesn't seem to work:

set_fact:
  list2: "{{ list1 1 | rejectattr('') |list }}"

Is anyone able to point me what I am doing wrong and provide a solution to my issue?

Ansible version: 2.9.1


Solution

  • Q: Remove empty values from list1 ["a", "b", "", "7", ""]

    A: Use the filter select. Quoting:

    "If no test is specified, each object will be evaluated as a boolean."

        - set_fact:
            list2: "{{ list1|select() }}"
          vars:
            list1: ["a", "b", "", "7", ""]
    

    gives

        list2: [a, b, '7']
    

    Q: If an element is 0 or False ?

    A: Both 0 and False evaluate to boolean False. The filter select will remove them too

        - set_fact:
            list2: "{{ list1|select() }}"
          vars:
            list1: ["a", "b", 0, "7", False, ""]
    

    gives the same result

        list2: [a, b, '7']
    

    To reject empty strings only use the test match

        - set_fact:
            list2: "{{ list1|reject('match', '^$') }}"
          vars:
            list1: ["a", "b", 0, "7", False, ""]
    

    gives

        list2: [a, b, 0, '7', false]