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.

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'

If X is 1, the playbook runs as expected:
#> ansible-playbook b.yml -e'X=1'

PLAY [127.0.0.1] 
***************************************************************

TASK [get json] 
****************************************************************
changed: [127.0.0.1]

TASK [echo a array] 
************************************************************
ok: [127.0.0.1] => (item=1) => {
    "item": 1,
    "msg": 1
}
ok: [127.0.0.1] => (item=2) => {
    "item": 2,
    "msg": 2
}
ok: [127.0.0.1] => (item=3) => {
    "item": 3,
    "msg": 3
}

PLAY RECAP 
*********************************************************************
127.0.0.1                  : ok=2    changed=1    unreachable=0    failed=0

But if X is not 1, then the 'get json' task doesn't run, so b is not 
defined, and the 'echo a array' task fails:
#> ansible-playbook b.yml -e'X=0'

PLAY [127.0.0.1] 
***************************************************************

TASK [get json] 
****************************************************************
skipping: [127.0.0.1]

TASK [echo a array] 
************************************************************
fatal:
 [127.0.0.1]: FAILED! => {"failed": true, "msg": "Unexpected 
templating type error occurred on ({{ (b.stdout | from_json).a }}): 
expected string or buffer"}

PLAY RECAP 
*********************************************************************
127.0.0.1                  : ok=0    changed=0    unreachable=0    failed=1


I've seen examples where folks use the default() filter on the with_items: 
loop, but I can't figure out how to include a filter that'll work with the 
from_json and the .a.  Any ideas?

Rob

-- 
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 [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/e93022c6-0347-4c23-931b-e5c5d2f057ab%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to