Ok, that was a bit arbitrary. In fact, if you're doing something that is inventory related you might just want to write a dynamic
inventory source instead (see :doc:`intro_dynamic_inventory`), but this can be occasionally useful in quick-and-dirty implementations.
Should you ever need to execute a command remotely, you would not use the above method. Instead do this::
- name: Example of looping over a REMOTE command result
shell: /usr/bin/something
register: command_result
- name: Do something with each result
shell: /usr/bin/something_else --param {{ item }}
with_items: command_result.stdout_lines
.._indexed_lists:
Looping Over A List With An Index
`````````````````````````````````
.. versionadded: 1.3
If you want to loop over an array and also get the numeric index of where you are in the array as you go, you can also do that.
It's uncommonly used::
- name: indexed loop demo
debug: msg="at array position {{ item.0 }} there is a value {{ item.1 }}"
with_indexed_items: some_list
.._flattening_a_list:
Flattening A List
`````````````````
In rare instances you might have several lists of lists, and you just want to iterate over every item in all of those lists. Assume
a really crazy hypothetical datastructure::
----
# file: roles/foo/vars/main.yml
packages_base:
- [ 'foo-package', 'bar-package' ]
packages_apps:
- [ ['one-package', 'two-package' ]]
- [ ['red-package'], ['blue-package']]
As you can see the formatting of packages in these lists is all over the place. How can we install all of the packages in both lists?::
- name: flattened loop demo
yum: name={{ item }} state=installed
with_flattened:
- packages_base
- packages_apps
That's how!
.._writing_your_own_iterators:
Writing Your Own Iterators
``````````````````````````
While you ordinarily shouldn't have to, should you wish to write your own ways to loop over arbitrary datastructures, you can read `developing_plugins` for some starter
information. Each of the above features are implemented as plugins in ansible, so there are many implementations to reference.