2
votes

In my Ansible Playbook I'd like to have a task that removes old files and folders from the application's directory. The twist to this otherwise simple task is that a few files or folders need to remain. Imagine something like this:

/opt/application
  - /config
    - *.properties
    - special.yml
  - /logs
  - /bin
  - /var
    - /data
    - /templates

Let's assume I'd like to keep /logs completely, /var/data and from /config I want to keep special.yml.

(I cannot provide exact code at the moment because I left work frustrated by this and, after cooling down, I am now writing up this question at home)

My idea was to have two lists of exclusions, one holding the folders and one the file. Then I use the find module to first get the folders in the application's directory into a variable and the same for the remaining files into another variable. Afterwards I wanted to remove every folder and file that are not in the lists of exclusions using the file module.

(Pseudo-YML because I'm not yet fluent enough in Ansible that I can whip up a properly structured example; it should be close enough though)

file:
  path: "{{ item.path }}"
  state: absent
with_items: "{{ found_files_list.files }}"
when: well, that is the big question

What I can't figure out is how to properly construct the when clause. Is it even possible like this?

2
Thanks for the answers. We decided that this problem is a smell of a potentially ill-advised directory layout which we'll fix first and then removing the directories is much more straight forward. - Robert Lohr

2 Answers

2
votes

I don't believe there is a when clause with the file module. But you can probably achieve what you need as follows:

- name: Find /opt/application all directories, exclude logs, data, and config
  find:
    paths: /opt/application
    excludes: 'logs,data,config'
  register: files_to_delete

- name: Ansible remove file glob
  file:
    path: "{{ item.path }}"
    state: absent
  with_items: "{{ files_to_delete.files }}"

I hope this is what you need.

1
votes

First use the find module like you said to get a total list of all files and directories. Register to a variable like all_objects.

- name: Get list of all files recursively
  find:
    path: /opt/application/
    recurse: yes
  register: all_objects

Then manually make a list of things you want to keep.

vars:
  keep_these:
    - /logs
    - /var/data
    - /config/special.yml

Then this task should delete everything except things in your list:

- name: Delete all files and directories except exclusions
  file:
    path: "{{ item.path }}"
    state: absent
    recurse: true
  with_items: "{{ all_objects.files }}"
  when: item.path not in keep_these

I think this general strategy should work... only thing I'm not sure about is the exact nesting heiararchy of the registered variable from the find module. You might have to play around with the debug module to get it exactly right.