Loop: Plays in the future, items in the past

February 15, 2018 by Dylan Silva


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
    data: '{{item}}'
    - 'Hello World'
    - 'Olá Mundo'

In Ansible 2.5, we're introducing loop as a shorter, simpler keyword for playbooks.


- name: Test that loop works with a manual list
    data: '{{item}}'
    - '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.


- name: Test that loop works with a list via the list lookup
    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
    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! 


[1]: query also has a short form of q 

loop: '{{ q("list", "Hello World", "Olá Mundo") }}'



Dylan Silva

Dylan is a Principal Product Manager, Ansible, Red Hat. Starting as an early Core community member in Ansible's early days, Dylan now manages product roadmap for Ansible Core. He’s a self-proclaimed Linux and OSS diehard, Internet geek, and father to #Ansipup Honey. You can follow him on twitter and GitHub at @Thaumos.

rss-icon  RSS Feed