Back up your data by using a snapshot
Vertex AI Workbench user-managed notebooks isdeprecated. On April 14, 2025, support for user-managed notebooks ended and the ability to create user-managed notebooks instances was removed. Existing instances will continue to function until March 30, 2026, but patches, updates, and upgrades won't be available. To continue using Vertex AI Workbench, we recommend that youmigrate your user-managed notebooks instances to Vertex AI Workbench instances.
This page shows you how to back up data stored on yourVertex AI Workbench user-managed notebooks instanceby creating a snapshot.
The data on your instance is stored ona zonalpersistent disk.You can create and use snapshots of this disk to back up your data,create a recurring backup schedule, and restore data to a new instance.
Create a snapshot
You can create snapshots from disks even while they are attached to runninginstances. Snapshots areglobal resources,so you can use them torestore data toa new disk or instance within the same project. You can alsoshare snapshots across projects.
Permissions required for this task
To perform this task, you must have the followingpermissions:
compute.snapshots.createon the projectcompute.disks.createSnapshoton the disk
INSTANCE_NAME-data.Console
In the Google Cloud console, go to theVM instances page.
Go to VM instances
The remaining steps will appear automatically in the Google Cloud console.- Select the project that contains your VM instances.
- In theName column, click the name of the VM that has the disk to back up.
- In
Storage :- To back up the boot disk, in theBoot disk section, click theName of the boot disk.
- To back up an attached data disk, inAdditional disks, click theName of the disk.
- Click
Create snapshot . - InName, enter a unique name to help identify the purpose of the snapshot, for example:
boot-disk-snapshotattached-data-disk-snapshot
- InType, the default is a standard snapshot. Standard snapshots are best for long-term back up and disaster recovery.
ChooseArchive snapshot to create a more cost-efficient backup than standard snapshots, but with a longer data recovery time.
For more information, see Snapshot type comparison.
In theLocation section,choose your snapshot storage location. The predefined or customized default location defined in your snapshot settings is automatically selected. Optionally, you can override the snapshot settings and store your snapshots in a custom storage location by doing the following:
Choose the type of storage location that you want for your snapshot.
- ChooseMulti-regional for higher availability at a higher cost.
- ChooseRegional snapshots for more control over the physical location of your data at a lower cost.
- ChooseMulti-regional for higher availability at a higher cost.
In theSelect location field, select the specific region or multi-region that you want to use. To use the region or multi-region that is closest to your source disk, choose a location from the section titledBased on disk's location.
- To create a snapshot, clickCreate.
gcloud
In the Google Cloud console, activate Cloud Shell.
At the bottom of the Google Cloud console, aCloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.
Create your snapshot using the storage location policy defined by yoursnapshot settingsor using an alternative storage location of your choice. For moreinformation, seeChoose your snapshot storage location.You must specify a snapshot name. The name must be 1-63characters long, and comply withRFC 1035.
To create a snapshot of a Persistent Disk volume in the predefined orcustomized default location configured in your snapshot settings, usethe
gcloud compute snapshots createcommand.gcloud compute snapshots createSNAPSHOT_NAME \ --source-diskSOURCE_DISK \ --snapshot-typeSNAPSHOT_TYPE \ --source-disk-zoneSOURCE_DISK_ZONE
Alternatively, to override the snapshot settings and create a snapshotin a custom storage location, include the
--storage-locationflag toindicate where to store your snapshot:gcloud compute snapshots createSNAPSHOT_NAME \ --source-diskSOURCE_DISK \ --source-disk-zoneSOURCE_DISK_ZONE \ --storage-locationSTORAGE_LOCATION \ --snapshot-typeSNAPSHOT_TYPE
Replace the following:
- SNAPSHOT_NAME: A name for the snapshot.
- SOURCE_DISK: The name of the zonal Persistent Disk volume from which you want to create a snapshot.
- SNAPSHOT_TYPE: The snapshot type, eitherSTANDARD orARCHIVE. If a snapshot type is not specified, aSTANDARD snapshot is created. Choose Archive for more cost-efficient data retention.
- SOURCE_DISK_ZONE: The zone of the zonal Persistent Disk volume from which you want to create a snapshot.
- STORAGE_LOCATION: For custom storage locations,this is theCloud Storage multi-regionor theCloud Storage regionwhere you want to store your snapshot. You can specify only onestorage location.
Use the
--storage-locationflag only when you want to override thepredefined or customized default storage location configured in yoursnapshot settings.
The gcloud CLI waits until the operation returns a status of
Note: Google recommends using theREADYorFAILED, or reaches the maximum timeout and returns the lastknown details of the snapshot.gcloud compute snapshots createcommand instead of thegcloud compute disks snapshotcommandbecause it supports more features, such as creating snapshots in aproject different from the source disk project.
Terraform
To create a snapshot of the zonal persistent disk, use thegoogle_compute_snapshot resource.
resource "google_compute_snapshot" "snapdisk" { name = "snapshot-name" source_disk = google_compute_disk.default.name zone = "us-central1-a"}To learn how to apply or remove a Terraform configuration, seeBasic Terraform commands.
API
Create your snapshot in the storage location policy defined by yoursnapshot settingsor using an alternative storage location of your choice. For moreinformation, seeChoose your snapshot storage location.
To create your snapshot in the predefined or customized default locationconfigured in your snapshot settings, make a
POSTrequest to thesnapshots.insertmethod:POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/global/snapshots{ "name":SNAPSHOT_NAME "sourceDisk": "projects/SOURCE_PROJECT_ID/zones/SOURCE_ZONE/disks/SOURCE_DISK_NAME "snapshotType":SNAPSHOT_TYPE}Replace the following:
- DESTINATION_PROJECT_ID: The ID of project in which you wantto create the snapshot.
- SNAPSHOT_NAME: A name for the snapshot.
- SOURCE_PROJECT_ID: The ID of the source disk project.
- SOURCE_ZONE: The zone of the source disk.
- SOURCE_DISK_NAME: The name of the persistent disk fromwhich you want to create a snapshot.
- SNAPSHOT_TYPE: The snapshot type, eitherSTANDARD orARCHIVE. If a snapshot type is not specified, aSTANDARDsnapshot is created.
Alternatively, to override the snapshot settings and create a snapshot ina custom storage location, make a
POSTrequest to thesnapshots.insertmethodand include thestorageLocationsproperty in your request:POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/global/snapshots{ "name":SNAPSHOT_NAME "sourceDisk": "projects/SOURCE_PROJECT_ID/zones/SOURCE_ZONE/disks/SOURCE_DISK_NAME "snapshotType":SNAPSHOT_TYPE "storageLocations":STORAGE_LOCATION}Replace the following:
- DESTINATION_PROJECT_ID: The ID of project in which you wantto create the snapshot.
- SNAPSHOT_NAME: A name for the snapshot.
- SOURCE_PROJECT_ID: The ID of the source disk project.
- SOURCE_ZONE: The zone of the source disk.
- SOURCE_DISK_NAME: The name of the persistent disk fromwhich you want to create a snapshot.
- SNAPSHOT_TYPE: The snapshot type, eitherSTANDARD orARCHIVE. If a snapshot type is not specified, aSTANDARDsnapshot is created.
STORAGE_LOCATION: TheCloud Storage multi-regionor theCloud Storage regionwhere you want to store your snapshot. You can specify only onestorage location.
Use the
storageLocationsparameter only when you want to overridethe predefined or customized default storage location configured inyour snapshot settings.
snapshots.insert methodinstead of thedisks.createSnapshot methodbecause it supports more features, such as creating snapshots in aproject different from the source disk project.Go
Go
Before trying this sample, follow the setup instructions in theCompute Engine quickstart using client libraries.To authenticate to Compute Engine, set up Application Default Credentials. Formore information, seeSet up authentication for a local development environment.
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/protobuf/proto")// createSnapshot creates a snapshot of a disk.funccreateSnapshot(wio.Writer,projectID,diskName,snapshotName,zone,region,location,diskProjectIDstring,)error{// projectID := "your_project_id"// diskName := "your_disk_name"// snapshotName := "your_snapshot_name"// zone := "europe-central2-b"// region := "eupore-central2"// location = "eupore-central2"// diskProjectID = "YOUR_DISK_PROJECT_ID"ctx:=context.Background()snapshotsClient,err:=compute.NewSnapshotsRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewSnapshotsRESTClient: %w",err)}defersnapshotsClient.Close()ifzone=="" &®ion==""{returnfmt.Errorf("you need to specify `zone` or `region` for this function to work")}ifzone!="" &®ion!=""{returnfmt.Errorf("you can't set both `zone` and `region` parameters")}ifdiskProjectID==""{diskProjectID=projectID}disk:=&computepb.Disk{}locations:=[]string{}iflocation!=""{locations=append(locations,location)}ifzone!=""{disksClient,err:=compute.NewDisksRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewDisksRESTClient: %w",err)}deferdisksClient.Close()getDiskReq:=&computepb.GetDiskRequest{Project:projectID,Zone:zone,Disk:diskName,}disk,err=disksClient.Get(ctx,getDiskReq)iferr!=nil{returnfmt.Errorf("unable to get disk: %w",err)}}else{regionDisksClient,err:=compute.NewRegionDisksRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewRegionDisksRESTClient: %w",err)}deferregionDisksClient.Close()getDiskReq:=&computepb.GetRegionDiskRequest{Project:projectID,Region:region,Disk:diskName,}disk,err=regionDisksClient.Get(ctx,getDiskReq)iferr!=nil{returnfmt.Errorf("unable to get disk: %w",err)}}req:=&computepb.InsertSnapshotRequest{Project:projectID,SnapshotResource:&computepb.Snapshot{Name:proto.String(snapshotName),SourceDisk:proto.String(disk.GetSelfLink()),StorageLocations:locations,},}op,err:=snapshotsClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create snapshot: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Snapshot created\n")returnnil}Java
Java
Before trying this sample, follow the setup instructions in theCompute Engine quickstart using client libraries.To authenticate to Compute Engine, set up Application Default Credentials. Formore information, seeSet up authentication for a local development environment.
importcom.google.cloud.compute.v1.Disk;importcom.google.cloud.compute.v1.DisksClient;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.RegionDisksClient;importcom.google.cloud.compute.v1.Snapshot;importcom.google.cloud.compute.v1.SnapshotsClient;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateSnapshot{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// You need to pass `zone` or `region` parameter relevant to the disk you want to// snapshot, but not both. Pass `zone` parameter for zonal disks and `region` for// regional disks.// Project ID or project number of the Cloud project you want to use.StringprojectId="YOUR_PROJECT_ID";// Name of the disk you want to create.StringdiskName="YOUR_DISK_NAME";// Name of the snapshot that you want to create.StringsnapshotName="YOUR_SNAPSHOT_NAME";// The zone of the source disk from which you create the snapshot (for zonal disks).Stringzone="europe-central2-b";// The region of the source disk from which you create the snapshot (for regional disks).Stringregion="your-disk-region";// The Cloud Storage multi-region or the Cloud Storage region where you// want to store your snapshot.// You can specify only one storage location. Available locations:// https://cloud.google.com/storage/docs/locations#available-locationsStringlocation="europe-central2";// Project ID or project number of the Cloud project that// hosts the disk you want to snapshot. If not provided, the value will be defaulted// to 'projectId' value.StringdiskProjectId="YOUR_DISK_PROJECT_ID";createSnapshot(projectId,diskName,snapshotName,zone,region,location,diskProjectId);}// Creates a snapshot of a disk.publicstaticvoidcreateSnapshot(StringprojectId,StringdiskName,StringsnapshotName,Stringzone,Stringregion,Stringlocation,StringdiskProjectId)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the `snapshotsClient.close()` method on the client to safely// clean up any remaining background resources.try(SnapshotsClientsnapshotsClient=SnapshotsClient.create()){if(zone.isEmpty() &®ion.isEmpty()){thrownewError("You need to specify 'zone' or 'region' for this function to work");}if(!zone.isEmpty() &&!region.isEmpty()){thrownewError("You can't set both 'zone' and 'region' parameters");}// If Disk's project id is not specified, then the projectId parameter will be used.if(diskProjectId.isEmpty()){diskProjectId=projectId;}// If zone is not empty, use the DisksClient to create a disk.// Else, use the RegionDisksClient.Diskdisk;if(!zone.isEmpty()){DisksClientdisksClient=DisksClient.create();disk=disksClient.get(projectId,zone,diskName);}else{RegionDisksClientregionDisksClient=RegionDisksClient.create();disk=regionDisksClient.get(diskProjectId,region,diskName);}// Set the snapshot properties.SnapshotsnapshotResource;if(!location.isEmpty()){snapshotResource=Snapshot.newBuilder().setName(snapshotName).setSourceDisk(disk.getSelfLink()).addStorageLocations(location).build();}else{snapshotResource=Snapshot.newBuilder().setName(snapshotName).setSourceDisk(disk.getSelfLink()).build();}// Wait for the operation to complete.Operationoperation=snapshotsClient.insertAsync(projectId,snapshotResource).get(3,TimeUnit.MINUTES);if(operation.hasError()){System.out.println("Snapshot creation failed!"+operation);return;}// Retrieve the created snapshot.Snapshotsnapshot=snapshotsClient.get(projectId,snapshotName);System.out.printf("Snapshot created: %s",snapshot.getName());}}}Node.js
Node.js
Before trying this sample, follow the setup instructions in theCompute Engine quickstart using client libraries.To authenticate to Compute Engine, set up Application Default Credentials. Formore information, seeSet up authentication for a local development environment.
/** * TODO(developer): Uncomment and replace these variables before running the sample. */// const projectId = 'YOUR_PROJECT_ID';// const diskName = 'YOUR_DISK_NAME';// const snapshotName = 'YOUR_SNAPSHOT_NAME';// const zone = 'europe-central2-b';// const region = '';// const location = 'europe-central2';// let diskProjectId = 'YOUR_DISK_PROJECT_ID';constcompute=require('@google-cloud/compute');asyncfunctioncreateSnapshot(){constsnapshotsClient=newcompute.SnapshotsClient();letdisk;if(!zone &&!region){thrownewError('You need to specify `zone` or `region` for this function to work.');}if(zone &®ion){thrownewError("You can't set both `zone` and `region` parameters");}if(!diskProjectId){diskProjectId=projectId;}if(zone){constdisksClient=newcompute.DisksClient();[disk]=awaitdisksClient.get({project:diskProjectId,zone,disk:diskName,});}else{constregionDisksClient=newcompute.RegionDisksClient();[disk]=awaitregionDisksClient.get({project:diskProjectId,region,disk:diskName,});}constsnapshotResource={name:snapshotName,sourceDisk:disk.selfLink,};if(location){snapshotResource.storageLocations=[location];}const[response]=awaitsnapshotsClient.insert({project:projectId,snapshotResource,});letoperation=response.latestResponse;constoperationsClient=newcompute.GlobalOperationsClient();// Wait for the create snapshot operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,});}console.log('Snapshot created.');}createSnapshot();Python
Python
Before trying this sample, follow the setup instructions in theCompute Engine quickstart using client libraries.To authenticate to Compute Engine, set up Application Default Credentials. Formore information, seeSet up authentication for a local development environment.
from__future__importannotationsimportsysfromtypingimportAnyfromgoogle.api_core.extended_operationimportExtendedOperationfromgoogle.cloudimportcompute_v1defwait_for_extended_operation(operation:ExtendedOperation,verbose_name:str="operation",timeout:int=300)->Any:""" Waits for the extended (long-running) operation to complete. If the operation is successful, it will return its result. If the operation ends with an error, an exception will be raised. If there were any warnings during the execution of the operation they will be printed to sys.stderr. Args: operation: a long-running operation you want to wait on. verbose_name: (optional) a more verbose name of the operation, used only during error and warning reporting. timeout: how long (in seconds) to wait for operation to finish. If None, wait indefinitely. Returns: Whatever the operation.result() returns. Raises: This method will raise the exception received from `operation.exception()` or RuntimeError if there is no exception set, but there is an `error_code` set for the `operation`. In case of an operation taking longer than `timeout` seconds to complete, a `concurrent.futures.TimeoutError` will be raised. """result=operation.result(timeout=timeout)ifoperation.error_code:print(f"Error during{verbose_name}: [Code:{operation.error_code}]:{operation.error_message}",file=sys.stderr,flush=True,)print(f"Operation ID:{operation.name}",file=sys.stderr,flush=True)raiseoperation.exception()orRuntimeError(operation.error_message)ifoperation.warnings:print(f"Warnings during{verbose_name}:\n",file=sys.stderr,flush=True)forwarninginoperation.warnings:print(f" -{warning.code}:{warning.message}",file=sys.stderr,flush=True)returnresultdefcreate_snapshot(project_id:str,disk_name:str,snapshot_name:str,*,zone:str|None=None,region:str|None=None,location:str|None=None,disk_project_id:str|None=None,)->compute_v1.Snapshot:""" Create a snapshot of a disk. You need to pass `zone` or `region` parameter relevant to the disk you want to snapshot, but not both. Pass `zone` parameter for zonal disks and `region` for regional disks. Args: project_id: project ID or project number of the Cloud project you want to use to store the snapshot. disk_name: name of the disk you want to snapshot. snapshot_name: name of the snapshot to be created. zone: name of the zone in which is the disk you want to snapshot (for zonal disks). region: name of the region in which is the disk you want to snapshot (for regional disks). location: The Cloud Storage multi-region or the Cloud Storage region where you want to store your snapshot. You can specify only one storage location. Available locations: https://cloud.google.com/storage/docs/locations#available-locations disk_project_id: project ID or project number of the Cloud project that hosts the disk you want to snapshot. If not provided, will look for the disk in the `project_id` project. Returns: The new snapshot instance. """ifzoneisNoneandregionisNone:raiseRuntimeError("You need to specify `zone` or `region` for this function to work.")ifzoneisnotNoneandregionisnotNone:raiseRuntimeError("You can't set both `zone` and `region` parameters.")ifdisk_project_idisNone:disk_project_id=project_idifzoneisnotNone:disk_client=compute_v1.DisksClient()disk=disk_client.get(project=disk_project_id,zone=zone,disk=disk_name)else:regio_disk_client=compute_v1.RegionDisksClient()disk=regio_disk_client.get(project=disk_project_id,region=region,disk=disk_name)snapshot=compute_v1.Snapshot()snapshot.source_disk=disk.self_linksnapshot.name=snapshot_nameiflocation:snapshot.storage_locations=[location]snapshot_client=compute_v1.SnapshotsClient()operation=snapshot_client.insert(project=project_id,snapshot_resource=snapshot)wait_for_extended_operation(operation,"snapshot creation")returnsnapshot_client.get(project=project_id,snapshot=snapshot_name)Schedule a recurring backup
When you create a snapshot schedule, you create aresource policythat you can apply to one or more persistent disks. You can create snapshotschedules in the following ways:
- Create a snapshot schedule and thenattach it to an existing persistentdisk.
- Create a new persistent disk with a snapshot schedule.
A snapshot schedule includes the following properties:
- Schedule name
- Schedule description
- Snapshot frequency (hourly, daily, weekly)
- Snapshot start time
- Region where the snapshot schedule is available
- Source disk deletion policy for handling auto-generated snapshotsif the source disk is deleted
- Retention policy to define how long to keep snapshots that are generatedfrom the snapshot schedule
Restrictions
- A persistent disk can have at most 10 snapshot schedules attached to itat a time.
- You cannot create archive snapshots using a snapshot schedule.
- You can create a maximum of 1,000 in-use snapshot schedules per region.
- Snapshot schedules apply only in the project that they were created in.Snapshot schedules cannot be used in other projects or organizations.
- You might need to request an increase inresource quotathrough the console if you require additional resources in your region.
- You cannot delete a snapshot schedule if it is attached to a disk. You mustdetach the schedulefrom all disks, then delete the schedule.
- You can update an existing snapshot schedule to change the description,schedule, and labels. To update other values for a snapshot schedule, youmust delete the snapshot schedule and create a new one.
- For persistent disks that use acustomer-supplied encryption key(CSEK), you can'tcreate snapshot schedules.
- For persistent disks that use acustomer-managed encryption key(CMEK), all snapshots created with a snapshot schedule areautomatically encrypted with the same key.
Create a schedule
Permissions required for this task
To perform this task, you must have the followingpermissions:
compute.resourcePolicies.createon the project or organization
Create a snapshot schedule for your persistent disks using the Google Cloud console,Google Cloud CLI, or the Compute Engine API. You must create your snapshotschedule in the same region where your persistent disk resides. For example, ifyour persistent disk resides in zoneus-west1-a, your snapshot schedule mustreside in theus-west1 region. For more information, seeChoose a storage location.
Console
In the Google Cloud console, go to theVM instances page.
Go to VM instances
The remaining steps will appear automatically in the Google Cloud console.- Select the project that contains your VM instances.
- In theName column, click the name of the VM that has the persistent disk to create a snapshot schedule for.
- In
Storage , click the name of theBoot disk or theAdditional disk to create a snapshot schedule for. - ClickEdit. You might need to click theMore actions menu and thenEdit.
- InSnapshot schedule, chooseCreate a schedule.
- InName, enter one of the following names for the snapshot schedule:
boot-disk-snapshot-scheduleattached-persistent-disk-snapshot-schedule
In theLocation section,choose your snapshot storage location. The predefined or customized default location defined in your snapshot settings is automatically selected. Optionally, you can override the snapshot settings and store your snapshots in a custom storage location by doing the following:
Choose the type of storage location that you want for your snapshot.
- ChooseMulti-regional for higher availability at a higher cost.
- ChooseRegional snapshots for more control over the physical location of your data at a lower cost.
- ChooseMulti-regional for higher availability at a higher cost.
In theSelect location field, select the specific region or multi-region that you want to use. To use the region or multi-region that is closest to your source disk, selectBased on disk's location.
- To finish creating the snapshot schedule, clickCreate.
- To attach this snapshot schedule to the persistent disk, clickSave.
gcloud
To create a snapshot schedule for persistent disks, use thecompute resource-policies create snapshot-schedulegcloud command. Set your schedule frequency to hourly, daily, or weekly.
gcloudcomputeresource-policiescreatesnapshot-schedule[SCHEDULE_NAME]\--description "[SCHEDULE_DESCRIPTION]" \--max-retention-days [MAX_RETENTION_DAYS] \--start-time [START_TIME] \--hourly-schedule [SNAPSHOT_INTERVAL] \--daily-schedule \--weekly-schedule [SNAPSHOT_INTERVAL] \--weekly-schedule-from-file [FILE_NAME] \--on-source-disk-delete [DELETION_OPTION]where:
[SCHEDULE_NAME]is the name of the new snapshot schedule."[SCHEDULE_DESCRIPTION]"is a description of the snapshot schedule. Use quotes around your description.[MAX_RETENTION_DAYS]is the number of days to retain the snapshot. For example, setting3would mean that snapshots are retained for 3 days before they are deleted. You must set a retention policy of at least 1 day.[START_TIME]is the UTC start time. The time must start on the hour. For example:- 2:00 PM PST is
22:00. - If you set a start time of
22:13, you will receive an error.
- 2:00 PM PST is
Note: If you want to specify a weekly schedule with different days of the week and with different start times, use[SNAPSHOT_INTERVAL]defines the interval at which you want snapshotting to occur. Set the hourly schedule using an integer between 1 and 23. Choose an hourly number that is evenly divided into 24. For example, setting--hourly-scheduleto 12, means the snapshot is generated every 12 hours. For a weekly schedule define the days you want the snapshotting to occur. You must spell out the week days, they are not case-sensitive. The snapshot frequency flagshourly-schedule,daily-schedule, andweekly-scheduleare mutually-exclusive. You must pick one for your snapshot schedule.--weekly-schedule-from-fileinstead.[FILE_NAME]is the file name that contains the weekly snapshot schedule, if you choose to provide the schedule in this format. Note that you can specify weekly schedules on different days of the week and at different times using a file (but you cannot specify multiple weekly schedules directly on the command-line). For example, your file might specify a snapshot schedule on Monday and Wednesday:[{"day": "MONDAY", "startTime": "04:00"}, {"day": "WEDNESDAY", "startTime": "02:00"}]If you include a start time in your file, you do not need to set the--start-timeflag. The schedule uses the UTC time standard.[DELETION_OPTION]determines what happens to your snapshots if the source disk is deleted. Choose either the defaultkeep-auto-snapshotsby omitting this flag, or useapply-retention-policyto apply a retention policy.
These are additional examples for setting up a snapshot schedule. In allthe following examples:
- The disk deletion rule is included; the
--on-source-disk-deleteflagis set to the default ofkeep-auto-snapshotsto permanently keep allauto-generated snapshots. The alternative is to set this flag toapply-retention-policyto use your snapshot retention policy. - The storage location is set the
USso all generated snapshots will bestored in the US multi-region. - The labels
env=devandmedia=imagesare applied to all generatedsnapshots. - The retention policy is set to 10 days.
Hourly schedule: In this example, the snapshot schedule starts at 22:00UTC and occurs every 4 hours.
gcloudcomputeresource-policiescreatesnapshot-scheduleSCHEDULE_NAME\--description"MY HOURLY SNAPSHOT SCHEDULE"\--max-retention-days10\--start-time22:00\--hourly-schedule4\--regionus-west1\--on-source-disk-deletekeep-auto-snapshots\--snapshot-labelsenv=dev,media=images\--storage-locationUSDaily schedule: In this example, the snapshot schedule starts at 22:00UTC and occurs every day at the same time. The--daily-schedule flag mustbe present, but not set to anything.
gcloudcomputeresource-policiescreatesnapshot-scheduleSCHEDULE_NAME\--description"MY DAILY SNAPSHOT SCHEDULE"\--max-retention-days10\--start-time22:00\--daily-schedule\--regionus-west1\--on-source-disk-deletekeep-auto-snapshots\--snapshot-labelsenv=dev,media=images\--storage-locationUSWeekly schedule: In this example, the snapshot schedule starts at 22:00UTC and occurs every week on Tuesday and Thursday.
gcloudcomputeresource-policiescreatesnapshot-scheduleSCHEDULE_NAME\--description"MY WEEKLY SNAPSHOT SCHEDULE"\--max-retention-days10\--start-time22:00\--weekly-scheduletuesday,thursday\--regionus-west1\--on-source-disk-deletekeep-auto-snapshots\--snapshot-labelsenv=dev,media=images\--storage-locationUSAPI
In the API, construct aPOST request toresourcePolicies.insertto create a snapshot schedule. At the minimum, you must include the snapshotschedule name, snapshot storage regional location, and snapshot frequency.
By default, theonSourceDiskDelete parameter is set tokeepAutoSnapshots.This means that if the source disk is deleted, the auto-generated snapshotfor that disk is retained indefinitely. Alternatively, you can set the flagtoapplyRetentionPolicy to apply your retention policy.
The following example sets a daily snapshot schedule that starts at 12:00UTC and repeats every day. The example also sets a retention policy of 5days; after 5 days, snapshots are automatically removed.
You can also includesnapshot locality optionsandsnapshot labelsin your request to ensure your snapshots are stored in the location of yourchoice.
POSThttps://compute.googleapis.com/compute/v1/projects/[PROJECT_ID]/regions/[REGION]/resourcePolicies{"name":"[SCHEDULE_NAME]","description":"[SCHEDULE_DESCRIPTION]","snapshotSchedulePolicy":{"schedule":{"dailySchedule":{"startTime":"12:00","daysInCycle":"1"}},"retentionPolicy":{"maxRetentionDays":"5"},"snapshotProperties":{"guestFlush":"False","labels":{"env":"dev","media":"images"},"storageLocations":["US"]}}}where:
[PROJECT_ID]is the project name.[REGION]is the location of the snapshot schedule resource policy.[SCHEDULE_DESCRIPTION]is the description of the snapshot schedule.[SCHEDULE_NAME]is the name of the snapshot schedule.
Similarly, you can create a weekly or monthly schedule. Review theAPI referencefor details specific to setting a weekly or monthly schedule.
For example, the following request creates a weekly schedule that runson Tuesday and Thursday, at 9:00 and 2:00 respectively.
POSThttps://compute.googleapis.com/compute/v1/projects/[PROJECT_ID]/regions/[REGION]/resourcePolicies{"name":"[SCHEDULE_NAME]","description":"[SCHEDULE_DESCRIPTION]","snapshotSchedulePolicy":{"schedule":{"weeklySchedule":{"dayOfWeeks":[ { "day": "Monday", "startTime": "9:00" }, { "day": "Thursday", "startTime": "2:00" }]}},"retentionPolicy":{"maxRetentionDays":"5"},"snapshotProperties":{"guestFlush":"False","labels":{"production":"webserver"},"storageLocations":["US"]}}}Attach a snapshot schedule to a disk
Permissions required for this task
To perform this task, you must have the followingpermissions:
compute.disks.addResourcePolicieson the diskcompute.resourcePolicies.useon the resource policy to use
Once you have a schedule, attach it to an existing disk. Use the console,gcloudcommand, or the Compute Engine API method.
Console
Attach a snapshot schedule to an existing disk.
- In the Google Cloud console, go to theDisks page.
- Select the name of the disk to which you want to attach a snapshotschedule. This opens theManage disk page.
- On theManage disk page, hover and click theMore actionsmenu and selectEdit.
- Use theSnapshot schedule drop-down menu to add the scheduleto the disk. Or create a new schedule.
- If you created a new schedule, clickCreate.
- ClickSave to complete the task.
gcloud
To attach a snapshot schedule to a disk, use thedisks add-resource-policiesgcloud command.
gcloudcomputedisksadd-resource-policies[DISK_NAME]\--resource-policies [SCHEDULE_NAME] \--zone [ZONE]where:
[DISK_NAME]is the name of the existing disk.[SCHEDULE_NAME]is the name of the snapshot schedule.[ZONE]is the location of your disk.
API
In the API, construct aPOST request todisks.addResourcePoliciesto attach a snapshot schedule to an existing disk.
POSThttps://compute.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/disks/[DISK_NAME]/addResourcePolicies{"resourcePolicies":[ "regions/[REGION]/resourcePolicies/[SCHEDULE_NAME]"]}where:
[PROJECT_ID]is the project name.[ZONE]is the location of the disk.[REGION]is the location of the snapshot schedule.[DISK_NAME]is the name of the disk.[SCHEDULE_NAME]is the name of the snapshot schedule in that region you are applying to this disk.
Restore data from a snapshot
If you backed up a boot or non-boot disk with a snapshot, you can create a newdisk based on the snapshot.
Restrictions
- The new disk must be at least the same size as the original sourcedisk for the snapshot. If you create a disk that is largerthan the original source disk for the snapshot, you mustresize the filesystem on that persistent diskto include the additional disk space. Depending on your operating system andfile system type, you might need to use a different file system resizing tool.For more information, see your operating system documentation.
Create a disk from a snapshot and attach it to a VM
Note: You must create the disk in the same zone as your instance.Permissions required for this task
To perform this task, you must have the followingpermissions:
compute.disks.createon the project to create a new diskcompute.instances.attachDiskon the VM instancecompute.disks.usepermission on the disk to attach
Console
In the Google Cloud console, go to theSnapshots page.
Find the name of the snapshot that you want to restore.
Go to theDisks page.
ClickCreate new disk.
Specify the following configuration parameters:
- A name for the disk.
- A type for the disk.
- Optionally, you can override the default region and zone selection.You can select any region and zone, regardless of the storagelocation of the source snapshot.
UnderSource type, clickSnapshot.
Select the name of the snapshot to restore.
Select the size of the new disk, in gigabytes. This number must be equalto or larger than the original source disk for the snapshot.
ClickCreate to create the disk.
You can then attach the new disk to an existing instance.
- Go to theVM instances page.
- Click the name of the instance where you want to restore your non-boot disk.
- At the top of the instance details page, clickEdit.
- UnderAdditional disks, clickAttach existing disk.
- Select the name of the new disk made from your snapshot.
- ClickDone to attach the disk.
- At the bottom of the instance details page, clickSave to applyyour changes to the instance.
gcloud
Use the
gcloud compute snapshots listcommandcommand to find the name of the snapshot you want to restore:gcloud compute snapshots listUse the
gcloud compute snapshots describecommandcommand to find the size of the snapshot you want to restore:gcloud compute snapshots describeSNAPSHOT_NAMEReplaceSNAPSHOT_NAME with the name of the snapshot beingrestored.
Use the
gcloud compute disks createcommandcommand to create a newregional orzonal disk from yoursnapshot. If you need an SSD persistent disk for additional throughputor IOPS, include the--typeflag and specifypd-ssd.gcloudcomputediskscreateDISK_NAME\--size=DISK_SIZE\--source-snapshot=SNAPSHOT_NAME\--type=DISK_TYPEReplace the following:
- DISK_NAME: the name of the new disk.
- DISK_SIZE: The size of the new disk, in gigabytes. Thisnumber must be equal to or larger than the original source disk forthe snapshot.
- SNAPSHOT_NAME: the name of the snapshot being restored.
- DISK_TYPE: full or partial URL for thetypeof the disk. For example,
https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/diskTypes/pd-ssd.
Attach the new disk to an existing instance byusing the
gcloud compute instances attach-diskcommand:gcloud compute instances attach-diskINSTANCE_NAME \ --diskDISK_NAMEReplace the following:
- INSTANCE_NAME is the name of the instance.
- DISK_NAME is the name of the disk made from your snapshot.
API
Construct a
GETrequest tosnapshots.listto display the list of snapshots in your project.GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/snapshots
ReplacePROJECT_ID with your project ID.
Construct a
POSTrequest to create a zonal disk usingthedisks.insertmethod. Include thename,sizeGb, andtypeproperties. To restore a disk using a snapshot, you must includethesourceSnapshotproperty.POSThttps://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/disks{"name":"DISK_NAME","sizeGb":"DISK_SIZE","type":"zones/ZONE/diskTypes/DISK_TYPE""sourceSnapshot":"SNAPSHOT_NAME"}Replace the following:
- PROJECT_ID: your project ID.
- ZONE the zone where your instance and newdisk are located.
- DISK_NAME: the name of the new disk.
- DISK_SIZE: the size of the new disk, in gigabytes. Thisnumber must be equal to or larger than the original source disk forthe snapshot.
- DISK_TYPE: full or partial URL for thetypeof the disk. For example
https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/diskTypes/pd-ssd. - SNAPSHOT_NAME: the source snapshot for the disk you are restoring.
You can then attach the new disk to an existing instance byconstructing a
POSTrequest to theinstances.attachDiskmethod,and including the URL to the zonal disk that you just created from yoursnapshot.POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/attachDisk{ "source": "/compute/v1/projects/PROJECT_ID/zones/ZONE/disks/DISK_NAME"}Replace the following:
- PROJECT_ID is your project ID.
- ZONE is the zone where your instance and new disk are located.
- INSTANCE_NAME is the name of the instance where you are adding thenew disk.
- DISK_NAME is the name of the new disk.
Go
Go
Before trying this sample, follow theGo setup instructions in theVertex AI quickstart using client libraries. For more information, see theVertex AIGo API reference documentation.
To authenticate to Vertex AI, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/protobuf/proto")// createDiskFromSnapshot creates a new disk in a project in given zone.funccreateDiskFromSnapshot(wio.Writer,projectID,zone,diskName,diskType,snapshotLinkstring,diskSizeGbint64,)error{// projectID := "your_project_id"// zone := "us-west3-b" // should match diskType below// diskName := "your_disk_name"// diskType := "zones/us-west3-b/diskTypes/pd-ssd"// snapshotLink := "projects/your_project_id/global/snapshots/snapshot_name"// diskSizeGb := 120ctx:=context.Background()disksClient,err:=compute.NewDisksRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewDisksRESTClient: %w",err)}deferdisksClient.Close()req:=&computepb.InsertDiskRequest{Project:projectID,Zone:zone,DiskResource:&computepb.Disk{Name:proto.String(diskName),Zone:proto.String(zone),Type:proto.String(diskType),SourceSnapshot:proto.String(snapshotLink),SizeGb:proto.Int64(diskSizeGb),},}op,err:=disksClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create disk: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Disk created\n")returnnil}Java
Java
Before trying this sample, follow theJava setup instructions in theVertex AI quickstart using client libraries. For more information, see theVertex AIJava API reference documentation.
To authenticate to Vertex AI, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
importcom.google.cloud.compute.v1.Disk;importcom.google.cloud.compute.v1.DisksClient;importcom.google.cloud.compute.v1.InsertDiskRequest;importcom.google.cloud.compute.v1.Operation;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateDiskFromSnapshot{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// Project ID or project number of the Cloud project you want to use.StringprojectId="YOUR_PROJECT_ID";// Name of the zone in which you want to create the disk.Stringzone="europe-central2-b";// Name of the disk you want to create.StringdiskName="YOUR_DISK_NAME";// The type of disk you want to create. This value uses the following format:// "zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".// For example: "zones/us-west3-b/diskTypes/pd-ssd"StringdiskType=String.format("zones/%s/diskTypes/pd-ssd",zone);// Size of the new disk in gigabytes.longdiskSizeGb=10;// The full path and name of the snapshot that you want to use as the source for the new disk.// This value uses the following format:// "projects/{projectName}/global/snapshots/{snapshotName}"StringsnapshotLink=String.format("projects/%s/global/snapshots/%s",projectId,"SNAPSHOT_NAME");createDiskFromSnapshot(projectId,zone,diskName,diskType,diskSizeGb,snapshotLink);}// Creates a new disk in a project in given zone, using a snapshot.publicstaticvoidcreateDiskFromSnapshot(StringprojectId,Stringzone,StringdiskName,StringdiskType,longdiskSizeGb,StringsnapshotLink)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests. After completing all of your requests, call// the `disksClient.close()` method on the client to safely// clean up any remaining background resources.try(DisksClientdisksClient=DisksClient.create()){// Set the disk properties and the source snapshot.Diskdisk=Disk.newBuilder().setName(diskName).setZone(zone).setSizeGb(diskSizeGb).setType(diskType).setSourceSnapshot(snapshotLink).build();// Create the insert disk request.InsertDiskRequestinsertDiskRequest=InsertDiskRequest.newBuilder().setProject(projectId).setZone(zone).setDiskResource(disk).build();// Wait for the create disk operation to complete.Operationresponse=disksClient.insertAsync(insertDiskRequest).get(3,TimeUnit.MINUTES);if(response.hasError()){System.out.println("Disk creation failed!"+response);return;}System.out.println("Disk created. Operation Status: "+response.getStatus());}}}Node.js
Node.js
Before trying this sample, follow theNode.js setup instructions in theVertex AI quickstart using client libraries. For more information, see theVertex AINode.js API reference documentation.
To authenticate to Vertex AI, set up Application Default Credentials. For more information, seeSet up authentication for a local development environment.
/** * TODO(developer): Uncomment and replace these variables before running the sample. */// const projectId = 'YOUR_PROJECT_ID';// const zone = 'europe-central2-b';// const diskName = 'YOUR_DISK_NAME';// const diskType = 'zones/us-west3-b/diskTypes/pd-ssd';// const diskSizeGb = 10;// const snapshotLink = 'projects/project_name/global/snapshots/snapshot_name';constcompute=require('@google-cloud/compute');asyncfunctioncreateDiskFromSnapshot(){constdisksClient=newcompute.DisksClient();const[response]=awaitdisksClient.insert({project:projectId,zone,diskResource:{sizeGb:diskSizeGb,name:diskName,zone,type:diskType,sourceSnapshot:snapshotLink,},});letoperation=response.latestResponse;constoperationsClient=newcompute.ZoneOperationsClient();// Wait for the create disk operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log('Disk created.');}createDiskFromSnapshot();Python
Python
To learn how to install or update the Vertex AI SDK for Python, seeInstall the Vertex AI SDK for Python. For more information, see thePython API reference documentation.
from__future__importannotationsimportsysfromtypingimportAnyfromgoogle.api_core.extended_operationimportExtendedOperationfromgoogle.cloudimportcompute_v1defwait_for_extended_operation(operation:ExtendedOperation,verbose_name:str="operation",timeout:int=300)->Any:""" Waits for the extended (long-running) operation to complete. If the operation is successful, it will return its result. If the operation ends with an error, an exception will be raised. If there were any warnings during the execution of the operation they will be printed to sys.stderr. Args: operation: a long-running operation you want to wait on. verbose_name: (optional) a more verbose name of the operation, used only during error and warning reporting. timeout: how long (in seconds) to wait for operation to finish. If None, wait indefinitely. Returns: Whatever the operation.result() returns. Raises: This method will raise the exception received from `operation.exception()` or RuntimeError if there is no exception set, but there is an `error_code` set for the `operation`. In case of an operation taking longer than `timeout` seconds to complete, a `concurrent.futures.TimeoutError` will be raised. """result=operation.result(timeout=timeout)ifoperation.error_code:print(f"Error during{verbose_name}: [Code:{operation.error_code}]:{operation.error_message}",file=sys.stderr,flush=True,)print(f"Operation ID:{operation.name}",file=sys.stderr,flush=True)raiseoperation.exception()orRuntimeError(operation.error_message)ifoperation.warnings:print(f"Warnings during{verbose_name}:\n",file=sys.stderr,flush=True)forwarninginoperation.warnings:print(f" -{warning.code}:{warning.message}",file=sys.stderr,flush=True)returnresultdefcreate_disk_from_snapshot(project_id:str,zone:str,disk_name:str,disk_type:str,disk_size_gb:int,snapshot_link:str,)->compute_v1.Disk:""" Creates a new disk in a project in given zone. Args: project_id: project ID or project number of the Cloud project you want to use. zone: name of the zone in which you want to create the disk. disk_name: name of the disk you want to create. disk_type: the type of disk you want to create. This value uses the following format: "zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)". For example: "zones/us-west3-b/diskTypes/pd-ssd" disk_size_gb: size of the new disk in gigabytes snapshot_link: a link to the snapshot you want to use as a source for the new disk. This value uses the following format: "projects/{project_name}/global/snapshots/{snapshot_name}" Returns: An unattached Disk instance. """disk_client=compute_v1.DisksClient()disk=compute_v1.Disk()disk.zone=zonedisk.size_gb=disk_size_gbdisk.source_snapshot=snapshot_linkdisk.type_=disk_typedisk.name=disk_nameoperation=disk_client.insert(project=project_id,zone=zone,disk_resource=disk)wait_for_extended_operation(operation,"disk creation")returndisk_client.get(project=project_id,zone=zone,disk=disk_name)Mount the disk
In the terminal, use the
lsblkcommand to list the disks that areattached to your instance and find the disk that you want to mount.$sudolsblkNAMEMAJ:MINRMSIZEROTYPEMOUNTPOINTsda8:0010G0disk└─sda18:1010G0part/sdb8:160250G0disk
In this example,
sdbis the device name for the new blank persistentdisk.Use themount toolto mount the disk to the instance, and enable the
discardoption:$sudomount-odiscard,defaults/dev/DEVICE_NAME/home/jupyterReplace the following:
DEVICE_NAME: the device name of the disk tomount.
Configure read and write permissions on the disk. For this example,grant write access to the disk for all users.
$sudochmoda+w/home/jupyter
What's next
- Learn how tosave a notebook to GitHub
- Learn more aboutcreating snapshots.
- Learn more aboutscheduling snapshots.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.