删除文件夹中超过 x 天的文件

问题描述 投票:0回答:3

我想使用 ansible 删除旧文件。我有一个数据日志文件夹,在这个文件夹中我有多个目录:

/data/log/folder1/
/data/log/folder2/
....

我尝试使用这个 ansible 剧本:

---
- hosts: all
  tasks:
    - name: find all files that are older than 10 days
      find:
        paths: /data/log/*/
        age: 10d
        recursive: yes
      register: filesOlderThan10
    - name: remove older than 10
      file:
        path: "{{ item.path }}" 
        state: absent
      with_items: "{{ (filesOlderThan10.files }}"

当我启动剧本时,没有任何内容被删除,我不确定是否可以使用此语法/data/log/*/
因此,我正在寻找改进此代码的建议

ansible delete-file
3个回答
12
投票

到目前为止,我在剧本中发现了三四个错误

  1. 如果您需要删除您没有权限的文件,请使用become或确保其在config/inventory中设置。
  2. 路径:应该是完全合格的路径,并且我认为路径中不接受通配符 它应该是路径:/data/log
  3. “递归”对于查找模块来说不是正确的选项。应该是“递归”
  4. 最后一行有一个不需要的“(”。

下面的代码应该可以工作

---
- hosts: all
  tasks:
    - name: find all files that are older than 10 days
      find:
        paths: /data/log
        age: 10d
        recurse: yes
      register: filesOlderThan10
    - name: remove older than 10
      file:
        path: "{{ item.path }}" 
        state: absent
      with_items: "{{ filesOlderThan10.files }}"

4
投票

我之前一直使用带有 find 的 cronjob,并决定转向 AWX,在检查了此处和其他文章后,我提出了以下建议。正如我们所说,已经过测试和工作。 第一个任务将所有超过 3 天的文件注册为 matched_files_dirs。 第二个任务将它们删除。 可以完成这项工作,但比在 Linux 上运行 cron 慢。

---
- name: Cleanup
  hosts: linux
  gather_facts: false
  tasks:
  - name: Collect files
    shell: find /opt/buildagent/system*/target_directory -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 }}"

0
投票

我就是这样做的

- name: clean up the /data/log/ directory and its subfolders - delete files older than 10d
  block:

    # this one detects all files-inside-folders inside /data/log/ and stores them in old_files variable
    - name: Select files - eventually older than "{{ retention }}"
      find:
        paths: "/data/log/"
        age: 10d
        recurse: yes
      register: old_files

    # uncomment this to see python printing the detected files which will be deleted
    # - name: debug using python - show old_files 
    #   command: /usr/bin/python
    #   args:
    #     stdin: |
    #       # coding=utf-8

    #       print(" ")

    #       print("""
    #       old_files:
    #       {{ old_files }}

    #       old_files paths:
    #       {{ old_files.files | map(attribute='path') | list }}
    #       """)

    #       print(" ")


    - name: Delete the detected files
      file:
        path: "{{ item }}"
        state: absent
      with_items: "{{ old_files.files | map(attribute='path') | list }}"  # make a list of the paths of the detected files
© www.soinside.com 2019 - 2024. All rights reserved.