建立封存和標準磁碟快照

建立標準快照,定期備份可用區和區域 Persistent Disk 及 Google Cloud Hyperdisk 磁碟區中的資料。

您甚至可以為已連結到執行中執行個體的磁碟建立快照。快照預設為全域資源,因此您可以使用快照,將資料還原至同一專案中的新磁碟或 VM。如要進一步保護資料及管理費用,您可以控管能使用快照建立新磁碟的位置。如要限制快照可還原資料的區域,您可以建立區域範圍快照,並設定允許的存取位置 (預先發布版)。您也可以跨專案共用快照。

事前準備

  • (預先發布版) 如要建立區域範圍的快照,請先設定預設的快照建立和還原位置,再完成本頁步驟。
  • 如果尚未設定驗證,請先完成設定。驗證機制會確認您的身分,以便授予 Google Cloud 服務和 API 的存取權。如要從本機開發環境執行程式碼或範例,您可以選取下列其中一個選項,向 Compute Engine 進行驗證:

    請根據您打算如何使用本頁範例,選取對應的分頁標籤:

    控制台

    使用 Google Cloud 控制台存取 Google Cloud 服務和 API 時,不需要設定驗證機制。

    gcloud

    1. 安裝 Google Cloud CLI。 安裝完成後,請執行下列指令,初始化 Google Cloud CLI:

      gcloud init

      若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

  • 設定預設區域和可用區。
  • Terraform

    如要在本機開發環境中使用本頁的 Terraform 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用的是 Cloud Shell,則不必執行這項操作。

      如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Go

    如要在本機開發環境中使用本頁面的 Go 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用的是 Cloud Shell,則不必執行這項操作。

      如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Java

    如要在本機開發環境中使用本頁的 Java 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用的是 Cloud Shell,則不必執行這項操作。

      如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Node.js

    如要在本機開發環境中使用本頁的 Node.js 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用的是 Cloud Shell,則不必執行這項操作。

      如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Python

    如要在本機開發環境中使用本頁面的 Python 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

    1. 安裝 Google Cloud CLI。

    2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用的是 Cloud Shell,則不必執行這項操作。

      如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    REST

    如要在本機開發環境中使用本頁的 REST API 範例,請使用您提供給 gcloud CLI 的憑證。

      安裝 Google Cloud CLI。

      若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    詳情請參閱 Google Cloud 驗證說明文件中的「使用 REST 進行驗證」一節。

必要角色和權限

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

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

這些預先定義的角色具備建立及管理快照所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

您必須具備下列權限,才能建立及管理快照:

  • 專案的 compute.snapshots.create
  • 如要建立可用區磁碟的快照,請按照下列步驟操作: compute.disks.createSnapshot
  • 如果磁碟是區域磁碟,且您想建立磁碟資料的快照:
    • compute.instances.useReadOnly
    • compute.disks.createSnapshot
  • 如果磁碟是區域磁碟,且您想建立副本復原檢查點的快照: compute.disks.createSnapshot
  • 如要建立區域範圍快照:
    • compute.regionSnapshots.create
    • compute.disks.useReadOnly
  • 如要從副本復原檢查點建立區域磁碟快照,請執行下列操作: compute.disks.createSnapshot 磁碟
  • 如要建立快照排程: compute.resourcePolicies.create 專案或組織
  • 如要將快照排程附加至磁碟,請按照下列步驟操作:
    • 磁碟上的 compute.disks.addResourcePolicies
    • compute.resourcePolicies.use 資源政策
  • 如要刪除快照,請按照下列步驟操作:
    • compute.snapshots.delete 快照
    • 專案的 compute.snapshots.list

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

準備建立快照

