如何在Ansible Playbook中未定义target_hosts时输出自定义提示?
实现NTP客户端Ansible Playbook的自定义变量缺失提示
原NTP客户端Playbook
--- - name: NTP client # hosts: all:!ntpserver hosts: "{{ target_hosts }}" roles: - ntp_client
执行命令
ansible-playbook -i hosts.yml -e target_hosts=<目标主机> <Playbook路径> --ask-become-pass
默认报错问题
当未设置target_hosts变量时,Playbook会抛出系统默认错误:
ERROR! The field 'hosts' has an invalid value, which includes an undefined variable. The error was: 'target_hosts' is undefined
需求是替换该默认错误,输出自定义提示:
The variable 'target_hosts' is not set, use e.g. '-e target_hosts=all:!ntpserver'.
(注:已知可通过hosts: "{{ target_hosts | default('all:!ntpserver') }}"设置默认值,但此处需要的是自定义提示而非默认值)
解决方案
通过添加前置检查逻辑,先验证target_hosts变量是否存在,不存在则输出自定义错误信息:
--- - name: 检查target_hosts变量是否已配置 hosts: localhost connection: local gather_facts: no tasks: - name: 验证target_hosts变量存在 fail: msg: "The variable 'target_hosts' is not set, use e.g. '-e target_hosts=all:!ntpserver'." when: target_hosts is undefined - name: NTP客户端配置 hosts: "{{ target_hosts }}" roles: - ntp_client
逻辑说明
- 第一个Play仅在本地(
localhost)执行,无需连接远程主机,关闭gather_facts以提升执行效率 - 通过
when条件判断target_hosts是否未定义,若满足条件则触发fail模块输出自定义提示 - 只有当变量验证通过后,才会执行后续的NTP客户端配置流程
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

