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.
Now, if we check the ansible document for the file module, there is no ‘delete’ parameter mentioned. However, we can do a trick that can delete the complete directory and recreate the same using the file module.
Ansible with_items is a keyword which you will use in playbook and provide a list of items under it. These are some scenarios when you have a simple list, an item is list is also a list, each item in list is a combination of few variables. 1. A simple list will be like below and used in a task as follows. 2.
One method to achieve this is by using the shell module. You can use the rm -rf command to delete the files, as you would do in the normal Linux operation. Since we are using rm -rf, it will not throw any error even if the file is not present. - name: Ansible delete file wildcard example shell: rm -rf hello*.txt.
Many other modules support the same options as the file module - including ansible.builtin.copy, ansible.builtin.template, and ansible.builtin.assemble. For Windows targets, use the ansible.windows.win_file module instead.
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'] }}"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With