Skip to content

Instantly share code, notes, and snippets.

@felixkrohn
Last active May 15, 2020 10:21
Show Gist options
  • Save felixkrohn/ef9bb30ff1a92bd70dd940f3db190974 to your computer and use it in GitHub Desktop.
Save felixkrohn/ef9bb30ff1a92bd70dd940f3db190974 to your computer and use it in GitHub Desktop.
PV recycler script

This script iterates through all released PVs, and does the following:

  • add an annotation with today's timestamp if missing
  • check if a present annotation indicates a date older than $KEEPDAYS days, and deletes the PV if yes

It's triggered by an ansile-managed cronjob on a bastion host.

---
- name: copy pv-garbagecollection script
template:
src: pv-garbagecollector.sh
dest: /usr/local/sbin/pv-garbagecollector.sh
mode: 0700
- name: set up cronjob for pv-garbagecollection script
cron:
name: Cronjob for the PersistentVolume (PV) Garbagecollector/recycler
user: root
cron_file: openshift_pv-garbagecollector
job: /usr/local/sbin/pv-garbagecollector.sh
hour: 12
weekday: 1-5 # mon-fri in order not to create any alerts for storage team when PVs are deleted on weekends
{% raw %}
#!/bin/sh
# This script iterates through all released PVs, and does the following:
# - add an annotation with today's timestamp if missing
# - check if a present annotation indicates a date older than $KEEPDAYS days, and deletes the PV if yes
{% endraw %}KEEPDAYS="{{ pv_garbagecollection_keepdays }}"
{% raw %}DAYTODAY="$(date +%Y-%m-%d)"
# get all unbound PVs and add annotation with datestamp(today) if it's not already set
for pv in $(oc get pv -ojsonpath='{range .items[?(@.status.phase=="Released")]}{.metadata.name}{"\n"}')
do
# do dry-run first in order not to get an error because the annotation already exists
oc annotate --overwrite=false pv $pv "{% endraw %}{{ clusterid }}.{{ COMPANYTLD }}{% raw %}/pv-release-date"="${DAYTODAY}" --dry-run 2>/dev/null && oc annotate --overwrite=false pv $pv "{% endraw %}{{ clusterid }}.{{ COMPANYTLD }}{% raw %}/pv-release-date"="${DAYTODAY}"
OLDDATESTAMP="$(oc get pv $pv -o go-template='{{ range $key, $value := .metadata.annotations}}{{if eq $key {% endraw %}"{{ clusterid }}.{{ COMPANYTLD }}{% raw %}/pv-release-date"}}{{$value}}{{"\n"}}{{end}}{{end}}')"
if [ "$(date -d "${OLDDATESTAMP}" +%s)" -lt "$(date -d "${KEEPDAYS} days ago" +%s)" ]
then
oc patch pv $pv -p '{"spec":{"persistentVolumeReclaimPolicy": "Delete"}}'
oc delete pv $pv
fi
done
{% endraw %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment