when: item is defined not working

22 views
Skip to first unread message

javed khan Siddque

unread,
Jun 23, 2023, 3:09:07 PM6/23/23
to Ansible Project
The below task is not working as expected.
i am expecting it will print message for at least 2 times which is defined and skip rest 2.


TASK [Connect to Isilon Device] ****************************************************************************************************
skipping: [localhost]



---
- name: "Loop Iteration List"
hosts: localhost
vars:
nfs_prod_target_id: "Khan"
nfs_prod_source_id: "Siddque"
tasks:
- name: "Connect to Isilon Device"
ansible.builtin.debug:
msg: "{{ item }}"
when: item is defined
loop:
- "{{ nfs_prod_source_id }}"
- "{{ nfs_prod_target_id }}"
- "{{ nfs_dev_source_id }}"
- "{{ nfs_dev_target_id }}"

Todd Lewis

unread,
Jun 25, 2023, 6:09:27 PM6/25/23
to ansible...@googlegroups.com, uto...@gmail.com
I believe the loop: values are evaluated first, before any iterations are performed, in which case any undefined variables in any of the loop: expressions will throw the error you see.

This is probably a desirable behavior in general even though in this case you got caught by surprise.

Here's a work-around that uses a sentinel value — and blatantly abuses "omit" for which I'm sure to be rightly scorned. :)
---
- name: "Loop Iteration List"
  hosts: localhost
  vars:
    nfs_prod_target_id: "Khan"
    nfs_prod_source_id: "Siddque"
  tasks:
    - name: "Connect to Isilon Device"
      ansible.builtin.debug:
        msg: "{{ item }}"
      when: item != omit
      loop:
        - "{{ nfs_prod_source_id | d(omit) }}"
        - "{{ nfs_prod_target_id | d(omit) }}"
        - "{{ nfs_dev_source_id | d(omit) }}"
        - "{{ nfs_dev_target_id | d(omit) }}"
Cheers,
--
Todd
--

Kosala Atapattu

unread,
Jun 25, 2023, 10:15:59 PM6/25/23
to ansible...@googlegroups.com, uto...@gmail.com
Just wonder what's stopping you from doing this:


---
- name: "Loop Iteration List"
hosts: localhost
vars:
my_list:
- nfs_prod_target_id: "Khan"
- nfs_prod_source_id: "Siddque"
tasks:
- name: "Connect to Isilon Device"
ansible.builtin.debug:
msg: "{{ item }}"
loop: "{{ my_list }}"


Kosala




--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/2366dc40-c7cb-234d-9fdb-f5cc110141f3%40gmail.com.
Reply all
Reply to author
Forward
0 new messages