建立封存和標準磁碟快照


建立標準快照,定期備份下列磁碟類型的資料:

  • 區域性永久磁碟磁碟區
  • 區域性 Persistent Disk 磁碟區
  • Google Cloud Hyperdisk 磁碟區

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

事前準備

必要角色和權限

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

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

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

所需權限

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

  • 如要建立區域磁碟的快照,請按照下列步驟操作:
    • compute.snapshots.create 專案
    • 磁碟的 compute.disks.createSnapshot 權限
  • 如要使用磁碟上的資料建立地區磁碟快照,請按照下列步驟操作:
    • compute.snapshots.create 專案
    • 來源 VM 的 compute.instances.useReadOnly
    • 磁碟的 compute.disks.createSnapshot 權限
  • 如要從複本復原檢查點建立地區磁碟的快照,請按照下列步驟操作:
    • compute.snapshots.create 專案
    • 磁碟的 compute.disks.createSnapshot 權限
  • (預先發布) 如要建立區域範圍的快照,請按照下列步驟操作:
    • compute.snapshots.create 專案
    • compute.regionSnapshots.create 專案
    • 磁碟的 compute.disks.useReadOnly 權限

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

準備建立快照

如要準備建立 Persistent Disk 或 Hyperdisk 磁碟區的快照,請執行下列操作:

  • 請參閱「Compute Engine 磁碟快照的最佳做法」,為磁碟做好建立快照的準備。

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

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

  • 您無法為處於多寫入模式的 Hyperdisk 磁碟區建立快照。停用磁碟的多重寫入模式,然後建立快照。

建立永久磁碟磁碟區的快照

建立永久磁碟磁區快照的操作說明會因您建立的是區域性永久磁碟還是地區性永久磁碟而有所不同。

建立區域性永久磁碟磁碟區的快照

主控台

  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往「VM 執行個體」
    其餘步驟會自動顯示在 Google Cloud 控制台中。

  2. 選取含有 VM 執行個體的專案。
  3. 在「Name」(名稱) 欄中,按一下要備份磁碟的 VM 名稱。
  4. 「Storage」(儲存空間) 中執行下列操作:
    • 如要備份開機磁碟,請按一下「Boot disk」(開機磁碟) 區段中的開機磁碟「Name」(名稱)
    • 如要備份已連接的資料磁碟,請在「Additional disks」(其他磁碟) 中點選磁碟「Name」(名稱)
  5. 按一下「Create snapshot」(建立快照)
  6. 在「Name」(名稱) 中輸入不重複的名稱,以利區分快照用途,例如:
    • boot-disk-snapshot
    • attached-data-disk-snapshot
  7. 在「Type」(類型) 中,預設為標準快照。標準快照最適合用於長期備份和災難復原。

    選擇「Archive snapshot」(封存快照),即可建立比標準快照更具成本效益的備份,但資料復原時間會較長。

    詳情請參閱「快照類型比較」。

  8. 在「Location」(位置) 部分,選擇快照儲存位置。系統會自動選取快照設定中指定的預先定義或自訂預設位置。如要覆寫快照設定,將快照儲存在自訂儲存位置,請執行下列步驟:

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

    2. 在「Select location」(選取位置) 欄位,選擇要使用的特定區域或多區域。如要使用最接近來源磁碟的區域或多區域,請從「Based on disk's location」(以磁碟位置為準) 專區選擇位置。

  9. 如要建立快照,請按一下「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:您要用來建立快照的永久磁碟磁區名稱。
  • SNAPSHOT_TYPE:快照類型,可選 STANDARDARCHIVE。 如果未指定快照類型,系統會建立 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:您要用來建立快照的永久磁碟磁區名稱。
  • SNAPSHOT_TYPE:快照類型,可選 STANDARDARCHIVE。 如果未指定快照類型,系統會建立 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. 選取快照類型。預設值為 STANDARD 快照,這是長期備份和災難復原的最佳選項。

    選擇「Archive snapshot」(封存快照),即可以更低廉的成本保留資料。

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

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

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

      • 若選擇「Multi-regional」(多區域),費用較高但提供較高可用性。
      • 選擇「Regional snapshots」(區域快照),便能以較低的費用進一步控管資料的實際位置。
    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 平衡高可用性磁碟區名稱。
  • SNAPSHOT_TYPE:快照類型,可選 STANDARDARCHIVE。 如果未指定快照類型,系統會建立 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 快照。

您只能在降級磁碟上使用備用資源復原檢查點來建立快照。如果在裝置已完全複製時,嘗試從複本復原檢查點建立快照,您會看到下列錯誤訊息:

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 "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 平衡高可用性磁碟區名稱。
  • SNAPSHOT_TYPE:快照類型,可選 STANDARDARCHIVE。 如果未指定快照類型,系統會建立 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 快照。

您只能在降級磁碟上使用備用資源復原檢查點來建立快照。如果在裝置已完全複製時,嘗試從複本復原檢查點建立快照,您會看到下列錯誤訊息:

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

建立 Hyperdisk 的快照

主控台

  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往 VM 執行個體

  2. 選取含有 VM 執行個體的專案。

  3. 在「Name」欄中,按一下要備份 Hyperdisk 的 VM 名稱。

  4. 在「儲存空間」的「Additional disks」 中,按一下已連接的 Hyperdisk 的「Name」

  5. 按一下 [Create snapshot] (建立快照)。

  6. 在「Name」 中輸入不重複的名稱,以利區分快照用途,例如 hyperdisk-data-snapshot

  7. 在「Type」中,預設為定期快照,最適合長期備份和災難復原。

  8. 在「Location」(位置) 部分,選擇快照儲存位置

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

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

      • 若選擇「Multi-regional」(多區域),費用較高但提供較高可用性。
      • 選擇「Regional snapshots,便能以較低的費用進一步控管資料的實際位置。
    2. 在「Select location」(選取位置) 欄位,選擇要使用的特定區域或多區域。如要使用最接近來源磁碟的區域或多區域,請選取「Based on disk's location」(以磁碟位置為準)

  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
    
  • (預先發布版) 如要在允許的地區建立地區範圍的快照,請加入 --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:您要建立快照的 Hyperdisk 磁區名稱。
  • SNAPSHOT_TYPE:快照類型,可選 STANDARDARCHIVE。 如果未指定快照類型,系統會建立 STANDARD 快照。
  • STORAGE_LOCATION:選用:如果是全球範圍的快照,請提供您要儲存快照的 Cloud Storage 多地區Cloud Storage 地區。您只能指定一個儲存位置。

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

  • SNAPSHOT_SCOPE_REGION:選填:針對區域範圍的快照,指定快照的範圍。如果您加入這個參數,就無法使用 --storage-location 參數。STORAGE_LOCATION 會自動設為 SNAPSHOT_SCOPE_REGION

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"
        ],
    }
    
  • (預先發布版) 如要在允許的區域中建立區域範圍的快照,請對 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:您要建立快照的 Hyperdisk 磁區名稱。
  • SNAPSHOT_TYPE:快照類型,可選 STANDARDARCHIVE。 如果未指定快照類型,系統會建立 STANDARD 快照。
  • STORAGE_LOCATION:選用:如果是全球範圍的快照,請提供您要儲存快照的 Cloud Storage 多地區Cloud Storage 地區。您只能指定一個儲存位置。

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

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

後續步驟