A variable registered in a loop is a dictionary that always keeps the results list in the attribute results. See Registering variables with a loop. For example,
- shell: echo {{ item }}_result
register: out
loop: [a, b, c]
- debug:
msg: "{{ item.stdout }}"
loop: "{{ out.results }}"
loop_control:
label: "{{ item.cmd }}"
gives abridged
msg: a_result
msg: b_result
msg: c_result
It is not possible to loop a block. See Playbook Keywords. Instead, you can loop either include_tasks or import_tasks. See Including and Importing. Put the tasks you want to iterate into a file. For example,
shell> cat abc.yml
- debug:
msg: step1 {{ item.stdout }}
- debug:
msg: step2 {{ item.stdout }}
and iterate include_tasks
- include_tasks: abc.yml
loop: "{{ out.results }}"
loop_control:
label: "{{ item.cmd }}"
gives abridged
msg: step1 a_result
msg: step2 a_result
msg: step1 b_result
msg: step2 b_result
msg: step1 c_result
msg: step2 c_result
Example of a complete playbook for testing
- hosts: localhost
tasks:
- shell: echo {{ item }}_result
register: out
loop: [a, b, c]
- debug:
msg: "{{ item.stdout }}"
loop: "{{ out.results }}"
loop_control:
label: "{{ item.cmd }}"
- include_tasks: abc.yml
loop: "{{ out.results }}"
loop_control:
label: "{{ item.cmd }}"
Q: Check that item result.rc !=0
A: Any rc != 0 makes the task fail. You have to ignore_errors. For example,
- shell: "{{ item }}"
register: out
loop: ['true', 'false', 'true']
ignore_errors: true
- debug:
msg: "{{ item.rc }}"
loop: "{{ out.results }}"
loop_control:
label: "{{ item.cmd }}"
gives abridged
msg: '0'
msg: '1'
msg: '0'
Now, you can conditionally iterate the tasks
- include_tasks: abc.yml
loop: "{{ out.results }}"
when: item.rc != 0
loop_control:
label: "{{ item.cmd }}"
gives abridged
skipping: [localhost] => (item=true)
skipping: [localhost] => (item=true)
included: /export/scratch/tmp1/test-44/abc.yml for localhost => (item=false)
msg: 'step1 '
msg: 'step2
Example of a complete playbook for testing
- hosts: localhost
tasks:
- shell: "{{ item }}"
register: out
loop: ['true', 'false', 'true']
ignore_errors: true
- debug:
msg: "{{ item.rc }}"
loop: "{{ out.results }}"
loop_control:
label: "{{ item.cmd }}"
- include_tasks: abc.yml
loop: "{{ out.results }}"
when: item.rc != 0
loop_control:
label: "{{ item.cmd }}"