You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现当文件大小为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 08:32:39