Search code examples
ansibleansible-2.x

Rerunning same Ansible task a few times


I am trying to implement a task that runs in a loop, for example, ten times. Currently, the task runs only once.

I am trying something like the following:

my_role/tasks/main.yaml

---

- set_fact: 
    counter: 0

- name: "Iteration"
  import_task: my_task.yaml
  until: counter <= 10

...

my_role/tasks/my_task.yaml

---

- name: "task 1"
  ...

- name: "task 2"
  ...

- set_fact:
    counter=={{ counter | int + 1 }}
...

I expected "task 1" and "task 2" to run ten times.

I would be happy to get some ideas on how to implement such loop.


Solution

  • You should use include_tasks module and loop over it.

    my_role/tasks/main.yaml

    ---
    
    - name: "Iteration"
      ansible.builtin.include_tasks:
        file: my_task.yaml
      with_sequence: start=1 end=10
    
    ...
    

    my_role/tasks/my_task.yaml

    ---
    
    - name: "task 1"
      ...
    
    - name: "task 2"
      ...
    
    ...