Delete all files under a specific directory

Per the documentation (in bold red below), the file module is working as designed:

If directory, all intermediate subdirectories will be created if they do not exist. Since Ansible 1.7 they will be created with the supplied permissions. If file, the file will NOT be created if it does not exist; see the touchvalue or the copy or template module if you want that behavior. If link, the symbolic link will be created or changed. Use hard for hardlinks. If **absent**, directories will be recursively deleted, and files or symlinks will be unlinked. Note that absent will not cause file to fail if the path does not exist as the state did not change. If touch (new in 1.4), an empty file will be created if the path does not exist, while an existing file or directory will receive updated file access and modification times (similar to the way touch works from the command line).

You probably want to use https://docs.ansible.com/ansible/latest/plugins/lookup/fileglob.html?highlight=with_fileglob

So without testing it, it would look something like (run in ‘test mode’ (-C) first!):

  • hosts: all
    tasks:

  • name: remove web dir contents
    file:
    path: “{{ item }}”
    state: absent

with_fileglob:

  • “/tmp/xyz/*”

You probably want to use
https://docs.ansible.com/ansible/latest/plugins/lookup/fileglob.html?highlight=with_fileglob

So without testing it, it would look something like (run in 'test mode'
(-C) first!):

- hosts: all
  tasks:
    - name: remove web dir contents
      file:
        path: "{{ item }}"
        state: absent
    with_fileglob:
      - "/tmp/xyz/*"

lookup plugins only work on Ansible controller aka localhost, not on remote hosts.

My bad, thanks for pointing that out.