如要準備建立 Persistent Disk 或 Hyperdisk 磁碟區的快照,請完成下列步驟:

  • 請參閱「Compute Engine 磁碟快照的最佳做法」,瞭解如何準備磁碟以建立快照。

  • 如要自訂所有新全域範圍快照的預設儲存位置,請更新專案的快照設定。Google Cloud 會保留預先定義的預設儲存位置值,直到您首次更新快照設定為止。這個預先定義的位置是距離來源磁碟最近的多區域。

  • 請參閱「建立磁碟快照排程」,瞭解如何建立快照排程並附加至磁碟。定期使用排定的快照備份磁碟,可降低意外資料遺失的風險。

建立磁碟快照

建立磁碟快照的步驟,取決於您要建立可用區磁碟或區域磁碟的快照。

建立可用區磁碟的快照

控制台

  1. 前往 Google Cloud 控制台的「Create a Snapshot」(建立快照) 頁面。

    前往「Create a Snapshot」(建立快照) 頁面
  2. 輸入快照的「Name」(名稱)。
  3. 選取「Snapshot type」(快照類型)。預設為 STANDARD 快照,這是長期備份和災難復原的最佳選項。

    選擇「封存快照」,以更符合成本效益的方式保留資料。

  4. 選用:輸入快照的說明。
  5. 在「Source disk」(來源磁碟) 下方,選取要建立快照的現有磁碟。
  6. 在「Location」(位置) 部分,選擇快照儲存位置。

    系統會自動選取快照設定中指定的預先定義或自訂預設位置。如要覆寫快照設定,將快照儲存在自訂儲存位置,請執行下列步驟:

    1. 選擇快照的儲存位置類型。

    2. 在「Select location」(選取位置) 欄位,選擇要使用的特定區域或多區域。如要使用離來源磁碟最近的區域或多區域,請選取「Based on disk's location」(以磁碟位置為準)。
  7. 按一下 [Create] (建立) 以建立快照。

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
    
  • (預先發布版) 如要在允許的區域中建立區域範圍快照,請加入 --region 旗標,指出快照的建立位置。

    gcloud beta compute snapshots create SNAPSHOT_NAME \
        --region=SNAPSHOT_SCOPE_REGION
        --source-disk=SOURCE_DISK_NAME \
        --source-disk-zone=SOURCE_ZONE \
        --snapshot-type=SNAPSHOT_TYPE
    

更改下列內容:

  • SNAPSHOT_NAME:快照名稱。
  • SOURCE_ZONE:來源磁碟的可用區。
  • SOURCE_DISK_NAME:要建立快照的 Persistent Disk 磁碟區名稱。
  • SNAPSHOT_TYPE:快照類型,可以是 STANDARD 或 ARCHIVE。如未指定快照類型,系統會建立 STANDARD 快照。
  • STORAGE_LOCATION:選用:如果是全域範圍的快照,請指定要儲存快照的 Cloud Storage 多區域或 Cloud Storage 區域。您只能指定一個儲存位置。

    只有在要覆寫快照設定中預先定義或自訂的預設儲存位置時,才需要使用 --storage-location 參數。

  • SNAPSHOT_SCOPE_REGION:選用:如果是區域範圍的快照,則為快照範圍所在的區域。如果加入這個參數,就無法使用 --storage-location 參數。STORAGE_LOCATION 會自動設為 SNAPSHOT_SCOPE_REGION。

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 "cloud.google.com/go/compute/apiv1/computepb"
	"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"
        ],
    }
    
  • (預先發布版) 如要在允許的區域中建立區域範圍快照,請向 snapshots.insert 方法發出 POST 要求,並定義建立區域:

    POST https://compute.googleapis.com/compute/beta/projects/DESTINATION_PROJECT_ID/regions/SNAPSHOT_SCOPE_REGION/snapshots
    {
        "name": "SNAPSHOT_NAME",
        "sourceDisk": "projects/SOURCE_PROJECT_ID/zones/SOURCE_ZONE/disks/SOURCE_DISK_NAME",
        "snapshotType": "SNAPSHOT_TYPE"
    }
    

