Creating a VM Snapshot in google cloud using Python

By September 26, 2019 October 7th, 2019 Blogs, GCP

Written by Nirmal Prabhu, Cloud Engineer, Powerupcloud Technologies.

Information is eternal, computers are ephemeral, backup is the saviour.

Keeping it to the point, we have a script to do that to automate VM disk snapshot for google cloud using python and it works with the help of tags.

This script will take a snapshot of all the disks of a VM whose tag matches under condition.

Tag your Virtual machine whose disks to be backed up. Here we used [‘env’:’prod’] where “env” is a key and “prod” is a value.

import apiclient

import json

from datetime import datetime, timedelta

day = datetime.now()

##To get the current date with format.

currday = day.strftime(‘%d-%m-%Y’)

compute = apiclient.discovery.build(‘compute’, ‘v1’)

def list_instances(compute, project, zone):

result = compute.instances().list(project=project, zone=zone).execute()

desired_vms= []

vmdisks= []

data=””

for each_item in result[‘items’]:

if each_item[‘labels’][‘env’]==’prod’: ##Mention the VM label to take snapshot

desired_vms.append(str(each_item[‘name’]))

disks = (each_item[‘disks’])

for disk in disks:

vmdisks.append(str(disk[‘deviceName’]))

data={“vmname”:desired_vms,”disk”:vmdisks}

for disk in vmdisks:

snapshot_body = {‘name’:’automated-snap-’+disk + currday} ## Name Format for new snapshot.

print “Creating snap for %s” % disk

request = compute.disks().createSnapshot(project=’xxx’, zone=’asia-south1-c’,disk=disk, body=snapshot_body) ##Mention the project and Zone

response = request.execute()

return data

print(list_instances(compute,’xxx’ ,’asia-south1-c’)) ##Mention the project and Zone

That’s it… We are done. Happy Automating…Let us know what you think!

Join the discussion One Comment

  • Thyago Machado says:

    Hi Nirmal Prabhu, im a newbie in coding, but u have a very clean a nice script! Thx. But if i want to set this script in a Cloud Functions, can u help me with this?

Leave a Reply