创建和管理磁盘快照

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

创建快照以定期备份可用区永久性磁盘区域永久性磁盘中的数据。

即使磁盘已挂接到了正在运行的实例上,您也可以为这些磁盘创建快照。快照是全球性资源,因此您可以使用快照将数据恢复到同一项目内的新磁盘或实例。您还可以跨项目共享快照

准备工作

准备创建快照

如需准备创建永久性磁盘快照,请执行以下操作:

创建地区永久性磁盘的快照

控制台

  1. 在 Google Cloud 控制台中,进入虚拟机实例页面。

    进入“虚拟机实例”
    其余步骤将自动显示在 Google Cloud 控制台中。

  2. 名称列中,点击拥有要备份的永久性磁盘的虚拟机的名称。
  3. 存储部分:
    • 若要备份启动磁盘,请在启动磁盘部分点击启动磁盘的名称
    • 若要备份挂接的永久性磁盘,请在额外磁盘部分点击挂接的永久性磁盘的名称
  4. 点击创建快照
  5. 名称中,输入一个唯一的名称以帮助标识快照的用途,例如:
    • boot-disk-snapshot
    • attached-persistent-disk-snapshot
  6. 类型中,默认值为常规快照,最适合长期备份和灾难恢复。

    选择归档快照,实现更经济高效的数据保留。

  7. 位置部分,默认为多区域,该选项可以提供更高的可用性,但费用也会更高。

    选择区域快照,该选项能够更好地控制数据的实际位置,并且费用也会更低。

  8. 如需创建手动快照,请点击创建

gcloud

在默认存储位置或选定的存储位置创建快照。您必须指定快照名称。名称的长度必须为 1-63 个字符,并且符合 RFC 1035 的要求。

  • 如需在默认存储位置创建永久性磁盘的快照,请使用 gcloud compute snapshots create 命令

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

    替换以下内容:

    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_DISK:要从中创建快照的永久性磁盘的名称。
    • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。
    • SOURCE_DISK_ZONE:要从中创建快照的永久性磁盘的可用区。
  • 或者,如需在自定义存储位置创建快照,请使用 --storage-location 标志指示存储快照的位置:

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

    替换以下内容:

    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_DISK:要从中创建快照的永久性磁盘的名称。
    • SOURCE_DISK_ZONE:要从中创建快照的永久性磁盘的可用区。
    • STORAGE_LOCATION:您要存储快照的 Cloud Storage 多区域Cloud Storage 区域。请注意,您只能指定一个存储位置。
    • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。

gcloud CLI 会等待操作返回 READYFAILED 状态,或达到超时时间上限并返回快照的最后已知详情。

API

在默认存储位置或选定的存储位置创建快照。

  • 如需在默认存储位置中创建快照,请向 snapshots.insert 方法发出 POST 请求:

    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
    }
    

    替换以下内容:

    • DESTINATION_PROJECT_ID:您要在其中创建快照的项目的 ID。
    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_PROJECT_ID:来源磁盘项目的 ID。
    • SOURCE_ZONE:来源磁盘的可用区。
    • SOURCE_DISK_NAME:要从中创建快照的永久性磁盘的名称。
    • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。
  • 或者,如需在自定义存储位置创建快照,请向 snapshots.insert 方法发送 POST 请求并指定存储位置:

    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
    }
    

    替换以下内容:

    • DESTINATION_PROJECT_ID:您要在其中创建快照的项目的 ID。
    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_PROJECT_ID:来源磁盘项目的 ID。
    • SOURCE_ZONE:来源磁盘的可用区。
    • SOURCE_DISK_NAME:要从中创建快照的永久性磁盘的名称。
    • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。
    • STORAGE_LOCATION:您要存储快照的 Cloud Storage 多区域Cloud Storage 区域。请注意,您只能指定一个存储位置。

Go

Go

试用此示例之前,请按照《Compute Engine 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Compute Engine Go API 参考文档

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

试用此示例之前,请按照《Compute Engine 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Compute Engine Java API 参考文档


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

试用此示例之前,请按照《Compute Engine 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Compute Engine Node.js API 参考文档

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

试用此示例之前,请按照《Compute Engine 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Compute Engine Python API 参考文档

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)

创建区域永久性磁盘的快照

准备好磁盘之后,便可以创建快照。创建区域永久性磁盘的快照时,必须指出磁盘所在的区域。

控制台

  1. 转到 Google Cloud Console 中的创建快照页面。
    转到“创建快照”页面
  2. 输入快照名称
  3. 选择快照类型。默认值为常规快照,最适合长期备份和灾难恢复。

    选择归档快照,实现更经济高效的数据保留。

  4. (可选)输入快照的说明

  5. 来源磁盘下方,选择要从中创建快照的现有磁盘。

  6. 或者,您可以选择指定自定义存储位置

    1. 位置下,选择是要将快照存储在多区域位置还是区域位置。
    2. 选择要使用的特定区域或多区域。要使用距离源磁盘最近的区域或多区域,请选择基于磁盘的位置
  7. 点击创建以创建快照。