更改下列內容:

  • DESTINATION_PROJECT_ID:要建立快照的專案 ID。
  • SNAPSHOT_NAME:快照名稱。
  • SOURCE_PROJECT_ID:來源磁碟專案的 ID。
  • SOURCE_ZONE:來源磁碟的可用區。
  • SOURCE_DISK_NAME:要建立快照的 Persistent Disk 磁碟區名稱。
  • SNAPSHOT_TYPE:快照類型,可以是 STANDARD 或 ARCHIVE。如未指定快照類型,系統會建立 STANDARD 快照。
  • STORAGE_LOCATION:選用:如果是全域範圍的快照,請指定要儲存快照的 Cloud Storage 多區域或 Cloud Storage 區域。您只能指定一個儲存位置。

    只有在要覆寫快照設定中預先定義或自訂的預設儲存位置時,才需要使用 storageLocations 參數。

  • SNAPSHOT_SCOPE_REGION:選用:如果是區域範圍的快照,則為快照範圍所在的區域。如果加入這個參數,就無法使用 storageLocations 參數。STORAGE_LOCATION 會自動設為 SNAPSHOT_SCOPE_REGION。

建立區域磁碟快照

您可以透過下列任一方式建立區域磁碟的快照:

  • 使用來源磁碟上的資料。如要使用這個快照建立方法,必須有已同步的可用可用區副本。
  • 使用降級磁碟的副本復原檢查點。您只能使用 Google Cloud CLI 或 REST,從檢查點建立快照。

準備好磁碟後,即可建立快照。建立區域磁碟的快照時,必須指出來源磁碟所在的區域。

控制台

  1. 前往 Google Cloud 控制台的「Create a Snapshot」(建立快照) 頁面。

    前往「Create a Snapshot」(建立快照) 頁面
  2. 輸入快照的「Name」(名稱)。
  3. 選取「Snapshot type」(快照類型)。預設為 STANDARD 快照,這是長期備份和災難復原的最佳選項。

    選擇「封存快照」,以更符合成本效益的方式保留資料。

  4. 選用:輸入快照的說明。
  5. 在「Source disk」(來源磁碟) 下方,選取要建立快照的現有磁碟。
  6. 在「Location」(位置) 部分,選擇快照儲存位置。

    系統會自動選取快照設定中指定的預先定義或自訂預設位置。如要覆寫快照設定,將快照儲存在自訂儲存位置,請執行下列步驟:

    1. 選擇快照的儲存位置類型。

    2. 在「Select location」(選取位置) 欄位,選擇要使用的特定區域或多區域。如要使用離來源磁碟最近的區域或多區域,請選取「Based on disk's location」(以磁碟位置為準)。
  7. 按一下 [Create] (建立) 以建立快照。

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
    
  • (預先發布版) 如要在允許的區域中建立區域範圍快照,請加入 --region 旗標,指出快照的建立位置。

    gcloud beta compute snapshots create SNAPSHOT_NAME \
        --region=SNAPSHOT_SCOPE_REGION \
        --source-disk=SOURCE_DISK_NAME \
        --source-disk-region=SOURCE_REGION \
        --snapshot-type=SNAPSHOT_TYPE
    

更改下列內容:

  • SNAPSHOT_NAME:快照名稱。
  • SOURCE_REGION:來源磁碟的區域。
  • SOURCE_DISK_NAME:要建立快照的 區域性永久磁碟或 Hyperdisk Balanced High Availability 磁碟區名稱。
  • SNAPSHOT_TYPE:快照類型,可以是 STANDARD 或 ARCHIVE。如未指定快照類型,系統會建立 STANDARD 快照。
  • STORAGE_LOCATION:選用:如果是全域範圍的快照,請指定要儲存快照的 Cloud Storage 多區域或 Cloud Storage 區域。您只能指定一個儲存位置。

    只有在要覆寫快照設定中預先定義或自訂的預設儲存位置時,才需要使用 --storage-location 參數。

  • SNAPSHOT_SCOPE_REGION:選用:如果是區域範圍的快照,則為快照範圍所在的區域。如果加入這個參數,就無法使用 --storage-location 參數。STORAGE_LOCATION 會自動設為 SNAPSHOT_SCOPE_REGION。

