Ansible - Remove a directory using the file module

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
  - name: rmdir /tmp/example
      path: /tmp/example
      state: absent


Directory removed

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: []


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.

Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter a0154 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |