Skip to content

Remove unwanted Files in a Directory#

Problem#

How o make sure 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
      with_items: "{{ 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.

See also#