Create archive and standard disk snapshots

Createstandard snapshots to periodically backup data from zonal and regional Persistent Disk and Google Cloud Hyperdisk volumes.

You can create snapshots from disks even while they are attached to runninginstances. Snapshots are, by default,global resources,so you can use them torestore data toa new disk or VM within the same project. For additional data protection andcost management, you can control where you can use your snapshots to create newdisks.To restrict the regions where your snapshots canrestore data, you can create aregionally scoped snapshot andset allowed access locations(Preview).You can alsoshare snapshotsacross projects.

Before you begin

Required roles and permissions

To get the permissions that you need to create a standard snapshot, ask your administrator to grant you the following IAM roles on the project:

For more information about granting roles, seeManage access to projects, folders, and organizations.

These predefined roles contain the permissions required to create a standard snapshot. To see the exact permissions that are required, expand theRequired permissions section:

Required permissions

The following permissions are required to create a standard snapshot:

  • To create a snapshot of a zonal disk:
    • compute.snapshots.create
    • compute.disks.createSnapshot
  • To create a snapshot of a regional disk using the data on the disk:
    • compute.snapshots.create
    • compute.instances.useReadOnly
    • compute.disks.createSnapshot
  • To create a snapshot of a regional disk from a replica recovery checkpoint:
    • compute.snapshots.create
    • compute.disks.createSnapshot
  • To create a regionally scoped snapshot:
    • compute.snapshots.create
    • compute.regionSnapshots.create
    • compute.disks.useReadOnly

You might also be able to get these permissions withcustom roles or otherpredefined roles.

Prepare for creating snapshots

To prepare for creating snapshots of Persistent Disk or Hyperdisk volumes,do the following:

  • ReviewBest practices for Compute Engine disk snapshotsto prepare your disk for snapshotting.

  • If you want to customize the default storage location for all your newglobally scoped snapshots,update the snapshot settings for your project.Google Cloud maintains apredefined default storage location value until you update the snapshotsettings for the first time. This predefined location is the nearestmulti-region to the source disk.

  • ReadCreate schedules for disk snapshotsto learn about creating a snapshot schedule and attaching it to your disks.Backing up your disks regularly with scheduled snapshots can reduce the riskof unexpected data loss.

Important: If you pause your applications before creating a snapshot,resume your workloads only after the snapshot resource reaches theUPLOADING status. For more information, see the table inManually creating application consistent snapshots.

Create a snapshot of a disk

The steps to create a snapshot of a disk depend on whether you're creating asnapshot of a zonal disk or regional disk.

Caution: If you try to create a snapshot from a diskand the snapshot creation process fails, you won't be able to delete the originaldisk until you capture a clean snapshot. This failsafehelps to prevent the accidental deletion of source data in the event of anunsuccessful backup.

Create a snapshot of a zonal disk

Console

  1. Go to theCreate a Snapshot page in the Google Cloud console.

    Go to the Create a Snapshot page
  2. Enter a snapshotName.
  3. Select aSnapshot type. The default is aSTANDARD snapshot, which is the best option for long-term back up and disaster recovery.

    ChooseArchive snapshot for more cost-efficient data retention.

  4. Optional: Enter aDescription of the snapshot.
  5. UnderSource disk, select the existing disk that you want to create a snapshot of.
  6. 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:

    1. 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.
    2. 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.
  7. ClickCreate to create the snapshot.

gcloud

