Question:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
--- - 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 |
Answer:
You just have to filter your list of files older than 3 days:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
--- - 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 }}" |