Ansible Pilot

Delete file or directory - Ansible module file

How to Delete files or directory with Ansible? I’m going to show you a live demo and some simple Ansible code. I’m Luca Berton and welcome to today’s episode of Ansible Pilot.

Ansible delete file/directory

Today we’re talking about the Ansible module file. The full name is ansible.builtin.file, which means that is part of the collection of modules “builtin” with ansible and shipped with it. It’s a module pretty stable and out for years. It works in a different variety of operating systems. It manages files and file properties. For Windows targets, use the module instead.

Main Parameters

This module has some parameters to perform any tasks. The only required is “path”, where you specify the filesystem path of the file you’re going to edit. The parameter “owner” sets the user that should own the file/directory. The parameter “group” sets the group that should own the file/directory. The parameter “mode” sets the permissions in the UNIX way of the file/directory. The state defines the type of object we are modifying, the default is “file” but we could also handle directories, hardlink, symlink, or only update the access time with the “touch” option. For our use case, we are going to use the “absent” option. Let me also highlight that we could also specify the SELinux properties.


Let’s jump into a real-life playbook on how to delete files or directories with Ansible.

- name: file module demo
  hosts: all
    mypath: "/home/devops/deleteme"
  become: false
    - name: "{{ mypath }}" not present
        path: "{{ mypath }}"
        state: "absent"

code with ❤️ in GitHub


Now you know better the Ansible module win_chocolatey and how you could use it successfully in your playbook to automate your day-to-day activities. Subscribe to the YouTube channel, Medium, Website and Twitter to not miss the next episode of the Ansible Pilot.


Want to keep this project going? Please donate

Follow me

Subscribe not to miss any new releases

September 9, 2021