Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ansible, how would I delete all items except for a specified set in a directory?

Tags:

ansible

I can, of course, use a shell command, but I was hoping there was an ansible way to do this, so that I can get the "changed/unchanged" response.

like image 780
Christian Goetze Avatar asked Nov 27 '13 20:11

Christian Goetze


People also ask

Is it possible to delete a directory in Ansible?

Now, if we check the ansible document for the file module, there is no ‘delete’ parameter mentioned. However, we can do a trick that can delete the complete directory and recreate the same using the file module.

What is the use of list in Ansible with_items?

Ansible with_items is a keyword which you will use in playbook and provide a list of items under it. These are some scenarios when you have a simple list, an item is list is also a list, each item in list is a combination of few variables. 1. A simple list will be like below and used in a task as follows. 2.

How do I delete a wildcard file in Ansible?

One method to achieve this is by using the shell module. You can use the rm -rf command to delete the files, as you would do in the normal Linux operation. Since we are using rm -rf, it will not throw any error even if the file is not present. - name: Ansible delete file wildcard example shell: rm -rf hello*.txt.

Which Ansible modules support the same options as the file module?

Many other modules support the same options as the file module - including ansible.builtin.copy, ansible.builtin.template, and ansible.builtin.assemble. For Windows targets, use the ansible.windows.win_file module instead.


2 Answers

Here's how I do it:

- name: Capture files to delete
  find:
    paths: /path/to/directory
    file_type: file
    excludes: 
      - "myfirst.file"
      - "mysecond.file"
  register: found_files

- name: Delete files
  file:
    path: "{{ item.path }}"
    state: absent
  with_items: "{{ found_files['files'] }}"
like image 95
Lars Nyström Avatar answered Sep 22 '22 13:09

Lars Nyström


In addition to what you found per your comment, if you end up needing to do a shell command, you can use the command module with removes parameter (doc). It will skip the step if the file already (doesn't) exist, which will prevent it from reporting a changed on the step. You'll still need to iterate over a list like in the other answer, however.

like image 21
Jake Kreider Avatar answered Sep 20 '22 13:09

Jake Kreider