從快照還原

如果您使用標準或封存快照備份磁碟,則可使用快照建立新磁碟,存取備份的資料。新磁碟可立即達到最高效能,不需要預熱。從快照建立新磁碟稱為還原快照。

您可以使用快照,透過下列方式備份及還原磁碟資料:

事前準備

  • 如果尚未設定驗證,請先完成設定。驗證程序會確認您的身分,以便授予 Google Cloud 服務和 API 的存取權。如要從本機開發環境執行程式碼或範例,請選取下列其中一個選項,向 Compute Engine 進行驗證:

    選取這個頁面上範例的預計用途分頁:

    控制台

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

    gcloud

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

      gcloud init

      如果您使用外部識別資訊提供者 (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 進行驗證」。

必要的角色

如要取得從快照還原所需的權限,請要求管理員授予您專案的 Compute 執行個體管理員 (v1) (roles/compute.instanceAdmin.v1) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

這個預先定義的角色具備從快照還原所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

您必須具備下列權限,才能從快照還原:

  • 如要從全域範圍快照 (預設) 建立磁碟,請按照下列步驟操作:
    • 專案的 compute.disks.create 權限
    • 執行個體的 compute.instances.attachDisk 權限
    • 要連結的磁碟上的 compute.disks.use
    • 專案的 compute.snapshots.useReadOnly、compute.snapshots.create 或 compute.disks.createSnapshot
  • 如要根據區域範圍快照建立磁碟,請按照下列步驟操作:
    • 專案的 compute.disks.create 權限
    • 執行個體的 compute.instances.attachDisk 權限
    • 要連結的磁碟上的 compute.disks.use
    • 專案的 compute.snapshots.useReadOnly 權限
  • 如要透過開機磁碟和非開機磁碟快照建立執行個體,您至少須具備下列權限:
    • 專案的 compute.instances.create 權限
    • 快照的 compute.snapshots.useReadOnly 權限
    • 專案的 compute.disks.create 權限
    • 磁碟的 compute.disks.use 權限
    • 執行個體的 compute.instances.attachDisk 權限

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

限制

  • 新磁碟的大小至少必須與快照的原始來源磁碟相同。如果您建立的磁碟大於快照的原始來源磁碟,則必須調整該磁碟上的檔案系統大小,才能納入額外的磁碟空間。視作業系統和檔案系統類型而定,您可能需要使用不同的檔案系統調整大小工具。詳情請參閱作業系統說明文件。

  • 您最多每十分鐘可從指定快照建立一次新的可用區或區域性磁碟。如要密集發出要求來建立磁碟快照,60 分鐘內最多可發出 6 項要求。從快照建立區域性磁碟時,則不受此限制。詳情請參閱「快照頻率限制」。

根據快照建立磁碟,並視需要附加至執行個體

如果您使用快照備份開機磁碟或非開機磁碟,可以根據快照建立新磁碟。

控制台

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

    前往「快照」

  2. 尋找您要還原的快照名稱。

  3. 前往「Disks」(磁碟) 頁面。

    前往「Disks」(磁碟) 頁面

  4. 點選「建立新磁碟」。

  5. 指定下列設定參數:

    • 磁碟名稱。
    • 磁碟類型。
    • 您也可以覆寫預設的區域和可用區選項。您可以選取任何區域和可用區,不論來源快照的儲存位置為何。
  6. 在 [Source type] (來源類型) 下方,按一下 [Snapshot] (快照)。

  7. 選取要還原的快照名稱。

  8. 選取新磁碟的大小 (以 GB 為單位)。這個數字必須等於或大於快照的原始來源磁碟。

  9. 按一下 [Create] (建立) 來建立磁碟。

視需要將非開機磁碟連接至執行個體。

gcloud

  1. 使用 gcloud compute snapshots list 指令找出要還原的快照名稱:

    gcloud compute snapshots list
    
  2. 使用 gcloud compute snapshots describe 指令,找出要還原的快照大小:

    gcloud compute snapshots describe SNAPSHOT_NAME
    

    將 SNAPSHOT_NAME 替換為要還原的快照名稱。

  3. 使用 gcloud compute disks create 指令,從快照建立新的區域或可用區磁碟。您可以加入 --type 旗標,指定要建立的磁碟類型。

    • 如要透過全域範圍的快照建立可用區磁碟,請按照下列步驟操作:
    gcloud compute disks create DISK_NAME \
        --zone=ZONE \
        --size=DISK_SIZE \
        --source-snapshot=SNAPSHOT_NAME \
        --type=DISK_TYPE
    
    • (預先發布版) 如要從區域範圍快照建立可用區磁碟,請按照下列步驟操作:
    gcloud beta compute disks create DISK_NAME \
        --zone=ZONE \
        --source-snapshot=SNAPSHOT_NAME \
        --source-snapshot-region=SOURCE_REGION \
        --type=DISK_TYPE
    
    • 如要透過全域範圍快照建立區域性磁碟,請按照下列步驟操作:
    gcloud beta compute disks create DISK_NAME \
        --size=DISK_SIZE \
        --source-snapshot=SNAPSHOT_NAME \
        --type=DISK_TYPE \
        --region=REGION \
        --replica-zones=ZONE1,ZONE2
    
    • (預覽版) 如要從區域範圍快照建立區域磁碟,請按照下列步驟操作:
    gcloud beta compute disks create DISK_NAME \
        --size=DISK_SIZE \
        --source-snapshot=SNAPSHOT_NAME \
        --source-snapshot-region=SOURCE_REGION \
        --type=DISK_TYPE \
        --region=REGION \
        --replica-zones=ZONE1,ZONE2
    

    更改下列內容:

    • DISK_NAME:新磁碟的名稱
    • DISK_SIZE:新磁碟的大小,以 gibibytes (GiB) 為單位。 這個數字必須等於或大於快照的原始來源磁碟。
    • SNAPSHOT_NAME:要還原的快照名稱
    • DISK_TYPE:磁碟的類型,例如、pd-ssd、 、hyperdisk-throughput 或 hyperdisk-balanced-high-availability
    • REGION:區域磁碟所在的區域,例如:europe-west1
    • SOURCE_REGION:來源快照的範圍所屬區域
    • ZONE:新磁碟所在的可用區
    • ZONE1,ZONE2:兩個磁碟副本所在的區域內,例如:europe-west1-b 和 europe-west1-c
  4. 選用:使用 gcloud compute instances attach-disk 指令將新磁碟連接至現有執行個體:

    gcloud compute instances attach-disk INSTANCE_NAME \
        --disk DISK_NAME
    

    更改下列內容:

    • INSTANCE_NAME:執行個體的名稱
    • DISK_NAME:從快照建立的磁碟名稱

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"
)

