Ansible在hosts字段使用动态变量出现变量未定义报错
问题描述
我想写一个带两个hosts段的Ansible playbook,因为应用里没有主机名信息,只能通过IP触发,需要先获取对应机器的主机名存成变量,后续任务直接用这个主机名,不用给每个任务加when条件。
原Playbook代码如下:
--- - hosts: all tasks: - name: 获取主机名并保存为变量 shell: hostname register: host_name when: ansible_host == "x.x.x.x" # 将由我的应用填充 - hosts: "{{ host_name.stdout }}" tasks: - name: 使用变量作为主机名 shell: whoami
执行后报错:
ERROR! The field 'hosts' has an invalid value, which includes an undefined variable. The error was: 'host_name' is undefined
解决方案
报错原因
Ansible是先解析整个playbook的结构(包括所有hosts字段),再执行各个play的任务。host_name是第一个play执行任务时才注册的变量,解析阶段根本不存在,所以第二个play的hosts字段引用它会直接报错。
正确写法:用add_host动态添加主机到临时组
通过add_host模块把目标主机添加到内存中的临时组,第二个play直接针对这个组执行,就能避开变量解析时机的问题。
修改后的Playbook:
--- - hosts: all tasks: - name: 获取目标主机的主机名 shell: hostname register: host_name when: ansible_host == "x.x.x.x" - name: 将目标主机添加到临时组target_hosts add_host: name: "{{ host_name.stdout }}" groups: target_hosts # 只在变量存在时执行,避免无匹配IP时报错 when: host_name is defined and host_name.stdout is defined - hosts: target_hosts tasks: - name: 在目标主机执行任务 shell: whoami
补充说明
add_host会把主机添加到Ansible的临时inventory里,第二个play就能直接识别这个组- 加上
when判断变量是否存在,防止当没有匹配到指定IP时,第二个play因为空组而跳过(或者报错,取决于你的配置)
内容的提问来源于stack exchange,提问作者cozpolat
相关产品推荐
相关产品推荐

