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

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

 



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