'ansible Iterate var only if var is not empty

I m trying to iterate over some variables in an ansible role. However, I want to ignore if the var is empty ex:ns3 from below code? I m trying when item length is greater than 0 but it seems not working? any ideas on how to do it?

---
- hosts: localhost
  gather_facts: no
  vars:
    ns1: adm_analytics
    ns2: adm_snap
    ns3: ""
    ns4: adm_eck
  tasks: 
  - name: print namespace loop
    with_items:
      - "{{ ns1 }}"
      - "{{ ns2 }}"
      - "{{ ns3 }}"
      - "{{ ns4 }}"      
    include_role:
      name: verify_pod_status
    vars:
      NAMESPACE: "{{ item }}"
    when: "{{ item | lenght > 0 }}"


Solution 1:[1]

You may have a look into the documentation about Conditionals.

There are some typos in your when clause.

---
- hosts: localhost
  gather_facts: false

  vars:

    ns1: adm_analytics
    ns2: adm_snap
    ns3: ""
    ns4: adm_eck

  tasks:

  - name: Print namespace loop
    debug:
      msg: "{{ item }}"
    when: item | length > 0
    with_items:
      - "{{ ns1 }}"
      - "{{ ns2 }}"
      - "{{ ns3 }}"
      - "{{ ns4 }}"

result into an output of

TASK [Print namespace loop] **************
ok: [localhost] => (item=adm_analytics) =>
  msg: adm_analytics
ok: [localhost] => (item=adm_snap) =>
  msg: adm_snap
ok: [localhost] => (item=adm_eck) =>
  msg: adm_eck

Solution 2:[2]

when: condition is expanded by default. Fix the syntax

    when: item|length > 0

Make your life easier and put the ns* variables into a dictionary. Then you can simply reference the values in the loop instead of listing the variables again. For example, the playbook

shell> cat playbook.yml
- hosts: localhost
  gather_facts: no
  vars:
    ns:
      ns1: adm_analytics
      ns2: adm_snap
      ns3: ""
      ns4: adm_eck
  tasks: 
    - name: print namespace loop
      include_role:
        name: verify_pod_status
      loop: "{{ ns.values()|list }}"
      vars:
        NAMESPACE: "{{ item }}"
      when: item|length > 0

and the role

shell> cat roles/verify_pod_status/tasks/main.yml 
- debug:
    var: NAMESPACE

give (abridged)

TASK [verify_pod_status : debug] ***********************************
skipping: [localhost] => (item=) 

TASK [verify_pod_status : debug] ***********************************
ok: [localhost] => 
  NAMESPACE: adm_analytics

TASK [verify_pod_status : debug] ***********************************
ok: [localhost] => 
  NAMESPACE: adm_snap

TASK [verify_pod_status : debug] ***********************************
ok: [localhost] => 
  NAMESPACE: adm_eck

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 U880D
Solution 2