How to create and rotate Automatic Snapshot?

前端 未结 10 2049
梦如初夏
梦如初夏 2020-12-14 08:33

On Compute Engine we can do Snapshots, which are basically backups. Could you try to figure out how we could create a script to do automated snapshots every day and keep lik

10条回答
  •  旧巷少年郎
    2020-12-14 08:55

    My solution is slightly simpler. I want to snapshot all disks not just the primary disk.

    By listing all disks in the project this handles all servers from one single script - as long as it is run within a gcloud project (and could be modified to run outside a project server too.

    To tidy up older snapshots doesn't need such complex date processing as it can be handled from the gcloud command line using a filter

    https://gitlab.com/alan8/google-cloud-auto-snapshot

    #!/bin/bash
    # loop through all disks within this project  and create a snapshot
    gcloud compute disks list | tail -n +2 | while read DISK_NAME ZONE c3 c4; do
      gcloud compute disks snapshot $DISK_NAME --snapshot-names auto-$DISK_NAME-$(date "+%s") --zone $ZONE 
    done
    #
    # snapshots are incremental and dont need to be deleted, deleting snapshots will merge snapshots, so deleting doesn't loose anything
    # having too many snapshots is unwieldy so this script deletes them after 60 days
    #
    gcloud compute snapshots list --filter="creationTimestamp<$(date -d "-60 days" "+%Y-%m-%d") AND (auto.*)" --uri | while read SNAPSHOT_URI; do
      gcloud compute snapshots delete --quiet $SNAPSHOT_URI
    done
    #
    

    Also note that for OSX users you have to use something like

    $(date -j -v-60d "+%Y-%m-%d")
    

    for the the creationTimestamp filter

提交回复
热议问题