管理磁碟快照


標準磁碟快照可協助您定期備份 Persistent Disk 和 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.
      3. REST

        如要在本機開發環境中使用本頁的 REST API 範例,請使用您提供給 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.

        詳情請參閱 Google Cloud 驗證說明文件中的「Authenticate for using REST」。

必要角色和權限

如要取得管理標準快照所需的權限,請要求管理員授予您專案的下列 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 控制台的「快照」頁面。

    前往「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」(快照) 頁面

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

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

    1. 在「Filter」(篩選器) 欄位中輸入 Source disk:filter_list,或按一下「Filter」(篩選器) 欄位,然後從「Properties」(屬性) 清單中選擇值 Source disk

    2. 在「Filter」(篩選器) 欄位中,選取 Source disk: 旁邊顯示的「Values」(值) 清單中的磁碟名稱。

      主控台顯示的快照現在會顯示指定磁碟的所有標準快照。

      如果「值」清單中沒有顯示磁碟名稱,請在 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」(快照) 頁面

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

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

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」(快照) 頁面

  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 建立的臨時磁碟名稱。

後續步驟