创建归档磁盘快照和标准磁盘快照


创建标准快照以定期备份以下类型的磁盘中的数据:

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

准备工作

  • 设置身份验证(如果尚未设置)。身份验证是通过其进行身份验证以访问 Google Cloud 服务和 API 的过程。如需从本地开发环境运行代码或示例,您可以按如下方式向 Compute Engine 进行身份验证。

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    1. Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init
    2. Set a default region and zone.
    3. Terraform

      如需在本地开发环境中使用本页面上的 Terraform 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

      如需了解详情,请参阅 Set up authentication for a local development environment

      Go

      如需在本地开发环境中使用本页面上的 Go 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

      如需了解详情,请参阅 Set up authentication for a local development environment

      Java

      如需在本地开发环境中使用本页面上的 Java 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

      如需了解详情,请参阅 Set up authentication for a local development environment

      Node.js

      如需在本地开发环境中使用本页面上的 Node.js 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

      如需了解详情,请参阅 Set up authentication for a local development environment

      Python

      如需在本地开发环境中使用本页面上的 Python 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

        gcloud init
      3. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

      如需了解详情,请参阅 Set up authentication for a local development environment

      REST

      如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 gcloud CLI 的凭据。

        Install the Google Cloud CLI, then initialize it by running the following command:

        gcloud init

      如需了解详情,请参阅 Google Cloud 身份验证文档中的使用 REST 时进行身份验证

所需的角色和权限

如需获得创建标准快照所需的权限,请让管理员在项目上向您授予以下 IAM 角色:

如需详细了解如何授予角色,请参阅管理访问权限

这些预定义角色包含创建标准快照所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

创建标准快照需要以下权限:

  • 创建可用区级磁盘的快照需要以下权限:
    • 针对项目的 compute.snapshots.create 权限
    • 针对磁盘的 compute.disks.createSnapshot 权限
  • 使用磁盘上的数据创建区域级磁盘的快照需要以下权限:
    • 针对项目的 compute.snapshots.create 权限
    • 针对源虚拟机的 compute.instances.useReadOnly 权限
    • 针对磁盘的 compute.disks.createSnapshot 权限
  • 通过副本恢复检查点创建区域级磁盘的快照需要以下权限:
    • 针对项目的 compute.snapshots.create 权限
    • 针对磁盘的 compute.disks.createSnapshot 权限

您也可以使用自定义角色或其他预定义角色来获取这些权限。

准备创建快照

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

  • 查看 Compute Engine 磁盘快照的最佳做法,准备磁盘来创建快照。

  • 如果想要自定义所有新快照的默认存储位置,请更新项目的快照设置。在您首次更新快照设置之前,Google Cloud 会一直保留预定义的默认存储位置值。此预定义位置是最靠近来源磁盘的多区域位置。

  • 阅读为磁盘快照创建时间表,了解如何创建快照时间表并将其挂接到磁盘。 使用计划快照定期备份磁盘可以降低数据意外丢失的风险。

创建 Persistent Disk 卷的快照

创建永久性磁盘卷快照的说明有所不同,具体取决于您是创建可用区级永久性磁盘的快照,还是创建区域级永久性磁盘的快照。

创建可用区级永久性磁盘卷的快照

控制台

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

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

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

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

  8. 位置部分,选择快照存储位置。系统会自动选择快照设置中定义的预定义或自定义默认位置。(可选)您可以通过执行以下操作来替换快照设置并将快照存储在自定义存储位置:

    1. 选择快照的存储位置类型。

      • 选择多区域,该选项以更高的费用实现更高的可用性。
      • 选择区域级快照,该选项使您能够更好地控制数据的实际位置,并且费用也会更低。
    2. 选择位置字段中,选择要使用的具体区域或多区域。如需使用最靠近源磁盘的区域或多区域,请选择基于磁盘的位置

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

gcloud

