Delete files resulting from a search

Hi,

I have yet to wrap my head around the way Ansible does some things.

I have the following task using the find module:

- name: Find existing desktop menu files on target system
  ansible.builtin.find:
    paths: /var/lib/flatpak/app
    recurse: true
    patterns: 'org.darktable.Darktable.desktop'
  register: find_result

I included a little debug task to see what this returns:

- name: Show results
  ansible.builtin.debug:
    var: find_result

How can I tell Ansible to simply delete the resulting files ? (Adding a rule like “if there are any” to avoid errors when repeating the play?)

Thanks & cheers !

ansible.builtin.file module, use parameter state with value of absent:
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html#parameters

2 Likes

I created a role for this GitHub - bcoca/ansible-tidy: tidy role

3 Likes

I use ansible.builtin.find and ansible.builtin.file for this, there is an example here, you could try something like this:

- name: Delete files found
  ansible.builtin.file:
    path: "{{ file.path }}"
    state: absent
  loop: "{{ find_result.files }}"
  loop_control:
    loop_var: file
  when: find_results.matched > 0

To debug the files to delete you could use:

- name: Debug files found
  ansible.builtin.debug:
    var: file.path
  loop: "{{ find_result.files }}"
  loop_control:
    loop_var: file
  when: find_results.matched > 0
1 Like