Delete content of FileSystem with a lot files using find and file module

I want to delete all files and directories in a filesystem.
I have done a playbook with module find and file.

I get a list of files with the module find and then I delete the list with module file and the option absent.

- name: Gen list
find:
paths: “{{fs1}}”
recurse: yes
file_type: any
excludes: “lost+found”
register: files_to_delete

- name: Delete
file:
path: “{{ item.path }}”
state: absent
loop: “{{ files_to_delete.files }}”

The playbook goes OK.

But now I want to use this playbook in a FileSystem with 15.000 files.

The task that list all files goes very fast, but task that delete file generates a log to each item and the execution time is too big.

I execute the playbook and it doesn´t appear the files that I want to remove. It looks that the remove has been executed, but the playbook it appears generate logs and this is the cause of delay finish.

Is possible not generate the log for each item in the loop?

I don´t want to use shell module with rm -fr command…

Is there other option with ansible to remove all content of a Filesystem with a lot of files and directories?

Hi,

Two obvious options would be

a) use shell module with find . -type f -print0 | xargs -0 rm or similar

b) use command module instead of file module as your second task

  • name: Delete
    command: xargs rm
    args:
    stdin: “{{ files_to_delete | json_query(‘files[*].path’) | join(‘\n’)}}”

That’s not a complete solution, you should perhaps use set_fact first and only do the delete task if there are files to be removed (otherwise it will lead to a no such

file or directory error, which may or may not be desired in your case)

I think option a is safer if you are not completely sure what you’re doing. And uses least amount of memory and network. At least test carefully for edge cases if you choose to go with option b.