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

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

 



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 caa9e 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   |