您可以在快照设置定义的存储位置政策中创建快照,也可以使用您选择的其他存储位置创建快照。如需了解详情,请参阅选择快照存储位置

  • 如需在快照设置中配置的预定义或自定义默认位置创建快照,请使用 gcloud compute snapshots create 命令

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk-zone=SOURCE_ZONE \
        --source-disk=SOURCE_DISK_NAME \
        --snapshot-type=SNAPSHOT_TYPE
    
  • 或者,如需替换快照设置并在自定义存储位置创建快照,请添加 --storage-location 标志以指定快照的存储位置。

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk-zone=SOURCE_ZONE \
        --source-disk=SOURCE_DISK_NAME \
        --snapshot-type=SNAPSHOT_TYPE \
        --storage-location=STORAGE_LOCATION
    

    替换以下内容:

    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_ZONE:来源磁盘的可用区。
    • SOURCE_DISK_NAME:要用于创建快照的 Persistent Disk 卷的名称。
    • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。
    • STORAGE_LOCATION:可选:要存储快照的 Cloud Storage 多区域Cloud Storage 区域。请注意,您只能指定一个存储位置。

      仅当您想要替换快照设置中配置的预定义或自定义默认存储位置时,才应使用 --storage-location 参数。

Terraform

如需创建可用区级永久性磁盘卷的快照,请使用 google_compute_snapshot 资源。

resource "google_compute_snapshot" "snapdisk" {
  name        = "snapshot-name"
  source_disk = google_compute_disk.default.name
  zone        = "us-central1-a"
}

如需了解如何应用或移除 Terraform 配置,请参阅基本 Terraform 命令

Go

Go

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

如需向 Compute Engine 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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: %w", 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: %w", 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 get disk: %w", err)
		}
	} else {
		regionDisksClient, err := compute.NewRegionDisksRESTClient(ctx)
		if err != nil {
			return fmt.Errorf("NewRegionDisksRESTClient: %w", 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 get disk: %w", err)
		}
	}

	req := &computepb.InsertSnapshotRequest{
		Project: projectID,
		SnapshotResource: &computepb.Snapshot{
			Name:             proto.String(snapshotName),
			SourceDisk:       proto.String(disk.GetSelfLink()),
			StorageLocations: locations,
		},
	}

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

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

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

	return nil
}

Java

Java

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

如需向 Compute Engine 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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 参考文档

如需向 Compute Engine 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * 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 参考文档

如需向 Compute Engine 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from __future__ import annotations

import sys
from typing import Any

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:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    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: str | None = None,
    region: str | None = None,
    location: str | None = None,
    disk_project_id: str | None = None,
) -> compute_v1.Snapshot:
    """
    Create a snapshot of a disk.

    You need to pass `zone` or `region` parameter relevant to the disk you want to
    snapshot, but not both. Pass `zone` parameter for zonal disks and `region` for
    regional disks.

    Args:
        project_id: project ID or project number of the Cloud project you want
            to use to store the snapshot.
        disk_name: name of the disk you want to snapshot.
        snapshot_name: name of the snapshot to be created.
        zone: name of the zone in which is the disk you want to snapshot (for zonal disks).
        region: name of the region in which is the disk you want to snapshot (for regional disks).
        location: The Cloud Storage multi-region or the Cloud Storage region where you
            want to store your snapshot.
            You can specify only one storage location. Available locations:
            https://cloud.google.com/storage/docs/locations#available-locations
        disk_project_id: project ID or project number of the Cloud project that
            hosts the disk you want to snapshot. If not provided, will look for
            the disk in the `project_id` project.

    Returns:
        The new snapshot instance.
    """
    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)

REST

您可以在快照设置定义的存储位置政策中创建快照,也可以使用您选择的其他存储位置创建快照。如需了解详情,请参阅选择快照存储位置

  • 如需在快照设置中配置的预定义或自定义默认位置创建快照,请向 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"
    }
    
  • 或者,如需替换快照设置并在自定义存储位置创建快照,请向 snapshots.insert 方法发出 POST 请求,并在请求中添加 storageLocations 属性:

    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:要用于创建快照的 Persistent Disk 卷的名称。
  • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。
  • STORAGE_LOCATION:可选:要存储快照的 Cloud Storage 多区域Cloud Storage 区域。请注意,您只能指定一个存储位置。

    仅当您想要替换快照设置中配置的预定义或自定义默认存储位置时,才应使用 storageLocations 参数。

