Ansible - Looping through an Array Dictionary List

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

IMPORTANT

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.

vars:
  fruit: [ apple, banana, orange, grapes ]

 

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

- name: output the contents of the 'fruit' array
  debug: 
    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: [server1.example.com] => {
    "msg": [
        "apple",
        "banana",
        "orange",
        "grapes"
    ]
}

 

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
  debug: 
    msg: "{{ item }}"
  loop: "{{ fruit }}"

 

Which should return the following.

TASK [loop through the 'fruit' array] 
ok: [server1.example.com] => (item=apple) => {
    "msg": "apple"
}
ok: [server1.example.com] => (item=banana) => {
    "msg": "banana"
}
ok: [server1.example.com] => (item=orange) => {
    "msg": "orange"
}
ok: [server1.example.com] => (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
  find:
    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
  debug:
    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.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |