Ansible:循环变量“item"已在使用中 [英] Ansible : The loop variable 'item' is already in use
问题描述
我想在 ansible 中运行类似于以下内容的任务.
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'
我希望输出将 my_var
打印为第一次迭代中的值 1 和 playbook 中循环的第二次迭代中的值 2.但相反,它正在打印主机名
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"
]
}
提前致谢
推荐答案
有两个问题:
在剧本中,任务被包含在一个循环中,循环变量名称为
item
,被包含的任务也有一个循环和默认变量名再次是item
.这就是警告的原因消息并使用loop_control
解决该问题.
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 againitem
. This is why the warning messages and to solve that useloop_control
.
my_var: item
分配需要采用 my_var: "{{ item }}"
格式才能正确分配.
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
这篇关于Ansible:循环变量“item"已在使用中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!