Goal:
There is a directory "/opt/application" where the archive with the application is downloaded and unpacked into a directory where the short derivative of the HASH commit (8 characters) is used as the name. And a symbolic link is created to this directory. It is necessary to store only the 3 latest versions of the application, both directories, and archives, and also do not delete directories called:
- logs
- media
Also, the deletion should be done using regex, so that in the future it does not delete directories that may be created.
Playbook:
--- - hosts: all tasks: - name: Find all application directories find: paths: "/opt/application/" file_type: directory use_regex: yes patterns: - '[a-z0-9]{8,8}' excludes: 'logs,media' register: dirs - name: Keep only the last 3 directories file: path: "{{ item }}" state: absent with_items: "{{ (dirs.files | sort(attribute='atime', reverse=True))[3:] | map(attribute='path') | list }}" - name: Find application artifacts find: paths: "/opt/application/" file_type: file use_regex: yes patterns: - '^[a-z0-9]{8,8}.tar.gz$' register: artifacts - name: Keep only the last 3 artifacts file: path: "{{ item }}" state: absent with_items: "{{ (artifacts.files | sort(attribute='atime', reverse=True))[3:] | map(attribute='path') | list }}"