Misha Zaslavsky
Misha Zaslavsky

Reputation: 9712

How to automatically backup snapshots/images in Google Compute Engine

I have Google Compute Engine instances and I want to do automatic snapshot/image backups. It should be like a schedule job that every 5 hours it makes a snapshot/image to my instances.

I read that it is possible to do with Cron job but I can't understand how to do it.

Could you please help me to understand how to do automatic snapshot/image?

Thanks in advance.

Upvotes: 0

Views: 1008

Answers (2)

enrique.tuya
enrique.tuya

Reputation: 11

Google has now introduced the Snapshot Scheduler. You can find it in the snapshot section -> Create Snapshot Schedule.

Once you have the schedule you can create a new disk and select the schedule or edit an existing this and assign the scheduler.

Upvotes: 0

Lennert Kuijpers
Lennert Kuijpers

Reputation: 296

You can create an .sh script to make the snapshot with the gcloud command. This is the script we are using:

# Settings
GCLOUD_PROJECT="my-project"
SERVICE_ACCOUNT_JSON="location to service account json"
DISK_NAME="my-disk"
GCE_ZONE="europe-west1-d"
DATETIME=`date "+%Y-%m-%d-%H-%M-%S"`

# authenticate first
export CLOUDSDK_PYTHON_SITEPACKAGES=1
gcloud auth activate-service-account --key-file $SERVICE_ACCOUNT_JSON --project $GCLOUD_PROJECT 

# sync => empty filesystem buffers
sync

# make the actual snapshot
gcloud --project $GCLOUD_PROJECT compute disks snapshot $DISK_NAME --zone $GCE_ZONE --snapshot-names $DISK_NAME-$DATETIME

This will create a new incremental snapshot every time you run (for example create a cron to run it at night). The next thing you need to do is to decide how many snapshots you want to keep. We are keeping 5 snapshots and created the next script to delete the snapshots older then the 5 most recent snapshots. We run this script 30 mins after the first one to make sure that the creation of the snapshot is finished.

# Settings
GCLOUD_PROJECT="my-project"
SERVICE_ACCOUNT_JSON="location to service account json"
DISK_NAME="my-disk"
GCE_ZONE="europe-west1-d"

# authenticate first
export CLOUDSDK_PYTHON_SITEPACKAGES=1
gcloud auth activate-service-account --key-file $SERVICE_ACCOUNT_JSON --project $GCLOUD_PROJECT

# list snapshots
snapshot_list=($(gcloud --project $GCLOUD_PROJECT compute snapshots list --sort-by NAME --regexp "$DISK_NAME-.*" | tail -n +2 | awk '{print $1}'))

keep_index=$(expr ${#snapshot_list[*]} - 5)

for i in $(seq 0 $keep_index);
do
    gcloud --project $GCLOUD_PROJECT compute snapshots delete ${snapshot_list[i]} -q
done

Upvotes: 1

Related Questions