Manage snapshot schedules for disks Stay organized with collections Save and categorize content based on your preferences.
This document describes how to manage snapshot schedules for yourzonal and regionalPersistent Disk andGoogle Cloud Hyperdisk volumes.
You can manage snapshot schedules as follows:
- View snapshot schedules
- Change snapshot schedules
- Delete snapshot schedules
You can alsoconfigure alerts for scheduled snapshots.
Before you begin
- If you haven't already, set upauthentication. Authentication verifies your identity for access to Google Cloud services and APIs. To run code or samples from a local development environment, you can authenticate to Compute Engine by selecting one of the following options:
Select the tab for how you plan to use the samples on this page:
Console
When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.
gcloud
Install the Google Cloud CLI. After installation,initialize the Google Cloud CLI by running the following command:
gcloudinit
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.- Set a default region and zone.
Go
To use the Go samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Java
To use the Java samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Node.js
To use the Node.js samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Python
To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
REST
To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.For more information, seeAuthenticate for using REST in the Google Cloud authentication documentation.
Required roles and permissions
To get the permissions that you need to create a snapshot schedule, ask your administrator to grant you the following IAM roles on the project:
- Compute Instance Admin (v1) (
roles/compute.instanceAdmin.v1) - To connect to a VM that can run as a service account:Service Account User (v1) (
roles/iam.serviceAccountUser)
For more information about granting roles, seeManage access to projects, folders, and organizations.
These predefined roles contain the permissions required to create a snapshot schedule. To see the exact permissions that are required, expand theRequired permissions section:
Required permissions
The following permissions are required to create a snapshot schedule:
- To view snapshot schedules:
compute.resourcePolicies.liston the project or organization - To update a snapshot schedule:
compute.resourcePolicies.updateon the resource policycompute.resourcePolicies.geton the resource policy
- To replace a snapshot schedule:
compute.resourcePolicies.useon the resource policycompute.disks.addResourcePolicieson the diskcompute.disks.removeResourcePolicieson the disk
- To delete a snapshot schedule:
compute.resourcePolicies.deleteon the resource policycompute.disks.removeResourcePolicieson the disk
You might also be able to get these permissions withcustom roles or otherpredefined roles.
View snapshot schedules
To get a list of snapshot schedules, use the console,gcloud command,or the Compute Engine API method.This request displays the name, description, and region of allsnapshot schedules within a project.
Console
- In the Google Cloud console, go to theSnapshots page.
- Select theSnapshot schedules tab.
- Use theFilter fieldto narrow the list of snapshot schedules.
- Click the name of a snapshot schedule to see its details.
gcloud
To see a list of your snapshot schedules, use theresource-policies list command.
gcloud compute resource-policies listTo see the description of a specific snapshot schedule, use theresource-policies describe command.
gcloud compute resource-policies describeSCHEDULE_NAMEReplaceSCHEDULE_NAME with the name of the snapshotschedule.
Go
List snapshot schedules
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/api/iterator""google.golang.org/protobuf/proto")// listSnapshotSchedule retrieves a list of snapshot schedules.funclistSnapshotSchedule(wio.Writer,projectID,region,filterstring)error{// projectID := "your_project_id"// snapshotName := "your_snapshot_name"// region := "eupore-central2"// Formatting for filters:// https://cloud.google.com/python/docs/reference/compute/latest/google.cloud.compute_v1.types.ListResourcePoliciesRequestctx:=context.Background()snapshotsClient,err:=compute.NewResourcePoliciesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewResourcePoliciesRESTClient: %w",err)}defersnapshotsClient.Close()req:=&computepb.ListResourcePoliciesRequest{Project:projectID,Region:region,Filter:proto.String(filter),}it:=snapshotsClient.List(ctx,req)for{policy,err:=it.Next()iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Fprintf(w,"- %s",policy.GetName())}returnnil}Describe a snapshot schedule
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb")// getSnapshotSchedule gets a snapshot schedule.funcgetSnapshotSchedule(wio.Writer,projectID,scheduleName,regionstring)error{// projectID := "your_project_id"// snapshotName := "your_snapshot_name"// region := "eupore-central2"ctx:=context.Background()snapshotsClient,err:=compute.NewResourcePoliciesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewResourcePoliciesRESTClient: %w",err)}defersnapshotsClient.Close()req:=&computepb.GetResourcePolicyRequest{Project:projectID,Region:region,ResourcePolicy:scheduleName,}schedule,err:=snapshotsClient.Get(ctx,req)iferr!=nil{returnfmt.Errorf("unable to get snapshot schedule: %w",err)}fmt.Fprintf(w,"Found snapshot schedule: %s\n",schedule.GetName())returnnil}Java
List snapshot schedules
importcom.google.cloud.compute.v1.ListResourcePoliciesRequest;importcom.google.cloud.compute.v1.ResourcePoliciesClient;importcom.google.cloud.compute.v1.ResourcePoliciesClient.ListPagedResponse;importcom.google.cloud.compute.v1.ResourcePolicy;importjava.io.IOException;publicclassListSnapshotSchedules{publicstaticvoidmain(String[]args)throwsIOException{// 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 region you want to list snapshot schedules from.Stringregion="us-central1";// Name of the snapshot schedule you want to list.StringsnapshotScheduleName="YOUR_SCHEDULE_NAME";listSnapshotSchedules(projectId,region,snapshotScheduleName);}// Lists snapshot schedules in a specified region, optionally filtered.publicstaticListPagedResponselistSnapshotSchedules(StringprojectId,Stringregion,StringsnapshotScheduleName)throwsIOException{Stringfilter=String.format("name = %s",snapshotScheduleName);// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests.try(ResourcePoliciesClientresourcePoliciesClient=ResourcePoliciesClient.create()){ListResourcePoliciesRequestrequest=ListResourcePoliciesRequest.newBuilder().setProject(projectId).setRegion(region).setFilter(filter).build();ListPagedResponseresponse=resourcePoliciesClient.list(request);for(ResourcePolicyresourcePolicy:response.iterateAll()){System.out.println(resourcePolicy);}returnresponse;}}}Describe a snapshot schedules
importcom.google.cloud.compute.v1.GetResourcePolicyRequest;importcom.google.cloud.compute.v1.ResourcePoliciesClient;importcom.google.cloud.compute.v1.ResourcePolicy;importjava.io.IOException;publicclassGetSnapshotSchedule{publicstaticvoidmain(String[]args)throwsIOException{// 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 region in which your snapshot schedule is located.Stringregion="us-central1";// Name of your snapshot schedule.StringsnapshotScheduleName="YOUR_SCHEDULE_NAME";getSnapshotSchedule(projectId,region,snapshotScheduleName);}// Retrieves the details of a snapshot schedule.publicstaticResourcePolicygetSnapshotSchedule(StringprojectId,Stringregion,StringsnapshotScheduleName)throwsIOException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests.try(ResourcePoliciesClientresourcePoliciesClient=ResourcePoliciesClient.create()){GetResourcePolicyRequestrequest=GetResourcePolicyRequest.newBuilder().setProject(projectId).setRegion(region).setResourcePolicy(snapshotScheduleName).build();ResourcePolicyresourcePolicy=resourcePoliciesClient.get(request);System.out.println(resourcePolicy);returnresourcePolicy;}}}Node.js
// Import the Compute libraryconstcomputeLib=require('@google-cloud/compute');// Instantiate a resourcePoliciesClientconstresourcePoliciesClient=newcomputeLib.ResourcePoliciesClient();/** * TODO(developer): Update/uncomment these variables before running the sample. */// The project name.constprojectId=awaitresourcePoliciesClient.getProjectId();// The location of the snapshot schedule resource policy.// region = 'us-central1';// The name of the snapshot schedule.// snapshotScheduleName = 'snapshot-schedule-name';asyncfunctioncallGetSnapshotSchedule(){const[response]=awaitresourcePoliciesClient.get({project:projectId,region,resourcePolicy:snapshotScheduleName,});console.log(JSON.stringify(response));}awaitcallGetSnapshotSchedule();Python
List snapshot schedules
fromgoogle.cloudimportcompute_v1fromgoogle.cloud.compute_v1.services.resource_policiesimportpagersdefsnapshot_schedule_list(project_id:str,region:str)->pagers.ListPager:""" Lists snapshot schedules for a specified project and region. Args: project_id (str): The ID of the Google Cloud project. region (str): The region where the snapshot schedules are located. Returns: ListPager: A pager for iterating through the list of snapshot schedules. """client=compute_v1.ResourcePoliciesClient()request=compute_v1.ListResourcePoliciesRequest(project=project_id,region=region,filter='status = "READY"',# Optional filter)schedules=client.list(request=request)returnschedulesDescribe a snapshot schedule
fromgoogle.cloudimportcompute_v1defsnapshot_schedule_get(project_id:str,region:str,snapshot_schedule_name:str)->compute_v1.ResourcePolicy:""" Retrieves a snapshot schedule for a specified project and region. Args: project_id (str): The ID of the Google Cloud project. region (str): The region where the snapshot schedule is located. snapshot_schedule_name (str): The name of the snapshot schedule. Returns: compute_v1.ResourcePolicy: The retrieved snapshot schedule. """client=compute_v1.ResourcePoliciesClient()schedule=client.get(project=project_id,region=region,resource_policy=snapshot_schedule_name)returnscheduleREST
Make aGET a request toresourcePolicies.aggregatedListto return a list of the snapshot schedules for a project.
GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/aggregated/resourcePoliciesReplacePROJECT_ID with the project name.
View snapshot schedules by region
To view the snapshot schedules for a project within a particular region, use theGoogle Cloud console, gcloud CLI, or REST.
Console
- In the Google Cloud console, go to theSnapshots page.
- Select theSnapshot schedules tab.
- Use theFilter fieldto list snapshot schedules for a specific region.
gcloud
To view the snapshot schedules for a project within a specific region,use theresource-policies list command.
gcloud compute resource-policies listPROJECT_ID --filterREGIONReplace the following:
PROJECT_ID: the project nameREGION: the region, for exampleus-west1
REST
Make aGET request toresourcePolicies.list methodto retrieve the snapshot schedules created within in a region.
GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePoliciesReplace the following:
PROJECT_ID: the project nameREGION: the region, for exampleus-west1
Change a snapshot schedule
After you create a snapshot schedule, you can modify the following fieldsdynamically, using theUpdate a snapshot scheduleprocedure:
- Description
- Snapshot schedule
- Labels applied to the generated snapshots
- Source disk deletion policy for handling auto-generated snapshots if thesource disk is deleted
- Retention policy to define how long to keep snapshots that are generatedfrom the snapshot schedule
To update other values for a snapshot schedule, you must delete the snapshotschedule and create a new one, as described inReplace a snapshot schedule.
The snapshot schedule updates take effect in the first snapshot after theupdates. If a snapshot is running while you update the snapshot schedule, thechanges take effect in the following snapshot.
Note: When you update a snapshot schedule, only the snapshots created after the update use the updated snapshot schedule values; existing snapshots are not updated.Update a snapshot schedule
You can use Google Cloud CLI or the Compute Engine APIto change some of the properties of your snapshot schedule, as described inChange a snapshot schedule.
To change other properties of your snapshot schedule, use themethod described inReplace a snapshot schedule.
Console
- In the Google Cloud console, go to theSnapshots page.
- SelectSnapshot schedules to see a list of your schedules.
- Click the name of the snapshot schedule that you want to modify.
- On the snapshot schedule detail page, click theEdit schedulebutton.
gcloud
Use thecompute resource-policies update commandto update a snapshot schedule's description, schedule, retention policy, orlabels.
gcloud compute resource-policies update snapshot-scheduleSCHEDULE_NAME \ --region=REGION \ --description="DESCRIPTION" \ --snapshot-labels="KEY=VALUE" \ --max-retention-days=DAYS \ --on-source-disk-delete=DELETE_OPTION \ --start-time=START_TIME \SCHEDULE_FLAGReplace the following:
- SCHEDULE_NAME: the name of the snapshotschedule.
- REGION: the region where yoursnapshot schedule resides.
- DESCRIPTION: a description of the snapshot schedule. Use quotes around your description.
- KEY andVALUE: a key-valuepair that can be used togroup related or associated resources.
- DAYS: Maximum number of days snapshot is retainedbefore being deleted.
- DELETE_OPTION: Retention behavior of automaticsnapshots after the original disk is deleted. The value must be one of:
apply-retention-policy: When the source disk is deleted, continue to apply the retention window for any snapshots created by the snapshot schedule.keep-auto-snapshots: (Default) If the source disk is deleted, keep any snapshots created by the snapshot schedule, regardless of the retention window.
- START_TIME: the UTC start time. The timemust 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
SCHEDULE_FLAG: one of the following flags:
--hourly-schedule=HOURLY_INTERVAL: the number of hours between every snapshot. TheHOURLY_INTERVALmust be an integer between1and23. For example, setting--hourly-scheduleto 12, means the snapshot is generated every 12 hours.--daily-schedule: performs a snapshot daily, at theSTART_TIME
Note: If you want to specify a weekly schedule with different days of the week and with different start times, use the--weekly-schedule=WEEKLY_INTERVAL: definesthe day you want the snapshotting to occur. You must spell out theweek day; the values are not case-sensitive.--weekly-schedule-from-fileflag instead of--weekly-schedule.--weekly-schedule-from-file=FILE_NAME:specifies a file that contains the weekly snapshot schedule. Youcan specify weekly schedules on different days of the weekand at different times using a file. For example, yourfile might specify a snapshot schedule on Monday and Wednesday:none[{"day": "MONDAY", "startTime": "04:00"}, {"day": "WEDNESDAY", "startTime": "02:00"}]If you include a start time in your file,you don't need to set the--start-timeflag. The schedule usesthe UTC time zone. 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
The snapshot frequency flags
hourly-schedule,daily-schedule,weekly-schedule, andweekly-schedule-from-filearemutually-exclusive. You can use only one for your snapshot schedule.
Examples:
To change a snapshot schedule to a daily schedule:
gcloud compute resource-policies update snapshot-scheduleSCHEDULE_NAME \ --region=REGION --daily-schedule --start-time=START_TIMETo change a snapshot to an hourly schedule, and also update the descriptionand snapshot label:
gcloud compute resource-policies update snapshot-scheduleSCHEDULE_NAME \ --region=REGION --description="DESCRIPTION" \ --hourly-schedule=HOURLY_INTERVAL --start-time=START_TIME \ --snapshot-labels="KEY=VALUE"To change a snapshot retention and source disk deletion policies for asnapshot schedule:
gcloud compute resource-policies update snapshot-scheduleSCHEDULE_NAME \ --region=REGION --max-retention-days=DAYS \ --on-source-disk-delete=DELETE_OPTIONGo
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/protobuf/proto")// editSnapshotSchedule edits a snapshot schedule.funceditSnapshotSchedule(wio.Writer,projectID,scheduleName,regionstring)error{// projectID := "your_project_id"// snapshotName := "your_snapshot_name"// region := "eupore-central2"ctx:=context.Background()snapshotsClient,err:=compute.NewResourcePoliciesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewResourcePoliciesRESTClient: %w",err)}defersnapshotsClient.Close()req:=&computepb.PatchResourcePolicyRequest{Project:projectID,Region:region,ResourcePolicy:scheduleName,ResourcePolicyResource:&computepb.ResourcePolicy{Name:proto.String(scheduleName),Description:proto.String("MY HOURLY SNAPSHOT SCHEDULE"),SnapshotSchedulePolicy:&computepb.ResourcePolicySnapshotSchedulePolicy{Schedule:&computepb.ResourcePolicySnapshotSchedulePolicySchedule{HourlySchedule:&computepb.ResourcePolicyHourlyCycle{HoursInCycle:proto.Int32(12),StartTime:proto.String("22:00"),},},},},}op,err:=snapshotsClient.Patch(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create snapshot schedule: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprint(w,"Snapshot schedule changed\n")returnnil}Java
importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.Operation.Status;importcom.google.cloud.compute.v1.PatchResourcePolicyRequest;importcom.google.cloud.compute.v1.ResourcePoliciesClient;importcom.google.cloud.compute.v1.ResourcePolicy;importcom.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicy;importcom.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicyRetentionPolicy;importcom.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicyRetentionPolicy.OnSourceDiskDelete;importcom.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicySchedule;importcom.google.cloud.compute.v1.ResourcePolicySnapshotSchedulePolicySnapshotProperties;importcom.google.cloud.compute.v1.ResourcePolicyWeeklyCycle;importcom.google.cloud.compute.v1.ResourcePolicyWeeklyCycleDayOfWeek;importjava.io.IOException;importjava.util.HashMap;importjava.util.Map;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassEditSnapshotSchedule{publicstaticvoidmain(String[]args)throwsException{// 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 region where your snapshot schedule is located.Stringregion="us-central1";// Name of the snapshot schedule you want to update.StringsnapshotScheduleName="YOUR_SCHEDULE_NAME";editSnapshotSchedule(projectId,region,snapshotScheduleName);}// Edits a snapshot schedule.publicstaticStatuseditSnapshotSchedule(StringprojectId,Stringregion,StringsnapshotScheduleName)throwsIOException,InterruptedException,ExecutionException,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.try(ResourcePoliciesClientresourcePoliciesClient=ResourcePoliciesClient.create()){Map<String,String>snapshotLabels=newHashMap<>();snapshotLabels.put("key","value");ResourcePolicySnapshotSchedulePolicySnapshotProperties.BuildersnapshotProperties=ResourcePolicySnapshotSchedulePolicySnapshotProperties.newBuilder();snapshotProperties.putAllLabels(snapshotLabels);ResourcePolicyWeeklyCycleDayOfWeekdayOfWeek=ResourcePolicyWeeklyCycleDayOfWeek.newBuilder().setDay("Tuesday").setStartTime("09:00").build();ResourcePolicyWeeklyCycleweeklySchedule=ResourcePolicyWeeklyCycle.newBuilder().addDayOfWeeks(dayOfWeek).build();intmaxRetentionDays=3;ResourcePolicySnapshotSchedulePolicyRetentionPolicy.BuilderretentionPolicy=ResourcePolicySnapshotSchedulePolicyRetentionPolicy.newBuilder();retentionPolicy.setOnSourceDiskDelete(OnSourceDiskDelete.APPLY_RETENTION_POLICY.toString());retentionPolicy.setMaxRetentionDays(maxRetentionDays);Stringdescription="Updated description";ResourcePolicyupdatedSchedule=ResourcePolicy.newBuilder().setName(snapshotScheduleName).setDescription(description).setSnapshotSchedulePolicy(ResourcePolicySnapshotSchedulePolicy.newBuilder().setSchedule(ResourcePolicySnapshotSchedulePolicySchedule.newBuilder().setWeeklySchedule(weeklySchedule)).setSnapshotProperties(snapshotProperties).setRetentionPolicy(retentionPolicy.build()).build()).build();PatchResourcePolicyRequestrequest=PatchResourcePolicyRequest.newBuilder().setProject(projectId).setRegion(region).setResourcePolicy(snapshotScheduleName).setResourcePolicyResource(updatedSchedule).build();Operationresponse=resourcePoliciesClient.patchAsync(request).get(3,TimeUnit.MINUTES);if(response.hasError()){thrownewError("Failed to update snapshot schedule! "+response.getError());}returnresponse.getStatus();}}}Node.js
// Import the Compute libraryconstcomputeLib=require('@google-cloud/compute');constcompute=computeLib.protos.google.cloud.compute.v1;// Instantiate a resourcePoliciesClientconstresourcePoliciesClient=newcomputeLib.ResourcePoliciesClient();// Instantiate a regionOperationsClientconstregionOperationsClient=newcomputeLib.RegionOperationsClient();/** * TODO(developer): Update/uncomment these variables before running the sample. */// The project name.constprojectId=awaitresourcePoliciesClient.getProjectId();// The location of the snapshot schedule resource policy.// region = 'us-central1';// The name of the snapshot schedule.// snapshotScheduleName = 'snapshot-schedule-name';asyncfunctioncallEditSnapshotSchedule(){const[response]=awaitresourcePoliciesClient.patch({project:projectId,region,resourcePolicy:snapshotScheduleName,resourcePolicyResource:compute.ResourcePolicy({snapshotSchedulePolicy:compute.ResourcePolicyInstanceSchedulePolicySchedule({schedule:compute.ResourcePolicySnapshotSchedulePolicySchedule({weeklySchedule:compute.ResourcePolicyWeeklyCycle({dayOfWeeks:[compute.ResourcePolicyWeeklyCycleDayOfWeek({day:'Tuesday',startTime:'9:00',}),],}),}),}),}),});letoperation=response.latestResponse;// Wait for the edit operation to complete.while(operation.status!=='DONE'){[operation]=awaitregionOperationsClient.wait({operation:operation.name,project:projectId,region,});}console.log(`Snapshot schedule:${snapshotScheduleName} edited.`);}awaitcallEditSnapshotSchedule();Python
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)returnresultdefsnapshot_schedule_update(project_id:str,region:str,schedule_name:str,schedule_description:str,labels:dict,)->compute_v1.ResourcePolicy:""" Updates a snapshot schedule for a specified project and region. Args: project_id (str): The ID of the Google Cloud project. region (str): The region where the snapshot schedule is located. schedule_name (str): The name of the snapshot schedule to update. schedule_description (str): The new description for the snapshot schedule. labels (dict): A dictionary of new labels to apply to the snapshot schedule. Returns: compute_v1.ResourcePolicy: The updated snapshot schedule. """# Every Monday, starts between 12:00 AM and 1:00 AMday=compute_v1.ResourcePolicyWeeklyCycleDayOfWeek(day="MONDAY",start_time="00:00")weekly_schedule=compute_v1.ResourcePolicyWeeklyCycle(day_of_weeks=[day])schedule=compute_v1.ResourcePolicySnapshotSchedulePolicySchedule()# You can change the schedule type to daily_schedule, weekly_schedule, or hourly_scheduleschedule.weekly_schedule=weekly_schedule# Autodelete snapshots after 10 daysretention_policy=compute_v1.ResourcePolicySnapshotSchedulePolicyRetentionPolicy(max_retention_days=10)snapshot_properties=(compute_v1.ResourcePolicySnapshotSchedulePolicySnapshotProperties(guest_flush=False,labels=labels))snapshot_policy=compute_v1.ResourcePolicySnapshotSchedulePolicy()snapshot_policy.schedule=schedulesnapshot_policy.retention_policy=retention_policysnapshot_policy.snapshot_properties=snapshot_propertiesresource_policy_resource=compute_v1.ResourcePolicy(name=schedule_name,description=schedule_description,snapshot_schedule_policy=snapshot_policy,)client=compute_v1.ResourcePoliciesClient()operation=client.patch(project=project_id,region=region,resource_policy=schedule_name,resource_policy_resource=resource_policy_resource,)wait_for_extended_operation(operation,"Resource Policy updating")returnclient.get(project=project_id,region=region,resource_policy=schedule_name)REST
Construct aPATCH request to theresourcePolicies methodto update a snapshot schedule's description, schedule, retention policy,source disk deletion policy, or labels. In the request body, you only needto specify thename and the fields you want to update.
Change the description and label:
PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAME{ "name": "SCHEDULE_NAME", "description": "DESCRIPTION", "snapshotProperties": { "labels": {"KEY": "VALUE"} }}Change the snapshot schedule to hourly:
PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAME{ "name": "SCHEDULE_NAME", "snapshotSchedulePolicy": { "schedule": { "hourlySchedule": { "hoursInCycle":HOURLY_INTERVAL, "startTime":START_TIME } } }}Change the snapshot schedule to daily:
PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAME{ "name": "SCHEDULE_NAME", "snapshotSchedulePolicy": { "schedule": { "dailySchedule": { "daysInCycle":DAILY_INTERVAL, "startTime":START_TIME } } }}Change the snapshot schedule to weekly:
PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAME{ "name": "SCHEDULE_NAME", "snapshotSchedulePolicy": { "schedule": { "weeklySchedule": { "dayOfWeeks": [ { "day":WEEKLY_INTERVAL, "startTime":START_TIME } ] } } }}Change the snapshot retention policy:
PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAME{ "name": "SCHEDULE_NAME", "snapshotSchedulePolicy": { "retentionPolicy": { "maxRetentionDays":DAYS, "onSourceDiskDelete":"DELETE_OPTION" } }}
Replace the following:
- PROJECT_ID: the project name.
- REGION: the region where the snapshot scheduleis located.
- SCHEDULE_NAME: the name of the snapshotschedule.
- DESCRIPTION: a description of the snapshot schedule. Use quotes around your description.
- KEY andVALUE: a key-value pair that can be used togroup related or associated resources.
- HOURLY_INTERVAL: defines the interval at whichyou want snapshotting to occur. Set the hourly schedule using an integerbetween
1and23. To have the snapshots created at the same timeevery day, choose a number that divides evenly into 24 (1, 2, 3, 4,6, 8, or 12). For example, setting--hourly-scheduleto 12, meansthe snapshot is generated every 12 hours. - DAILY_INTERVAL: defines the number of daysbetween each snapshot. To create a snapshot every day, use thevalue
1. - WEEKLY_INTERVAL: defines a schedule that runs onspecific days of the week. Specify one or more days. The followingoptions are available:
MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY, andSUNDAY. You must spell out the week days;they are not case-sensitive. You can define up to 7 intervals fordayOfWeeks, one for each day of the week. - START_TIME: the UTC start time. The time muststart on the hour. For example:
- 2:00 PM PST is
22:00UTC. - If you set a start time of
22:13, you will receive an error.
- 2:00 PM PST is
- DAYS: Maximum number of days snapshot is retainedbefore being deleted.
- DELETE_OPTION: Retention behavior of automaticsnapshots after the original disk is deleted. The value must be one of:
APPLY_RETENTION_POLICY: When the source disk is deleted, continue to apply the retention window for any snapshots created by the snapshot schedule.KEEP_AUTO_SNAPSHOTS: (Default) If the source disk is deleted, keep any snapshots created by the snapshot schedule, regardless of the retention window.
Replace a snapshot schedule
Follow these steps to delete the snapshot schedule and create a new one. Usethis method to modify snapshot schedule properties that can't bechanged by using theupdate a snapshot schedule procedure.
If you are replacing a snapshot schedule that is already attached to a disk, youmust first detach the schedule from the disk and delete it. Then you can createa new schedule, and attach it to the disk.
Snapshots that are generated from the detached snapshot schedule won't bemanaged by the new policy. Those snapshots will be retained indefinitely untilyou delete them.
Use the Google Cloud console, gcloud CLI, or RESTto remove and replace your snapshot schedule.
Console
- In the Google Cloud console, go to theDisks page.
- Select the disk that has the schedule you want to detach.
- On theManage disk page, clickEdit.You might need to click theMore actions menufirst.
- Open theSnapshot schedule drop-down menu.
- ClickNo schedule to detach the schedule from the disk.
- You can create a new schedule, or swap the schedule while youare editing the disk options.
- ClickSave to complete the task.
gcloud
Use the
gcloud disks remove-resource-policiescommandto detach the snapshot schedule from the disk with the schedule that youwant to change.gcloud compute disks remove-resource-policiesDISK_NAME \ --resource-policiesSCHEDULE_NAME \ --regionREGION \ --zoneZONEReplace the following:
DISK_NAME: the name of the disk with thesnapshot schedule attached to itSCHEDULE_NAME: the name of the snapshotschedule that you want to detach from this diskREGION: the region where your snapshotschedule residesZONE: the zone where your zonal disk resides
Use the
gcloud disks add-resource-policiescommandto add the new snapshot schedule to the disk.gcloud compute disks add-resource-policiesDISK_NAME \ --resource-policiesSCHEDULE_NAME \ --zoneZONEReplace the following:
DISK_NAME: the name of the diskwith the snapshot schedule resource policySCHEDULE_NAME: the name of thesnapshot schedule that you want to add to this diskZONE: the zone where your diskresides
REST
Detach the current snapshot schedule from a disk by constructinga
POSTrequest todisks.removeResourcePolicies.POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/disks/DISK_NAME/removeResourcePolicies{ "resourcePolicies": [ "regions/REGION/resourcePolicies/SCHEDULE_NAME" ]}Replace the following:
PROJECT_ID: the project nameZONE: the zone where the disk residesDISK_NAME: the name of the disk with theassociated snapshot scheduleREGION: the location of the snapshot scheduleSCHEDULE_NAME: the name of the snapshotschedule that you are removing from this disk
Attach the new snapshot schedule to the disk by constructing a
POSTrequest to thedisks.addResourcePoliciesmethod.POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/disks/DISK_NAME/addResourcePolicies{ "resourcePolicies": [ "regions/REGION/resourcePolicies/SCHEDULE_NAME" ]}Replace the following:
PROJECT_ID: the project nameZONE: the location of the diskDISK_NAME: the name of the diskREGION: the location of the snapshot scheduleSCHEDULE_NAME: the name of the snapshotschedule that you are applying to this disk
Delete a snapshot schedule
If you delete a snapshot schedule, all auto-generated snapshots associatedwith the snapshot schedule are kept permanently. However, after the scheduleis deleted, it can no longer generate snapshots.
Your retention policy is part of your snapshot schedule. After the scheduleis deleted, your retention policy no longer applies. Snapshots that havealready been generated are kept permanently until you manually delete them.
To delete an existing snapshot schedule, use theGoogle Cloud console, Google Cloud CLI, or the Compute Engine API method. If theschedule is already attached to a disk,detach the schedule from the disk first,then delete the schedule. You cannot delete a snapshot schedule that isattached to a disk.
Console
- In the Google Cloud console, go to theSnapshots page.
- SelectSnapshot schedules to see a list of your schedules.
- Select any schedule not associated with a disk.
ClickDelete.
Note: If the schedule is already attached to a disk, you mustfirstdetach the schedule from its disk,then you can delete the schedule.
gcloud
To delete a snapshot schedule, use theresource-policies delete command.
gcloud compute resource-policies deleteSCHEDULE_NAME \ --regionREGIONReplace the following:
SCHEDULE_NAME: the name of the snapshot scheduleREGION: the location of the snapshot schedule
Go
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb")// deleteSnapshotSchedule deletes a snapshot schedule.funcdeleteSnapshotSchedule(wio.Writer,projectID,scheduleName,regionstring)error{// projectID := "your_project_id"// snapshotName := "your_snapshot_name"// region := "eupore-central2"ctx:=context.Background()snapshotsClient,err:=compute.NewResourcePoliciesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewResourcePoliciesRESTClient: %w",err)}defersnapshotsClient.Close()req:=&computepb.DeleteResourcePolicyRequest{Project:projectID,Region:region,ResourcePolicy:scheduleName,}op,err:=snapshotsClient.Delete(ctx,req)iferr!=nil{returnfmt.Errorf("unable to delete snapshot schedule: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprint(w,"Snapshot schedule deleted\n")returnnil}Java
importcom.google.cloud.compute.v1.DeleteResourcePolicyRequest;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.Operation.Status;importcom.google.cloud.compute.v1.ResourcePoliciesClient;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassDeleteSnapshotSchedule{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 region where your snapshot schedule is located.Stringregion="us-central1";// Name of the snapshot schedule you want to delete.StringsnapshotScheduleName="YOUR_SCHEDULE_NAME";deleteSnapshotSchedule(projectId,region,snapshotScheduleName);}// Deletes a snapshot schedule policy.publicstaticStatusdeleteSnapshotSchedule(StringprojectId,Stringregion,StringsnapshotScheduleName)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.try(ResourcePoliciesClientresourcePoliciesClient=ResourcePoliciesClient.create()){DeleteResourcePolicyRequestrequest=DeleteResourcePolicyRequest.newBuilder().setProject(projectId).setRegion(region).setResourcePolicy(snapshotScheduleName).build();Operationresponse=resourcePoliciesClient.deleteAsync(request).get(3,TimeUnit.MINUTES);if(response.hasError()){thrownewError("Snapshot schedule deletion failed! "+response.getError());}returnresponse.getStatus();}}}Node.js
// Import the Compute libraryconstcomputeLib=require('@google-cloud/compute');// Instantiate a resourcePoliciesClientconstresourcePoliciesClient=newcomputeLib.ResourcePoliciesClient();// Instantiate a regionOperationsClientconstregionOperationsClient=newcomputeLib.RegionOperationsClient();/** * TODO(developer): Update/uncomment these variables before running the sample. */// The project name.constprojectId=awaitresourcePoliciesClient.getProjectId();// The location of the snapshot schedule resource policy.// region = 'us-central1';// The name of the snapshot schedule.// snapshotScheduleName = 'snapshot-schedule-name'asyncfunctioncallDeleteSnapshotSchedule(){// If the snapshot schedule is already attached to a disk, you will receive an error.const[response]=awaitresourcePoliciesClient.delete({project:projectId,region,resourcePolicy:snapshotScheduleName,});letoperation=response.latestResponse;// Wait for the delete operation to complete.while(operation.status!=='DONE'){[operation]=awaitregionOperationsClient.wait({operation:operation.name,project:projectId,region,});}console.log(`Snapshot schedule:${snapshotScheduleName} deleted.`);}awaitcallDeleteSnapshotSchedule();Python
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)returnresultdefsnapshot_schedule_delete(project_id:str,region:str,snapshot_schedule_name:str)->None:""" Deletes a snapshot schedule for a specified project and region. Args: project_id (str): The ID of the Google Cloud project. region (str): The region where the snapshot schedule is located. snapshot_schedule_name (str): The name of the snapshot schedule to delete. Returns: None """client=compute_v1.ResourcePoliciesClient()operation=client.delete(project=project_id,region=region,resource_policy=snapshot_schedule_name)wait_for_extended_operation(operation,"Resource Policy deletion")REST
To delete a snapshot schedule, make aDELETE request toresourcePolicies.delete method.If the snapshot schedule is already attached to a disk, you will receivean error.
DELETE https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies/SCHEDULE_NAMEReplace the following:
PROJECT_ID: the project nameREGION: the location of the snapshot scheduleSCHEDULE_NAME: the name of the snapshot schedule
Logging and monitoring
Every scheduled snapshot associated with a disk is continuously creatingasystem event,which is monitored and logged at all times. The system event audit logs arealways enabled.
These logs provide behavioral information about yourscheduled snapshots for each associated disk. You can view your logs from theLogging menu in the Google Cloud console.
For more information about using the Logs Explorer, seeView logs by using the Logs Explorer.
Console
In the Google Cloud console, go to theLogs Explorer page.
In theAll resource drop-down list, point toDisk and selectAll disk_id.
In theAll logs drop-down list, selectcloudaudit.googleapis.com/system_event and clickOK.
In theAny log level drop-down list, select the log type.
What's next
- Learn about snapshot schedule frequencies, retention policies, and namingrules inAbout snapshot schedules for disks.
- View and delete the generated snapshots, as described inManage disk snapshots.
- Learn how toview logs.
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.