创建区域级 Persistent Disk 卷的快照

您可以通过以下任一方式创建区域级永久性磁盘卷的快照:

  • 使用来源磁盘上的数据。如需使用此快照创建方法,您必须拥有可用的同步可用区副本。
  • 使用已降级的磁盘的副本恢复检查点。您只能使用 Google Cloud CLI 或 REST 通过检查点创建快照。

准备磁盘之后,便可以创建快照。创建区域级 Persistent Disk 的快照时,必须指出来源磁盘所在的区域。

控制台

  1. 转到 Google Cloud 控制台中的创建快照页面。

    转到“创建快照”页面
  2. 输入快照名称
  3. 选择快照类型。默认值为 STANDARD 快照,这最适合长期备份和灾难恢复。

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

  4. 可选:输入配置的说明
  5. 来源磁盘下,选择您想要创建其快照的现有磁盘。
  6. 位置部分,选择快照存储位置

    系统会自动选择快照设置中定义的预定义或自定义默认位置。(可选)您可以通过执行以下操作来替换快照设置并将快照存储在自定义存储位置:

    1. 选择快照的存储位置类型。

      • 选择多区域,该选项以更高的费用实现更高的可用性。
      • 选择区域级快照,该选项使您能够更好地控制数据的实际位置,并且费用也会更低。
    2. 选择位置字段中,选择要使用的具体区域或多区域。如需使用最靠近源磁盘的区域或多区域,请选择基于磁盘的位置
  7. 点击创建以创建快照。

gcloud

您可以使用来源磁盘的数据或其副本恢复检查点来创建快照。

通过磁盘数据

您可以使用快照设置定义的存储位置政策或使用您选择的替代存储位置来根据磁盘数据创建快照。如需了解详情,请参阅选择快照存储位置

  • 如需在快照设置中配置的预定义或自定义默认位置创建快照,请使用 gcloud compute snapshots create 命令

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk-region=SOURCE_REGION \
        --source-disk=SOURCE_DISK_NAME \
        --snapshot-type=SNAPSHOT_TYPE
    
  • 或者,如需替换快照设置并在自定义存储位置创建快照,请添加 --storage-location 标志以指定快照的存储位置。

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

    替换以下内容:

    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_REGION:来源磁盘的区域。
    • SOURCE_DISK_NAME:区域级 Persistent Disk 卷的名称,您将根据其创建快照。
    • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。
    • STORAGE_LOCATION:可选:要存储快照的 Cloud Storage 多区域Cloud Storage 区域。请注意,您只能指定一个存储位置。

      仅当您想要替换快照设置中配置的预定义或自定义默认存储位置时,才应使用 --storage-location 参数。

通过检查点

您可以使用已降级的磁盘的副本恢复检查点预览版)创建快照。只要您的不完整副本可用,系统就会创建快照。

如需使用副本恢复检查点创建快照,请使用 gcloud compute snapshots create 命令。添加 --source-disk-for-recovery-checkpoint 标志以指定要使用副本恢复检查点创建快照。排除 --source-disk--source-disk-region 参数。

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

请替换以下内容:

  • DESTINATION_PROJECT_ID:您要在其中创建快照的项目的 ID。
  • SNAPSHOT_NAME:快照的名称。
  • SOURCE_PROJECT_ID:要用于创建快照的检查点的来源磁盘的项目 ID。
  • SOURCE_REGION:要用于创建快照的检查点的来源磁盘的区域。
  • SOURCE_DISK_NAME:要用于创建快照的检查点的来源磁盘的名称。
  • STORAGE_LOCATION:可选:要存储快照的 Cloud Storagemulti-regionCloud Storageregion。请注意,您只能指定一个存储位置。
    只有在您想要替换在快照设置中配置的预定义或自定义默认存储位置时,才应使用此参数。
  • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。

您可以使用副本恢复检查点仅在降级的磁盘上创建快照。如果您尝试在完全复制设备后根据副本恢复检查点创建快照,则会看到以下错误消息:

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

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

Terraform

适用于 Google Cloud 的 Terraform 提供程序不支持创建区域级永久性磁盘卷的快照。如需跟踪此限制,请参阅 GitHub 上的问题

