Reputation: 103
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
Upvotes: 10
Views: 9194
Reputation: 103
I've been previously using a cronjob with find and decided to move to AWX and after checking here and other articles, I've come up with the following. Tested and working as we speak. First task registers all files older than 3 days as being matched_files_dirs. Second task removes them. Does the job but is slower than just running cron on linux:
find /opt/system*/target_directories -type f -mtime +3 -exec rm {} \;
---
- name: Cleanup
hosts: linux
gather_facts: false
tasks:
- name: Collect files
shell: find /opt/system*/target_directories -type f -mtime +3
register: matched_files_dirs
- name: Remove files
become_user: root
file:
path: "{{ item }}"
state: absent
with_items: "{{ matched_files_dirs.stdout_lines }}"
Upvotes: 0
Reputation: 11625
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 }}"
Upvotes: 14