lae / ansible-role-netbox

Cross-platform Ansible role for deploying NetBox, a DCIM/IPAM tool, in a production environment.
MIT License
191 stars 73 forks source link

Prune old deployment directories #22

Open lae opened 6 years ago

lae commented 6 years ago

For every release, this role creates a new directory to deploy NetBox into, as well as a virtualenv for that particular release. This allows us to do naive downgrades (it's fine if there aren't any database migrations) to an older version when necessary, but after some time leads to a lot of old release directories:

:~$ ls -l /srv/netbox/releases/
total 48
drwxr-xr-x 8 netbox netbox 4096 Jun 23 01:48 git
drwxr-xr-x 7 netbox netbox 4096 Aug 29 01:18 git-deploy
drwxr-xr-x 7 netbox netbox 4096 Aug 29 01:17 git-repo
drwxr-xr-x 6 netbox netbox 4096 Jul 10 22:36 git-static
drwxr-xr-x 7 netbox netbox 4096 Jul 17 15:34 netbox-2.0.10
drwxr-xr-x 7 netbox netbox 4096 Jun 19 20:43 netbox-2.0.7
drwxr-xr-x 7 netbox netbox 4096 Jul 11 18:39 netbox-2.0.9
drwxr-xr-x 7 netbox netbox 4096 Jul 25 17:12 netbox-2.1.0
drwxr-xr-x 7 netbox netbox 4096 Aug  2 21:26 netbox-2.1.1
drwxr-xr-x 7 netbox netbox 4096 Aug 29 00:04 netbox-2.1.3
drwxr-xr-x 7 netbox netbox 4096 Aug 31 20:43 netbox-2.1.4
drwxr-xr-x 7 netbox netbox 4096 Oct  3 00:44 netbox-2.1.5

This role should probably have a role variable to specify when to prune old releases, e.g. prune all releases except the last 5. There should be a task to check for prunable releases and remove them entirely.

tyler-8 commented 1 week ago

Not sure if this is exactly fitting the criteria, but without a bunch of regex and layered filtering, I'm not sure how else to do this. This uses path modification time:

# defaults/main.yml
netbox_releases_to_keep: 3

# tasks/main.yml
- name: Get list of release directories
  ansible.builtin.find:
    paths: /srv/netbox/releases
    file_type: directory
  register: release_dirs

- name: Sort and prune old releases
  block:
    - name: Sort release directories by modification time
      ansible.builtin.set_fact:
        sorted_release_dirs: "{{ release_dirs.files | sort(attribute='mtime', reverse=True) }}"

    - name: Determine directories to remove
      ansible.builtin.set_fact:
        directories_to_remove: "{{ sorted_release_dirs[netbox_releases_to_keep:] | map(attribute='path') | list }}"

    - name: Remove old release directories
      ansible.builtin.file:
        path: "{{ item }}"
        state: absent
      with_items: "{{ directories_to_remove }}"
  when: release_dirs.matched > netbox_releases_to_keep