Saturday 22 October 2016

Purge or Delete Old Disk Snapshot | Google Cloud

Regular purging of Google Cloud Disk Snapshot

Script to Delete Google Cloud Disk Snapshot Older than Few Days

In the previous post, we have seen "How to take regular snapshot of disks". Here in this post will setup a bash script to purge those snapshots older than specific days (say older than 7 days).


#!/usr/bin/env bash

export PATH=$PATH:/usr/local/bin/:/usr/bin

echo "Backup is running on `date +%Y%m%d-%H%M`"

#
# DELETE OLD SNAPSHOTS (OLDER THAN 7 DAYS)
#
# get a list of existing snapshots, that were created by this process (gcs-), for this vm disk (DEVICE_ID)

echo "Getting list of snapshots..."
SNAPSHOT_LIST="$(gcloud compute snapshots list --regexp "(.*sn-.*)" --uri)"
if [ $? -eq 0 ]; then
    echo "List retrieved successfully"
else
    echo "There are issues in retrieving the snapshot list... "
    exit
fi

echo "${SNAPSHOT_LIST}" | while read line ; do

   # get the snapshot name from full URL that google returns
   SNAPSHOT_NAME="${line##*/}"

   # get the date that the snapshot was created
   SNAPSHOT_DATETIME="$(gcloud compute snapshots describe ${SNAPSHOT_NAME} | grep "creationTimestamp" | cut -d " " -f 2 | tr -d \')"
   # format the date
   SNAPSHOT_DATETIME="$(date -d ${SNAPSHOT_DATETIME} +%Y%m%d)"
   # get the expiry date for snapshot deletion (currently 7 days)
   SNAPSHOT_EXPIRY="$(date -d "-7 days" +"%Y%m%d")"
   # check if the snapshot is older than expiry date
   if [ $SNAPSHOT_EXPIRY -ge $SNAPSHOT_DATETIME ];
   then
       echo "${SNAPSHOT_NAME} is older than 7 days, deleting the snapshot...\n"

       # delete the snapshot
       echo "$(gcloud compute snapshots delete ${SNAPSHOT_NAME} --quiet)"
       if [ $? -eq 0 ]; then
           echo "snapshot - ${SNAPSHOT_NAME} deleted successfully.."
       else
           echo "snapshot deletion not successful..."
       fi
   fi
done

The comments are itself explanatory about what the script is exactly doing. Set this script to run via cron to run it on the regular interval.

PS: You may change the number of days as per your requirement and the regex expression  <.*sn-.*>  as per the name you have been giving to the snapshots. If not, you can remove this regex filter and perform purging on all the snapshots on the basis of time only.

1 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete

 

Copyright @ 2013 Appychip.

Designed by Appychip & YouTube Channel