You can create your snapshot in the storage location policydefined by yoursnapshot settings orusing an alternative storage location of your choice. For more information, seeChoose your snapshot storage location.

  • To create a snapshot in the predefined or customized default location configured in your snapshot settings, use thegcloud compute snapshots create command.

    gcloud compute snapshots createSNAPSHOT_NAME \    --source-disk-zone=SOURCE_ZONE \    --source-disk=SOURCE_DISK_NAME \    --snapshot-type=SNAPSHOT_TYPE
  • Alternatively, to override the snapshot settings and create a snapshot in a custom storage location, include the--storage-location flag to indicate where to store your snapshot.

    gcloud compute snapshots createSNAPSHOT_NAME \    --source-disk-zone=SOURCE_ZONE \    --source-disk=SOURCE_DISK_NAME \    --snapshot-type=SNAPSHOT_TYPE \    --storage-location=STORAGE_LOCATION
  • (Preview) To create a regionally scoped snapshot in an allowed region, include the--region flag to indicate where to create your snapshot.

    gcloud beta compute snapshots createSNAPSHOT_NAME \    --region=SNAPSHOT_SCOPE_REGION    --source-disk=SOURCE_DISK_NAME \    --source-disk-zone=SOURCE_ZONE \    --snapshot-type=SNAPSHOT_TYPE

Replace the following:

  • SNAPSHOT_NAME: A name for the snapshot.
  • SOURCE_ZONE: The zone of the source disk.
  • SOURCE_DISK_NAME: The name of the 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.
  • STORAGE_LOCATION: Optional: For globally scoped snapshots, theCloud Storage multi-region or theCloud Storage region where you want to store your snapshot. You can specify only one storage location.

    Use the--storage-location parameter only when you want to override the predefined or customized default storage location configured in your snapshot settings.

  • SNAPSHOT_SCOPE_REGION: Optional: For regionally scoped snapshots, the region that the snapshot is scoped to. If you include this parameter, you can't use the--storage-location parameter. TheSTORAGE_LOCATION is automatically set to theSNAPSHOT_SCOPE_REGION.

Note: Google recommends using thegcloud compute snapshots create command instead of thegcloud compute disks snapshot command because it supports more features, such as creating snapshots in a project different from the source disk project.

Terraform

To create a snapshot of the zonal Persistent Disk volume, use thegoogle_compute_snapshotresource.

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.

Go

Go

Before trying this sample, follow theGo setup instructions in theCompute Engine quickstart using client libraries. For more information, see theCompute EngineGo API reference documentation.

To authenticate to Compute Engine, 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")// 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=="" &&region==""{returnfmt.Errorf("you need to specify `zone` or `region` for this function to work")}ifzone!="" &&region!=""{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 theJava setup instructions in theCompute Engine quickstart using client libraries. For more information, see theCompute EngineJava API reference documentation.

To authenticate to Compute Engine, 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.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() &&region.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 theNode.js setup instructions in theCompute Engine quickstart using client libraries. For more information, see theCompute EngineNode.js API reference documentation.

To authenticate to Compute Engine, 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 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 &&region){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 thePython setup instructions in theCompute Engine quickstart using client libraries. For more information, see theCompute EnginePython API reference documentation.

To authenticate to Compute Engine, set up Application Default Credentials. For more 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)

REST

You can create your snapshot in the storage location policydefined by yoursnapshot settings orusing an alternative storage location of your choice. For more information, seeChoose your snapshot storage location.

  • To create a snapshot in the predefined or customized default location configured in your snapshot settings, make aPOST request to thesnapshots.insert method:

    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"}
  • Alternatively, to override the snapshot settings and create a snapshot in a custom storage location, make aPOST request to thesnapshots.insert method and include thestorageLocations property 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"    ],}
  • (Preview) To create a regionally scoped snapshot in an allowed region, make aPOST request to thesnapshots.insert method and define the creation region:

    POST https://compute.googleapis.com/compute/beta/projects/DESTINATION_PROJECT_ID/regions/SNAPSHOT_SCOPE_REGION/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 want to 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 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.
  • STORAGE_LOCATION: Optional: For globally scoped snapshots, theCloud Storage multi-region or theCloud Storage region where you want to store your snapshot. You can specify only one storage location.

    Use thestorageLocations parameter only when you want to override the predefined or customized default storage location configured in your snapshot settings.

  • SNAPSHOT_SCOPE_REGION: Optional: For regionally scoped snapshots, the region that the snapshot is scoped to. If you include this parameter, you can't use thestorageLocations parameter. TheSTORAGE_LOCATION is automatically set to theSNAPSHOT_SCOPE_REGION.

