如何实现当文件大小为0时让Ansible Playbook执行失败?
Ansible Playbook文件大小为0时未触发失败的解决方法
问题分析
你的Playbook意图是在目标文件大小为0时触发失败,但实际执行中Fail if the filesize 0任务被跳过,核心原因是条件判断的数据类型不匹配:
stat模块返回的file1.stat.size是整数类型- 原代码中使用了字符串
'0'进行相等比较,整数与字符串永远不会相等,导致条件不成立,任务被跳过
修正后的Playbook
将条件中的字符串'0'改为整数0即可触发预期的失败逻辑:
--- - hosts: localhost gather_facts: no tasks: - name: "Get stats of a file" stat: path: files/file1.txt register: file1 - name: "Fail if the filesize is 0" fail: msg: "error: filesize is 0" when: file1.stat.size == 0
验证说明
如果需要确认size字段的类型,可以添加debug任务查看:
- name: Check file size data type debug: msg: "Size value: {{ file1.stat.size }}, Type: {{ file1.stat.size | type_debug }}"
执行后会输出类似Size value: 0, Type: int的结果,明确size是整数类型。
内容的提问来源于stack exchange,提问作者Teemu
相关产品推荐
相关产品推荐

