Home > database >  Ansible find matched patterns directory, remove all but keep the last 3 versions
Ansible find matched patterns directory, remove all but keep the last 3 versions

Time:09-22

I have surf the stackoverflow site around but couldn't find anything similar to what I want to achieve and hope that someone can point me out would be much appreciated.

I have a directory which stored all the artifacts Release Candidate and Dev versions when ever there is a bamboo build kick in. So far, I can figure out how to find the directory patterns and verify the results to remove. But could not filter the results to exclude the last 3 latest versions which I want to keep.

Here is the structures and the code

Structures

---
- name: Ansible find match directory, keep the last 3 version and remove all other
  hosts: localhost
  connection: local
  vars:
base_dir: "/opt/repo/"
artifacts:
  - "subject-mapper"
  - "artemis-margin-api"
  tasks:
- name: Find Release Candidate Directory Packages
  become: yes
  find:
    paths: "{{ base_dir }}/{{ item }}"
    patterns: 
      - "{{ item }}-[0-9]*.[0-9]*.[0-9]*$"
    use_regex: yes
    recurse: no
    file_type: directory
  loop: "{{ artifacts }}"
  register: output
- debug:
    msg: "{{ output }}"

- name: Filter out the Release Candidate results and keep the last 3 versions
  set_fact:
    files_to_delete: "{{ (files_to_delete|default([]))   (item['files'] | sort(attribute='mtime'))[:-3] }}"
  loop: "{{ output['results'] }}"

- debug: 
    msg: "{{ files_to_delete }}"

- name: Delete the filtered results but keep the last 3 version
  file:
    path: "{{ item.path }}"
    state: absent
  loop: "{{ files_to_delete }}"      
  when: confirm|default(false)|bool
  register: output_delete
- debug: 
    msg: "{{ output_delete }}"

here

CodePudding user response:

Simplest way would be to pop first three matches from each result:

    - set_fact:
        files_to_delete: "{{ (files_to_delete|default([]))   (item['files'] | sort(attribute='mtime'))[3:] }}"
      loop: "{{ output['results'] }}"
  • Related