Creating a VM Snapshot in google cloud using Python

By September 26, 2019 May 18th, 2020 Blogs, Cloud, Cloud Assessment, 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 =

##To get the current date with format.

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

compute =‘compute’, ‘v1’)

def list_instances(compute, project, zone):

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

desired_vms= []

vmdisks= []


for each_item in result[‘items’]:

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


disks = (each_item[‘disks’])

for disk in disks:



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!

Leave a Reply