Delete files older than x days inside folder of folders

Viewed 6651

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

2 Answers

As of now I've found three or four errors in the playbook

  1. Use become or make sure its set in config/inventory if you need to remove the files which you do not have permission.
  2. paths: Should be fully qualified path and no wild cards accepted in the path I believe It should be paths: /data/log
  3. 'recursive' is not correct option with find module. It should be 'recurse'
  4. There is an unneeded '(' in the last line.

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

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