2

I want to remove a folder only if the size is larger than a certain size. Unfortunately I can't achieve the wanted result with the stat module.

Attempt:

---
- 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

Error:

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"}

How can I solve this issue?

aardbol
  • 2,147
  • 3
  • 31
  • 42
  • 1
    Debug the `folder` var and look at it. The `size` key is not on the first level. It is a subkey of `stat`. => `folder.stat.size` – Zeitounator Jan 25 '20 at 15:05

1 Answers1

3

The size attribute returned by the stat module for a folder does not tell you the size of the folder's contents! It only reports the size of the directory entry, which may depend on a number of factors such as the number of files contained in the directory.

If you're looking to calculate the amount of data contained in a folder, you're going to need to run du or a similar command. The following gets the folder size in 1024 blocks:

---
- 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 }}"
larsks
  • 277,717
  • 41
  • 399
  • 399
  • 1
    I just want to add to that answer that the value of folder_size needs to be converted to an int before a number comparison can be done: `when: folder_size|int < 100000` – aardbol Jan 25 '20 at 15:41