Ansible - Looping through an Array Dictionary List

The following parameters can be used to loop through an array / dictionary / list.


When possible, Ansible recommends using the loop parameter, as the loop parameter is meant to supercede the with_items option.


In this example, an array of fruit is creating using the vars plugin.

  fruit: [ apple, banana, orange, grapes ]


The debug module can be used to output the entire array.

- name: output the contents of the 'fruit' array
    var: fruit


Which should return the following. Notice the [ ] character, which means this is an array. The values are wrapped in double quotes, meaning the values are strings.

TASK [output the contents of the 'fruit' array]
ok: [] => {
    "msg": [


In this example, the debug module and loop parameter are used to loop over an array of fruit (a fruit loop!). Notice the double curley braces {{ ... }}. Jinja2 uses double curley braces for variables.

- name: loop through the 'fruit' array
    msg: "{{ item }}"
  loop: "{{ fruit }}"


Which should return the following.

TASK [loop through the 'fruit' array] 
ok: [] => (item=apple) => {
    "msg": "apple"
ok: [] => (item=banana) => {
    "msg": "banana"
ok: [] => (item=orange) => {
    "msg": "orange"
ok: [] => (item=grapes) => {
    "msg": "grapes"


Often, you will find yourself in a situation where JSON formatted data is being stored in a variable. In this example, the find module is being used to store the files below the /tmp directory in a variable named "out".

- name: store the contents of the /tmp directory in the 'out' variable
    paths: /tmp
  register: out


Assuming the /tmp directory contains two (or more) files or directories, you will want to loop over the "out" variable, like this.

- name: display the contents of the 'out' variable
    msg: "{{ item }}"
  with_items: "{{ out.files }}"


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 4be45 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |