Google Compute Engine auto snapshot
很多人都知道之前 gitlab 裏頭的工程師不小心 rm -rf 的事件,所以當然要做好備份。
在 google cloud 的機器可以乾脆直接寫 crontab 定期做 snapshot,不過這樣的方式也不能防止手殘砍掉負責跑這 crontab 的 instance 就是了 XD
#!/usr/bin/env bash
export PATH=$PATH:/usr/local/bin/:/usr/bin
#create snapshot
echo "$(gcloud compute disks snapshot my-webserver --snapshot-names=www-$(date "+%Y%m%d") --zone=asia-east1-c)"
#get snapshot list
SNAPSHOT_LIST="$(gcloud compute snapshots list --regexp "(.*www-.*)" --uri)"
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 "-10 days" +"%Y%m%d")"
    # check if the snapshot is older than expiry date
    if [ $SNAPSHOT_EXPIRY -ge $SNAPSHOT_DATETIME ];
    then
        # delete the snapshot
        echo "$(gcloud compute snapshots delete ${SNAPSHOT_NAME} --quiet)"
   fi
done
Original link: Phanix's Blog
