Ansible变量校验:如何阻止record_name输入带域名的完整名称
Ansible变量输入校验:禁止含点号的完整域名
要实现当record_name包含点号(即完整域名格式,如test.example.com)时终止剧本,最直接的方式是用assert模块或者fail模块,没必要绕set_fact,以下是具体实现:
方法1:使用assert模块(推荐)
assert模块专门用于断言校验,条件不满足时直接终止剧本,示例如下:
--- - name: Validate record_name input hosts: localhost vars_prompt: - name: record_name prompt: "Enter record name (do not use full domain with dots)" private: no tasks: - name: Ensure record_name is not a full domain assert: that: - "." not in record_name fail_msg: "Aborting: record_name '{{ record_name }}' is a full domain (contains dot), please enter a simple name without dots." success_msg: "record_name '{{ record_name }}' passed validation."
解释:
that里的"." not in record_name直接检查变量中是否包含点号- 如果断言失败,
fail_msg会输出错误信息并终止剧本;校验通过则输出success_msg(可选)
方法2:使用fail模块
如果更倾向于显式触发失败,也可以用fail模块配合when条件:
--- - name: Validate record_name input hosts: localhost vars_prompt: - name: record_name prompt: "Enter record name (do not use full domain with dots)" private: no tasks: - name: Check for full domain in record_name fail: msg: "Error: record_name '{{ record_name }}' contains a dot - full domains are not allowed." when: "." in record_name
解释:
- 当
record_name包含点号时,when条件成立,执行fail任务终止剧本 - 若条件不成立,该任务跳过,剧本继续执行
关于你之前的set_fact + error_when报错问题
set_fact的作用是设置变量,本身不会主动触发失败,error_when是用来标记任务执行成功但结果不符合预期时视为失败,但这种组合不适合做输入校验——因为set_fact只要语法正确就会成功,error_when的条件判断在这里逻辑绕且容易出错,直接用上面的assert或fail模块才是正确的做法。
内容的提问来源于stack exchange,提问作者liquid
相关产品推荐
相关产品推荐

