Reputation: 601
I would like to use ansible to delete older files. I have a data log folder, inside this folder I have multiple directories:
/data/log/folder1/
/data/log/folder2/
....
I tried to use this ansible playbook :
---
- 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 }}"
When I launch the playbook nothing is deleted, I'm not sure that I could use this syntax /data/log/*/
I am therefore looking for suggestions to improve this code
Upvotes: 5
Views: 15771
Reputation: 4234
This is how I would do it
- 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
Upvotes: 1
Reputation: 103
I've been previously using a cronjob with find and decided to move to AWX and after checking here and other articles, I've come up with the following. Tested and working as we speak. First task registers all files older than 3 days as being matched_files_dirs. Second task removes them. Does the job but is slower than just running cron on linux.
---
- 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 }}"
Upvotes: 4
Reputation: 226
As of now I've found three or four errors in the playbook
The below code should work
---
- 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 }}"
Upvotes: 12