title: Ansible: Skip loop when list is undefined
body: <p>Example playbook -</p>
  <pre class="lang-yaml prettyprint-override"><code>---
  - hosts: localhost
  
    vars:
      lesson:
       name: Physics
       students:
        - Bob
        - Joe
  
    tasks:
       - name: Display student names
         debug:
           msg: '{{ item }}'
         loop: &quot;{{ lesson.students }}&quot;
         when: item | default(&quot;&quot;)
  </code></pre>
  <p>The above playbook works well to output the student names.</p>
  <p>However, if the input changes (as per below) such that no student names have been defined, then an error occurs. Is there a simple way to have the playbook skip this task if the list is undefined as per the input below? I realize it would work if the input specifies <strong>students: []</strong>, but as this input is coming from simple users, they're not going to know this. Much Thanks!</p>
  <pre class="lang-yaml prettyprint-override"><code>  vars:
      lesson:
       name: Physics
       students:
  </code></pre>
  <blockquote>
  <p>Error: fatal: [localhost]: FAILED! =&gt;
  msg: 'Invalid data passed to ''loop'', it requires a list, got this instead: . Hint: If you passed a list/dict of just one element, try adding wantlist=True to your lookup invocation or use q/query instead of lookup.</p>
  </blockquote>
  <p>Update - I've tried the below variations but still get the same error -</p>
  <pre class="lang-yaml prettyprint-override"><code>---
  - hosts: localhost
  
    vars:
      lesson:
       name: Physics
       students:
  
    tasks:
       - name: Display student names variation 1
         debug:
           msg: '{{ item }}'
         loop: &quot;{{ lesson.students }}&quot;
         when: lesson.students is iterable
  
       - name: Display student names variation 2
         debug: 
           msg: '{{ item }}'
         loop: &quot;{{ lesson.students }}&quot;
         when: lesson.students is not none
  
       - name: Display student names variation 3
         debug: 
           msg: '{{ item }}'
         loop: &quot;{{ lesson.students }}&quot;
         when: ( item | default(&quot;&quot;) ) or ( item is not none )
  </code></pre>