双重条件 - 删除超过3天的所有文件夹,但保持最少10个

时间:2017-08-24 07:43:57

标签: ansible

我有一些问题,我似乎无法克服。我有一个包含大量文件夹的文件夹。我想删除超过三天的所有文件夹,但我想保留至少10个文件夹。

我想出了这个半工作代码,我想知道如何解决这个问题。

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

1 个答案:

答案 0 :(得分:4)

您只需要过滤超过3天的文件列表:

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