Remove unwanted Files in a Directory#
Problem#
How do we make sure that only expected files are present in a certain directory?
Solution#
cleanup_directory.yaml
- name: Cleanup Directory
hosts: all
vars:
expected_files:
- one.txt
- two.txt
- picture.jpg
in_this_path: /srv/stuff
tasks:
- name: Look what files are there
ansible.builtin.find:
paths: "{{ in_this_path }}"
register: existing
- name: Clean up unknown files
ansible.builtin.file:
path: "{{ item.path }}"
state: absent
when: item.path | basename not in expected_files
loop: "{{ existing.files | default([]) }}"
Explanation#
In the first task, we collect the existing files in the specific directory and register the result. In the second task, we run through the result with the existing files and remove any file whose name is not included in our list of expected files.
Note that ansible.builtin.find returns files only and does not descend into subdirectories by default. Directories in our path therefore survive the cleanup. Use file_type: any and recurse: true if that is not what we want.