How to Delete Files and Folders in a Directory using Ansible
If you need to delete files and folders in a directory using Ansible, then you can do the following:
- name: Delete content & entire directory
file:
state: absent
path: /some/directory/path/
This removes the entire directory and everything inside it. I use this in deployment playbooks to clean up old release artifacts before copying new ones. The state: absent directive is idempotent — running it multiple times won’t cause errors if the directory is already gone.
If you only want to delete the contents but keep the directory itself, you’ll need a different approach: use find module to list the contents first, then loop over them with file: state=absent. There’s also the shell module with rm -rf /path/* as a quick alternative, though it’s less “Ansible-like”.