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). 


remove / delete a single file

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

- name: delete foo.txt
  file:
    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
  file:
    path: "{{ items }}"
    state: absent
  with_items:
    - /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
  find:
    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
  file:
    path: "{{ item.path }}"
    state: absent
  with_items: "{{ out.files }}"
  loop_control:
    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 286c3 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |