Bootstrap FreeKB - Ansible - loop_control loop_var (set custom item)
Ansible - loop_control loop_var (set custom item)

Updated:   |  Ansible articles

Let's say you have the following task. Notice in this example that the item variable is used. The loop parameters loop, with_items, and with_list will, by default, use the {{ item }} variable for each item in the list.

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

 

Sometimes, this may cause warning The loop variable 'item' is already in use to be returned.

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.

 

The loop_control parameter with loop_var can be used to define your own variable for each item in the list. In this example, the files variable is used for each item in the list instead of the {{ item }} variable.

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