管理磁盘快照


标准磁盘快照可帮助您定期备份永久性磁盘和 Google Cloud Hyperdisk 中的数据。

您可以查看、列出和删除磁盘快照。您还可以跨项目共享快照

准备工作

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

    选择标签页以了解您打算如何使用本页面上的示例:

    控制台

    当您使用 Google Cloud 控制台访问 Google Cloud 服务和 API 时,无需设置身份验证。

    gcloud

    1. 安装 Google Cloud CLI,然后通过运行以下命令初始化 Google Cloud CLI:

      gcloud init
    2. 设置默认区域和可用区

    REST

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

      安装 Google Cloud CLI,然后通过运行以下命令初始化 Google Cloud CLI:

      gcloud init

所需的角色和权限

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

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

这些预定义角色可提供管理标准快照所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

您需要具备以下权限才能管理标准快照:

  • 如需列出快照:针对项目的 compute.snapshots.list 权限
  • 如需查看快照的相关信息:针对快照的 compute.snapshots.get 权限
  • 如需删除快照:针对快照的 compute.snapshots.delete 权限
  • 如需根据过滤条件删除快照,需要以下权限:
    • 针对快照的 compute.snapshots.delete 权限
    • 针对项目的 compute.snapshots.list 权限
  • 如需跨项目共享快照数据,需要以下权限:
    • 针对项目的 compute.storageAdmin 权限(用于访问所有标准快照)
    • 针对要共享的项目的 compute.disks.create 权限
    • 针对源项目的 compute.snapshots.create 权限。
    • 针对来源磁盘的 compute.disks.createSnapshot 权限

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

查看某个项目或位置中的标准快照

您可以使用 gcloud CLI、Google Cloud 控制台或 REST 查看或列出某个项目或位置中的标准快照。

控制台

  1. 在 Google Cloud 控制台中,转到快照页面。

    转到“快照”页面

  2. 快照标签页上,您可以查看当前项目的标准快照。

  3. 可选。使用 filter_list 过滤条件字段缩小结果范围。在过滤条件字段中输入属性名称或值,或从可用属性中选择。

gcloud

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

gcloud compute snapshots list --project=PROJECT_ID

可选。将 PROJECT_ID 替换为项目 ID。 如果省略此标志,则使用当前项目。您可以使用 gcloud CLI 命令 gcloud config set project PROJECT_ID 为会话设置默认项目。

REST

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

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

PROJECT_ID 替换为项目 ID。

查看磁盘的标准快照

您可以使用 Google Cloud 控制台、gcloud CLI 或 REST 查看磁盘的标准快照列表。

控制台

  1. 在 Google Cloud 控制台中,转到快照页面。

    转到“快照”页面

  2. 快照标签页上会显示项目中所有标准快照的列表。

  3. 按来源磁盘缩小结果范围:

    1. filter_list 过滤条件字段中输入 Source disk:,或点击过滤条件字段,然后从属性列表选择值 Source disk

    2. 过滤条件字段中 Source disk: 旁边显示的列表中选择磁盘名称。

      现在,控制台中显示的快照会显示指定磁盘的所有标准快照。

      如果您在列表中没有看到磁盘名称,请在 Source disk: 旁边的过滤条件字段中输入以来源磁盘名称的前几个字母,以更改您看到的值列表。

gcloud

使用 gcloud compute snapshots list 命令--filter 参数列出磁盘的标准快照。

  • 列出某个可用区级磁盘的标准快照:

    gcloud compute snapshots list --filter="sourceDisk:projects/PROJECT_ID/zones/SOURCE_ZONE/disks/DISK_NAME
    
  • 列出某个区域级磁盘的标准快照:

    gcloud compute snapshots list --filter=sourceDisk:projects/PROJECT_ID/regions/SOURCE_REGION/disks/DISK_NAME
    

替换以下内容:

  • PROJECT_ID:项目的 ID。
  • SOURCE_ZONE:(仅限可用区级磁盘)磁盘所在可用区的名称,例如 us-west1-a
  • SOURCE_REGION:(仅限区域级磁盘)磁盘所在区域的名称,例如 us-west1
  • DISK_NAME:磁盘的名称,例如 disk-1

REST

