using when inside and outside a loop

9 views
Skip to first unread message

Spiro Mitsialis

unread,
Jan 21, 2020, 3:17:18 PM1/21/20
to Ansible Project
I want to do something like this below:

  - name: Create Simple list from Connection Dict
    set_fact
:
      connections
: "{{ connections | default([]) + [ {
        'switchid': item.id,
        'connectionid': item.connections[0].id
        } ] }}"

   
when: item.connections                                     #only want to create facts if connections exist
    loop
: "{{ connections_result.json.0.switchPorts | flatten }}"
   
when: connections_result is defined                        #depending on the host,connection_result.json may not be defined so need  to check
When I run the playbook, I get the following warning at the top

[WARNING]: While constructing a mapping from /home/xxx/xxxxx.yml, line 245, column 5, found a duplicate dict key (when). Using last defined value only.

Is there a way to get both when to work?

Vladimir Botka

unread,
Jan 21, 2020, 4:09:50 PM1/21/20
to Spiro Mitsialis, ansible...@googlegroups.com
No. It's not possible. Instead, default to an empty list if the variable does
not exist. For example

- name: Create Simple list from Connection Dict
set_fact:
connections: "{{ connections | default([]) + [ {
'switchid': item.id,
'connectionid': item.connections[0].id
} ] }}"
when: item.connections
loop: "{{ connections_result.json.0.switchPorts|
default([])|
flatten }}"

HTH,

-vlado

Reply all
Reply to author
Forward
0 new messages