Bootstrap FreeKB - Ansible - Remove a directory using the file module
Ansible - Remove a directory using the file module

Updated:   |  Ansible articles

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 you want to empty out a target directory, you'll probably want to use the find module to get list of files and directories in the target directory and to then remove the files and directories.

---
- hosts: all
  tasks:
  - ansible.builtin.find:
      paths: /tmp
      file_type: any
    register: out

  - name: empty out the /tmp directory
    ansible.builtin.file:
      path: "{{ item.path }}"
      state: absent
    with_items: "{{ out.files }}"
    loop_control:
      label: "{{ item.path }}"
...

 

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




Did you find this article helpful?

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



Comments


Add a Comment


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