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

如何用Ansible find模块查找并删除指定目录下的空文件?

用Ansible内置模块实现指定空文件的查找与删除

要替代这条Bash命令:find /etc/apparmor.d/libvirt/ -type f -name 'libvirt-*' -empty -delete,直接用find模块的size参数没法精准匹配0字节文件(因为该参数仅支持>=或<=的逻辑),可以通过先获取匹配文件的完整信息,再筛选size为0的文件进行删除的方式实现,完全依赖Ansible内置模块,无需使用shell:

---
- name: 清理指定目录下的空文件
  hosts: 你的目标主机组
  tasks:
    - name: 查找目录下符合命名模式的所有文件
      ansible.builtin.find:
        path: /etc/apparmor.d/libvirt/
        file_type: file
        patterns: 'libvirt-*'
      register: found_files

    - name: 删除其中的0字节空文件
      ansible.builtin.file:
        path: "{{ item.path }}"
        state: absent
      loop: "{{ found_files.files }}"
      when: item.size == 0

关键说明:

  • 第一步的find模块会返回所有符合libvirt-*命名规则的文件,包含每个文件的size属性;
  • 第二步通过loop遍历所有找到的文件,用when条件精准筛选出size等于0的空文件,再用file模块删除;
  • 这种方式利用了Ansible模块返回的结构化数据,后续如果需要添加额外筛选条件(比如修改时间、权限等),直接在when里扩展即可,比shell命令更灵活可控。

内容的提问来源于stack exchange,提问作者Kaan Bereketli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:12:42