Ansible Task Looping Directives: Difference between revisions
Jump to navigation
Jump to search
(→loop) |
(→Loops) |
||
Line 5: | Line 5: | ||
=Overview= | =Overview= | ||
=Loops= | =Loops= | ||
==<tt>loop</tt>== | |||
Takes a list for the task to iterate over, saving each list element into the <code>item</code> variable (configurable via <code>[[#loop_control|loop_control]]</code>) | |||
<syntaxhighlight lang='yaml'> | |||
jdks: | |||
- corretto8 | |||
- corretto11 | |||
... | |||
- name: Multiple items in a loop | |||
homebrew_cask: | |||
name: "{{ item }}" | |||
state: present | |||
loop: "{{ jdks }}" | |||
</syntaxhighlight> | |||
An existing variable's field that reference a list can be used: | |||
<syntaxhighlight lang='yaml'> | |||
- name: Debug | |||
debug: | |||
var: item.path | |||
loop: "{{ some_task_result.files }}" | |||
</syntaxhighlight> | |||
==<tt>with_items</tt>== | ==<tt>with_items</tt>== | ||
An iterator whose elements can be accessed with <code>item.<element></code>. The content to iterate over may came from in-line declaration or from a variable. | An iterator whose elements can be accessed with <code>item.<element></code>. The content to iterate over may came from in-line declaration or from a variable. |
Revision as of 05:18, 5 July 2021
External
Internal
Overview
Loops
loop
Takes a list for the task to iterate over, saving each list element into the item
variable (configurable via loop_control
)
jdks:
- corretto8
- corretto11
...
- name: Multiple items in a loop
homebrew_cask:
name: "{{ item }}"
state: present
loop: "{{ jdks }}"
An existing variable's field that reference a list can be used:
- name: Debug
debug:
var: item.path
loop: "{{ some_task_result.files }}"
with_items
An iterator whose elements can be accessed with item.<element>
. The content to iterate over may came from in-line declaration or from a variable.
In-line declaration:
- name: debug
debug:
msg: "{{ item }}"
with_items:
- A
- B
- C
Variable:
- name: Find some files
find:
paths: '/some/dir'
patterns: '*.txt'
register: find_result
- name: debug
debug:
msg: "{{ item }}"
with_items: "{{ find_result.files | json_query('[*].path') }}"
loop_control
with_<lookup_plugin>
The same as loop
but adds the output of any lookup plugin to generate the item list.