在条件下使用文件夹大小

Use folder size in conditional

我只想删除大于特定大小的文件夹。不幸的是,我无法使用 stat 模块获得想要的结果。

尝试:

---
- hosts: pluto
  tasks:
    - stat:
        path: /home/ik/.thunderbird
      register: folder
    - name: Remove .thunderbird folder on host if folder size > 100MiB
      file:
        path: /home/ik/.thunderbird
        state: absent
      when: folder.stat.size > 100000000

错误:

fatal: [pluto]: FAILED! => {"msg": "The conditional check 'folder.size > 100000000' failed. The error was: error while evaluating conditional (folder.size > 100000000): 'dict object' has no attribute 'size'\n\nThe error appears to be in '/home/ik/Playbooks/susesetup.yml': line 12, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n      register: folder\n    - name: Remove .thunderbird folder on host if folder size > 100MiB\n      ^ here\n"}

我该如何解决这个问题?

stat 模块为文件夹返回的 size 属性 而不是 告诉您文件夹内容的大小!它只报告目录条目的大小,这可能取决于许多因素,例如目录中包含的文件数。

如果您要计算文件夹中包含的数据量,您将需要 运行 du 或类似的命令。以下获取文件夹大小,以 1024 块为单位:

---
- hosts: localhost
  gather_facts: false
  tasks:
    - command: du -sk /path/to/some/directory
      register: folder_size_raw

    - set_fact:
        folder_size: "{{ folder_size_raw.stdout.split()[0] }}"

    - debug:
        msg: "{{ folder_size }}"