Ansible - file module (delete remove files directories rmdir)

If you are not familiar with modules, check out Ansible - Getting Started with Modules.

The file module with state: absent can be used to remove a file or a directory (and the contents of the directory) on a managed node (e.g. the target system). If the file or directory does not exist, the task will be skipped, thus there is no need to check if the file or directory exists.

remove / delete a single file or directory

In this example, /tmp/foo will be removed if it exists. It does not matter if /tmp/foo is a file or directory. Ansible should remove /tmp/foo regardless if /tmp/foo is a file or a directory. Be aware that if /tmp/foo is a directory, all of the contents of /tmp/foo will be removed.

- name: delete /tmp/foo
    path: /tmp/foo
    state: absent


Permission denied

If permission denied is returned when running the play, refer to our article on resolving permission denied.


Successfully removed

If the file or directory was successfully removed, the play should indicate changed.

TASK [delete /tmp/foo]
changed: []


Directory not removed

If the file or directory was not removed, the play should indicate ok. This is the expected behavior if the file or directory does not exist.

TASK [delete /tmp/foo]
ok: []


remove / delete multiple files or directories

The with_items parameter can be used to remove multiple files or directories.

- name: remove /tmp/foo and /tmp/bar
    path: "{{ items }}"
    state: absent
    - /tmp/foo
    - /tmp/bar


remove files or directories that match a pattern

Let's say you want to remove any file or directory that contains "foo". In this example, the find module with the patterns parameter is used to store all of the files that contain "foo" in the "out" variable.

- name: store all of the files and directories in the /tmp directory that contain 'foo' in the 'out' variable
    paths: /tmp
    patterns: (?i).*foo.*
    use_regex: true
  register: out


Now, you can use the with_items parameter to loop through the out variable, and remove them. Note that the loop_control parameter is optional, not required.

- name: remove files and directories containing 'foo' in the /tmp directory
    path: "{{ item.path }}"
    state: absent
  with_items: "{{ out.files }}"
    label: "{{ item.path }}"


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 f197a in the box below so that we can be sure you are a human.


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