// createDiskFromSnapshot creates a new disk in a project in given zone.
func createDiskFromSnapshot(
	w io.Writer,
	projectID, zone, diskName, diskType, snapshotLink string,
	diskSizeGb int64,
) error {
	// projectID := "your_project_id"
	// zone := "us-west3-b" // should match diskType below
	// diskName := "your_disk_name"
	// diskType := "zones/us-west3-b/diskTypes/pd-ssd"
	// snapshotLink := "projects/your_project_id/global/snapshots/snapshot_name"
	// diskSizeGb := 120

	ctx := context.Background()
	disksClient, err := compute.NewDisksRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewDisksRESTClient: %w", err)
	}
	defer disksClient.Close()

	req := &computepb.InsertDiskRequest{
		Project: projectID,
		Zone:    zone,
		DiskResource: &computepb.Disk{
			Name:           proto.String(diskName),
			Zone:           proto.String(zone),
			Type:           proto.String(diskType),
			SourceSnapshot: proto.String(snapshotLink),
			SizeGb:         proto.Int64(diskSizeGb),
		},
	}

	op, err := disksClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create disk: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Disk 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.InsertDiskRequest;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateDiskFromSnapshot {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.

    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the zone in which you want to create the disk.
    String zone = "europe-central2-b";

    // Name of the disk you want to create.
    String diskName = "YOUR_DISK_NAME";

    // The type of disk you want to create. This value uses the following format:
    // "zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
    // For example: "zones/us-west3-b/diskTypes/pd-ssd"
    String diskType = String.format("zones/%s/diskTypes/pd-ssd", zone);

    // Size of the new disk in gigabytes.
    long diskSizeGb = 10;

    // The full path and name of the snapshot that you want to use as the source for the new disk.
    // This value uses the following format:
    // "projects/{projectName}/global/snapshots/{snapshotName}"
    String snapshotLink = String.format("projects/%s/global/snapshots/%s", projectId,
        "SNAPSHOT_NAME");

    createDiskFromSnapshot(projectId, zone, diskName, diskType, diskSizeGb, snapshotLink);
  }

  // Creates a new disk in a project in given zone, using a snapshot.
  public static void createDiskFromSnapshot(String projectId, String zone, String diskName,
      String diskType, long diskSizeGb, String snapshotLink)
      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 `disksClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (DisksClient disksClient = DisksClient.create()) {

      // Set the disk properties and the source snapshot.
      Disk disk = Disk.newBuilder()
          .setName(diskName)
          .setZone(zone)
          .setSizeGb(diskSizeGb)
          .setType(diskType)
          .setSourceSnapshot(snapshotLink)
          .build();

      // Create the insert disk request.
      InsertDiskRequest insertDiskRequest = InsertDiskRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setDiskResource(disk)
          .build();

      // Wait for the create disk operation to complete.
      Operation response = disksClient.insertAsync(insertDiskRequest)
          .get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        System.out.println("Disk creation failed!" + response);
        return;
      }
      System.out.println("Disk created. Operation Status: " + response.getStatus());
    }
  }
}

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 zone = 'europe-central2-b';
// const diskName = 'YOUR_DISK_NAME';
// const diskType = 'zones/us-west3-b/diskTypes/pd-ssd';
// const diskSizeGb = 10;
// const snapshotLink = 'projects/project_name/global/snapshots/snapshot_name';

const compute = require('@google-cloud/compute');

async function createDiskFromSnapshot() {
  const disksClient = new compute.DisksClient();

  const [response] = await disksClient.insert({
    project: projectId,
    zone,
    diskResource: {
      sizeGb: diskSizeGb,
      name: diskName,
      zone,
      type: diskType,
      sourceSnapshot: snapshotLink,
    },
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

  // Wait for the create disk operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log('Disk created.');
}

createDiskFromSnapshot();

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_disk_from_snapshot(
    project_id: str,
    zone: str,
    disk_name: str,
    disk_type: str,
    disk_size_gb: int,
    snapshot_link: str,
) -> compute_v1.Disk:
    """
    Creates a new disk in a project in given zone.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone in which you want to create the disk.
        disk_name: name of the disk you want to create.
        disk_type: the type of disk you want to create. This value uses the following format:
            "zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
            For example: "zones/us-west3-b/diskTypes/pd-ssd"
        disk_size_gb: size of the new disk in gigabytes
        snapshot_link: a link to the snapshot you want to use as a source for the new disk.
            This value uses the following format: "projects/{project_name}/global/snapshots/{snapshot_name}"

    Returns:
        An unattached Disk instance.
    """
    disk_client = compute_v1.DisksClient()
    disk = compute_v1.Disk()
    disk.zone = zone
    disk.size_gb = disk_size_gb
    disk.source_snapshot = snapshot_link
    disk.type_ = disk_type
    disk.name = disk_name
    operation = disk_client.insert(project=project_id, zone=zone, disk_resource=disk)

    wait_for_extended_operation(operation, "disk creation")

    return disk_client.get(project=project_id, zone=zone, disk=disk_name)

REST

  1. 建構對 snapshots.list 的 GET 要求,以顯示專案中的快照清單。

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

    將 PROJECT_ID 替換為專案 ID。

  2. 建構 POST 要求,使用對應的 disks.insert 方法建立可用區磁碟或區域磁碟:

    加入 name、sizeGb 和 type 屬性。如要使用快照還原磁碟,請務必加入 sourceSnapshot 屬性。

    • 如要從全域範圍快照建立可用區磁碟,請按照下列步驟操作:
    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/disks
    {
      "name": "DISK_NAME",
      "sourceSnapshot": "SNAPSHOT_NAME",
      "sizeGb": "DISK_SIZE",
      "type": "zones/ZONE/diskTypes/DISK_TYPE"
    }
    
    • (預覽) 如要從區域範圍快照建立區域磁碟,請按照下列步驟操作:
    POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/disks
    {
      "name": "DISK_NAME",
      "sourceSnapshot": "projects/PROJECT_ID/regions/SOURCE_REGION/snapshots/SNAPSHOT_NAME",
      "sizeGb": "DISK_SIZE",
      "type": "projects/PROJECT_ID/zones/ZONE/diskTypes/DISK_TYPE",
      "zone": "projects/PROJECT_ID/zones/ZONE"
    }
    
    • 如要透過全域範圍快照建立區域性磁碟,請按照下列步驟操作:
    POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/regions/REGION/disks
    {
      "name": "DISK_NAME",
      "sourceSnapshot": "SNAPSHOT_NAME",
      "region": "projects/PROJECT_ID/regions/REGION",
      "replicaZones": [
         "projects/PROJECT_ID/zones/ZONE1",
         "projects/PROJECT_ID/zones/ZONE2"
      ],
      "sizeGb": "DISK_SIZE",
      "type": "zones/ZONE/diskTypes/DISK_TYPE"
    }
    
    • (預先發布版) 如要從區域範圍快照建立區域磁碟,請按照下列指示操作:
    POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/regions/REGION/disks
    {
      "name": "DISK_NAME",
      "sourceSnapshot": "projects/PROJECT_ID/regions/SOURCE_REGION/snapshots/SNAPSHOT_NAME",
      "replicaZones": [
         "projects/PROJECT_ID/zones/ZONE1",
         "projects/PROJECT_ID/zones/ZONE2"
      ],
      "sizeGb": "DISK_SIZE",
      "type": "projects/PROJECT_ID/regions/REGION/diskTypes/DISK_TYPE"
    }
    

    更改下列內容:

    • PROJECT_ID:專案 ID
    • ZONE:執行個體和新磁碟所在的可用區
    • DISK_NAME:新磁碟的名稱
    • SNAPSHOT_NAME:要還原的磁碟來源快照
    • REGION:區域磁碟所在的區域,例如:europe-west1
    • SOURCE_REGION:來源快照的範圍區域
    • ZONE1、ZONE2:新磁碟副本所在的可用區
    • DISK_SIZE:新磁碟的大小,以 gibibytes (GiB) 為單位。 這個數字必須等於或大於快照的原始來源磁碟。
    • DISK_TYPE:磁碟類型的完整或部分網址,例如、PROJECT_ID/zones/ZONE/diskTypes/pd-ssd、、PROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced 或 PROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced-high-availability
  3. 選用。將新磁碟連接至現有執行個體。

    建構對 instances.attachDisk 方法的 POST 要求,並加入您剛從快照建立的磁碟網址。

    可用區磁碟:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/attachDisk
    {
      "source": "/compute/v1/projects/PROJECT_ID/zones/ZONE/disks/DISK_NAME"
    }
    

    如果是區域性磁碟:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/attachDisk
    {
      "source": "/compute/v1/projects/PROJECT_ID/regions/REGION/disks/DISK_NAME"
    }
    

    更改下列內容:

    • PROJECT_ID:專案 ID
    • ZONE:執行個體和新磁碟所在的可用區
    • REGION:區域磁碟所在的區域。必須與運算執行個體位於相同區域。
    • INSTANCE_NAME:要新增磁碟的執行個體名稱
    • DISK_NAME:新磁碟的名稱

建立新磁碟並附加至執行個體後,您必須掛接磁碟,作業系統才能使用可用儲存空間。

從現有磁碟建立執行個體

您可以從快照建立開機磁碟和資料磁碟,然後將這些磁碟連結至新的運算執行個體。

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"
)

// createWithExistingDisks create a new VM instance using selected disks.
// The first disk in diskNames will be used as boot disk.
func createWithExistingDisks(
	w io.Writer,
	projectID, zone, instanceName string,
	diskNames []string,
) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// diskNames := []string{"boot_disk", "disk1", "disk2"}

	ctx := context.Background()
	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

	disksClient, err := compute.NewDisksRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewDisksRESTClient: %w", err)
	}
	defer disksClient.Close()

	disks := [](*computepb.Disk){}

	for _, diskName := range diskNames {
		reqDisk := &computepb.GetDiskRequest{
			Project: projectID,
			Zone:    zone,
			Disk:    diskName,
		}

		disk, err := disksClient.Get(ctx, reqDisk)
		if err != nil {
			return fmt.Errorf("unable to get disk: %w", err)
		}

		disks = append(disks, disk)
	}

	attachedDisks := [](*computepb.AttachedDisk){}

	for _, disk := range disks {
		attachedDisk := &computepb.AttachedDisk{
			Source: proto.String(disk.GetSelfLink()),
		}
		attachedDisks = append(attachedDisks, attachedDisk)
	}

	attachedDisks[0].Boot = proto.Bool(true)

	instanceResource := &computepb.Instance{
		Name:        proto.String(instanceName),
		Disks:       attachedDisks,
		MachineType: proto.String(fmt.Sprintf("zones/%s/machineTypes/n1-standard-1", zone)),
		NetworkInterfaces: []*computepb.NetworkInterface{
			{
				Name: proto.String("global/networks/default"),
			},
		},
	}

	req := &computepb.InsertInstanceRequest{
		Project:          projectID,
		Zone:             zone,
		InstanceResource: instanceResource,
	}

	op, err := instancesClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create instance: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Instance created\n")

	return nil
}

Java

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 Compute Engine 快速入門導覽課程」中的 Java 設定操作說明進行操作。詳情請參閱 Compute Engine Java API 參考文件。

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。


import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.InsertInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateInstanceWithExistingDisks {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.

    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the zone to create the instance in. For example: "us-west3-b"
    String zone = "europe-central2-b";

    // Name of the new virtual machine (VM) instance.
    String instanceName = "YOUR_INSTANCE_NAME";

    // Array of disk names to be attached to the new virtual machine.
    // First disk in this list will be used as the boot disk.
    List<String> diskNames = List.of("your-boot-disk", "another-disk1", "another-disk2");

    createInstanceWithExistingDisks(projectId, zone, instanceName, diskNames);
  }

  // Create a new VM instance using the selected disks.
  // The first disk in diskNames will be used as the boot disk.
  public static void createInstanceWithExistingDisks(String projectId, String zone,
      String instanceName, List<String> diskNames)
      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 `instancesClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (InstancesClient instancesClient = InstancesClient.create();
        DisksClient disksClient = DisksClient.create()) {

      if (diskNames.size() == 0) {
        throw new Error("At least one disk should be provided");
      }

      // Create the list of attached disks to be used in instance creation.
      List<AttachedDisk> attachedDisks = new ArrayList<>();
      for (int i = 0; i < diskNames.size(); i++) {
        String diskName = diskNames.get(i);
        Disk disk = disksClient.get(projectId, zone, diskName);
        AttachedDisk attDisk = null;

        if (i == 0) {
          // Make the first disk in the list as the boot disk.
          attDisk = AttachedDisk.newBuilder()
              .setSource(disk.getSelfLink())
              .setBoot(true)
              .build();
        } else {
          attDisk = AttachedDisk.newBuilder()
              .setSource(disk.getSelfLink())
              .build();
        }
        attachedDisks.add(attDisk);
      }

      // Create the instance.
      Instance instance = Instance.newBuilder()
          .setName(instanceName)
          // Add the attached disks to the instance.
          .addAllDisks(attachedDisks)
          .setMachineType(String.format("zones/%s/machineTypes/n1-standard-1", zone))
          .addNetworkInterfaces(
              NetworkInterface.newBuilder().setName("global/networks/default").build())
          .build();

      // Create the insert instance request.
      InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setInstanceResource(instance)
          .build();

      // Wait for the create operation to complete.
      Operation response = instancesClient.insertAsync(insertInstanceRequest)
          .get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        System.out.println("Instance creation failed!" + response);
        return;
      }
      System.out.println("Operation Status: " + response.getStatus());

    }
  }
}

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 zone = 'europe-central2-b';
// const instanceName = 'YOUR_INSTANCE_NAME';
// const diskNames = ['boot_disk', 'disk1', 'disk2'];

