On 08.08.2018 22:10, rjwagner....@gmail.com wrote:
I'm running into the infamous issue where with_items isn't skipped if when evaluates to false (https://github.com/ansible/ansible/issues/13791). That
said, I'm at loss as to how to workaround my particular issue.

It's not that infamous, it's just how Jinja work, and when you understand the concept it is easy to deal with.


Consider these two tasks (simplified for discussion):

#> cat b.yml
---
- hosts: 127.0.0.1
  connection: local
  gather_facts: False
  tasks:
  - name: get json
    shell: "echo '{ \"a\": [ 1,2,3 ] }'"
    register: b
    when: X=='1'
  - name: echo a array
    debug: msg="{{ item }}"
    with_items: "{{ (b.stdout | from_json).a }}"
    when: X=='1'

When X=0 the variable b will be defined, it contains data about the sipped reason. But b will not contain the key stdout so this variable need to be filtered through default filter.

Since b.stdout is filter through from_json the default filter need to provide a empty json string to satisfy the filter.

  with_items: "{{ (b.stdout | from_json).a }}"

becomes

  with_items: "{{ (b.stdout | default('{}') | from_json).a }}"

but this will also fail since the empty {} json string doesn't contain a key name "a" so this also need to go through the default filter. Since with_items need a list this must be an empty list [], so it becomes

with_items: "{{ (b.stdout | default('{}') | from_json).a | default([]) }}"

So the principle is, if a variable is not defined it need to go through the default filter.

I hope this explanation gave some meaning.


--
Kai Stian Olstad

--
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-project+unsubscr...@googlegroups.com.
To post to this group, send email to ansible-project@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/4296f29d08c25ca89e2e52fec0f3d52c%40olstad.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to