gcloud

在默认存储位置或选定的存储位置创建快照。

  • 如需在默认存储位置创建区域永久性磁盘的快照,请使用 gcloud compute snapshots create 命令

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

    替换以下内容:

    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_DISK:要从中创建快照的永久性磁盘的名称。
    • SOURCE_DISK_REGION:您要根据其创建快照的区域永久性磁盘的区域。
  • 或者,您可以选择指定自定义存储位置。

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

    替换以下内容:

    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_DISK:要从中创建快照的永久性磁盘的名称。
    • SOURCE_DISK_REGION:您要根据其创建快照的区域永久性磁盘的区域。
    • STORAGE_LOCATION:您要存储快照的 Cloud Storage 多区域Cloud Storage 区域。请注意,您只能指定一个存储位置。
    • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。

    Google Cloud CLI 将等到操作返回 READYFAILED 状态,或者等到操作达到超时时间上限并返回快照最新的已知详细信息。

API

  • 如需在默认存储位置中创建快照,请向 snapshots.insert 方法发出 POST 请求:

    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
    }
    

    替换以下内容:

    • DESTINATION_PROJECT_ID:您要在其中创建快照的项目的 ID。
    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_PROJECT_ID:来源磁盘项目的 ID。
    • SOURCE_REGION:来源磁盘的区域。
    • SOURCE_DISK_NAME:要从中创建快照的永久性磁盘的名称。
    • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。
  • 或者,如需在自定义存储位置创建快照,请向 snapshots.insert 方法发送 POST 请求并指定存储位置:

    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
    }
    

    替换以下内容:

    • DESTINATION_PROJECT_ID:您要在其中创建快照的项目的 ID。
    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_PROJECT_ID:来源磁盘项目的 ID。
    • SOURCE_REGION:来源磁盘的区域。
    • SOURCE_DISK_NAME:要从中创建快照的永久性磁盘的名称。
    • STORAGE_LOCATION:您要存储快照的 Cloud Storage 多区域Cloud Storage 区域。请注意,您只能指定一个存储位置。
    • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。

Go

Go

试用此示例之前,请按照《Compute Engine 快速入门:使用客户端库》中的 Go 设置说明进行操作。如需了解详情,请参阅 Compute Engine Go API 参考文档

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

试用此示例之前,请按照《Compute Engine 快速入门:使用客户端库》中的 Java 设置说明进行操作。如需了解详情,请参阅 Compute Engine Java API 参考文档


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

试用此示例之前,请按照《Compute Engine 快速入门:使用客户端库》中的 Node.js 设置说明进行操作。如需了解详情,请参阅 Compute Engine Node.js API 参考文档

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

试用此示例之前,请按照《Compute Engine 快速入门:使用客户端库》中的 Python 设置说明进行操作。如需了解详情,请参阅 Compute Engine Python API 参考文档

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)

删除快照

Compute Engine 使用差分快照,以使每个快照仅包含自上一个快照创建以来发生了更改的数据。由于后续快照可能需要之前的快照中存储的信息,因此请注意,删除快照未必会删除该快照上的所有数据。如需详细了解快照删除,请参阅快照删除

要删除快照,请执行以下操作:

控制台

  1. 在 Google Cloud Console 中,转到快照页面。

    转到“快照”页面

  2. 选择要删除的一个或多个快照。
  3. 点击快照页面顶部的删除

gcloud

如需删除某个快照,请使用 gcloud compute snapshots delete 命令:

gcloud compute snapshots delete SNAPSHOT_NAME

其中,SNAPSHOT_NAME 是要删除的快照的名称。

API

compute.snapshots.delete 方法发出 DELETE 请求以删除快照。

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

其中:

  • PROJECT_ID 是您的项目的名称。
  • SNAPSHOT_NAME 是要删除的快照的名称。

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

根据过滤条件删除多个快照

Compute Engine 使用差分快照,以使每个快照仅包含自上一个快照创建以来发生了更改的数据。由于后续快照可能需要之前的快照中存储的信息,因此删除快照未必会删除该快照上的所有数据。如需详细了解快照删除,请参阅快照删除

以下部分介绍如何根据给定的过滤条件删除大量快照。如需详细了解 gcloud CLI 过滤条件,请参阅 gcloud CLI 主题过滤条件

如需删除快照,请结合使用 gcloud compute snapshots list 命令和给定过滤条件,并结合使用 gcloud compute snapshots delete 命令xargs

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

EXPRESSION 替换为 gcloud 主题过滤条件。

例如,--filter="creationTimestamp>'2021-01-01'" 会删除 2021-01-01 之后创建的所有快照。

列出快照

gcloud

如需查看特定项目中可供您使用的快照的列表,请使用 gcloud compute snapshots list 命令

