Search code examples
ansibleuntil-loop

Execute ansible include_tasks until a certain condition is met (kind of while until loop)


I want to execute an include tasks list until a certain condition is met, I do not have a fixed loop but execution depends upon a condition.

A sample play below

Tasks list playbook tasks.yml

---

- name: "inc test-var {{ test_var }}"
  set_fact:
    test_var: "{{ test_var | int + 1  }} "

parent playbook parent.yml

---

- hosts: all
  gather_facts: no

  tasks:
    - set_fact:
        test_var: '1'
        req_var: '4'

    - name: "Test multi run of task"
      include_tasks: ./includes/tasks.yml
      register: versions_result
      until: test_var is version(req_var, '<')
      retries: 5

here I am expecting parent.yml tasks to run multiple times but it only run once. Could some one point out what I am doing wrong and how to run a task multiple times until a condition is met.

Cheers,


Solution

  • One way to include_tasks multiple times is to loop over the range of numbers till it reaches the required number. However as you expect the "parent" playbook will not be run multiple times, the tasks file will be.

    Consider the below example:

    Through my main playbook parent.yml, I would like to run tasks1.yml multiple times (as defined in set_fact).

      tasks:
      - set_fact:
          num: 1
          req_num: 4
      - include_tasks: tasks1.yml
        loop: "{{ range(num, req_num + 1)|list }}"
    

    And in my tasks1.yml, I have a simple debug message:

    - debug:
        msg: "Run {{ item }}"
    

    Includes tasks1.yml 4 times and gives below output when I run ansible-playbook parent.yml:

    TASK [include_tasks] ******************************************************************************************************************************************************************
    included: /home/user/tasks1.yml for localhost
    included: /home/user/tasks1.yml for localhost
    included: /home/user/tasks1.yml for localhost
    included: /home/user/tasks1.yml for localhost
    
    TASK [debug] **************************************************************************************************************************************************************************
    ok: [localhost] => 
      msg: Run 1
    
    TASK [debug] **************************************************************************************************************************************************************************
    ok: [localhost] => 
      msg: Run 2
    
    # ...goes till "Run 4"