Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double conditional - delete all folders older than 3 days but keep a minimum of 10

Tags:

ansible

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
like image 419
Sanders54 Avatar asked Aug 24 '17 07:08

Sanders54


1 Answers

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 }}"
like image 150
zigarn Avatar answered Oct 22 '22 20:10

zigarn