Bootstrap FreeKB - Ansible - Resolve "The loop variable 'item' is already in use"
Ansible - Resolve "The loop variable 'item' is already in use"

Updated:   |  Ansible articles

Let's say the following warning is being returned when running a playbook.

The loop variable 'item' is already in use.
You should set the `loop_var` value in the `loop_control` option for the task to something else to avoid variable collisions and unexpected behavior.

 

This often happens when a parent (outer) playbook is looping through a list of items using the loopwith_items, or with_list parameters, and a child (inner) is also looping. 

For example, let's say parent.yml contains the following. Notice parent.yml contains with_items and the {{ item }} variable.

---
- hosts: all
  tasks:
    - name: include roles
      include_role:
        name: touch
        tasks_from: "{{ item }}"
      with_items:
        - foo

 

Let's say foo role contains the following. Notice that foo role also contains with_items and the {{ item }} variable.

- name: touch files
  file:
    path: "{{ item }}"
    state: touch
  with_items:
    - /tmp/foo.txt
    - /tmp/bar.txt

 

As the warning suggests, the loop_control parameter with loop_var can be used to avoid variable collisions. In this example, the foo role could look something like this, where variable files is used instead of items. Or, the loop_control parameter could be applied to parent.yml all the same.

- name: touch files
  file:
    path: "{{ files }}"
    state: touch
  with_items:
    - /tmp/foo.txt
    - /tmp/bar.txt
  loop_control:
    loop_var: files

 




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