Ansible:循环变量'item'已被使用

Ansible : The loop variable 'item' is already in use

我想 运行 在 ansible 中执行类似于以下内容的任务。

#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'

我希望输出将 my_var 打印为剧本中循环的第一次迭代中的值 1 和第二次迭代中的值 2。但相反,它正在打印主机名

# 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"
    ]
}

提前致谢

有两个问题:

  1. 在剧本中,任务包含在一个循环中,循环变量名称为 item,包含的任务也有一个循环和 默认变量名又是 item。这就是警告的原因 消息并使用 loop_control.

  2. 解决该问题
  3. my_var: item 赋值需要采用 my_var: "{{ item }}" 格式才能正确赋值。

两次更正后,剧本将如下所示。

  - 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