【问题标题】:Ansible : The loop variable 'item' is already in useAnsible:循环变量“item”已在使用中
【发布时间】:2020-06-08 23:20:15
【问题描述】:

我想在 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,在 playbook 循环的第二次迭代中打印为 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"
    ]
}

提前致谢

【问题讨论】:

    标签: ansible ansible-2.x


    【解决方案1】:

    有两个问题:

    1. 在 playbook 中,任务包含在循环变量名称为 item 的循环中,并且包含的​​任务也有一个循环和 默认变量名称再次为item。这就是为什么警告 消息并使用loop_control解决。

    2. 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 2015-01-02
      • 1970-01-01
      • 2015-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多