建立封存和標準磁碟快照


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

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

事前準備

必要角色和權限

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

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

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

所需權限

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

  • 如要建立區域磁碟的快照,請按照下列步驟操作:
    • 專案的 compute.snapshots.create
    • compute.disks.createSnapshot 磁碟的權限
  • 如要使用磁碟上的資料建立地區磁碟的快照,請按照下列步驟操作:
    • 專案的 compute.snapshots.create
    • compute.instances.useReadOnly 來源 VM 上的
    • 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 會維持預先定義的預設儲存位置值,直到您首次更新快照設定為止。這個預先定義的位置是離來源磁碟最近的多區域。

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

建立 Persistent Disk 或 Hyperdisk 磁碟區的快照

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

建立區域磁碟的快照

主控台

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

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

    選擇「封存快照」,即可更有效率地保留資料。

  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-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:快照類型,可以是 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

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Compute Engine 快速入門」中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Compute Engine 快速入門」中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Compute Engine 快速入門」中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Compute Engine 快速入門」中的操作說明進行設定。詳情請參閱 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:快照類型,可以是 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 快照,這是長期備份和災難復原的最佳選擇。

    選擇「封存快照」,即可更有效率地保留資料。

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

Terraform 供應商不支援建立區域性磁碟的快照。 Google Cloud 如要追蹤這項限制,請參閱 GitHub 上的問題

Go

Go

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Compute Engine 快速入門」中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Compute Engine 快速入門」中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Compute Engine 快速入門」中的操作說明進行設定。詳情請參閱 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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Compute Engine 快速入門」中的操作說明進行設定。詳情請參閱 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:快照類型,可以是 STANDARDARCHIVE。如果未指定快照類型,系統會建立 STANDARD 快照。

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

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

後續步驟