If you are not familiar with modules, check out Ansible - Getting Started with Modules.
The file module with state: absent is used to delete a file or directory. In this example, the /tmp/example directory and every file and directory below /tmp/example will be removed if it exists.
If you get rmtree failed: [Errno 13] Permission denied, check out my article Ansible - Resolve "rmtree failed: [Errno 13] Permission denied".
--- - hosts: localhost tasks: - name: rmdir /tmp/example ansible.builtin.file: path: /tmp/example state: absent ...
If the directory was successfully removed, the play should indicate changed.
TASK [rmdir /tmp/example] changed: [localhost]
Directory not removed
If the directory was not created or, the play should indicate ok. This is the expected behavior if the directory already exists. If the directory already exists, the directory will not be created, overwritten, or changed.
TASK [rmdir /tmp/example] ok: [server1.example.com]
You may also want to use x.stat.exists to determine if the directory exists, and x.stat.isdir to determine if the object is a directory.