const compute = require('@google-cloud/compute');

async function createWithExistingDisks() {
  const instancesClient = new compute.InstancesClient();
  const disksClient = new compute.DisksClient();

  if (diskNames.length < 1) {
    throw new Error('At least one disk should be provided');
  }

  const disks = [];
  for (const diskName of diskNames) {
    const [disk] = await disksClient.get({
      project: projectId,
      zone,
      disk: diskName,
    });
    disks.push(disk);
  }

  const attachedDisks = [];

  for (const disk of disks) {
    attachedDisks.push({
      source: disk.selfLink,
    });
  }

  attachedDisks[0].boot = true;

  const [response] = await instancesClient.insert({
    project: projectId,
    zone,
    instanceResource: {
      name: instanceName,
      disks: attachedDisks,
      machineType: `zones/${zone}/machineTypes/n1-standard-1`,
      networkInterfaces: [
        {
          name: 'global/networks/default',
        },
      ],
    },
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

  // Wait for the create operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log('Instance created.');
}

createWithExistingDisks();

Python

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Compute Engine 快速入門導覽課程」中的 Python 設定說明操作。詳情請參閱「Compute Engine Python API 參考文件」。

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

from __future__ import annotations

import re
import sys
from typing import Any
import warnings

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def get_disk(project_id: str, zone: str, disk_name: str) -> compute_v1.Disk:
    """
    Gets a disk from a project.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone where the disk exists.
        disk_name: name of the disk you want to retrieve.
    """
    disk_client = compute_v1.DisksClient()
    return disk_client.get(project=project_id, zone=zone, disk=disk_name)


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_instance(
    project_id: str,
    zone: str,
    instance_name: str,
    disks: list[compute_v1.AttachedDisk],
    machine_type: str = "n1-standard-1",
    network_link: str = "global/networks/default",
    subnetwork_link: str = None,
    internal_ip: str = None,
    external_access: bool = False,
    external_ipv4: str = None,
    accelerators: list[compute_v1.AcceleratorConfig] = None,
    preemptible: bool = False,
    spot: bool = False,
    instance_termination_action: str = "STOP",
    custom_hostname: str = None,
    delete_protection: bool = False,
) -> compute_v1.Instance:
    """
    Send an instance creation request to the Compute Engine API and wait for it to complete.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone to create the instance in. For example: "us-west3-b"
        instance_name: name of the new virtual machine (VM) instance.
        disks: a list of compute_v1.AttachedDisk objects describing the disks
            you want to attach to your new instance.
        machine_type: machine type of the VM being created. This value uses the
            following format: "zones/{zone}/machineTypes/{type_name}".
            For example: "zones/europe-west3-c/machineTypes/f1-micro"
        network_link: name of the network you want the new instance to use.
            For example: "global/networks/default" represents the network
            named "default", which is created automatically for each project.
        subnetwork_link: name of the subnetwork you want the new instance to use.
            This value uses the following format:
            "regions/{region}/subnetworks/{subnetwork_name}"
        internal_ip: internal IP address you want to assign to the new instance.
            By default, a free address from the pool of available internal IP addresses of
            used subnet will be used.
        external_access: boolean flag indicating if the instance should have an external IPv4
            address assigned.
        external_ipv4: external IPv4 address to be assigned to this instance. If you specify
            an external IP address, it must live in the same region as the zone of the instance.
            This setting requires `external_access` to be set to True to work.
        accelerators: a list of AcceleratorConfig objects describing the accelerators that will
            be attached to the new instance.
        preemptible: boolean value indicating if the new instance should be preemptible
            or not. Preemptible VMs have been deprecated and you should now use Spot VMs.
        spot: boolean value indicating if the new instance should be a Spot VM or not.
        instance_termination_action: What action should be taken once a Spot VM is terminated.
            Possible values: "STOP", "DELETE"
        custom_hostname: Custom hostname of the new VM instance.
            Custom hostnames must conform to RFC 1035 requirements for valid hostnames.
        delete_protection: boolean value indicating if the new virtual machine should be
            protected against deletion or not.
    Returns:
        Instance object.
    """
    instance_client = compute_v1.InstancesClient()

    # Use the network interface provided in the network_link argument.
    network_interface = compute_v1.NetworkInterface()
    network_interface.network = network_link
    if subnetwork_link:
        network_interface.subnetwork = subnetwork_link

    if internal_ip:
        network_interface.network_i_p = internal_ip

    if external_access:
        access = compute_v1.AccessConfig()
        access.type_ = compute_v1.AccessConfig.Type.ONE_TO_ONE_NAT.name
        access.name = "External NAT"
        access.network_tier = access.NetworkTier.PREMIUM.name
        if external_ipv4:
            access.nat_i_p = external_ipv4
        network_interface.access_configs = [access]

    # Collect information into the Instance object.
    instance = compute_v1.Instance()
    instance.network_interfaces = [network_interface]
    instance.name = instance_name
    instance.disks = disks
    if re.match(r"^zones/[a-z\d\-]+/machineTypes/[a-z\d\-]+$", machine_type):
        instance.machine_type = machine_type
    else:
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"

    instance.scheduling = compute_v1.Scheduling()
    if accelerators:
        instance.guest_accelerators = accelerators
        instance.scheduling.on_host_maintenance = (
            compute_v1.Scheduling.OnHostMaintenance.TERMINATE.name
        )

    if preemptible:
        # Set the preemptible setting
        warnings.warn(
            "Preemptible VMs are being replaced by Spot VMs.", DeprecationWarning
        )
        instance.scheduling = compute_v1.Scheduling()
        instance.scheduling.preemptible = True

    if spot:
        # Set the Spot VM setting
        instance.scheduling.provisioning_model = (
            compute_v1.Scheduling.ProvisioningModel.SPOT.name
        )
        instance.scheduling.instance_termination_action = instance_termination_action

    if custom_hostname is not None:
        # Set the custom hostname for the instance
        instance.hostname = custom_hostname

    if delete_protection:
        # Set the delete protection bit
        instance.deletion_protection = True

    # Prepare the request to insert an instance.
    request = compute_v1.InsertInstanceRequest()
    request.zone = zone
    request.project = project_id
    request.instance_resource = instance

    # Wait for the create operation to complete.
    print(f"Creating the {instance_name} instance in {zone}...")

    operation = instance_client.insert(request=request)

    wait_for_extended_operation(operation, "instance creation")

    print(f"Instance {instance_name} created.")
    return instance_client.get(project=project_id, zone=zone, instance=instance_name)


def create_with_existing_disks(
    project_id: str, zone: str, instance_name: str, disk_names: list[str]
) -> compute_v1.Instance:
    """
    Create a new VM instance using selected disks. The first disk in disk_names will
    be used as boot disk.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone to create the instance in. For example: "us-west3-b"
        instance_name: name of the new virtual machine (VM) instance.
        disk_names: list of disk names to be attached to the new virtual machine.
            First disk in this list will be used as the boot device.

    Returns:
        Instance object.
    """
    assert len(disk_names) >= 1
    disks = [get_disk(project_id, zone, disk_name) for disk_name in disk_names]
    attached_disks = []
    for disk in disks:
        adisk = compute_v1.AttachedDisk()
        adisk.source = disk.self_link
        attached_disks.append(adisk)
    attached_disks[0].boot = True
    instance = create_instance(project_id, zone, instance_name, attached_disks)
    return instance

從開機磁碟快照建立執行個體

如果您已建立運算執行個體開機磁碟的快照,可以使用該快照建立新的執行個體。

如要使用相同的開機磁碟快速建立多個執行個體,請建立自訂映像檔,然後從該映像檔建立執行個體,而非使用快照。

如要使用從快照建立的區域開機磁碟建立運算執行個體,請使用 Google Cloud CLI 或 REST。

控制台

  1. 前往 Google Cloud 控制台的「建立執行個體」頁面。

    前往「建立執行個體」

    如果出現提示,請選取專案,然後按一下「繼續」。「建立執行個體」頁面隨即顯示,並顯示「機器設定」窗格。

  2. 在「機器設定」窗格中,執行下列操作:

    1. 在「Name」(名稱) 欄位中,指定執行個體的名稱。詳情請參閱「資源命名慣例」。
    2. 選用:在「Zone」(可用區) 欄位中,選取這個執行個體的可用區。

      預設選取項目為「不限」。如果沒有變更這項預設選取項目,Google 會根據機型和可用性,自動為您選擇可用區。

    3. 選取執行個體的機器家族。 Google Cloud 控制台隨即會顯示所選機器家族可用的機器系列。可用的機器系列選項如下:

      • 一般用途
      • 運算最佳化
      • 記憶體最佳化
      • 儲存空間最佳化
      • 網路最佳化
      • GPU
      • TPU

    4. 在「Series」(系列) 欄中,選取執行個體的機器系列。

      如果您在上一個步驟中選取 GPU 做為機器家族,請選取所需的 GPU 類型。系統會根據所選 GPU 類型,自動選取機器系列。

    5. 在「Machine type」(機型) 部分,選取執行個體的機型。

  3. 從導覽選單點選「OS and storage」(OS 和儲存空間)。在隨即顯示的「作業系統和儲存空間」窗格中,完成下列步驟來設定開機磁碟:

    1. 點選「變更」。系統會顯示「開機磁碟」窗格和「公開映像檔」分頁。
    2. 按一下「快照」。系統隨即會顯示「快照」分頁。
    3. 在「Snapshot」(快照) 清單中,選取要使用的快照。
    4. 在「Boot disk type」(開機磁碟類型) 清單中,選取開機磁碟類型。
    5. 在「Size (GB)」(大小 (GB)) 欄位中,指定開機磁碟大小。
    6. 選用:如要查看進階設定選項,請展開「Show advanced configurations」(顯示進階設定) 部分。
    7. 如要確認開機磁碟選項並返回「Operating system and storage」(作業系統和儲存空間) 窗格,請按一下「Select」(選取)。
  4. 點選導覽選單中的「Networking」(網路)。在隨即顯示的「Networking」(網路) 窗格中,執行下列操作:

    1. 前往「防火牆」部分。
    2. 如要允許 HTTP 或 HTTPS 流量傳送至執行個體,請選取「Allow HTTP traffic」(允許 HTTP 流量) 或「Allow HTTPS traffic」(允許 HTTPS 流量)。

    Google Cloud 控制台會將網路標記新增至執行個體,並建立對應的輸入防火牆規則,允許所有傳入的 tcp:80 (HTTP) 或 tcp:443 (HTTPS) 流量。網路標記會建立防火牆規則與執行個體之間的關聯。詳情請參閱虛擬私有雲說明文件中的「防火牆規則總覽」。

  5. 視需要指定其他設定選項。詳情請參閱「建立執行個體時的設定選項」。

  6. 如要建立並啟動執行個體,請按一下「建立」。

gcloud

可用區開機磁碟

使用 gcloud compute instances create 指令,並加入 --source-snapshot 旗標。

   gcloud compute instances create INSTANCE_NAME  
--source-snapshot=BOOT_SNAPSHOT_NAME
--boot-disk-size=BOOT_DISK_SIZE
--boot-disk-type=BOOT_DISK_TYPE
--boot-disk-device-name=BOOT_DISK_NAME

更改下列內容:

  • INSTANCE_NAME:新執行個體的名稱
  • BOOT_SNAPSHOT_NAME:要還原至新執行個體開機磁碟的開機磁碟快照名稱
  • BOOT_DISK_SIZE:選用:新開機磁碟的大小 (以 GiB 為單位)

    大小必須等於或大於建立快照的來源磁碟。

  • BOOT_DISK_TYPE:選用:開機磁碟的類型,例如 PROJECT_ID/zones/ZONE/diskTypes/pd-ssd 或 PROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced

  • BOOT_DISK_NAME:這個執行個體的新開機磁碟名稱

區域性開機磁碟

使用 gcloud compute instances create 指令,並加入 --create-disk 旗標以及 source-snapshot、replica-zones 和 boot 屬性。

  gcloud compute instances create INSTANCE_NAME 
--zone=ZONE
--create-disk=^:^name=DISK_NAME:source-snapshot=BOOT_SNAPSHOT_NAME:boot=true:type=BOOT_DISK_TYPE:replica-zones=ZONE,REMOTE_ZONE

字元 ^:^ 指定冒號 : 做為每個磁碟屬性之間的分隔符。這是必要步驟,這樣您才能在指定 replica-zones 的區域時使用半形逗號 ,。

更改下列內容:

  • INSTANCE_NAME:新執行個體的名稱
  • ZONE:要在哪個可用區建立執行個體
  • DISK_NAME:選用:磁碟名稱
  • BOOT_SNAPSHOT_NAME:要還原至新執行個體開機磁碟的開機磁碟快照名稱。
  • BOOT_DISK_TYPE:選用:開機磁碟的類型,例如 pd-ssd 或 hyperdisk-balanced-high-availability
  • REMOTE_ZONE:開機磁碟複製到的區域。replica-zones 屬性需要兩個以半形逗號分隔的可用區,其中一個可用區必須與執行個體的可用區相同。

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"
)

// createInstanceFromSnapshot creates a new VM instance with boot disk created from a snapshot.
func createInstanceFromSnapshot(w io.Writer, projectID, zone, instanceName, snapshotLink string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// snapshotLink := "projects/project_name/global/snapshots/snapshot_name"

	ctx := context.Background()
	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

	req := &computepb.InsertInstanceRequest{
		Project: projectID,
		Zone:    zone,
		InstanceResource: &computepb.Instance{
			Name: proto.String(instanceName),
			Disks: []*computepb.AttachedDisk{
				{
					InitializeParams: &computepb.AttachedDiskInitializeParams{
						DiskSizeGb:     proto.Int64(11),
						SourceSnapshot: proto.String(snapshotLink),
						DiskType:       proto.String(fmt.Sprintf("zones/%s/diskTypes/pd-standard", zone)),
					},
					AutoDelete: proto.Bool(true),
					Boot:       proto.Bool(true),
					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
				},
			},
			MachineType: proto.String(fmt.Sprintf("zones/%s/machineTypes/n1-standard-1", zone)),
			NetworkInterfaces: []*computepb.NetworkInterface{
				{
					Name: proto.String("global/networks/default"),
				},
			},
		},
	}

	op, err := instancesClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create instance: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Instance created\n")

	return nil
}

Java

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 Compute Engine 快速入門導覽課程」中的 Java 設定說明操作。詳情請參閱「Compute Engine Java API 參考文件」。

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDisk.Type;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.Image;
import com.google.cloud.compute.v1.ImagesClient;
import com.google.cloud.compute.v1.InsertInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateInstancesAdvanced {

  /**
   * @param diskType the type of disk you want to create. This value uses the following format:
   * "zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)". For example:
   * "zones/us-west3-b/diskTypes/pd-ssd"
   * @param diskSizeGb size of the new disk in gigabytes
   * @param boot boolean flag indicating whether this disk should be used as a boot disk of an
   * instance
   * @param diskSnapshot disk snapshot to use when creating this disk. You must have read access to
   * this disk. This value uses the following format:
   * "projects/{project_name}/global/snapshots/{snapshot_name}"
   * @return AttachedDisk object configured to be created using the specified snapshot.
   */
  private static AttachedDisk diskFromSnapshot(String diskType, int diskSizeGb, boolean boot,
      String diskSnapshot) {
    AttachedDisk disk =
        AttachedDisk.newBuilder()
            .setBoot(boot)
            // Remember to set auto_delete to True if you want the disk to be deleted when
            // you delete your VM instance.
            .setAutoDelete(true)
            .setType(Type.PERSISTENT.toString())
            .setInitializeParams(
                AttachedDiskInitializeParams.newBuilder()
                    .setSourceSnapshot(diskSnapshot)
                    .setDiskSizeGb(diskSizeGb)
                    .setDiskType(diskType)
                    .build())
            .build();
    return disk;
  }


  /**
   * Send an instance creation request to the Compute Engine API and wait for it to complete.
   *
   * @param project project ID or project number of the Cloud project you want to use.
   * @param zone name of the zone to create the instance in. For example: "us-west3-b"
   * @param instanceName name of the new virtual machine (VM) instance.
   * @param disks a list of compute_v1.AttachedDisk objects describing the disks you want to attach
   * to your new instance.
   * @param machineType machine type of the VM being created. This value uses the following format:
   * "zones/{zone}/machineTypes/{type_name}".
   * For example: "zones/europe-west3-c/machineTypes/f1-micro"
   * @param network name of the network you want the new instance to use. For example:
   * "global/networks/default" represents the network named "default", which is created
   * automatically for each project.
   * @param subnetwork name of the subnetwork you want the new instance to use. This value uses the
   * following format: "regions/{region}/subnetworks/{subnetwork_name}"
   * @return Instance object.
   */
  private static Instance createWithDisks(String project, String zone, String instanceName,
      Vector<AttachedDisk> disks, String machineType, String network, String subnetwork)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (InstancesClient instancesClient = InstancesClient.create()) {
      // Use the network interface provided in the networkName argument.
      NetworkInterface networkInterface;
      if (subnetwork != null) {
        networkInterface = NetworkInterface.newBuilder()
            .setName(network).setSubnetwork(subnetwork)
            .build();
      } else {
        networkInterface = NetworkInterface.newBuilder()
            .setName(network).build();
      }

      machineType = String.format("zones/%s/machineTypes/%s", zone, machineType);

      // Bind `instanceName`, `machineType`, `disk`, and `networkInterface` to an instance.
      Instance instanceResource =
          Instance.newBuilder()
              .setName(instanceName)
              .setMachineType(machineType)
              .addAllDisks(disks)
              .addNetworkInterfaces(networkInterface)
              .build();

      System.out.printf("Creating instance: %s at %s ", instanceName, zone);

      // Insert the instance in the specified project and zone.
      InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
          .setProject(project)
          .setZone(zone)
          .setInstanceResource(instanceResource).build();

      OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
          insertInstanceRequest);

      // Wait for the operation to complete.
      Operation response = operation.get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        System.out.println("Instance creation failed ! ! " + response);
        return null;
      }
      System.out.println("Operation Status: " + response.getStatus());

      return instancesClient.get(project, zone, instanceName);
    }
  }

  /**
   * Create a new VM instance with boot disk created from a snapshot.
   *
   * @param project project ID or project number of the Cloud project you want to use.
   * @param zone name of the zone to create the instance in. For example: "us-west3-b"
   * @param instanceName name of the new virtual machine (VM) instance.
   * @param snapshotName link to the snapshot you want to use as the source of your boot disk in the
   * form of: "projects/{project_name}/global/snapshots/{snapshot_name}"
   * @return Instance object.
   */
  public static Instance createFromSnapshot(String project, String zone, String instanceName,
      String snapshotName)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    String diskType = String.format("zones/%s/diskTypes/pd-standard", zone);
    Vector<AttachedDisk> disks = new Vector<>();
    disks.add(diskFromSnapshot(diskType, 11, true, snapshotName));
    return createWithDisks(project, zone, instanceName, disks, "n1-standard-1",
        "global/networks/default", null);
  }

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 zone = 'europe-central2-b';
// const instanceName = 'YOUR_INSTANCE_NAME';
// const snapshotLink = 'projects/YOUR_PROJECT/global/snapshots/YOUR_SNAPSHOT_NAME';