Note: Google recommends using thesnapshots.insert method instead of thedisks.createSnapshot method because it supports more features, such as creating snapshots in a project different from the source disk project.

Create a snapshot of a regional disk

You can create snapshots of your regional disk in one of thefollowing ways:

  • By using the data on the source disk. To use this snapshot creation method, you must have a synced zonal replica available.
  • By using the replica recovery checkpoint of a degraded disk. You can createsnapshots from a checkpoint only by using the Google Cloud CLI or REST.
Important: Google recommends that you use the checkpoint to create standard snapshots onlywhen your degraded replicated disk doesn't have a syncedreplica available. To avoid data loss, if your degraded disk has a syncedreplica available, always use the data on the disk to create your snapshot.

After youprepare the disk,you can create a snapshot. When creating a snapshot of a regional disk,you must indicate the region where the source disk is located.

Console

  1. Go to theCreate a Snapshot page in the Google Cloud console.

    Go to the Create a Snapshot page
  2. Enter a snapshotName.
  3. Select aSnapshot type. The default is aSTANDARD snapshot, which is the best option for long-term back up and disaster recovery.

    ChooseArchive snapshot for more cost-efficient data retention.

  4. Optional: Enter aDescription of the snapshot.
  5. UnderSource disk, select the existing disk that you want to create a snapshot of.
  6. 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:

    1. 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.
    2. 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.
  7. ClickCreate to create the snapshot.

gcloud

You can create a snapshot either by using the source disk's data or itsreplica recovery checkpoint.

From disk data

You can create a snapshot from your disk's data using the storage location policydefined by yoursnapshot settings orusing an alternative storage location of your choice. For more information, seeChoose your snapshot storage location.

  • To create a snapshot in the predefined or customized default location configured in your snapshot settings, use thegcloud compute snapshots create command.

    gcloud compute snapshots createSNAPSHOT_NAME \    --source-disk-region=SOURCE_REGION \    --source-disk=SOURCE_DISK_NAME \    --snapshot-type=SNAPSHOT_TYPE
  • Alternatively, to override the snapshot settings and create a snapshot in a custom storage location, include the--storage-location flag to indicate where to store your snapshot.

    gcloud compute snapshots createSNAPSHOT_NAME \    --source-disk-region=SOURCE_REGION \    --source-disk=SOURCE_DISK_NAME \    --snapshot-type=SNAPSHOT_TYPE \    --storage-location=STORAGE_LOCATION
  • (Preview) To create a regionally scoped snapshot in an allowed region, include the--region flag to indicate where to create your snapshot.

    gcloud beta compute snapshots createSNAPSHOT_NAME \    --region=SNAPSHOT_SCOPE_REGION \    --source-disk=SOURCE_DISK_NAME \    --source-disk-region=SOURCE_REGION \    --snapshot-type=SNAPSHOT_TYPE

Replace the following:

  • SNAPSHOT_NAME: A name for the snapshot.
  • SOURCE_REGION: The region of the source disk.
  • SOURCE_DISK_NAME: The name of the Regional Persistent Disk or Hyperdisk Balanced High Availability 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.
  • STORAGE_LOCATION: Optional: For globally scoped snapshots, theCloud Storage multi-region or theCloud Storage region where you want to store your snapshot. You can specify only one storage location.

    Use the--storage-location parameter only when you want to override the predefined or customized default storage location configured in your snapshot settings.

  • SNAPSHOT_SCOPE_REGION: Optional: For regionally scoped snapshots, the region that the snapshot is scoped to. If you include this parameter, you can't use the--storage-location parameter. TheSTORAGE_LOCATION is automatically set to theSNAPSHOT_SCOPE_REGION.

Note: Google recommends using thegcloud compute snapshots create command instead of thegcloud compute disks snapshot command because it supports more features, such as creating snapshots in a project different from the source disk project.

From checkpoint

You can create your snapshot using thereplica recovery checkpointof a degraded disk. Yoursnapshot gets created as long as your incomplete replica is available.

