Create and manage disk snapshots

Stay organized with collections Save and categorize content based on your preferences.

Create snapshots to periodically back up data from your zonal persistent disks or regional persistent disks.

You can create snapshots from disks even while they are attached to running instances. Snapshots are global resources, so you can use them to restore data to a new disk or instance within the same project. You can also share snapshots across projects.

Before you begin

Prepare for creating snapshots

To prepare for creating persistent disk snapshots, do the following:

Create a snapshot of a zonal persistent disk

Console

  1. In the Google Cloud console, go to the VM instances page.

    Go to VM instances
    The remaining steps will appear automatically in the Google Cloud console.

  2. In the Name column, click the name of the VM that has the persistent disk to back up.
  3. In Storage:
    • To back up the boot disk, in the Boot disk section, click the Name of the boot disk.
    • To back up an attached persistent disk, in Additional disks, click the Name of the attached persistent disk.
  4. Click Create snapshot.
  5. In Name, enter a unique name to help identify the purpose of the snapshot, for example:
    • boot-disk-snapshot
    • attached-persistent-disk-snapshot
  6. In Type, the default is a regular snapshot, which is best for long-term back up and disaster recovery.

    Choose Archive snapshot for more cost-efficient data retention.

  7. In Location, the default is Multi-regional, which provides higher availability at a higher cost.

    Choose Regional snapshots for more control over the physical location of your data at a lower cost.

  8. To create a manual snapshot, click Create.

gcloud

Create your snapshot in the default storage location or in a selected storage location. You must specify a snapshot name. The name must be 1-63 characters long, and comply with RFC 1035.

  • To create a snapshot of a persistent disk in the default storage location, use the gcloud compute snapshots create command.

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk SOURCE_DISK \
        --snapshot-type SNAPSHOT_TYPE \
        --source-disk-zone SOURCE_DISK_ZONE
    

    Replace the following:

    • SNAPSHOT_NAME: A name for the snapshot.
    • SOURCE_DISK: The name of the persistent disk from which you want to create a snapshot.
    • SNAPSHOT_TYPE: The snapshot type, either STANDARD or ARCHIVE. If a snapshot type is not specified, a STANDARD snapshot is created.
    • SOURCE_DISK_ZONE: The zone of the persistent disk from which you want to create a snapshot.
  • Alternatively, to create a snapshot in a custom storage location, use the --storage-location flag to indicate where to store your snapshot:

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk SOURCE_DISK \
        --source-disk-zone SOURCE_DISK_ZONE \
        --storage-location STORAGE_LOCATION \
        --snapshot-type SNAPSHOT_TYPE
    

    Replace the following:

    • SNAPSHOT_NAME: A name for the snapshot.
    • SOURCE_DISK: The name of the persistent disk from which you want to create a snapshot.
    • SOURCE_DISK_ZONE: The zone of the persistent disk from which you want to create a snapshot.
    • STORAGE_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.
    • SNAPSHOT_TYPE: The snapshot type, either STANDARD or ARCHIVE. If a snapshot type is not specified, a STANDARD snapshot is created.

The gcloud CLI waits until the operation returns a status of READY or FAILED, or reaches the maximum timeout and returns the last known details of the snapshot.

API

Create your snapshot in the default storage location or in a selected storage location.

  • To create your snapshot in the default storage location, make a POST request to the snapshots.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
    }
    

    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 from which you want to create a snapshot.
    • SNAPSHOT_TYPE: The snapshot type, either STANDARD or ARCHIVE. If a snapshot type is not specified, a STANDARD snapshot is created.
  • Alternatively, to create a snapshot in a custom storage location, make a POST request to the snapshots.insert method and specify the storage location:

    POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/global/snapshots
    
    {
      "name": SNAPSHOT_NAME
      "sourceDisk": "projects/SOURCE_PROJECT_ID/zones/SOURCE_ZONE/disks/SOURCE_DISK_NAME
      "snapshotType": SNAPSHOT_TYPE
      "storageLocations": STORAGE_LOCATION
    }
    

    Replace the following:

    • DESTINATION_PROJECT_ID: The ID of project in which you 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 from which you want to create a snapshot.
    • SNAPSHOT_TYPE: The snapshot type, either STANDARD or ARCHIVE. If a snapshot type is not specified, a STANDARD snapshot is created.
    • STORAGE_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.

