管理磁碟快照


標準磁碟快照可協助您定期備份永久磁碟和 Google Cloud Hyperdisk 中的資料。

您可以查看、列出及刪除磁碟快照。您也可以跨專案共用快照

事前準備

  • 如果尚未設定,請先設定驗證機制。驗證是指驗證身分,以便存取 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. After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    2. Set a default region and zone.

    REST

    To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.

      After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    For more information, see Authenticate for using REST in the Google Cloud authentication documentation.

必要角色和權限

如要取得管理標準快照所需的權限,請要求管理員為您授予專案的下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

這些預先定義的角色包含管理標準快照所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要管理標準快照,您必須具備下列權限:

  • 如要列出快照,請在專案中執行 compute.snapshots.list 命令:
  • 如要查看快照相關資訊,請執行下列操作: compute.snapshots.get on the snapshot
  • 如要刪除快照,請按照下列步驟操作: 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 控制台的「Snapshots」(快照)頁面。

    前往「Snapshots」(快照) 頁面

  2. 您可以在「快照」分頁中,查看目前專案的標準快照。

  3. 選用設定。您可以使用 filter_list 篩選器欄位縮小結果範圍。在「Filter」欄位中輸入屬性名稱或值,或從可用的屬性中選擇。

gcloud

更改下列內容:

  • PROJECT_ID:選用。請用專案 ID 取代。如果省略這個標記,系統會使用目前的專案。您可以使用 gcloud CLI 指令 gcloud config set project PROJECT_ID 設定工作階段的預設專案。
  • REGION_NAME:您要查看快照的區域名稱。

REST

  • 如要查看特定專案中可用的所有快照清單,請對 snapshots.list 方法發出 GET 要求,並指定「aggregated」。

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/aggregated/snapshots
    
  • (預先發布版) 如要查看特定專案中可用的區域範圍快照清單,請對 snapshots.list 方法發出 GET 要求,然後指定區域。

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_NAME/snapshots
    
  • 如要在特定專案中查看可用的全域範圍快照清單,請對 snapshots.list 方法發出 GET 要求,並指定「global」。

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

更改下列內容:

  • PROJECT_ID:專案 ID。
  • REGION_NAME:您要查看快照的區域名稱。

查看磁碟的標準快照

您可以使用 Google Cloud 控制台、gcloud CLI 或 REST,查看磁碟的標準快照清單。

主控台

  1. 前往 Google Cloud 控制台的「Snapshots」(快照)頁面。

    前往「Snapshots」(快照) 頁面

  2. 在「快照」分頁中,系統會顯示專案中所有標準快照的清單。

  3. 依來源磁碟縮小搜尋結果範圍:

    1. filter_list「Filter」欄位中輸入 Source disk:,或按一下「Filter」欄位,然後從「Properties」清單中選擇 Source disk 值。

    2. 在「Filter」欄位中,從「Values」清單中選取「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 控制台的「Snapshots」(快照)頁面。

    前往「Snapshots」(快照) 頁面

  2. 在「快照」分頁中,查看專案中的快照清單。

  3. 在「Name」欄中,按一下標準快照的名稱。系統會顯示所選快照的「Snapshot details」頁面,並顯示其屬性。

gcloud

更改下列內容:

  • SNAPSHOT_NAME:標準快照的名稱。
  • REGION_NAME:快照的範圍所在區域名稱。

REST

  • 如要查看全域範圍標準快照的相關資訊,請對 snapshots.get 方法發出 GET 要求。

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/snapshots/SNAPSHOT_NAME
    
  • (預覽) 如要查看地區範圍標準快照的相關資訊,請對 snapshots.get 方法提出 GET 要求,並指定地區。

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

更改下列內容:

  • PROJECT_ID:包含標準快照的專案名稱。
  • SNAPSHOT_NAME:標準快照的名稱。
  • REGION_NAME:快照的範圍所在區域名稱。

刪除快照

Compute Engine 使用差異快照,讓每個快照只包含前一個快照後變更的資料。由於後續快照可能需要存放在先前快照上的資訊,因此請注意,刪除快照不一定會刪除快照上的所有資料。

如要進一步瞭解如何刪除快照,請參閱「刪除快照」。

主控台

  1. 前往 Google Cloud 控制台的「Snapshots」(快照) 頁面。

    前往「Snapshots」(快照) 頁面

  2. 選取您要刪除的一或多個快照。

  3. 按一下「Snapshots」(快照) 頁面頂端的 [Delete] (刪除)

gcloud

更改下列內容:

  • SNAPSHOT_NAME:您要刪除的快照名稱。
  • REGION_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
    
  • (預先發布) 如要刪除地區範圍的快照,請對 snapshots.delete 方法發出 DELETE 要求,並指定地區。

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

更改下列內容:

  • PROJECT_ID:專案名稱。
  • SNAPSHOT_NAME:要刪除的快照名稱。
  • REGION_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 中建立的臨時磁碟名稱。

後續步驟