I have a bit of problem I can't seem overcome. I have a folder with a lot of folders that are generated. I want to delete all folders that are older than three days, but I want to keep a minimum of 10 folders.
I came up with this half-working code and I'd like some suggestions how to tackle this.
---
- hosts: all
tasks:
# find all files that are older than three
- find:
paths: "/Users/asteen/Downloads/sites/"
age: "3d"
file_type: directory
register: dirsOlderThan3d
# find all files that are in the directory
- find:
paths: "/Users/asteen/Downloads/sites/"
file_type: directory
register: allDirs
# delete all files that are older than three days, but keep a minimum of 10 files
- file:
path: "{{ item.path }}"
state: absent
with_items: "{{ dirsOlderThan3d.files }}"
when: allDirs.files > 10 and not item[0].exists ... item[9].exists
You just have to filter your list of files older than 3 days:
---
- hosts: all
tasks:
- name: find all files that are older than three
find:
paths: "/Users/asteen/Downloads/sites/"
age: "3d"
file_type: directory
register: dirsOlderThan3d
- name: remove older than 3 days but first ten newest
file:
path: "{{ item.path }}"
state: absent
with_items: "{{ (dirsOlderThan3d.files | sort(attribute='ctime'))[:-10] | list }}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With