Use loop control only when condition is met

218 views
Skip to first unread message

Aleksandar Ilic

unread,
Nov 2, 2021, 2:27:44 PM11/2/21
to Ansible Project
Hello everyone,

Im new to ansible and im trying to use loop_contorl pause only for specific item.

Is this something that is possible to do ?

Thanks

Brian Coca

unread,
Nov 2, 2021, 4:02:12 PM11/2/21
to Ansible Project
pause gets calculated before the looping starts so it cannot be set per item

-
----------
Brian Coca

Todd Lewis

unread,
Nov 4, 2021, 11:26:36 AM11/4/21
to Ansible Project
Given what Brian pointed out, you can achieve the same effect by using include_tasks where the tasks file contains the task you want to loop over followed by a conditional invocation of the pause module. Here's a sample playbook with some data. Note that the 3rd item has a non-zero pause value.
---
# inc-loop-demo-main.yml
- hosts: localhost
  vars:
    aaa:
    - {able: fee, baker: fie, charlie: foe, pause: 0 }
    - {able: nee, baker: nie, charlie: noe, pause: 0 }
    - {able: see, baker: sie, charlie: soe, pause: 5 }
    - {able: zee, baker: zie, charlie: zoe, pause: 0 }
  tasks:
  - name: Dump data
    debug:
      msg: "{{ aaa }}"

  - name: Loop over aaa calling inc-loop-demo-tasks.yml
    include_tasks: inc-loop-demo-tasks.yml
    loop: "{{ aaa }}"

and the task file that it includes:
---
# inc-loop-demo-tasks.yml
- name: show item
  debug:
    msg: "able: {{ item.able }}, baker: {{ item.baker }}, charlie: {{ item.charlie }}, pause: {{ item.pause }}"

- name: optional delay after prior tasks
  pause:
    seconds: "{{ item.pause }}"
  when: item.pause > 0

Here's a subset of the output:
TASK [show item] *******************************************
ok: [localhost] =>
  msg: 'able: nee, baker: nie, charlie: noe, pause: 0'

TASK [optional delay after prior tasks] ********************
skipping: [localhost]

TASK [show item] *******************************************
ok: [localhost] =>
  msg: 'able: see, baker: sie, charlie: soe, pause: 5'

TASK [optional delay after prior tasks] ********************
Pausing for 5 seconds
(ctrl+C then 'C' = continue early, ctrl+C then 'A' = abort)
ok: [localhost]

TASK [show item] *******************************************
ok: [localhost] =>
  msg: 'able: zee, baker: zie, charlie: zoe, pause: 0'

TASK [optional delay after prior tasks] ********************
skipping: [localhost]

PLAY RECAP *************************************************
localhost: ok=11   changed=0    unreachable=0    failed=0
      skipped=3    rescued=0    ignored=0   

Reply all
Reply to author
Forward
0 new messages