One loop over multiple Ansible tasks

66,404

Solution 1

No that's currently not possible. with_items used to work with the include statement in previous versions of Ansible but was unfortunately dropped.

Though it will be brought back in Ansible 2.0, see slide 14/15 of What's New in v2 - AnsibleFest London 2015

enter image description here

You could try to work with the v2 branch from github, the feature should be available in there.

What you can do with 1.9.1 is to move your tasks into a role and reference this role multiple times in your playbook.

Solution 2

An update:

In 2.0 you are able to use with_ loops and task includes (but not playbook includes), this adds the ability to loop over the set of tasks in one shot. There are a couple of things that you need to keep in mind, a included task that has it’s own with_ loop will overwrite the value of the special item variable. So if you want access to both the include’s item and the current task’s item you should use set_fact to create a alias to the outer one.:

- include_tasks: test.yml
  with_items:
    - 1
    - 2
    - 3

in test.yml:

- set_fact: outer_loop="{{item}}"
- debug: msg="outer item={{outer_loop}} inner item={{item}}"
  with_items:
    - a
    - b
    - c

Source: Ansible Docs

Solution 3

I managed to do this by recursively including the same yaml file based on a condition. Here is the gist: https://gist.github.com/ParagDoke/5ddfc3d5647ce9b0110d1b9790090092. Effectively, in your playbook, include a file with some vars:

  - name: Invoke poller
    vars:
      some_condition: '"failed" not in response.content and response.json.status=="running"'
    include_tasks: status-poller.yml

Then in status-poller.yml, include itself:

- include_tasks: includes/status-poller.yml
  when: some_condition
Share:
66,404
AverageWorker
Author by

AverageWorker

Updated on April 28, 2021

Comments

  • AverageWorker
    AverageWorker about 3 years

    I've created an Ansible playbook that creates a cloud instance and then installs some programs on the instance. I want to run this playbook multiple times (without using a bash script). Is it possible to use a loop to loop over those two tasks together (I.E. One loop for two tasks?). All I've been able to find so far is one loop for each individual task

  • RichVel
    RichVel over 7 years
    This has been improved in 2.1, with a feature to specify a different variable name for the outer loop - see loop control section of Ansible docs. There are related improvements in 2.2 in same section.
  • masterial
    masterial almost 6 years
    Dude, what is up with the screenshot?
  • acat
    acat over 2 years
    @masterial if you follow the "what's new in v2" link it looks like it's just a slide from the slide-deck. slides just have a plain black background and don't seem to fill the whole space all the time