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

Updated:   |  Ansible articles

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

In this example, the debug module and with_indexed_items parameter are used to loop over an array and return the index number and value of each item.

---
- hosts: localhost
  tasks:
  - name: loop through items
    debug: 
      var: item
    with_indexed_items:
      - apple
      - banana
      - orange
      - grapes
...

 

Which should return the following.

ok: [localhost] => (item=[0, u'apple']) => {
    "ansible_loop_var": "item", 
    "item": [
        0, 
        "apple"
    ]
}
ok: [localhost] => (item=[1, u'banana']) => {
    "ansible_loop_var": "item", 
    "item": [
        1, 
        "banana"
    ]
}
ok: [localhost] => (item=[2, u'orange']) => {
    "ansible_loop_var": "item", 
    "item": [
        2, 
        "orange"
    ]
}
ok: [localhost] => (item=[3, u'grapes']) => {
    "ansible_loop_var": "item", 
    "item": [
        3, 
        "grapes"
    ]
}

 

item.0 can be used to get the index number of each item.

---
- hosts: localhost
  tasks:
  - name: loop through items
    debug: 
      msg: "{{ item.0 }}"
    with_indexed_items:
      - apple
      - banana
      - orange
      - grapes
...

 

Which should return the following

ok: [localhost] => (item=[0, u'apple']) => {
    "msg": "0"
}
ok: [localhost] => (item=[1, u'banana']) => {
    "msg": "1"
}
ok: [localhost] => (item=[2, u'orange']) => {
    "msg": "2"
}
ok: [localhost] => (item=[3, u'grapes']) => {
    "msg": "3"
}

 

item.1 can be used to get the value of each item.

---
- hosts: localhost
  tasks:
  - name: loop through items
    debug: 
      msg: "{{ item.1 }}"
    with_indexed_items:
      - apple
      - banana
      - orange
      - grapes
...

 

Which should return the following.

ok: [localhost] => (item=[0, u'apple']) => {
    "msg": "apple"
}
ok: [localhost] => (item=[1, u'banana']) => {
    "msg": "banana"
}
ok: [localhost] => (item=[2, u'orange']) => {
    "msg": "orange"
}
ok: [localhost] => (item=[3, u'grapes']) => {
    "msg": "grapes"
}

 




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 d059aa in the box below so that we can be sure you are a human.