Using ansible, how would I delete all items except for a specified set in a directory

ansible

I can, of course, use a shell command, but I was hoping there was an ansible way to do this, so that I can get the "changed/unchanged" response.

Best Answer

Here's how I do it:

- name: Capture files to delete
  find:
    paths: /path/to/directory
    file_type: file
    excludes: 
      - "myfirst.file"
      - "mysecond.file"
  register: found_files

- name: Delete files
  file:
    path: "{{ item.path }}"
    state: absent
  with_items: "{{ found_files['files'] }}"