從查核點

您可以使用降級磁碟的副本復原檢查點建立快照。只要不完整的副本可用,系統就會建立快照。

如要使用副本復原檢查點建立快照,請使用 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 Storage 多區域或 Cloud Storage 區域。您只能指定一個儲存位置。
    只有在您想覆寫快照設定中預先定義或自訂的預設儲存位置時,才需要使用這個選項。
  • SNAPSHOT_TYPE:快照類型,可以是 STANDARD 或 ARCHIVE。如未指定快照類型,系統會建立 STANDARD 快照。

您可以使用副本復原檢查點,僅在降級磁碟上建立快照。如果裝置已完全複製,而您嘗試從副本復原檢查點建立快照,系統會顯示下列錯誤訊息:

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

Google Cloud CLI 會等待作業傳回 READY、FAILED 狀態,或達到逾時上限,並傳回快照的最後已知詳細資料。

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 "cloud.google.com/go/compute/apiv1/computepb"
	"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"
      ],
    }
    
  • (預先發布版) 如要在允許的區域中建立區域範圍快照,請向 snapshots.insert 方法發出 POST 要求,並定義建立區域:

    POST https://compute.googleapis.com/compute/beta/projects/DESTINATION_PROJECT_ID/regions/SNAPSHOT_SCOPE_REGION/snapshots
    {
      "name": "SNAPSHOT_NAME",
      "sourceDisk": "projects/SOURCE_PROJECT_ID/regions/SOURCE_REGION/disks/SOURCE_DISK_NAME",
      "snapshotType": "SNAPSHOT_TYPE",
    }
    

更改下列內容:

  • DESTINATION_PROJECT_ID:要建立快照的專案 ID。
  • SNAPSHOT_NAME:快照名稱。
  • SOURCE_PROJECT_ID:來源磁碟專案的 ID。
  • SOURCE_REGION:來源磁碟的區域。
  • SOURCE_DISK_NAME:要建立快照的 區域性永久磁碟或 Hyperdisk Balanced High Availability 磁碟區名稱。
  • SNAPSHOT_TYPE:快照類型,可以是 STANDARD 或 ARCHIVE。如未指定快照類型,系統會建立 STANDARD 快照。
  • STORAGE_LOCATION:選用:如果是全域範圍的快照,請指定要儲存快照的 Cloud Storage 多區域或 Cloud Storage 區域。您只能指定一個儲存位置。

    只有在要覆寫快照設定中預先定義或自訂的預設儲存位置時,才需要使用 storageLocations 參數。

  • SNAPSHOT_SCOPE_REGION:選用:如果是區域範圍的快照,則為快照範圍所在的區域。如果加入這個參數,就無法使用 storageLocations 參數。STORAGE_LOCATION 會自動設為 SNAPSHOT_SCOPE_REGION。

從查核點

或者,您也可以使用降級磁碟的副本復原檢查點建立快照。只要不完整的副本可用,系統就會建立快照。

如要使用副本復原檢查點建立快照,請向 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 Storage 多區域或 Cloud Storage 區域。您只能指定一個儲存位置。
    只有在您想覆寫快照設定中預先定義或自訂的預設儲存位置時,才需要使用 storageLocations 參數。
  • SNAPSHOT_TYPE:快照類型,可以是 STANDARD 或 ARCHIVE。如未指定快照類型,系統會建立 STANDARD 快照。

您可以使用副本復原檢查點,僅在降級磁碟上建立快照。如果裝置已完全複製,而您嘗試從副本復原檢查點建立快照,系統會顯示下列錯誤訊息:

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

後續步驟