FreeKB - Ansible file module (delete remove file)
Ansible - file module (delete remove file)

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

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

remove / delete a single file

In this example, the /tmp/foo.txt file will be removed if it exists.

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


remove / delete multiple files

The with_items parameter can be used to remove multiple files.

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


remove files that match a pattern

Let's say you want to remove any files 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 "foo" variable.

- name: store all of the files 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 all of the files in the foo variable, and remove them. Note that the loop_control parameter is optional, not required.

- name: remove files 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 bb5d5 in the box below so that we can be sure you are a human.


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