mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-05-08 22:33:25 +00:00
Make the loop variable (item by default) settable per task
Required for include+with* tasks which may include files that also have tasks containing a with* loop. Fixes #12736
This commit is contained in:
@@ -544,27 +544,57 @@ There is also a specific lookup plugin ``inventory_hostname`` that can be used l
|
||||
|
||||
More information on the patterns can be found on :doc:`intro_patterns`
|
||||
|
||||
.. _loops_and_includes:
|
||||
.. _loop_control:
|
||||
|
||||
Loops and Includes
|
||||
``````````````````
|
||||
Loop Control
|
||||
````````````
|
||||
|
||||
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, an included task that has its 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 an alias to the outer one.::
|
||||
.. versionadded: 2.1
|
||||
|
||||
In 2.0 you are again 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.
|
||||
Ansible by default sets the loop variable `item` for each loop, which causes these nested loops to overwrite the value of `item` from the "outer" loops.
|
||||
As of Ansible 2.1, the `loop_control` option can be used to specify the name of the variable to be used for the loop::
|
||||
|
||||
# main.yml
|
||||
- include: test.yml outer_loop="{{outer_item}}"
|
||||
with_items:
|
||||
- 1
|
||||
- 2
|
||||
- 3
|
||||
loop_control:
|
||||
loop_var: outer_item
|
||||
|
||||
# inner.yml
|
||||
- debug: msg="outer item={{outer_loop}} inner item={{item}}"
|
||||
with_items:
|
||||
- a
|
||||
- b
|
||||
- c
|
||||
|
||||
.. note:: If Ansible detects that the current loop is using a variable which has already been defined, it will raise an error to fail the task.
|
||||
|
||||
|
||||
.. _loops_and_includes_2.0:
|
||||
|
||||
Loops and Includes in 2.0
|
||||
`````````````````````````
|
||||
|
||||
Because `loop_control` is not available in Ansible 2.0, when using an include with a loop you should use `set_fact` to save the "outer" loops value
|
||||
for `item`::
|
||||
|
||||
# main.yml
|
||||
- include: test.yml
|
||||
with_items:
|
||||
- 1
|
||||
- 2
|
||||
- 3
|
||||
|
||||
in test.yml::
|
||||
# inner.yml
|
||||
- set_fact:
|
||||
outer_item: "{{item}}"
|
||||
|
||||
- set_fact: outer_loop="{{item}}"
|
||||
|
||||
- debug: msg="outer item={{outer_loop}} inner item={{item}}"
|
||||
- debug:
|
||||
msg: "outer item={{outer_item}} inner item={{item}}"
|
||||
with_items:
|
||||
- a
|
||||
- b
|
||||
|
||||
Reference in New Issue
Block a user