3

I made a playbook with two task

The first task is for getting all the directories in the selected directory.
The second task is for deleting the directories. But, I only want to delete a directory if the list length is longer than two.

---
- name: cleanup Backend versions
  hosts: backend
  become: true
  become_user: root
  vars:
    backend_deploy_path: /opt/app/test/
  tasks:
    - name: Get all the versions
      ansible.builtin.find:
        paths: "{{ backend_deploy_path }}"
        file_type: directory
      register: file_stat

    - name: Delete old versions
      ansible.builtin.file:
        path: "{{ item.path }}"
        state: absent
      with_items: "{{ file_stat.files }}"
      when: file_stat.files|length > 2

When I run this playbook it deletes all the directories instead of keeping three directories.

My question is how can I keep the variable updated? So that it keeps checking every time it tries to delete a directory?

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
LaurenceVZ
  • 33
  • 3

1 Answers1

3

This won't be possible, once a module is executed, the result is saved in the variable and won't dynamically change with the state of the node.

What you should do instead is to limit the list you are looping on with a slice notation to exclude the three last items of the said list: files[:-3].

So, your task deleting files would look like this:

- name: Delete old versions
  ansible.builtin.file:
    path: "{{ item.path }}"
    state: absent
  loop: "{{ file_stat.files[:-3] }}"

Side note: you probably want to sort that find result based on the creation date of the folder, too, something like:

loop: "{{ (file_stat.files | sort(attribute='ctime'))[:-3] }}"
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83