13

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.

Christian Goetze
  • 2,254
  • 3
  • 34
  • 51

2 Answers2

16

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'] }}"
Lars Nyström
  • 5,786
  • 3
  • 32
  • 33
2

In addition to what you found per your comment, if you end up needing to do a shell command, you can use the command module with removes parameter (doc). It will skip the step if the file already (doesn't) exist, which will prevent it from reporting a changed on the step. You'll still need to iterate over a list like in the other answer, however.

Community
  • 1
  • 1
Jake Kreider
  • 950
  • 7
  • 12