Go

Go

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

如需向 Compute Engine 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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: %w", 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: %w", 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 get disk: %w", err)
		}
	} else {
		regionDisksClient, err := compute.NewRegionDisksRESTClient(ctx)
		if err != nil {
			return fmt.Errorf("NewRegionDisksRESTClient: %w", 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 get disk: %w", err)
		}
	}

	req := &computepb.InsertSnapshotRequest{
		Project: projectID,
		SnapshotResource: &computepb.Snapshot{
			Name:             proto.String(snapshotName),
			SourceDisk:       proto.String(disk.GetSelfLink()),
			StorageLocations: locations,
		},
	}

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

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

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

	return nil
}

Java

Java

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

如需向 Compute Engine 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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 参考文档

如需向 Compute Engine 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * 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 参考文档

如需向 Compute Engine 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from __future__ import annotations

import sys
from typing import Any

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:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    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: str | None = None,
    region: str | None = None,
    location: str | None = None,
    disk_project_id: str | None = None,
) -> compute_v1.Snapshot:
    """
    Create a snapshot of a disk.

    You need to pass `zone` or `region` parameter relevant to the disk you want to
    snapshot, but not both. Pass `zone` parameter for zonal disks and `region` for
    regional disks.

    Args:
        project_id: project ID or project number of the Cloud project you want
            to use to store the snapshot.
        disk_name: name of the disk you want to snapshot.
        snapshot_name: name of the snapshot to be created.
        zone: name of the zone in which is the disk you want to snapshot (for zonal disks).
        region: name of the region in which is the disk you want to snapshot (for regional disks).
        location: The Cloud Storage multi-region or the Cloud Storage region where you
            want to store your snapshot.
            You can specify only one storage location. Available locations:
            https://cloud.google.com/storage/docs/locations#available-locations
        disk_project_id: project ID or project number of the Cloud project that
            hosts the disk you want to snapshot. If not provided, will look for
            the disk in the `project_id` project.

    Returns:
        The new snapshot instance.
    """
    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)

REST

您可以使用来源磁盘的数据或其副本恢复检查点来创建快照。

通过磁盘数据

您可以使用快照设置定义的存储位置政策或使用您选择的替代存储位置来根据磁盘数据创建快照。如需了解详情,请参阅选择快照存储位置

  • 如需在快照设置中配置的预定义或自定义默认位置创建快照,请向 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"
    }
    
  • 或者,如需替换快照设置并在自定义存储位置创建快照,请向 snapshots.insert 方法发出 POST 请求,并在请求中添加 storageLocations 属性:

    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:区域级 Persistent Disk 卷的名称,您将根据其创建快照。
  • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。
  • STORAGE_LOCATION:可选:要存储快照的 Cloud Storage 多区域Cloud Storage 区域。请注意,您只能指定一个存储位置。

    仅当您想要替换快照设置中配置的预定义或自定义默认存储位置时,才应使用 storageLocations 参数。

通过检查点

或者,您可以使用已降级的磁盘的副本恢复检查点创建快照。只要您的不完整副本可用,系统就会创建快照。

若要使用副本恢复检查点创建快照,请向 snapshots.insert 方法发出 POST 请求。排除 sourceDisk 参数,添加 sourceDiskForRecoveryCheckpoint 参数,以指定要使用检查点创建快照。

POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/global/snapshots

{
  "name": "SNAPSHOT_NAME",
  "sourceDiskForRecoveryCheckpoint": "projects/SOURCE_PROJECT_ID/regions/SOURCE_REGION/disks/SOURCE_DISK_NAME",
  "storageLocations": "STORAGE_LOCATION",
  "snapshotType": "SNAPSHOT_TYPE"
}

请替换以下内容:

  • DESTINATION_PROJECT_ID:您要在其中创建快照的项目的 ID。
  • SNAPSHOT_NAME:快照的名称。
  • SOURCE_PROJECT_ID:要用于创建快照的检查点的来源磁盘的项目 ID。
  • SOURCE_REGION:要用于创建快照的检查点的来源磁盘的区域。
  • SOURCE_DISK_NAME:要用于创建快照的检查点的来源磁盘的名称。
  • STORAGE_LOCATION:可选:要存储快照的 Cloud Storagemulti-regionCloud Storageregion。请注意,您只能指定一个存储位置。
    仅当您想要替换快照设置中配置的预定义或自定义默认存储位置时,才应使用 storageLocations 参数。
  • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。