gcloud compute snapshots list --project PROJECT_ID

其中,PROJECT_ID 是项目的 ID。

API

如需查看特定项目中可供您使用的快照的列表,请向 snapshots.list 方法发出 GET 请求:

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

其中,PROJECT_ID 是项目的 ID。

查看有关快照的信息

如需列出特定快照的相关信息(例如创建时间、大小和来源磁盘),请使用 gcloud compute snapshots describe 命令:

gcloud compute snapshots describe SNAPSHOT_NAME

其中,SNAPSHOT_NAME 是快照的名称。

在同一组织中的多个项目之间共享快照数据

如需将数据从一个项目中的磁盘移动到同一组织内不同项目中的磁盘,请按照以下流程操作:

gcloud

  1. 使用 gcloud compute snapshots create 命令在目标项目中创建磁盘快照。例如,要创建可用区级永久性磁盘的快照,请使用以下命令:

    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
    

    替换以下内容:

    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_PROJECT_ID:来源磁盘项目的 ID。
    • ZONE:来源磁盘的可用区。
    • SOURCE_DISK_NAME:来源磁盘的名称。
    • DESTINATION_PROJECT_ID:新快照的目标项目的 ID。
  2. 在目标项目中,使用 gcloud compute disks create 命令创建基于快照的可用区级磁盘或区域级磁盘:

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

    替换以下内容:

    • DISK_NAME:新磁盘的名称。
    • SNAPSHOT_NAME:快照的名称。
    • DESTINATION_PROJECT_ID:新磁盘的目标项目的 ID。

API

  1. 通过调用 snapshots.insert 方法,在目标项目中创建磁盘快照。例如,如需截取可用区级永久性磁盘的快照,请发出以下请求:

    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
    }
    

    替换以下内容:

    • DESTINATION_PROJECT_ID:新快照的目标项目的 ID。
    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_PROJECT_ID:来源磁盘项目的 ID。
    • SOURCE_ZONE:来源磁盘的可用区。
    • SOURCE_DISK_NAME:来源磁盘的名称。
  2. 在目标项目中,使用可用区 disks.insert 方法或区域 regionDisks.insert 方法创建基于快照的可用区级或区域级磁盘。例如,如需创建可用区级磁盘,请发出以下请求:

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

    替换以下内容:

    • DESTINATION_PROJECT_ID:新磁盘的目标项目的 ID。
    • DISK_NAME:新磁盘的名称。
    • SNAPSHOT_NAME:快照的名称。

如需获取可用的快照列表,请参阅列出快照

在不同组织的多个项目之间共享快照

如需将快照从一个组织内的项目共享到另一个组织中的其他项目,请按照以下流程操作:

gcloud

  1. 在来源项目中,使用 gcloud compute disks create 命令创建基于快照的磁盘:

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

    请替换以下内容:

    • DISK_NAME:新磁盘的名称。
    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_PROJECT_ID:源项目的 ID。
    • ZONE:将在其中创建新磁盘的可用区。

    此磁盘是临时磁盘,仅创建用于跨组织复制快照。快照复制完成后,您可以删除此磁盘。

  2. 在目标项目中,使用 gcloud compute snapshots create 命令创建快照。比方说,如需使用步骤 1 中创建的可用区磁盘创建快照,请使用以下命令:

    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
    

    请替换以下内容:

    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_PROJECT_ID:包含来源磁盘的项目的 ID。
    • ZONE:来源磁盘的可用区。
    • SOURCE_DISK_NAME:步骤 1 中创建的磁盘的名称。
    • DESTINATION_PROJECT_ID:新快照的目标项目的 ID。

    如需获取可用的快照列表,请参阅列出快照

  3. 使用 gcloud compute disks delete 命令删除步骤 1 中创建的临时磁盘。

API

  1. 在来源项目中,使用可用区 disks.insert 方法创建基于快照的可用区或区域磁盘。例如,如需创建可用区级磁盘,请发出以下请求:

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

    请替换以下内容:

    • SOURCE_PROJECT_ID:新磁盘的来源项目的 ID。
    • ZONE:新磁盘的可用区。
    • DISK_NAME:新磁盘的名称。
    • SNAPSHOT_NAME:快照的名称。

    此磁盘是临时磁盘,仅创建用于跨组织复制快照。

  2. 通过调用 snapshots.insert 方法,在目标项目中创建快照。例如,如需截取可用区级永久性磁盘的快照,请发出以下请求:

    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
    }
    

    替换以下内容:

    • DESTINATION_PROJECT_ID:新快照的目标项目的 ID。
    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_PROJECT_ID:包含来源磁盘的项目的 ID。
    • SOURCE_ZONE:来源磁盘的可用区。
    • SOURCE_DISK_NAME:来源磁盘的名称。
  3. 使用 disks.delete 方法删除步骤 1 中创建的临时磁盘。

后续步骤