To create a snapshot using the replica recovery checkpoint, use thegcloud compute snapshots create command.Include the--source-disk-for-recovery-checkpoint flag tospecify that you want to create the snapshot using a replica recoverycheckpoint. Exclude the--source-disk and--source-disk-region parameters.

gcloud compute snapshots createSNAPSHOT_NAME \    --source-disk-for-recovery-checkpoint=SOURCE_DISK \    --source-disk-for-recovery-checkpoint-region=SOURCE_REGION \    --storage-location=STORAGE_LOCATION \    --snapshot-type=SNAPSHOT_TYPE

Replace the following:

  • DESTINATION_PROJECT_ID: The ID of project in which you want to create the snapshot.
  • SNAPSHOT_NAME: A name for the snapshot.
  • SOURCE_PROJECT_ID: The project ID of the source disk whose checkpoint you want to use to create the snapshot.
  • SOURCE_REGION: The region of the source disk whose checkpoint you want to use to create the snapshot.
  • SOURCE_DISK_NAME: The name of the source disk whose checkpoint you want to use to create the snapshot.
  • STORAGE_LOCATION: Optional:TheCloud Storage multi-regionor theCloud Storage regionwhere you want to store your snapshot. You can specify only one storage location.
    Use theonly if you want to override the predefined or customized default storagelocation configured in your snapshot settings.
  • SNAPSHOT_TYPE: The snapshot type, eitherSTANDARD orARCHIVE. If a snapshot type is not specified, aSTANDARDsnapshot is created.

You can use replica recovery checkpoint to create a snapshotonly ondegraded disks.If you try to create a snapshot from a replica recoverycheckpoint when the device is fully replicated, you see the following error message:

The device is fully replicated and should not create snapshots out of a recovery checkpoint. Pleasecreate regular snapshots instead.

The Google Cloud CLI waits until the operation returns a status ofREADY,FAILED, or reaches the maximum timeout and returns the lastknown details of the snapshot.

Terraform

The Terraform provider for Google Cloud doesn't support creating asnapshot of a regional disk. To track this limitation, see theissue on GitHub.

Go

Go

Before trying this sample, follow theGo setup instructions in theCompute Engine quickstart using client libraries. For more information, see theCompute EngineGo API reference documentation.

To authenticate to Compute Engine, 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")// 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=="" &&region==""{returnfmt.Errorf("you need to specify `zone` or `region` for this function to work")}ifzone!="" &&region!=""{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 theJava setup instructions in theCompute Engine quickstart using client libraries. For more information, see theCompute EngineJava API reference documentation.

To authenticate to Compute Engine, 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.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() &&region.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 theNode.js setup instructions in theCompute Engine quickstart using client libraries. For more information, see theCompute EngineNode.js API reference documentation.

To authenticate to Compute Engine, 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 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 &&region){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 thePython setup instructions in theCompute Engine quickstart using client libraries. For more information, see theCompute EnginePython API reference documentation.

To authenticate to Compute Engine, set up Application Default Credentials. For more 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)

REST

You can create a snapshot either by using the source disk's data or itsreplica recovery checkpoint.

From disk data

You can create a snapshot from your disk's data using the storage location policydefined by yoursnapshot settings orusing an alternative storage location of your choice. For more information, seeChoose your snapshot storage location.

  • To create a snapshot in the predefined or customized default location configured in your snapshot settings, make aPOST request to thesnapshots.insert method:

    POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/global/snapshots{  "name": "SNAPSHOT_NAME",  "sourceDisk": "projects/SOURCE_PROJECT_ID/regions/SOURCE_REGION/disks/SOURCE_DISK_NAME",  "snapshotType": "SNAPSHOT_TYPE"}
  • Alternatively, to override the snapshot settings and create a snapshot in a custom storage location, make aPOST request to thesnapshots.insert method and include thestorageLocations property in your request:

    POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/global/snapshots{  "name": "SNAPSHOT_NAME",  "sourceDisk": "projects/SOURCE_PROJECT_ID/regions/SOURCE_REGION/disks/SOURCE_DISK_NAME",  "snapshotType": "SNAPSHOT_TYPE",  "storageLocations": [      "STORAGE_LOCATION"  ],}
  • (Preview) To create a regionally scoped snapshot in an allowed region, make aPOST request to thesnapshots.insert method and define the creation region:

    POST https://compute.googleapis.com/compute/beta/projects/DESTINATION_PROJECT_ID/regions/SNAPSHOT_SCOPE_REGION/snapshots{  "name": "SNAPSHOT_NAME",  "sourceDisk": "projects/SOURCE_PROJECT_ID/regions/SOURCE_REGION/disks/SOURCE_DISK_NAME",  "snapshotType": "SNAPSHOT_TYPE",}

