Create schedules for disk snapshots Stay organized with collections Save and categorize content based on your preferences.
You create a snapshot schedule to regularly and automatically back upzonal and regionalPersistent Disk andGoogle Cloud Hyperdisk volumes.Use snapshot schedules as a best practice to back up your Compute Engineworkloads.
If you want to create a snapshot schedule that captures the state ofthe application data at the time of back up, also referred to as anapplication consistent,guest-flush, orVSS snapshot, seeCreate Linux application consistent disk snapshotsorCreate a Windows application consistent disk snapshot.
For more information about the snapshot schedule properties, seeSnapshot schedule properties.
Before you begin
- Review theLimitationsfor snapshot schedules.
- 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 create a snapshot schedule:
compute.resourcePolicies.createon the project or organization - To attach a snapshot schedule to a disk:
compute.disks.addResourcePolicieson the diskcompute.resourcePolicies.useon the resource policy
- To create a disk with a snapshot schedule:
compute.disks.createon the projectcompute.resourcePolicies.createon the projectcompute.disks.addResourcePolicieson the disk
You might also be able to get these permissions withcustom roles or otherpredefined roles.
Overview of creating snapshot schedules
When you create a snapshot schedule, you create aresource policythat you can apply to one or more Persistent Disk or Hyperdiskvolumes.
You can create snapshot schedules in the following ways:
- Create a snapshot schedule and thenattach it to an existing disk.
- Create a new disk with a snapshot schedule.
Using encryption with snapshot schedules
If a disk uses acustomer-managed encryption key (CMEK),when you use a snapshot schedule to create snapshots of that disk, all thecreated snapshots are automatically encrypted with the same key.
You can't use snapshot schedules with disks that use acustomer-supplied encryption key (CSEK).
Create a snapshot schedule
You can create a snapshot schedule for your disks using the Google Cloud console,Google Cloud CLI, or REST. You must create your snapshotschedule in the same region where your disk resides. For example, ifyour disk resides in zoneus-west1-a, you must create the snapshot schedulein theus-west1 region. However, you can choose to store thesnapshots generated by the snapshot schedule in a different 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 schedule globally scoped snapshots for a disk, use the
gcloud compute resource-policies create snapshot-schedulecommand.Set your schedule frequency to hourly, daily, or weekly.gcloud compute resource-policies create snapshot-scheduleSCHEDULE_NAME \ --description "SCHEDULE_DESCRIPTION" \ --max-retention-daysMAX_RETENTION_DAYS \ --start-timeSTART_TIME \ --hourly-scheduleSNAPSHOT_INTERVAL \ --daily-schedule \ --weekly-scheduleSNAPSHOT_INTERVAL or --weekly-schedule-from-fileFILE_NAME \ --on-source-disk-deleteDELETION_OPTION \ --storage-location=STORAGE_LOCATION(Preview) To schedule regionallyscoped snapshots for a disk, use the
gcloud compute resource-policies create snapshot-schedulecommandand specify the snapshot region.gcloud beta compute resource-policies create snapshot-scheduleSCHEDULE_NAME \ --description "SCHEDULE_DESCRIPTION" \ --max-retention-daysMAX_RETENTION_DAYS \ --start-timeSTART_TIME \ --hourly-scheduleSNAPSHOT_INTERVAL \ --daily-schedule \ --weekly-scheduleSNAPSHOT_INTERVAL or --weekly-schedule-from-fileFILE_NAME \ --on-source-disk-deleteDELETION_OPTION \ --storage-location=STORAGE_LOCATION \ --regionREGION \ --snapshot-regionSNAPSHOT_REGION
Replace the following:
SCHEDULE_NAME: the name of the snapshotschedule.SCHEDULE_DESCRIPTION: a description of thesnapshot schedule. Use quotes around your description.REGION: the location of the snapshot schedule resource policy.SNAPSHOT_REGION: the region that the scheduledsnapshot is scoped to.MAX_RETENTION_DAYS: the number of days toretain the snapshot.For example, a value of
3means that the snapshots are retained for 3days before being deleted. You must use a value of1or higher.START_TIME: the start time in the UTC timezone. The time must start on the hour.For example:
- 2:00 PM PST must be specified as
22:00. - If you set a start time of
22:13, you receive an error.
If you use the
--weekly-schedule-from-fileflag and specify a starttime within the file, you don't need to include this flag.- 2:00 PM PST must be specified as
SNAPSHOT_INTERVAL: the interval between creatingsuccessive snapshots. The snapshot frequency flagshourly-schedule,daily-schedule,weekly-schedule, andweekly-schedule-from-filearemutually-exclusive. You can use only one for your snapshot schedule.- Set a daily schedule by including the
--daily-scheduleflag withoutany value. - Set an hourly schedule with the
--hourly-scheduleflag set to aninteger value between 1 and 23. To generate snapshots at the sametime every day, choose an hourly number that is evenly dividedinto 24. For example, setting--hourly-scheduleto12, means asnapshot is created every 12 hours. - Set a weekly schedule with the
--weekly-scheduleflag set to theday of the week on which you want the snapshot to be created.You must spell out the week day; the values are not case-sensitive.For example, to back up your disk every Friday, your command wouldinclude--weekly-schedule=friday. Set an advanced weekly schedule, specifying different days of theweek and with different start times by including the
--weekly-schedule-from-fileflag. ReplaceFILE_NAMEwith the filename that containsthe weekly snapshot schedule. While you can specify different daysof the week and different start times using a file, you can't specifymultiple weekly schedules directly on the command-line. For example,your file might specify two weekly schedules, on Monday andWednesday, but you can't duplicate this setting on the command line:[ {"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 on the command line. The schedule uses the UTC time zone.
- Set a daily schedule by including the
DELETION_OPTION: determines what happens toyour snapshots if the source disk is deleted. If you want to keep allgenerated snapshots, you can omit this flag. Otherwise, specifyapply-retention-policyto use the settings in a retention policy.STORAGE_LOCATION: Optional: thestorage location. If you omit this flag, the default storage location is used.
Examples
In all the 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 manually set to
US, so all generated snapshotsare stored 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 (14:00 PST) and occurs every 4 hours.
gcloud compute resource-policies create snapshot-schedule hourly-schedule1 \ --description "MY HOURLY SNAPSHOT SCHEDULE" \ --max-retention-days 10 \ --start-time 22:00 \ --hourly-schedule 4 \ --region us-west1 \ --on-source-disk-delete keep-auto-snapshots \ --snapshot-labels env=dev,media=images \ --storage-location USDaily schedule: In this example, the snapshot schedule starts at 22:00UTC (14:00 PST) and occurs every day at the same time. The--daily-schedule flag must be present, but without an associated value.
gcloud compute resource-policies create snapshot-schedule daily-schedule2 \ --description "MY DAILY SNAPSHOT SCHEDULE" \ --max-retention-days 10 \ --start-time 22:00 \ --daily-schedule \ --region us-west1 \ --on-source-disk-delete keep-auto-snapshots \ --snapshot-labels env=dev,media=images \ --storage-location USWeekly schedule: In this example, the snapshot schedule starts at 22:00UTC (14:00 PST) and occurs every week on Tuesday.
gcloud compute resource-policies create snapshot-schedule weekly-schedule3 \ --description "MY WEEKLY SNAPSHOT SCHEDULE" \ --max-retention-days 10 \ --start-time 22:00 \ --weekly-schedule tuesday \ --region us-west1 \ --on-source-disk-delete keep-auto-snapshots \ --snapshot-labels env=dev,media=images \ --storage-location USGo
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/protobuf/proto")// createSnapshotSchedule creates a snapshot schedule.funccreateSnapshotSchedule(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.InsertResourcePolicyRequest{Project:projectID,Region:region,ResourcePolicyResource:&computepb.ResourcePolicy{Name:proto.String(scheduleName),Description:proto.String("MY DAILY SNAPSHOT SCHEDULE"),Region:proto.String("europe-central2"),SnapshotSchedulePolicy:&computepb.ResourcePolicySnapshotSchedulePolicy{RetentionPolicy:&computepb.ResourcePolicySnapshotSchedulePolicyRetentionPolicy{MaxRetentionDays:proto.Int32(10),// Check the OnSourceDiskDelete enum for the list of possible values.OnSourceDiskDelete:proto.String("KEEP_AUTO_SNAPSHOTS"),},Schedule:&computepb.ResourcePolicySnapshotSchedulePolicySchedule{DailySchedule:&computepb.ResourcePolicyDailyCycle{DaysInCycle:proto.Int32(1),StartTime:proto.String("22:00"),},},SnapshotProperties:&computepb.ResourcePolicySnapshotSchedulePolicySnapshotProperties{StorageLocations:[]string{"eu"},Labels:map[string]string{"env":"dev","media":"images",},},},},}op,err:=snapshotsClient.Insert(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 created\n")returnnil}Java
importcom.google.cloud.compute.v1.InsertResourcePolicyRequest;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.Operation.Status;importcom.google.cloud.compute.v1.ResourcePoliciesClient;importcom.google.cloud.compute.v1.ResourcePolicy;importcom.google.cloud.compute.v1.ResourcePolicyHourlyCycle;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;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateSnapshotSchedule{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 in which you want to create the snapshot schedule.Stringregion="us-central1";// Name of the snapshot schedule you want to create.StringsnapshotScheduleName="YOUR_SCHEDULE_NAME";// Description of the snapshot schedule.StringscheduleDescription="YOUR_SCHEDULE_DESCRIPTION";// Maximum number of days to retain snapshots.intmaxRetentionDays=10;// Storage location for the snapshots.// More about storage locations:// https://cloud.google.com/compute/docs/disks/snapshots?authuser=0#selecting_a_storage_locationStringstorageLocation="US";createSnapshotSchedule(projectId,region,snapshotScheduleName,scheduleDescription,maxRetentionDays,storageLocation);}// Creates a snapshot schedule policy.publicstaticStatuscreateSnapshotSchedule(StringprojectId,Stringregion,StringsnapshotScheduleName,StringscheduleDescription,intmaxRetentionDays,StringstorageLocation)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()){intsnapshotInterval=10;// Create a snapshot every 10 hoursStringstartTime="08:00";// Define the hourly scheduleResourcePolicyHourlyCyclehourlyCycle=ResourcePolicyHourlyCycle.newBuilder().setHoursInCycle(snapshotInterval).setStartTime(startTime).build();ResourcePolicySnapshotSchedulePolicyRetentionPolicyretentionPolicy=ResourcePolicySnapshotSchedulePolicyRetentionPolicy.newBuilder().setMaxRetentionDays(maxRetentionDays).setOnSourceDiskDelete(OnSourceDiskDelete.KEEP_AUTO_SNAPSHOTS.toString()).build();ResourcePolicySnapshotSchedulePolicySnapshotPropertiessnapshotProperties=ResourcePolicySnapshotSchedulePolicySnapshotProperties.newBuilder().addStorageLocations(storageLocation).build();ResourcePolicySnapshotSchedulePolicysnapshotSchedulePolicy=ResourcePolicySnapshotSchedulePolicy.newBuilder().setRetentionPolicy(retentionPolicy).setSchedule(ResourcePolicySnapshotSchedulePolicySchedule.newBuilder().setHourlySchedule(hourlyCycle).build()).setSnapshotProperties(snapshotProperties).build();ResourcePolicyresourcePolicy=ResourcePolicy.newBuilder().setName(snapshotScheduleName).setDescription(scheduleDescription).setSnapshotSchedulePolicy(snapshotSchedulePolicy).build();InsertResourcePolicyRequestrequest=InsertResourcePolicyRequest.newBuilder().setProject(projectId).setRegion(region).setResourcePolicyResource(resourcePolicy).build();Operationresponse=resourcePoliciesClient.insertAsync(request).get(3,TimeUnit.MINUTES);if(response.hasError()){thrownewError("Snapshot schedule creation failed! "+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';// The description of the snapshot schedule.constsnapshotScheduleDescription='snapshot schedule description...';asyncfunctioncallCreateSnapshotSchedule(){const[response]=awaitresourcePoliciesClient.insert({project:projectId,region,resourcePolicyResource:newcompute.ResourcePolicy({name:snapshotScheduleName,description:snapshotScheduleDescription,snapshotSchedulePolicy:newcompute.ResourcePolicyInstanceSchedulePolicySchedule({retentionPolicy:newcompute.ResourcePolicySnapshotSchedulePolicyRetentionPolicy({maxRetentionDays:5,}),schedule:newcompute.ResourcePolicySnapshotSchedulePolicySchedule({// Similarly, you can create a weekly or monthly schedule.// Review the resourcePolicies.insert method for details specific to setting a weekly or monthly schedule.// To see more details, open: `https://cloud.google.com/compute/docs/disks/scheduled-snapshots?authuser=0#create_snapshot_schedule`dailySchedule:newcompute.ResourcePolicyDailyCycle({startTime:'12:00',daysInCycle:1,}),}),snapshotProperties:newcompute.ResourcePolicySnapshotSchedulePolicySnapshotProperties({guestFlush:false,labels:{env:'dev',media:'images',},// OPTIONAL: the storage location. If you omit this flag, the default storage location is used.// storageLocations: 'storage-location',}),}),}),});letoperation=response.latestResponse;// Wait for the create operation to complete.while(operation.status!=='DONE'){[operation]=awaitregionOperationsClient.wait({operation:operation.name,project:projectId,region,});}console.log(`Snapshot schedule:${snapshotScheduleName} created.`);}awaitcallCreateSnapshotSchedule();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_create(project_id:str,region:str,schedule_name:str,schedule_description:str,labels:dict,)->compute_v1.ResourcePolicy:""" Creates a snapshot schedule for disks 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 will be created. schedule_name (str): The name of the snapshot schedule group. schedule_description (str): The description of the snapshot schedule group. labels (dict): The labels to apply to the snapshots. Example: {"env": "dev", "media": "images"} Returns: compute_v1.ResourcePolicy: The created resource policy. """# # Every hour, starts at 12:00 AM# hourly_schedule = compute_v1.ResourcePolicyHourlyCycle(# hours_in_cycle=1, start_time="00:00"# )## # Every Monday, starts between 12:00 AM and 1:00 AM# day = compute_v1.ResourcePolicyWeeklyCycleDayOfWeek(# day="MONDAY", start_time="00:00"# )# weekly_schedule = compute_v1.ResourcePolicyWeeklyCycle(day_of_weeks=[day])# In this example we use daily_schedule - every day, starts between 12:00 AM and 1:00 AMdaily_schedule=compute_v1.ResourcePolicyDailyCycle(days_in_cycle=1,start_time="00:00")schedule=compute_v1.ResourcePolicySnapshotSchedulePolicySchedule()# You can change the schedule type to daily_schedule, weekly_schedule, or hourly_scheduleschedule.daily_schedule=daily_schedule# Autodelete snapshots after 5 daysretention_policy=compute_v1.ResourcePolicySnapshotSchedulePolicyRetentionPolicy(max_retention_days=5)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.insert(project=project_id,region=region,resource_policy_resource=resource_policy_resource,)wait_for_extended_operation(operation,"Resource Policy creation")returnclient.get(project=project_id,region=region,resource_policy=schedule_name)REST
To create a snapshot schedule for globally scoped snapshots, constructa
POSTrequest toresourcePolicies.insert.You must include the snapshot schedule name and snapshot frequency.You can alsomanually specify a snapshot storage locationand addresource labelsin your request.
By default, the
onSourceDiskDeleteparameter is set tokeepAutoSnapshots. This means that if the source disk is deleted, theauto-generated snapshot for that disk is retained indefinitely.Alternatively, you can set the flag toapplyRetentionPolicyto applyyour retention policy.The following example sets a daily snapshot schedule that starts at 12:00UTC (04:00 PST) and repeats every day. The example also sets a retentionpolicy of 5 days; after 5 days, snapshots are automatically removed.
POST https://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": "STORAGE_LOCATION" } } }(Preview) To create a snapshotschedule for regionally scoped snapshots, construct a
POSTrequesttoresourcePolicies.insertand specify the snapshot region.POST https://compute.googleapis.com/compute/beta/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", "region": "SNAPSHOT_REGION" } } }
Replace the following:
PROJECT_ID: the project nameREGION: the location of the snapshot schedule resource policySNAPSHOT_REGION: the region that the scheduled snapshot is scoped toSCHEDULE_DESCRIPTION: the description of the snapshot scheduleSCHEDULE_NAME: the name of the snapshot scheduleSTORAGE_LOCATION: Optional: thestorage location. If you omit this flag, the default storage location is used.
Similarly, you can create a weekly or monthly schedule. Review theresourcePolicies.insert methodfor details specific to setting a weekly or monthly schedule.
For example, the following request creates a weekly schedule that runson Tuesday at 9:00 UTC.
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/resourcePolicies{ "name": "SCHEDULE_NAME", "description": "SCHEDULE_DESCRIPTION", "snapshotSchedulePolicy": { "schedule": { "weeklySchedule": { "dayOfWeeks": [ { "day": "Tuesday", "startTime": "9:00" } ] } }, "retentionPolicy": { "maxRetentionDays": "5" }, "snapshotProperties": { "guestFlush": "False", "labels": { "production": "webserver" }, "storageLocations":"US" } }}Attach a snapshot schedule to a disk
After you create a schedule, attach it to an existing disk. Use the console,gcloud CLI, or the Compute Engine API.
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, clickEdit.You might need to click theMore actions menufirst.
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 thegcloud disks add-resource-policies command.
gcloud compute disks add-resource-policiesDISK_NAME \ --resource-policiesSCHEDULE_NAME \ --zoneZONEReplace the following:
DISK_NAME: the name of the existing diskSCHEDULE_NAME: the name of the snapshot scheduleZONE: the location of your disk
Go
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb")// attachSnapshotSchedule attaches a snapshot schedule to disk.funcattachSnapshotSchedule(wio.Writer,projectID,scheduleName,diskName,regionstring)error{// projectID := "your_project_id"// snapshotName := "your_snapshot_name"// diskName := "your_disk_name"// region := "europe-central2"ctx:=context.Background()disksClient,err:=compute.NewRegionDisksRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewDisksRESTClient: %w",err)}deferdisksClient.Close()req:=&computepb.AddResourcePoliciesRegionDiskRequest{Project:projectID,Region:region,Disk:diskName,RegionDisksAddResourcePoliciesRequestResource:&computepb.RegionDisksAddResourcePoliciesRequest{ResourcePolicies:[]string{fmt.Sprintf("projects/%s/regions/%s/resourcePolicies/%s",projectID,region,scheduleName),},},}op,err:=disksClient.AddResourcePolicies(ctx,req)iferr!=nil{returnfmt.Errorf("unable to attach schedule: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprint(w,"Snapshot schedule attached\n")returnnil}Java
importcom.google.cloud.compute.v1.AddResourcePoliciesDiskRequest;importcom.google.cloud.compute.v1.DisksAddResourcePoliciesRequest;importcom.google.cloud.compute.v1.DisksClient;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.Operation.Status;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassAttachSnapshotScheduleToDisk{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 zone where your disk is located.Stringzone="us-central1-a";// Name of the disk you want to attach the snapshot schedule to.StringdiskName="YOUR_DISK_NAME";// Name of the snapshot schedule you want to attach.StringsnapshotScheduleName="YOUR_SNAPSHOT_SCHEDULE_NAME";// Name of the region where your snapshot schedule is located.Stringregion="us-central1";attachSnapshotScheduleToDisk(projectId,zone,diskName,snapshotScheduleName,region);}// Attaches a snapshot schedule to a disk.publicstaticStatusattachSnapshotScheduleToDisk(StringprojectId,Stringzone,StringdiskName,StringsnapshotScheduleName,Stringregion)throwsIOException,ExecutionException,InterruptedException,TimeoutException{StringresourcePolicyLink=String.format("projects/%s/regions/%s/resourcePolicies/%s",projectId,region,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(DisksClientdisksClient=DisksClient.create()){AddResourcePoliciesDiskRequestrequest=AddResourcePoliciesDiskRequest.newBuilder().setProject(projectId).setZone(zone).setDisk(diskName).setDisksAddResourcePoliciesRequestResource(DisksAddResourcePoliciesRequest.newBuilder().addResourcePolicies(resourcePolicyLink).build()).build();Operationresponse=disksClient.addResourcePoliciesAsync(request).get(3,TimeUnit.MINUTES);if(response.hasError()){thrownewError("Error attaching snapshot schedule to disk: "+response.getError());}returnresponse.getStatus();}}}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_attach(project_id:str,zone:str,region:str,disk_name:str,schedule_name:str)->None:""" Attaches a snapshot schedule to a specified disk. Args: project_id (str): The ID of the Google Cloud project. zone (str): The zone where the disk is located. region (str): The region where the snapshot schedule was created disk_name (str): The name of the disk to which the snapshot schedule will be attached. schedule_name (str): The name of the snapshot schedule that you are applying to this disk Returns: None """disks_add_request=compute_v1.DisksAddResourcePoliciesRequest(resource_policies=[f"regions/{region}/resourcePolicies/{schedule_name}"])client=compute_v1.DisksClient()operation=client.add_resource_policies(project=project_id,zone=zone,disk=disk_name,disks_add_resource_policies_request_resource=disks_add_request,)wait_for_extended_operation(operation,"Attaching snapshot schedule to disk")REST
Construct aPOST request todisks.addResourcePoliciesto attach a snapshot schedule to an existing disk.
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 zone where the disk is locatedREGION: the region where the snapshot schedulewas createdDISK_NAME: the name of the diskSCHEDULE_NAME: the name of the snapshot schedule that you are applying to this disk
Create a disk with a snapshot schedule
You can use the Google Cloud console or gcloud CLI to create adisk and a snapshot schedule at the same time.
Console
In the Google Cloud console, go to theDisks page.
ClickCreate Disk.
Complete the required fields to create a zonal or regional disk.
Create your disk in the same region as your snapshot schedule.
Populate the fields for yourSnapshot schedule.
Use the drop-down menu and complete the fields to create the schedule.
ClickCreate to create the schedule.
ClickCreate to create the disk.
gcloud
Use thegcloud disks create commandto create a zonal or regional Persistent Disk or Hyperdiskand attach a snapshot schedule to it.
gcloud compute disks createDISK_NAME \ --resource-policiesSCHEDULE_NAME \ --zoneZONEReplace the following:
DISK_NAME: the name of the new diskSCHEDULE_NAME: the name of the snapshotscheduleZONE: the location where you are creating thedisk. The disk must be in a zone that is in the same region as thesnapshot schedule.
Go
import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/protobuf/proto")// createDiskWithSnapshotSchedule creates a new empty regional disk with snapshot schedulefunccreateDiskWithSnapshotSchedule(wio.Writer,projectID,region,diskName,diskType,scheduleNamestring,replicaZones[]string,diskSizeGbint64,)error{// projectID := "your_project_id"// region := "us-west3" // should match diskType below// diskName := "your_disk_name"// diskType := "regions/us-west3/diskTypes/pd-ssd"// scheduleName := "your_schedule_name"// replicaZones := []string{"us-west3-a", "us-west3-b"}// diskSizeGb := 120// Exactly two replica zones must be specifiedreplicaZoneURLs:=[]string{fmt.Sprintf("projects/%s/zones/%s",projectID,replicaZones[0]),fmt.Sprintf("projects/%s/zones/%s",projectID,replicaZones[1]),}ctx:=context.Background()disksClient,err:=compute.NewRegionDisksRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewRegionDisksRESTClient: %w",err)}deferdisksClient.Close()req:=&computepb.InsertRegionDiskRequest{Project:projectID,Region:region,DiskResource:&computepb.Disk{Name:proto.String(diskName),Region:proto.String(region),Type:proto.String(diskType),SizeGb:proto.Int64(diskSizeGb),ReplicaZones:replicaZoneURLs,ResourcePolicies:[]string{fmt.Sprintf("projects/%s/regions/%s/resourcePolicies/%s",projectID,region,scheduleName),},},}op,err:=disksClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create disk with schedule: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Disk with schedule created\n")returnnil}Java
importcom.google.cloud.compute.v1.Disk;importcom.google.cloud.compute.v1.DisksClient;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.Operation.Status;importjava.io.IOException;importjava.util.List;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateDiskWithSnapshotSchedule{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="us-central1-a";// Name of the disk you want to create.StringdiskName="YOUR_DISK_NAME";// Name of the schedule you want to link to the disk.StringsnapshotScheduleName="YOUR_SCHEDULE_NAME";createDiskWithSnapshotSchedule(projectId,zone,diskName,snapshotScheduleName);}// Creates disk with linked snapshot schedule.publicstaticStatuscreateDiskWithSnapshotSchedule(StringprojectId,Stringzone,StringdiskName,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(DisksClientdisksClient=DisksClient.create()){Stringregion=zone.substring(0,zone.lastIndexOf('-'));// Get the resource policy to link to the diskStringresourcePolicyLink=String.format("projects/%s/regions/%s/resourcePolicies/%s",projectId,region,snapshotScheduleName);Diskdisk=Disk.newBuilder().setName(diskName).setZone(zone).addAllResourcePolicies(List.of(resourcePolicyLink)).build();Operationresponse=disksClient.insertAsync(projectId,zone,disk).get(3,TimeUnit.MINUTES);if(response.hasError()){thrownewError("Disk creation failed! "+response.getError());}returnresponse.getStatus();}}}What's next
- Learn aboutmanaging snapshot schedules.
- Learn about scheduled snapshot frequencies, retention policies, and namingrules inAbout snapshot schedules for disks.
- Learn how tocreate a custom image from your snapshot.
- 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.