11

I want to run a task in ansible something similar to the following.

#Task in Playbook

    - name : Include tasks 
      block:
      - name: call example.yml
        include_tasks: "example.yml"
        vars:
          my_var: item
        with_items:
        - [1, 2]
# example.yml

- name: Debug.
  debug:
    msg:
    - "my_var: {{ my_var }}"
  with_inventory_hostnames:
    - 'all'

I expect the output to be printing the my_var as values 1 in the first iteration and 2 in second iteration of the loop in the playbook. But instead, it is printing the hostnames

# Output

TASK [proxysql : Debug.] ************************************************************************************************
 [WARNING]: 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.
ok: [10.1xx.xx.xx] => (item=None) => {
    "msg": [
        "my_var: 10.134.34.34"
    ]
}
ok: [10.1xx.xx.xx] => (item=None) => {
    "msg": [
        "my_var: 10.123.23.23"
    ]
}
ok: [10.1xx.xx.xx] => (item=None) => {
    "msg": [
        "my_var: 10.112.12.12"
    ]
}

TASK [proxysql : Debug.] ************************************************************************************************
 [WARNING]: 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.
ok: [10.1xx.xx.xx] => (item=None) => {
    "msg": [
        "my_var: 10.134.34.34"
    ]
}
ok: [10.1xx.xx.xx] => (item=None) => {
    "msg": [
        "my_var: 10.123.23.23"
    ]
}
ok: [10.1xx.xx.xx] => (item=None) => {
    "msg": [
        "my_var: 10.112.12.12"
    ]
}

Thanks in advance

Kaushik Vijayakumar
  • 755
  • 3
  • 10
  • 19

1 Answers1

22

There are two problems:

  1. In the playbook, tasks are included in a loop that has the loop variable name item and the included task also has a loop and the default variable name is again item. This is why the warning messages and to solve that use loop_control.

  2. my_var: item assignment needs to be in format my_var: "{{ item }}" for correct assignment.

After both the corrections, playbook would look like this.

  - name : Include tasks 
    block:
    - name: call example.yml
      include_tasks: "example.yml"
      vars:
        my_var: "{{ outer_item }}" 
      with_items:
      - [1, 2]
      loop_control:
        loop_var: outer_item
Moon
  • 2,837
  • 1
  • 20
  • 34