在谷歌云平台上创建自动磁盘快照(备份)保留



我想知道是否有一种方法可以为实例(更具体地说是磁盘)创建自动备份保留。我对控制台不是很有经验,所以我更喜欢GUI方式,但如果没有,我很乐意了解控制台方法。

我一直在寻找这个,但只找到了SQL的解决方案。

谢谢!

更新:

自从我第一次给出这个答案以来,脚本已经发生了很大的变化——请参阅Github repo了解最新代码:https://github.com/jacksegal/google-compute-snapshot

原始答案:

我也遇到了同样的问题,所以我创建了一个简单的shell脚本来拍摄每日快照,并在7天内删除所有快照:https://github.com/jacksegal/google-compute-snapshot

#!/usr/bin/env bash
export PATH=$PATH:/usr/local/bin/:/usr/bin
#
# CREATE DAILY SNAPSHOT
#
# get the device name for this vm
DEVICE_NAME="$(curl -s "http://metadata.google.internal/computeMetadata/v1/instance/disks/0/device-name" -H "Metadata-Flavor: Google")"
# get the device id for this vm
DEVICE_ID="$(curl -s "http://metadata.google.internal/computeMetadata/v1/instance/id" -H "Metadata-Flavor: Google")"
# get the zone that this vm is in
INSTANCE_ZONE="$(curl -s "http://metadata.google.internal/computeMetadata/v1/instance/zone" -H "Metadata-Flavor: Google")"
# strip out the zone from the full URI that google returns
INSTANCE_ZONE="${INSTANCE_ZONE##*/}"
# create a datetime stamp for filename
DATE_TIME="$(date "+%s")"
# create the snapshot
echo "$(gcloud compute disks snapshot ${DEVICE_NAME} --snapshot-names gcs-${DEVICE_NAME}-${DEVICE_ID}-${DATE_TIME} --zone ${INSTANCE_ZONE})"

#
# 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)
SNAPSHOT_LIST="$(gcloud compute snapshots list --regexp "(.*gcs-.*)|(.*-${DEVICE_ID}-.*)" --uri)"
# loop through the snapshots
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
     # delete the snapshot
         echo "$(gcloud compute snapshots delete ${SNAPSHOT_NAME} --quiet)"
   fi
done

关于这个非常有用的脚本的两条评论(如果您正在使用上面的脚本)

线路

--regexp"(.gcs-.)|(.-${DEVICE_ID}-.)"

可能有bug;这列出了从GCS开始的所有内容我认为应该读

--regexp"(.gcs-.)-(.-${DEVICE_ID}-.)"

至少这是我用来输出预期结果的

此外,这个--regexp现在已被弃用,如果您关心警告,可以使用

SNAPSHOT_LIST="$(gcloud计算快照列表--filter="name~'(.gcs-.)-(.-${DEVICE_ID}-.)'"--uri)"

作者在他的git上有一个更新的版本,这些只是对上述脚本的评论。regexp相当危险,因为上面的脚本基本上是使用相同的脚本从其他虚拟机中删除快照。

最新更新