snapshots.list 方法发出 GET 请求,以列出某个可用区级或区域级磁盘的标准快照。

使用 filter=sourceDisk 查询参数指定磁盘的名称。

  • 列出某个可用区级磁盘的标准快照:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/snapshots?filter=sourceDisk:'https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/SOURCE_ZONE/disks/DISK_NAME'
    
  • 列出某个区域级磁盘的标准快照:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/snapshots?filter=sourceDisk:'https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/SOURCE_REGION/disks/DISK_NAME'
    

替换以下内容:

  • PROJECT_ID:项目的 ID。
  • SOURCE_ZONE:(仅限可用区级磁盘)磁盘所在可用区的名称,例如 us-west1-a
  • SOURCE_REGION:(仅限区域级磁盘)磁盘所在区域的名称,例如 us-west1
  • DISK_NAME:来源磁盘的名称,例如 disk-1

查看有关标准快照的信息

使用 Google Cloud 控制台、Google Cloud CLI 或 REST 检索标准快照的详细信息,例如创建时间、来源磁盘和大小。

控制台

  1. 在 Google Cloud 控制台中,转到快照页面。

    转到“快照”页面

  2. 快照标签页上,查看项目中的快照的列表。

  3. 名称列中,点击标准快照的名称。此时会显示所选快照的快照详情页面,其中显示快照的属性。

gcloud

如需查看标准快照的相关信息,请使用 gcloud compute snapshots describe 命令

gcloud compute snapshots describe SNAPSHOT_NAME

SNAPSHOT_NAME 替换为标准快照的名称。

REST

snapshots.get 方法发出 GET 请求。

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

替换以下内容:

  • PROJECT_ID:包含标准快照的项目的名称。
  • SNAPSHOT_NAME:标准快照的名称。

删除快照

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

如需详细了解快照删除,请参阅快照删除

控制台

  1. 在 Google Cloud 控制台中,转到快照页面。

    转到“快照”页面

  2. 选择要删除的一个或多个快照。

  3. 点击快照页面顶部的删除

gcloud

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

gcloud compute snapshots delete SNAPSHOT_NAME

SNAPSHOT_NAME 替换为要删除的快照的名称。

Go

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
)

// 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: %w", 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: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", 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

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 delete_snapshot(project_id: str, snapshot_name: str) -> None:
    """
    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")

REST

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

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

替换以下内容:

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

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

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 CLI 主题过滤条件。

例如,--filter="creationTimestamp<'2023-12-31'" 会删除 2023 年 12 月 31 日之前创建的所有快照。

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

您可以按照此过程将数据从一个项目中的磁盘移动到同一组织内其他项目中的磁盘。

gcloud

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

    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。

REST

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

    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。
    • DESTINATION_ZONE:新磁盘的目标项目中的可用区。
    • 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 命令创建快照。

    例如,如需使用第一步中创建的可用区级磁盘创建快照,请使用以下命令:

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

    替换以下内容:

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

    如需获取可用快照的列表,请参阅查看某个项目或位置中的标准快照

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

    gcloud compute disks delete DISK_NAME \
     --project SOURCE_PROJECT_ID --zone ZONE
    

    替换以下内容:

    • DISK_NAME:步骤 1 中创建的磁盘的名称。
    • SOURCE_PROJECT_ID:包含来源磁盘的项目的 ID。
    • ZONE:磁盘的可用区。

REST

  1. 在来源项目中,使用可用区 disks.insert 方法创建基于快照的可用区级或区域级磁盘。

    例如,如需创建可用区级磁盘,请发出以下请求:

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

    替换以下内容:

    • SOURCE_PROJECT_ID:新磁盘的来源项目的 ID。
    • SOURCE_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/DISK_NAME
    }
    

    替换以下内容:

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

    DELETE https://compute.googleapis.com/compute/v1/projects/SOURCE_PROJECT_ID/zones/SOURCE_ZONE/disks/DISK_NAME
    

    替换以下内容:

    • SOURCE_PROJECT_ID:包含临时磁盘的项目的 ID。
    • SOURCE_ZONE:磁盘的可用区。
    • DISK_NAME:步骤 1 中创建的临时磁盘的名称。

后续步骤