Ansible简单任务中item变量未定义问题求助
问题描述
编写了一段简短的Ansible任务,意图通过with_items循环在指定主机上执行操作,但无论如何都提示'item'变量未定义。任务代码如下:
- name: Prepare for install shell: cmd: "touch /root/testfile" delegate_to: "{{ item }}" with_items: - "host102" - "host103"
始终收到如下错误:
The task includes an option with an undefined variable. The error was: 'item' is undefined. The error appears to be in '/runner/project/roles/
.yml
尝试了多种列表、循环的写法,但'item'始终无法获取数据,请问哪里操作有误?
解决方案
核心错误是把delegate_to写在了shell模块的参数块内部,而非任务的顶级参数层级。Ansible的循环变量item在模块参数的作用域内无法被正确解析,必须将delegate_to提升到与name、shell同级的任务层级。
修正后的代码如下:
- name: Prepare for install shell: "touch /root/testfile" delegate_to: "{{ item }}" with_items: - "host102" - "host103"
另外,如果你使用的是Ansible 2.5及以上版本,官方推荐使用loop替代旧的with_items语法,写法如下:
- name: Prepare for install shell: "touch /root/testfile" delegate_to: "{{ item }}" loop: - "host102" - "host103"
内容的提问来源于stack exchange,提问作者jmt
相关产品推荐
相关产品推荐

