我想使用 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/*/
因此,我正在寻找改进此代码的建议
到目前为止,我在剧本中发现了三四个错误
下面的代码应该可以工作
---
- 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 }}"
我之前一直使用带有 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 }}"
我就是这样做的
- 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