How to skip null values in ansible loop

Viewed 2993

I need to skip the value null from a list in ansible loop. I am using the when condition, still the null value gets printed. Below is my playbook:

 - hosts: localhost
   vars:
    show:
     - read
     - write
     - null
     - test
    val: []
   tasks:
   - name: Fact
     set_fact:
      val: "{{val+[item]}}"
     loop: "{{show}}"
     when: item != "null"

   - name: Print
     debug:
      msg: "{{val}}"

Output:

TASK [Print] ***
ok: [localhost] => {
    "msg": [
        "read",
        "write",
        null,
        "test"
    ]
}

Please advise.

2 Answers

Quoting from YAML 10.2.1.1. Null

"Represents the lack of a value. This is typically bound to a native null-like value (e.g., undef in Perl, None in Python). ..."

There are more options on how to test null.

  1. Compare to Python None
when: item != None 
  1. Use Jinja test none
when: item is not none
  1. If you for whatever reason have to compare to a string the Jinja filter string converts null to string 'None'
when: item|string != 'None'
  1. The most efficient way is to remove null values from the list before the iteration
loop: "{{ show|reject('none')|list }}"

I don't know if you want to check if the variable is "null" as a text or if the variable doesn't have a value and it's nullified so I will write both examples :), make null value a string and compare as a string:

- hosts: localhost
  vars:
    show:
      - read
      - write
      - "null"
      - test
    val: []
  tasks:
    - name: Fact
      set_fact:
        val: "{{val+[item]}}"
      loop: "{{show}}"
      when: "'{{item}}' != 'null'"

    - name: Print
      debug:
        msg: "{{val}}"

Test if the value is nullified and it really doesn't have any value we will use, is none for that example:

- hosts: localhost
  vars:
    show:
      - read
      - write
      - null
      - test
    val: []
  tasks:
    - name: Fact
      set_fact:
        val: "{{val+[item]}}"
      loop: "{{show}}"
      when: item is not none

    - name: Print
      debug:
        msg: "{{val}}"
Related