const compute = require('@google-cloud/compute');

// Creates a new VM instance with boot disk created from a snapshot.
async function createInstanceFromSnapshot() {
  const instancesClient = new compute.InstancesClient();

  const [response] = await instancesClient.insert({
    project: projectId,
    zone,
    instanceResource: {
      name: instanceName,
      disks: [
        {
          initializeParams: {
            diskSizeGb: '11',
            sourceSnapshot: snapshotLink,
            diskType: `zones/${zone}/diskTypes/pd-standard`,
          },
          autoDelete: true,
          boot: true,
          type: 'PERSISTENT',
        },
      ],
      machineType: `zones/${zone}/machineTypes/n1-standard-1`,
      networkInterfaces: [
        {
          name: 'global/networks/default',
        },
      ],
    },
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

  // Wait for the create operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log('Instance created.');
}

createInstanceFromSnapshot();

Python

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Compute Engine 快速入門導覽課程」中的 Python 設定操作說明進行操作。詳情請參閱「Compute Engine Python API 參考文件」。

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

from __future__ import annotations

import re
import sys
from typing import Any
import warnings

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def disk_from_snapshot(
    disk_type: str,
    disk_size_gb: int,
    boot: bool,
    source_snapshot: str,
    auto_delete: bool = True,
) -> compute_v1.AttachedDisk():
    """
    Create an AttachedDisk object to be used in VM instance creation. Uses a disk snapshot as the
    source for the new disk.

    Args:
         disk_type: the type of disk you want to create. This value uses the following format:
            "zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
            For example: "zones/us-west3-b/diskTypes/pd-ssd"
        disk_size_gb: size of the new disk in gigabytes
        boot: boolean flag indicating whether this disk should be used as a boot disk of an instance
        source_snapshot: disk snapshot to use when creating this disk. You must have read access to this disk.
            This value uses the following format: "projects/{project_name}/global/snapshots/{snapshot_name}"
        auto_delete: boolean flag indicating whether this disk should be deleted with the VM that uses it

    Returns:
        AttachedDisk object configured to be created using the specified snapshot.
    """
    disk = compute_v1.AttachedDisk()
    initialize_params = compute_v1.AttachedDiskInitializeParams()
    initialize_params.source_snapshot = source_snapshot
    initialize_params.disk_type = disk_type
    initialize_params.disk_size_gb = disk_size_gb
    disk.initialize_params = initialize_params
    # Remember to set auto_delete to True if you want the disk to be deleted when you delete
    # your VM instance.
    disk.auto_delete = auto_delete
    disk.boot = boot
    return disk


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_instance(
    project_id: str,
    zone: str,
    instance_name: str,
    disks: list[compute_v1.AttachedDisk],
    machine_type: str = "n1-standard-1",
    network_link: str = "global/networks/default",
    subnetwork_link: str = None,
    internal_ip: str = None,
    external_access: bool = False,
    external_ipv4: str = None,
    accelerators: list[compute_v1.AcceleratorConfig] = None,
    preemptible: bool = False,
    spot: bool = False,
    instance_termination_action: str = "STOP",
    custom_hostname: str = None,
    delete_protection: bool = False,
) -> compute_v1.Instance:
    """
    Send an instance creation request to the Compute Engine API and wait for it to complete.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone to create the instance in. For example: "us-west3-b"
        instance_name: name of the new virtual machine (VM) instance.
        disks: a list of compute_v1.AttachedDisk objects describing the disks
            you want to attach to your new instance.
        machine_type: machine type of the VM being created. This value uses the
            following format: "zones/{zone}/machineTypes/{type_name}".
            For example: "zones/europe-west3-c/machineTypes/f1-micro"
        network_link: name of the network you want the new instance to use.
            For example: "global/networks/default" represents the network
            named "default", which is created automatically for each project.
        subnetwork_link: name of the subnetwork you want the new instance to use.
            This value uses the following format:
            "regions/{region}/subnetworks/{subnetwork_name}"
        internal_ip: internal IP address you want to assign to the new instance.
            By default, a free address from the pool of available internal IP addresses of
            used subnet will be used.
        external_access: boolean flag indicating if the instance should have an external IPv4
            address assigned.
        external_ipv4: external IPv4 address to be assigned to this instance. If you specify
            an external IP address, it must live in the same region as the zone of the instance.
            This setting requires `external_access` to be set to True to work.
        accelerators: a list of AcceleratorConfig objects describing the accelerators that will
            be attached to the new instance.
        preemptible: boolean value indicating if the new instance should be preemptible
            or not. Preemptible VMs have been deprecated and you should now use Spot VMs.
        spot: boolean value indicating if the new instance should be a Spot VM or not.
        instance_termination_action: What action should be taken once a Spot VM is terminated.
            Possible values: "STOP", "DELETE"
        custom_hostname: Custom hostname of the new VM instance.
            Custom hostnames must conform to RFC 1035 requirements for valid hostnames.
        delete_protection: boolean value indicating if the new virtual machine should be
            protected against deletion or not.
    Returns:
        Instance object.
    """
    instance_client = compute_v1.InstancesClient()

    # Use the network interface provided in the network_link argument.
    network_interface = compute_v1.NetworkInterface()
    network_interface.network = network_link
    if subnetwork_link:
        network_interface.subnetwork = subnetwork_link

    if internal_ip:
        network_interface.network_i_p = internal_ip

    if external_access:
        access = compute_v1.AccessConfig()
        access.type_ = compute_v1.AccessConfig.Type.ONE_TO_ONE_NAT.name
        access.name = "External NAT"
        access.network_tier = access.NetworkTier.PREMIUM.name
        if external_ipv4:
            access.nat_i_p = external_ipv4
        network_interface.access_configs = [access]

    # Collect information into the Instance object.
    instance = compute_v1.Instance()
    instance.network_interfaces = [network_interface]
    instance.name = instance_name
    instance.disks = disks
    if re.match(r"^zones/[a-z\d\-]+/machineTypes/[a-z\d\-]+$", machine_type):
        instance.machine_type = machine_type
    else:
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"

    instance.scheduling = compute_v1.Scheduling()
    if accelerators:
        instance.guest_accelerators = accelerators
        instance.scheduling.on_host_maintenance = (
            compute_v1.Scheduling.OnHostMaintenance.TERMINATE.name
        )

    if preemptible:
        # Set the preemptible setting
        warnings.warn(
            "Preemptible VMs are being replaced by Spot VMs.", DeprecationWarning
        )
        instance.scheduling = compute_v1.Scheduling()
        instance.scheduling.preemptible = True

    if spot:
        # Set the Spot VM setting
        instance.scheduling.provisioning_model = (
            compute_v1.Scheduling.ProvisioningModel.SPOT.name
        )
        instance.scheduling.instance_termination_action = instance_termination_action

    if custom_hostname is not None:
        # Set the custom hostname for the instance
        instance.hostname = custom_hostname

    if delete_protection:
        # Set the delete protection bit
        instance.deletion_protection = True

    # Prepare the request to insert an instance.
    request = compute_v1.InsertInstanceRequest()
    request.zone = zone
    request.project = project_id
    request.instance_resource = instance

    # Wait for the create operation to complete.
    print(f"Creating the {instance_name} instance in {zone}...")

    operation = instance_client.insert(request=request)

    wait_for_extended_operation(operation, "instance creation")

    print(f"Instance {instance_name} created.")
    return instance_client.get(project=project_id, zone=zone, instance=instance_name)


def create_from_snapshot(
    project_id: str, zone: str, instance_name: str, snapshot_link: str
):
    """
    Create a new VM instance with boot disk created from a snapshot. The
    new boot disk will have 20 gigabytes.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone to create the instance in. For example: "us-west3-b"
        instance_name: name of the new virtual machine (VM) instance.
        snapshot_link: link to the snapshot you want to use as the source of your
            boot disk in the form of: "projects/{project_name}/global/snapshots/{snapshot_name}"

    Returns:
        Instance object.
    """
    disk_type = f"zones/{zone}/diskTypes/pd-standard"
    disks = [disk_from_snapshot(disk_type, 20, True, snapshot_link)]
    instance = create_instance(project_id, zone, instance_name, disks)
    return instance

REST

當您使用 API 從快照建立執行個體時,會受到以下限制:

  • 只能使用一個磁碟做為開機磁碟。
  • 您必須將開機磁碟連接至該執行個體,做為第一個磁碟。
  • 如果您指定 source 屬性,則無法同時指定 initializeParams 屬性。提供 source 表示開機磁碟已存在,但 initializeParams 屬性表示 Compute Engine 應建立新的開機磁碟。

可用區開機磁碟

如要從開機磁碟快照建立例項,請使用 instances.insert 方法,並在 disks 屬性下指定 sourceSnapshot 欄位。您可以選擇為新開機磁碟指定 diskSizeGb 和 diskType 屬性。
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances
{
  "name": "INSTANCE_NAME",
  "machineType": "machineTypes/MACHINE_TYPE",
  "disks": [{
     "boot": true,
     "initializeParams": {
       "sourceSnapshot": "global/snapshots/BOOT_SNAPSHOT_NAME",
       "diskSizeGb": "BOOT_DISK_SIZE",
       "diskType": "BOOT_DISK_TYPE"
      }
   }],
  "networkInterfaces": [
    {
       "nicType": "GVNIC"
    }
  ]
}
更改下列內容:
  • PROJECT_ID:專案 ID
  • ZONE:要建立新執行個體的可用區
  • INSTANCE_NAME:要還原快照的執行個體名稱
  • MACHINE_TYPE:執行個體的機型
  • BOOT_SNAPSHOT_NAME:要用來建立新執行個體開機磁碟的快照名稱
  • BOOT_DISK_SIZE:選用:新開機磁碟的大小 (以 GiB 為單位)

    大小必須等於或大於建立快照的來源磁碟。

  • BOOT_DISK_TYPE:選用:開機磁碟的類型,例如 、PROJECT_ID/zones/ZONE/diskTypes/pd-ssd、 或 PROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced

區域性開機磁碟

如要使用開機磁碟快照做為來源,建立具有區域開機磁碟的運算執行個體,請使用 instances.insert 方法,並在 disks 屬性中指定 sourceSnapshot 和 replicaZones 欄位。
   POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances
   {
     "name": "INSTANCE_NAME",
     "disks": [
       {
         "boot": true,
         "initializeParams": {
            "sourceSnapshot": "global/snapshots/BOOT_SNAPSHOT_NAME",
            "replicaZones": [
                "projects/PROJECT_ID/zones/ZONE",
                "projects/PROJECT_ID/zones/REMOTE_ZONE"
              ],
            "diskType": "BOOT_DISK_TYPE"
         }
       }
     ],
     "networkInterfaces": [
       {
         "nicType": "GVNIC"
       }
     ]
   }
   
取代下列內容:
  • PROJECT_ID:專案 ID
  • ZONE:要建立執行個體的可用區名稱
  • INSTANCE_NAME:執行個體的名稱
  • BOOT_SNAPSHOT_NAME:開機磁碟快照的名稱
  • REMOTE_ZONE:區域性磁碟的遠端可用區
  • BOOT_DISK_TYPE:選用:開機磁碟的類型,例如 PROJECT_ID/zones/ZONE/diskTypes/pd-ssd 或 PROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced-high-availability

從非開機磁碟快照建立運算執行個體

如果您使用快照備份非開機磁碟,可以根據快照建立執行個體,並附加非開機磁碟。

控制台

將非開機快照從主控台還原到新的執行個體時,請先從每個快照建立一個磁碟。接著,在建立執行個體時附加新磁碟。

  1. 將每個非開機快照還原至新磁碟。

    1. 前往 Google Cloud 控制台的「Disks」(磁碟) 頁面。

      前往「Disks」(磁碟)

    2. 按一下 [Create Disk] (建立磁碟)。

    3. 指定磁碟的「Name」(名稱)。詳情請參閱「資源命名慣例」。

    4. 選取這個磁碟的「區域」和「可用區」。如果是可用區磁碟,磁碟和執行個體必須位於同一個可用區;如果是區域磁碟,則必須位於同一個區域。

    5. 選取磁碟的 [Type] (類型)。

    6. 選取「Source type」(來源類型) 底下的 [Snapshot] (快照)。

    7. 在新的 [Source snapshot] (來源快照)欄位下,選擇要還原到新磁碟的非開機快照。

    8. 如要建立磁碟,請按一下「建立」。

    針對要還原的每個快照重複上述步驟,建立磁碟。

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

    前往 VM 執行個體

  3. 選取您的專案並點選 [繼續]。

  4. 點選「建立執行個體」。

  5. 指定執行個體的名稱。詳情請參閱「資源命名慣例」。

  6. 選取這個執行個體的「區域」和「可用區」。如果是可用區磁碟,磁碟和執行個體必須位於同一個可用區;如果是區域磁碟,則必須位於同一個區域。

  7. 為執行個體選取「機型」。

  8. 如要允許外來流量,請變更執行個體的防火牆規則。

  9. 如要將磁碟附加至執行個體,請展開「Advanced options」(進階選項) 區段,然後執行下列操作:

    1. 展開「磁碟」部分。
    2. 按一下「連接現有的磁碟」。
    3. 在「Disk」(磁碟) 清單中,選取要連結至這個執行個體的磁碟。
    4. 在「Attachment Setting」(附件設定) 部分,選取磁碟的附件「Mode」(模式) 和「Deletion rule」(刪除規則)。如要進一步瞭解如何新增磁碟,請參閱 新增永久磁碟或 新增 Hyperdisk。
    5. 按一下 [儲存]。

    針對要附加的每個磁碟重複執行這些步驟。

  10. 如要建立並啟動執行個體,請按一下「建立」。

gcloud

使用 gcloud compute instances create 指令建立執行個體。針對要還原的每個非開機快照,加入 --create-disk 旗標,並指定 source-snapshot。

舉例來說,如要將兩個非開機磁碟的快照還原至新執行個體,請使用下列指令:

gcloud compute instances create INSTANCE_NAME \
    --create-disk source-snapshot=SNAPSHOT_1_NAME,name=DISK_1_NAME,size=DISK_1_SIZE,type=DISK_1_TYPE \
    --create-disk source-snapshot=SNAPSHOT_2_NAME,name=DISK_2_NAME,size=DISK_2_SIZE,type=DISK_2_TYPE

更改下列內容:

  • INSTANCE_NAME:新執行個體的名稱
  • SNAPSHOT_1_NAME 和 SNAPSHOT_2_NAME:要還原的非開機磁碟快照名稱
  • DISK_1_NAME 和 DISK_2_NAME:要為這個執行個體建立的新非開機磁碟名稱
  • DISK_1_SIZE 和 DISK_2_SIZE:選用:每個新非開機磁碟的大小 (以 GiB 為單位)

    大小必須等於或大於建立快照的來源磁碟大小。

  • DISK_1_TYPE 和 DISK_2_TYPE:選用,要建立的磁碟類型,例如 pd-ssd 或 hyperdisk-balanced

REST

使用 REST 將非開機快照還原至新執行個體時,適用下列限制:

  • 只能有一個磁碟做為開機磁碟。
  • 您必須將開機磁碟連接為該執行個體的第一個磁碟。
  • 如果您指定 source 屬性,則無法同時指定 initializeParams 屬性。提供 source 表示開機磁碟已存在,但 initializeParams 屬性表示 Compute Engine 應建立新的開機磁碟。

對 instances.insert 方法建立 POST 要求,並指定 initializeParams 屬性下的 sourceSnapshot 欄位。如要新增多個非開機磁碟,請為每個要建立的非開機磁碟重複 initializeParams 屬性。您可以選擇為建立的任何磁碟指定 diskSizeGb 和 diskType 屬性。

舉例來說,如要將兩個非開機磁碟快照還原至新執行個體,請提出下列要求:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances
{
  "name": "INSTANCE_NAME",
  "machineType": "machineTypes/MACHINE_TYPE",
  "networkInterfaces": [
    {
      "nicType": "GVNIC"
    }
  ],
  "disks": [
    {
      "autoDelete": "true",
      "boot": "true",
      "diskSizeGb": "BOOT_DISK_SIZE",
      "diskType": "BOOT_DISK_TYPE",
      "initializeParams": {
         "sourceImage": "projects/IMAGE_PROJECT/global/images/family/IMAGE_FAMILY"
      }
    },
    {
      "deviceName": "DEVICE_1_NAME",
      "initializeParams": {
         "sourceSnapshot": "global/snapshots/SNAPSHOT_1_NAME",
         "diskSizeGb": "DISK_1_SIZE",
         "diskType": "DISK_1_TYPE"
      }
    },
    {
      "deviceName": "DEVICE_2_NAME",
      "initializeParams": {
         "sourceSnapshot": "global/snapshots/SNAPSHOT_2_NAME",
         "diskSizeGb": "DISK_2_SIZE",
         "diskType": "DISK_2_TYPE"
      }
    }
  ]
}

更改下列內容:

  • PROJECT_ID:專案 ID
  • ZONE:要建立執行個體的可用區
  • INSTANCE_NAME:新執行個體的名稱
  • MACHINE_TYPE:執行個體的機型
  • DISK_SIZE:選用:對應磁碟的大小 (以 GiB 為單位)

    如要提供這項屬性,其值必須等於或大於快照來源磁碟的大小。

  • DISK_TYPE:選用:對應磁碟類型的完整或部分網址,例如 PROJECT_ID/zones/ZONE/diskTypes/pd-ssd 或 PROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced

  • IMAGE_PROJECT:包含圖片的專案。例如:debian-cloud

  • IMAGE_FAMILY:映像檔系列。這樣做會使用該系列中未淘汰的最新 OS 映像檔建立執行個體。舉例來說,如果您指定 "sourceImage": "projects/debian-cloud/global/images/family/debian-13",Compute Engine 會使用 Debian 13 映像檔系列中最新版本的 OS 映像檔建立執行個體。

  • DEVICE_NAME:選用:執行個體客體 OS 中顯示的裝置名稱

  • SNAPSHOT_NAME:對應的非開機磁碟快照名稱,您要將這些快照還原至執行個體上的新磁碟