您可以使用副本恢复检查点仅在降级的磁盘上创建快照。如果您尝试在完全复制设备后根据副本恢复检查点创建快照,则会看到以下错误消息:

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

创建 Hyperdisk 的快照

控制台

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

    转到虚拟机实例

  2. 选择包含您的虚拟机实例的项目。

  3. 名称列中,点击含有要备份的 Hyperdisk 的虚拟机的名称。

  4. 存储空间额外磁盘中,点击挂接的 Hyperdisk 的名称

  5. 点击创建快照

  6. 名称中,输入一个唯一的名称以帮助标识快照的用途,例如:hyperdisk-data-snapshot

  7. 类型中,默认值为常规快照,最适合长期备份和灾难恢复。

  8. 位置部分,选择快照存储位置

    系统会自动选择快照设置中定义的预定义或自定义默认位置。(可选)您可以通过执行以下操作来替换快照设置并将快照存储在自定义存储位置:

    1. 选择快照的存储位置类型。

      • 选择多区域,该选项以更高的费用实现更高的可用性。
      • 选择区域级快照,该选项使您能够更好地控制数据的实际位置,并且费用也会更低。
    2. 选择位置字段中,选择要使用的具体区域或多区域。如需使用最靠近源磁盘的区域或多区域,请选择基于磁盘的位置

  9. 点击创建

gcloud

您可以在快照设置定义的存储位置政策中创建快照,也可以使用您选择的其他存储位置创建快照。如需了解详情,请参阅选择快照存储位置

您必须指定快照名称。名称的长度必须为 1-63 个字符,并且符合 RFC 1035 的要求。

  • 如需在快照设置中配置的预定义或自定义默认位置创建快照,请使用 gcloud compute snapshots create 命令

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk-zone=SOURCE_ZONE \
        --source-disk=SOURCE_DISK_NAME \
        --snapshot-type=SNAPSHOT_TYPE
    
  • 或者,如需替换快照设置并在自定义存储位置创建快照,请添加 --storage-location 标志以指定快照的存储位置。

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk-zone=SOURCE_ZONE \
        --source-disk=SOURCE_DISK_NAME \
        --snapshot-type=SNAPSHOT_TYPE \
        --storage-location=STORAGE_LOCATION
    

    替换以下内容:

    • SNAPSHOT_NAME:快照的名称。
    • SOURCE_ZONE:来源磁盘的可用区。
    • SOURCE_DISK_NAME:Hyperdisk 卷的名称,您将根据其创建快照。
    • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。
    • STORAGE_LOCATION:可选:要存储快照的 Cloud Storage 多区域Cloud Storage 区域。请注意,您只能指定一个存储位置。

      仅当您想要替换快照设置中配置的预定义或自定义默认存储位置时,才应使用 --storage-location 参数。

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

REST

您可以在快照设置定义的存储位置政策中创建快照,也可以使用您选择的其他存储位置创建快照。如需了解详情,请参阅选择快照存储位置

您必须指定快照名称。名称的长度必须为 1-63 个字符,并且符合 RFC 1035 的要求。

  • 如需在快照设置中配置的预定义或自定义默认位置创建快照,请向 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"
    }
    
  • 或者,如需替换快照设置并在自定义存储位置创建快照,请向 snapshots.insert 方法发出 POST 请求,并在请求中添加 storageLocations 属性:

    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:Hyperdisk 卷的名称,您将根据其创建快照。
  • SNAPSHOT_TYPE:快照类型:STANDARDARCHIVE。如果未指定快照类型,系统会创建 STANDARD 快照。
  • STORAGE_LOCATION:可选:要存储快照的 Cloud Storage 多区域Cloud Storage 区域。请注意,您只能指定一个存储位置。

    仅当您想要替换快照设置中配置的预定义或自定义默认存储位置时,才应使用 storageLocations 参数。

后续步骤