Ansible 双重条件-删除所有超过3天的文件夹,但至少保留10天

Ansible 双重条件-删除所有超过3天的文件夹,但至少保留10天,ansible,Ansible,我有一点问题似乎无法克服。我有一个文件夹,其中包含大量生成的文件夹。我想删除所有超过三天的文件夹,但我想保留至少10个文件夹 我提出了这个半工作代码,我想要一些如何解决这个问题的建议 --- - hosts: all tasks: # find all files that are older than three - find: paths: "/Users/asteen/Downloads/sites/" age: "3d"

我有一点问题似乎无法克服。我有一个文件夹,其中包含大量生成的文件夹。我想删除所有超过三天的文件夹,但我想保留至少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

您只需筛选超过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 }}"

查找所有三天以前或更新的文件夹;如果是10个或更多,则删除其余部分;否则,查找最近的10个并删除其余的。它应该是
排序(attribute='ctime',reverse=true)
-否则它会保留10个最旧的,并删除新的。此外,即使有10多个文件夹比3天新,也会保留10个比3天旧的文件夹。对于顺序,我改为
[:-10]
,从要删除的文件夹列表中删除最后10个(最新的10个)。关于另一点,根据我从问题中了解到的情况,所有超过3天的文件都必须保留,对于超过3天的文件,只保留10个最新的文件。