
Welcome to another episode of Feature Spotlight. In today's post, we'll quickly cover the loop keyword being introduced in Ansible 2.5.
Everyone knows the with_* syntax in playbooks.
For example:
- name: Test that with_list works with a list
ping:
data: '{{item}}'
with_list:
- 'Hello World'
- 'Olá Mundo'
In Ansible 2.5, we're introducing loop as a shorter, simpler keyword for playbooks.
Example:
- name: Test that loop works with a manual list
ping:
data: '{{item}}'
loop:
- 'Hello World'
- 'Olá Mundo'
It's a very minute change, and can easily be overlooked when skimming a playbook! However, when writing many lines of tasks in a playbook, why not save some potential muscle fatigue?
Let's be real, even if a playbook accomplishes a whole lot in 10 lines, that's still ten lines!
All joking aside, we wanted to make things simpler. It's much easier to remember loop than with_items or with_list.
The question after this very well may be, "What happens to with_first_found or with_dict or .... etc, etc, etc?
Well the idea here is to abstract out some of the magic that with_* really is.
Example:
- name: Test that loop works with a list via the list lookup
ping:
data: '{{ item }}'
loop: '{{ lookup("list", "Hello World", "Olá Mundo", wantlist=True) }}'
Looking at this example the nitty gritty level we see is that the with_* concept is just a bunch of lookups! As a user and playbook author, the amount of control provided by using lookups and jinja can be leaps and bounds higher than what could be abstracted out as a with_* keyword.
Here's another example[1]:
- name: Test that loop works with a list via the query lookup
ping:
data: '{{ item }}'
loop: '{{ query("list", "Hello World", "Olá Mundo") }}'
Ultimately, that list can keep getting larger and larger. We also notice that most playbooks we come across use with_items. As such, we feel the impact is going to be way low. However, we really want to leave this open for user feedback before we take away with_*. So for now this is in tech preview.
The Engine team is looking for feedback on this. Please keep us posted! Hit us up in #ansible on Freenode or the Ansible project list!
If interested in seeing the playbook I used in my webinar, you can find it here!
END OF LINE.
[1]: query also has a short form of q
loop: '{{ q("list", "Hello World", "Olá Mundo") }}'