Go

Go

Before trying this sample, follow the Go setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
	"google.golang.org/protobuf/proto"
)

// createSnapshot creates a snapshot of a disk.
func createSnapshot(
	w io.Writer,
	projectID, diskName, snapshotName, zone, region, location, diskProjectID string,
) 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)
	if err != nil {
		return fmt.Errorf("NewSnapshotsRESTClient: %v", err)
	}
	defer snapshotsClient.Close()

	if zone == "" && region == "" {
		return fmt.Errorf("you need to specify `zone` or `region` for this function to work")
	}

	if zone != "" && region != "" {
		return fmt.Errorf("you can't set both `zone` and `region` parameters")
	}

	if diskProjectID == "" {
		diskProjectID = projectID
	}

	disk := &computepb.Disk{}
	locations := []string{}
	if location != "" {
		locations = append(locations, location)
	}

	if zone != "" {
		disksClient, err := compute.NewDisksRESTClient(ctx)
		if err != nil {
			return fmt.Errorf("NewDisksRESTClient: %v", err)
		}
		defer disksClient.Close()

		getDiskReq := &computepb.GetDiskRequest{
			Project: projectID,
			Zone:    zone,
			Disk:    diskName,
		}

		disk, err = disksClient.Get(ctx, getDiskReq)
		if err != nil {
			return fmt.Errorf("unable to create disk: %v", err)
		}
	} else {
		regionDisksClient, err := compute.NewRegionDisksRESTClient(ctx)
		if err != nil {
			return fmt.Errorf("NewRegionDisksRESTClient: %v", err)
		}
		defer regionDisksClient.Close()

		getDiskReq := &computepb.GetRegionDiskRequest{
			Project: projectID,
			Region:  region,
			Disk:    diskName,
		}

		disk, err = regionDisksClient.Get(ctx, getDiskReq)
		if err != nil {
			return fmt.Errorf("unable to create disk: %v", 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)
	if err != nil {
		return fmt.Errorf("unable to create snapshot: %v", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %v", err)
	}

	fmt.Fprintf(w, "Snapshot created\n")

	return nil
}

Java

Java

Before trying this sample, follow the Java setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Java API reference documentation.


import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.RegionDisksClient;
import com.google.cloud.compute.v1.Snapshot;
import com.google.cloud.compute.v1.SnapshotsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateSnapshot {

  public static void main(String[] args)
      throws IOException, 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.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the disk you want to create.
    String diskName = "YOUR_DISK_NAME";

    // Name of the snapshot that you want to create.
    String snapshotName = "YOUR_SNAPSHOT_NAME";

    // The zone of the source disk from which you create the snapshot (for zonal disks).
    String zone = "europe-central2-b";

    // The region of the source disk from which you create the snapshot (for regional disks).
    String region = "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-locations
    String location = "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.
    String diskProjectId = "YOUR_DISK_PROJECT_ID";

    createSnapshot(projectId, diskName, snapshotName, zone, region, location, diskProjectId);
  }

  // Creates a snapshot of a disk.
  public static void createSnapshot(String projectId, String diskName, String snapshotName,
      String zone, String region, String location, String diskProjectId)
      throws IOException, 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 (SnapshotsClient snapshotsClient = SnapshotsClient.create()) {

      if (zone.isEmpty() && region.isEmpty()) {
        throw new Error("You need to specify 'zone' or 'region' for this function to work");
      }

      if (!zone.isEmpty() && !region.isEmpty()) {
        throw new Error("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.
      Disk disk;
      if (!zone.isEmpty()) {
        DisksClient disksClient = DisksClient.create();
        disk = disksClient.get(projectId, zone, diskName);
      } else {
        RegionDisksClient regionDisksClient = RegionDisksClient.create();
        disk = regionDisksClient.get(diskProjectId, region, diskName);
      }

      // Set the snapshot properties.
      Snapshot snapshotResource;
      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.
      Operation operation = snapshotsClient.insertAsync(projectId, snapshotResource)
          .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Snapshot creation failed!" + operation);
        return;
      }

      // Retrieve the created snapshot.
      Snapshot snapshot = snapshotsClient.get(projectId, snapshotName);
      System.out.printf("Snapshot created: %s", snapshot.getName());

    }
  }
}

Node.js

Node.js

Before trying this sample, follow the Node.js setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Node.js API reference documentation.

/**
 * 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';

const compute = require('@google-cloud/compute');

async function createSnapshot() {
  const snapshotsClient = new compute.SnapshotsClient();

  let disk;

  if (!zone && !region) {
    throw new Error(
      'You need to specify `zone` or `region` for this function to work.'
    );
  }

  if (zone && region) {
    throw new Error("You can't set both `zone` and `region` parameters");
  }

  if (!diskProjectId) {
    diskProjectId = projectId;
  }

  if (zone) {
    const disksClient = new compute.DisksClient();
    [disk] = await disksClient.get({
      project: diskProjectId,
      zone,
      disk: diskName,
    });
  } else {
    const regionDisksClient = new compute.RegionDisksClient();
    [disk] = await regionDisksClient.get({
      project: diskProjectId,
      region,
      disk: diskName,
    });
  }

  const snapshotResource = {
    name: snapshotName,
    sourceDisk: disk.selfLink,
  };

  if (location) {
    snapshotResource.storageLocations = [location];
  }

  const [response] = await snapshotsClient.insert({
    project: projectId,
    snapshotResource,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.GlobalOperationsClient();

  // Wait for the create snapshot operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
    });
  }

  console.log('Snapshot created.');
}

createSnapshot();

Python

Python

Before trying this sample, follow the Python setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Python API reference documentation.

import sys
from typing import Any, Optional

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    This method will wait 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)

    if operation.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)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def create_snapshot(
    project_id: str,
    disk_name: str,
    snapshot_name: str,
    *,
    zone: Optional[str] = None,
    region: Optional[str] = None,
    location: Optional[str] = None,
    disk_project_id: Optional[str] = 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.
    """
    if zone is None and region is None:
        raise RuntimeError(
            "You need to specify `zone` or `region` for this function to work."
        )
    if zone is not None and region is not None:
        raise RuntimeError("You can't set both `zone` and `region` parameters.")

    if disk_project_id is None:
        disk_project_id = project_id

    if zone is not None:
        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_link
    snapshot.name = snapshot_name
    if location:
        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")

    return snapshot_client.get(project=project_id, snapshot=snapshot_name)

Create a snapshot of a regional persistent disk

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

Console

  1. Go to the Create a Snapshot page in the Google Cloud console.
    Go to the Create a Snapshot page
  2. Enter a snapshot Name.
  3. Select a Snapshot type. The default is a regular snapshot, which is best for long-term back up and disaster recovery.

    Choose Archive snapshot for more cost-efficient data retention.

  4. Optionally, enter a Description of the snapshot.

  5. Under Source disk, select an existing disk from which you want to create a snapshot.

  6. Optionally, you can specify a custom storage location:

    1. Under Location, select whether you want to store your snapshot in a Multi-regional location or a Regional location.
    2. Select which specific region or multi-region that you want to use. To use the region or multi-region that is closest to your source disk, select Based on disk's location.
  7. Click Create to create the snapshot.

gcloud

Create your snapshot in the default storage location or in a selected storage location.

  • To create a snapshot of a regional persistent disk in the default storage location, use the gcloud compute snapshots create command.

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk SOURCE_DISK \
        --source-disk-region=SOURCE_DISK_REGION
    

    Replace the following:

    • SNAPSHOT_NAME: A name for the snapshot.
    • SOURCE_DISK: The name of the persistent disk from which you want to create a snapshot.
    • SOURCE_DISK_REGION: The region of the regional persistent disk from which you want to create a snapshot.
  • Optionally, you can specify a custom storage location.

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk SOURCE_DISK \
        --source-disk-region=SOURCE_DISK_REGION
        --storage-location STORAGE_LOCATION \
        --snapshot-type SNAPSHOT_TYPE
    

    Replace the following:

    • SNAPSHOT_NAME: A name for the snapshot.
    • SOURCE_DISK: The name of the persistent disk from which you want to create a snapshot.
    • SOURCE_DISK_REGION: The region of the regional persistent disk from which you want to create a snapshot.
    • STORAGE_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.
    • SNAPSHOT_TYPE: The snapshot type, either STANDARD or ARCHIVE. If a snapshot type is not specified, a STANDARD snapshot is created.

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

API

  • To create a snapshot in the default storage location, make a POST request to the snapshots.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
    }
    

    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 persistent disk from which you want to create a snapshot.
    • SNAPSHOT_TYPE: The snapshot type, either STANDARD or ARCHIVE. If a snapshot type is not specified, a STANDARD snapshot is created.
  • Alternatively, to create a snapshot in a custom storage location, make a POST request to thesnapshots.insert method and specify the storage location:

    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
    }
    

    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 persistent disk from which you want to create a snapshot.
    • STORAGE_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.
    • SNAPSHOT_TYPE: The snapshot type, either STANDARD or ARCHIVE. If a snapshot type is not specified, a STANDARD snapshot is created.

Go

Go

Before trying this sample, follow the Go setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
	"google.golang.org/protobuf/proto"
)

// createSnapshot creates a snapshot of a disk.
func createSnapshot(
	w io.Writer,
	projectID, diskName, snapshotName, zone, region, location, diskProjectID string,
) 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)
	if err != nil {
		return fmt.Errorf("NewSnapshotsRESTClient: %v", err)
	}
	defer snapshotsClient.Close()

	if zone == "" && region == "" {
		return fmt.Errorf("you need to specify `zone` or `region` for this function to work")
	}

	if zone != "" && region != "" {
		return fmt.Errorf("you can't set both `zone` and `region` parameters")
	}

	if diskProjectID == "" {
		diskProjectID = projectID
	}

	disk := &computepb.Disk{}
	locations := []string{}
	if location != "" {
		locations = append(locations, location)
	}

	if zone != "" {
		disksClient, err := compute.NewDisksRESTClient(ctx)
		if err != nil {
			return fmt.Errorf("NewDisksRESTClient: %v", err)
		}
		defer disksClient.Close()

		getDiskReq := &computepb.GetDiskRequest{
			Project: projectID,
			Zone:    zone,
			Disk:    diskName,
		}

		disk, err = disksClient.Get(ctx, getDiskReq)
		if err != nil {
			return fmt.Errorf("unable to create disk: %v", err)
		}
	} else {
		regionDisksClient, err := compute.NewRegionDisksRESTClient(ctx)
		if err != nil {
			return fmt.Errorf("NewRegionDisksRESTClient: %v", err)
		}
		defer regionDisksClient.Close()

		getDiskReq := &computepb.GetRegionDiskRequest{
			Project: projectID,
			Region:  region,
			Disk:    diskName,
		}

		disk, err = regionDisksClient.Get(ctx, getDiskReq)
		if err != nil {
			return fmt.Errorf("unable to create disk: %v", 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)
	if err != nil {
		return fmt.Errorf("unable to create snapshot: %v", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %v", err)
	}

	fmt.Fprintf(w, "Snapshot created\n")

	return nil
}

Java

Java

Before trying this sample, follow the Java setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Java API reference documentation.


import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.RegionDisksClient;
import com.google.cloud.compute.v1.Snapshot;
import com.google.cloud.compute.v1.SnapshotsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateSnapshot {

  public static void main(String[] args)
      throws IOException, 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.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the disk you want to create.
    String diskName = "YOUR_DISK_NAME";

    // Name of the snapshot that you want to create.
    String snapshotName = "YOUR_SNAPSHOT_NAME";

    // The zone of the source disk from which you create the snapshot (for zonal disks).
    String zone = "europe-central2-b";

    // The region of the source disk from which you create the snapshot (for regional disks).
    String region = "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-locations
    String location = "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.
    String diskProjectId = "YOUR_DISK_PROJECT_ID";

    createSnapshot(projectId, diskName, snapshotName, zone, region, location, diskProjectId);
  }

  // Creates a snapshot of a disk.
  public static void createSnapshot(String projectId, String diskName, String snapshotName,
      String zone, String region, String location, String diskProjectId)
      throws IOException, 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 (SnapshotsClient snapshotsClient = SnapshotsClient.create()) {

      if (zone.isEmpty() && region.isEmpty()) {
        throw new Error("You need to specify 'zone' or 'region' for this function to work");
      }

      if (!zone.isEmpty() && !region.isEmpty()) {
        throw new Error("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.
      Disk disk;
      if (!zone.isEmpty()) {
        DisksClient disksClient = DisksClient.create();
        disk = disksClient.get(projectId, zone, diskName);
      } else {
        RegionDisksClient regionDisksClient = RegionDisksClient.create();
        disk = regionDisksClient.get(diskProjectId, region, diskName);
      }

      // Set the snapshot properties.
      Snapshot snapshotResource;
      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.
      Operation operation = snapshotsClient.insertAsync(projectId, snapshotResource)
          .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Snapshot creation failed!" + operation);
        return;
      }

      // Retrieve the created snapshot.
      Snapshot snapshot = snapshotsClient.get(projectId, snapshotName);
      System.out.printf("Snapshot created: %s", snapshot.getName());

    }
  }
}

Node.js

Node.js

Before trying this sample, follow the Node.js setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Node.js API reference documentation.

/**
 * 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';

const compute = require('@google-cloud/compute');

async function createSnapshot() {
  const snapshotsClient = new compute.SnapshotsClient();

  let disk;

  if (!zone && !region) {
    throw new Error(
      'You need to specify `zone` or `region` for this function to work.'
    );
  }

  if (zone && region) {
    throw new Error("You can't set both `zone` and `region` parameters");
  }

  if (!diskProjectId) {
    diskProjectId = projectId;
  }

  if (zone) {
    const disksClient = new compute.DisksClient();
    [disk] = await disksClient.get({
      project: diskProjectId,
      zone,
      disk: diskName,
    });
  } else {
    const regionDisksClient = new compute.RegionDisksClient();
    [disk] = await regionDisksClient.get({
      project: diskProjectId,
      region,
      disk: diskName,
    });
  }

  const snapshotResource = {
    name: snapshotName,
    sourceDisk: disk.selfLink,
  };

  if (location) {
    snapshotResource.storageLocations = [location];
  }

  const [response] = await snapshotsClient.insert({
    project: projectId,
    snapshotResource,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.GlobalOperationsClient();

  // Wait for the create snapshot operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
    });
  }

  console.log('Snapshot created.');
}

createSnapshot();

Python

Python

Before trying this sample, follow the Python setup instructions in the Compute Engine quickstart using client libraries. For more information, see the Compute Engine Python API reference documentation.

import sys
from typing import Any, Optional

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    This method will wait 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)

    if operation.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)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def create_snapshot(
    project_id: str,
    disk_name: str,
    snapshot_name: str,
    *,
    zone: Optional[str] = None,
    region: Optional[str] = None,
    location: Optional[str] = None,
    disk_project_id: Optional[str] = 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.
    """
    if zone is None and region is None:
        raise RuntimeError(
            "You need to specify `zone` or `region` for this function to work."
        )
    if zone is not None and region is not None:
        raise RuntimeError("You can't set both `zone` and `region` parameters.")

    if disk_project_id is None:
        disk_project_id = project_id

    if zone is not None:
        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_link
    snapshot.name = snapshot_name
    if location:
        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")

    return snapshot_client.get(project=project_id, snapshot=snapshot_name)

Delete a snapshot

Compute Engine uses differential snapshots so that each snapshot contains only the data that has changed since the previous snapshot. Because subsequent snapshots might require information stored in a previous snapshot, keep in mind that deleting a snapshot does not necessarily delete all the data on the snapshot. To learn more about snapshot deletion, see Snapshot deletion.

To delete a snapshot:

Console

  1. Go to the Snapshots page in the Google Cloud console.

    Go to the Snapshots page

  2. Select one or more snapshots that you want to delete.
  3. At the top of the Snapshots page, click Delete.

gcloud

To delete a snapshot, use the gcloud compute snapshots delete command:

gcloud compute snapshots delete SNAPSHOT_NAME

where SNAPSHOT_NAME is the name of the snapshot being deleted.

API

Make a DELETE request to compute.snapshots.delete method to delete snapshots.

DELETE https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/snapshots/SNAPSHOT_NAME

where:

  • PROJECT_ID is the name of your project.
  • SNAPSHOT_NAME is the name of the snapshot to delete.

Go

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
)

// deleteSnapshot deletes a snapshot of a disk.
func deleteSnapshot(w io.Writer, projectID, snapshotName string) error {
	// projectID := "your_project_id"
	// snapshotName := "your_snapshot_name"

	ctx := context.Background()
	snapshotsClient, err := compute.NewSnapshotsRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewSnapshotsRESTClient: %v", err)
	}
	defer snapshotsClient.Close()

	req := &computepb.DeleteSnapshotRequest{
		Project:  projectID,
		Snapshot: snapshotName,
	}

	op, err := snapshotsClient.Delete(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to delete snapshot: %v", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %v", err)
	}

	fmt.Fprintf(w, "Snapshot deleted\n")

	return nil
}

Java


import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.SnapshotsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteSnapshot {

  public static void main(String[] args)
      throws IOException, 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.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the snapshot to be deleted.
    String snapshotName = "YOUR_SNAPSHOT_NAME";

    deleteSnapshot(projectId, snapshotName);
  }

  // Delete a snapshot of a disk.
  public static void deleteSnapshot(String projectId, String snapshotName)
      throws IOException, 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 (SnapshotsClient snapshotsClient = SnapshotsClient.create()) {

      Operation operation = snapshotsClient.deleteAsync(projectId, snapshotName)
          .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Snapshot deletion failed!" + operation);
        return;
      }

      System.out.println("Snapshot deleted!");
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const snapshotName = 'YOUR_SNAPSHOT_NAME';

const compute = require('@google-cloud/compute');

async function deleteSnapshot() {
  const snapshotsClient = new compute.SnapshotsClient();

  const [response] = await snapshotsClient.delete({
    project: projectId,
    snapshot: snapshotName,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.GlobalOperationsClient();

  // Wait for the create disk operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
    });
  }

  console.log('Snapshot deleted.');
}

deleteSnapshot();

Python

import sys
from typing import Any, NoReturn

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    This method will wait 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)

    if operation.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)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def delete_snapshot(project_id: str, snapshot_name: str) -> NoReturn:
    """
    Delete a snapshot of a disk.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        snapshot_name: name of the snapshot to delete.
    """

    snapshot_client = compute_v1.SnapshotsClient()
    operation = snapshot_client.delete(project=project_id, snapshot=snapshot_name)

    wait_for_extended_operation(operation, "snapshot deletion")

    return

Delete multiple snapshots based on a filter

Compute Engine uses differential snapshots so that each snapshot contains only the data that has changed since the previous snapshot. Because subsequent snapshots might require information stored in a previous snapshot, deleting a snapshot does not necessarily delete all the data on the snapshot. To learn more about snapshot deletion, see Snapshot deletion.

The following sections describe how to delete a number of snapshots based on a given filter. For more information on gcloud CLI filters, see gcloud CLI topic filters.

To delete the snapshots, use a combination of the gcloud compute snapshots list command with a given filter, and the gcloud compute snapshots delete command with xargs:

gcloud compute snapshots list --filter="EXPRESSION" --uri |
   xargs gcloud compute snapshots delete

Replace EXPRESSION with a gcloud topic filter.

For example, --filter="creationTimestamp>'2021-01-01'" deletes all snapshots created after 2021-01-01.

List snapshots

gcloud

To see a list of snapshots available to you in a particular project, use the gcloud compute snapshots list command.

gcloud compute snapshots list --project PROJECT_ID

where PROJECT_ID is the ID of the project.

API

To see a list of snapshot available to you in a particular project, make a GET request to the snapshots.list method:

GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/snapshots

where PROJECT_ID is the ID of the project.

View information about a snapshot

To list information about a particular snapshot, such as the creation time, size, and source disk, use the gcloud compute snapshots describe command:

gcloud compute snapshots describe SNAPSHOT_NAME

where SNAPSHOT_NAME is the name of the snapshot.

Share snapshot data across projects in the same organization

To move data from a disk in one project to a disk in a different project within the same organization, use the following process:

gcloud

  1. Create a disk snapshot in the destination project by using the gcloud compute snapshots create command. For example, to create a snapshot of a zonal persistent disk, use the following command:

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk https://www.googleapis.com/compute/v1/projects/SOURCE_PROJECT_ID/zones/ZONE/disks/SOURCE_DISK_NAME \
        --project DESTINATION_PROJECT_ID
    

    Replace the following:

    • SNAPSHOT_NAME: A name for the snapshot.
    • SOURCE_PROJECT_ID: The ID of the source disk project.
    • ZONE: The zone of the source disk.
    • SOURCE_DISK_NAME: The name of the source disk.
    • DESTINATION_PROJECT_ID: The ID of the destination project for the new snapshot.
  2. In the destination project, create a zonal or regional disk that's based on the snapshot by using the gcloud compute disks create command:

    gcloud compute disks create DISK_NAME \
        --source-snapshot SNAPSHOT_NAME \
        --project DESTINATION_PROJECT_ID
    

    Replace the following:

    • DISK_NAME: A name for the new disk.
    • SNAPSHOT_NAME: The name of the snapshot.
    • DESTINATION_PROJECT_ID: The ID of the destination project for the new disk.

API

  1. Create a disk snapshot in the destination project by calling the snapshots.insert method. For example, to take a snapshot of a zonal persistent disk, make the following 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
    }
    

    Replace the following:

    • DESTINATION_PROJECT_ID: The ID of the destination project for the new 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 source disk.
  2. In the destination project, create a zonal or regional disk that's based on the snapshot by using the zonal disks.insert method or the regional regionDisks.insert method. For example, to create a zonal disk, make the following request:

    POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/zones/DESTINATION_ZONE/disks
    {
      "name": DISK_NAME
      "sourceSnapshot": SNAPSHOT_NAME
    }
    

    Replace the following:

    • DESTINATION_PROJECT_ID: The ID of the destination project for the new disk.
    • DISK_NAME: A name for the new disk.
    • SNAPSHOT_NAME: The name of the snapshot.

To get a list of snapshots available to you, see Listing snapshots.

Share a snapshot across projects in different organizations

To share a snapshot from a project in one organization to a different project in another organization, use the following process:

gcloud

  1. In the source project, create a disk that's based on the snapshot by using the gcloud compute disks create command:

     gcloud compute disks create DISK_NAME \
        --source-snapshot SNAPSHOT_NAME \
        --project SOURCE_PROJECT_ID \ --zone ZONE
    

    Replace the following:

    • DISK_NAME: a name for the new disk.
    • SNAPSHOT_NAME: The name of the snapshot.
    • SOURCE_PROJECT_ID: The ID of the source project.
    • ZONE: Zone in which new disk will be created.

    This disk is a temporary disk that is created only to copy the snapshot across organizations. You can delete this disk after the snapshot copy completes.

  2. In the destination project, create a snapshot by using the gcloud compute snapshots create command. For example, to create a snapshot using the zonal disk created in step 1, use the following command:

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk https://www.googleapis.com/compute/v1/projects/SOURCE_PROJECT_ID/zones/ZONE/disks/SOURCE_DISK_NAME \
        --project DESTINATION_PROJECT_ID
    

    Replace the following:

    • SNAPSHOT_NAME: A name for the snapshot.
    • SOURCE_PROJECT_ID: The ID of the project that contains the source disk.
    • ZONE: The zone of the source disk.
    • SOURCE_DISK_NAME: The name of the disk created in step 1.
    • DESTINATION_PROJECT_ID: The ID of the destination project for the new snapshot.

    To get a list of snapshots available to you, see Listing snapshots.

  3. Delete the temporary disk created in step 1 using gcloud compute disks delete command.

API

  1. In the source project, create a zonal or regional disk that's based on the snapshot by using the zonal disks.insert method. For example, to create a zonal disk, make the following request:

    POST https://compute.googleapis.com/compute/v1/projects/SOURCE_PROJECT_ID/zones/ZONE/disks
    {
      "name": DISK_NAME
      "sourceSnapshot": SNAPSHOT_NAME
    }
    

    Replace the following:

    • SOURCE_PROJECT_ID: The ID of the source project for the new disk.
    • ZONE: Zone for new disk.
    • DISK_NAME: A name for the new disk.
    • SNAPSHOT_NAME: The name of the snapshot.

    This disk is a temporary disk that is created only to copy the snapshot across organizations.

  2. Create a snapshot in the destination project by calling the snapshots.insert method. For example, to take a snapshot of a zonal persistent disk, make the following 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
    }
    

    Replace the following:

    • DESTINATION_PROJECT_ID: The ID of the destination project for the new snapshot.
    • SNAPSHOT_NAME: A name for the snapshot.
    • SOURCE_PROJECT_ID: The ID of the project that contains the source disk.
    • SOURCE_ZONE: The zone of the source disk.
    • SOURCE_DISK_NAME: The name of the source disk.
  3. Delete the temporary disk created in step 1 using disks.delete method.

What's next