Replace the following:

  • DESTINATION_PROJECT_ID: The ID of project in which you want to create the snapshot.
  • SNAPSHOT_NAME: A name for the snapshot.
  • SOURCE_PROJECT_ID: The ID of the source disk project.
  • SOURCE_REGION: The region of the source disk.
  • SOURCE_DISK_NAME: The name of the Regional Persistent Disk or Hyperdisk Balanced High Availability 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.
  • STORAGE_LOCATION: Optional: For globally scoped snapshots, theCloud Storage multi-region or theCloud Storage region where you want to store your snapshot. You can specify only one storage location.

    Use thestorageLocations parameter only when you want to override the predefined or customized default storage location configured in your snapshot settings.

  • SNAPSHOT_SCOPE_REGION: Optional: For regionally scoped snapshots, the region that the snapshot is scoped to. If you include this parameter, you can't use thestorageLocations parameter. TheSTORAGE_LOCATION is automatically set to theSNAPSHOT_SCOPE_REGION.

Note: Google recommends using thesnapshots.insert method instead of thedisks.createSnapshot method because it supports more features, such as creating snapshots in a project different from the source disk project.

From checkpoint

Alternatively, you can create your snapshot using thereplica recovery checkpointof a degraded disk. Your snapshot gets created as long as yourincomplete replica is available.

To create a snapshot using the replica recovery checkpoint, make aPOST request to thesnapshots.insert method.Exclude thesourceDisk parameter and instead include thesourceDiskForRecoveryCheckpoint parameter to specify thatyou want to create the snapshot using the checkpoint.

POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/global/snapshots{  "name": "SNAPSHOT_NAME",  "sourceDiskForRecoveryCheckpoint": "projects/SOURCE_PROJECT_ID/regions/SOURCE_REGION/disks/SOURCE_DISK_NAME",  "storageLocations": "STORAGE_LOCATION",  "snapshotType": "SNAPSHOT_TYPE"}

Replace the following:

  • DESTINATION_PROJECT_ID: The ID of project in which you want to create the snapshot.
  • SNAPSHOT_NAME: A name for the snapshot.
  • SOURCE_PROJECT_ID: The project ID of the source disk whose checkpoint you want to use to create the snapshot.
  • SOURCE_REGION: The region of the source disk whose checkpoint you want to use to create the snapshot.
  • SOURCE_DISK_NAME: The name of the source disk whose checkpoint you want to use to create the snapshot.
  • STORAGE_LOCATION: Optional:TheCloud Storage multi-regionor theCloud Storage regionwhere you want to store your snapshot. You can specify only one storage location.
    Use thestorageLocations parameteronly if you want to override the predefined or customized default storagelocation configured in your snapshot settings.
  • SNAPSHOT_TYPE: The snapshot type, eitherSTANDARD orARCHIVE. If a snapshot type is not specified, aSTANDARDsnapshot is created.

You can use replica recovery checkpoint to create a snapshotonly ondegraded disks.If you try to create a snapshot from a replica recoverycheckpoint when the device is fully replicated, you see the following error message:

The device is fully replicated and should not create snapshots out of a recovery checkpoint. Pleasecreate regular snapshots instead.

What's next

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.