Bootstrap FreeKB - Ansible - Loop through list using the with_list parameter
Ansible - Loop through list using the with_list parameter

Updated:   |  Ansible articles

The following parameters can be used to loop through each item in an array / list.

The with_list parameter is equivelant to the loop parameter, and can be used interchangeably. In this example, the debug module and with_list 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.

The loop parameters will, by default, use the {{ item }} variable for each item in the list. Or, the loop_control parameter with loop_var can be used to define your own variable for each item in the list.

- name: "loop through the 'fruit' array"
  debug: 
    msg: "{{ item }}"
  with_list:
    - apple
    - banana
    - orange
    - grapes

 

The loop parameter could be used instead of the with_list parameter.

- name: "loop through the 'fruit' array"
  debug: 
    msg: "{{ item }}"
  loop:
    - apple
    - banana
    - orange
    - grapes

 

Regardless of whether the loop or with_list parameter are used, the following should be returned.

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"
}

 

SInce the loop parameter is preferred over the with_list parameter, refer to Ansible - loop parameter.

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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