從快照還原


磁碟可能是用於在運算執行個體上啟動及執行作業系統的開機磁碟,或是執行個體用於資料儲存的非開機磁碟。

您可以使用快照備份及還原磁碟資料,方法如下:

事前準備

必要的角色

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

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

所需權限

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

  • 如要從全域範圍的快照建立磁碟 (預設):
    • 專案的 compute.disks.create 權限
    • 執行個體的 compute.instances.attachDisk 權限
    • 所要連接磁碟的 compute.disks.use 權限
    • 專案上的 compute.snapshots.useReadOnlycompute.snapshots.createcompute.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 權限

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

限制

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

  • 您最多每 10 分鐘可以從特定快照建立一次新的區域性或區域磁碟。如果您想發出連續要求,以便為磁碟建立快照,則最多可以在 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:新磁碟的大小,以 GiB 為單位。這個數字必須等於或大於快照原始來源磁碟的大小。
    • SNAPSHOT_NAME:要還原的快照名稱
    • DISK_TYPE:磁碟的類型,例如 pd-ssdhyperdisk-throughputhyperdisk-balanced-high-availability
    • REGION:地區磁碟所在的地區,例如:europe-west1
    • SOURCE_REGION:來源快照的範圍
    • ZONE:新磁碟所在的區域
    • ZONE1,ZONE2:該地區中這兩個磁碟備用資源所在的區域,例如:europe-west1-beurope-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.listGET 要求,以顯示專案中的快照清單。

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

    PROJECT_ID 替換為您的專案 ID。

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

    請加入 namesizeGbtype 屬性。如要使用快照還原磁碟,就必須包含 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:來源快照的範圍
    • ZONE1ZONE2:新磁碟備用資源所在的區域
    • DISK_SIZE:新磁碟的大小,以 GiB 為單位。這個數字必須等於或大於快照原始來源磁碟的大小。
    • DISK_TYPE:磁碟的類型完整或部分網址,例如 PROJECT_ID/zones/ZONE/diskTypes/pd-ssdPROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balancedPROJECT_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 控制台的「Create an instance」(建立執行個體) 頁面。

    前往「Create an instance」(建立執行個體)

    如果出現系統提示,請選取您的專案,然後按一下「Continue」。系統隨即會顯示「Create an instance」(建立執行個體) 頁面,並顯示「Machine configuration」(機器設定) 窗格。

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

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

      預設選項為「任何」。如果您沒有變更這個預設選項,Google 會根據機器類型和可用性自動為您選擇可用區。

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

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

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

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

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

  3. 在導覽選單中,按一下「OS 和儲存空間」。在隨即顯示的「Operating system and storage」(作業系統和儲存空間) 窗格中,按照下列步驟設定啟動磁碟:

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

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

    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:選用:開機磁碟的type,例如 PROJECT_ID/zones/ZONE/diskTypes/pd-ssdPROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced

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

區域性開機磁碟

使用 gcloud compute instances create 指令,並在 source-snapshotreplica-zonesboot 屬性中加入 --create-disk 標記。

  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-ssdhyperdisk-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 欄位。您可以視需要指定新開機磁碟的 diskSizeGbdiskType 屬性。
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:選用:開機磁碟的type,例如 PROJECT_ID/zones/ZONE/diskTypes/pd-ssdPROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced

區域性開機磁碟

如要建立含有區域開機磁碟的運算執行個體,並使用開機磁碟快照做為來源,請使用 instances.insert 方法,並在 disks 屬性中指定 sourceSnapshotreplicaZones 欄位。
   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:選用:開機磁碟的type,例如 PROJECT_ID/zones/ZONE/diskTypes/pd-ssdPROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced-high-availability

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

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

主控台

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

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

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

      前往「Disks」(磁碟) 頁面

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

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

    4. 選取此磁碟的「Region」(地區)和「Zone」(區域)。磁碟和執行個體必須位於相同的可用區 (區域磁碟) 或區域 (地區磁碟) 中。

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

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

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

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

    重複這些步驟,從要還原的每個快照建立磁碟。

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

    前往 VM 執行個體

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

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

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

  6. 選取這個執行個體的「區域」和「可用區」。磁碟和執行個體必須位於相同的可用區 (區域磁碟) 或區域 (地區磁碟) 中。

  7. 選取執行個體的「Machine type」(機器類型)

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

  9. 如要將磁碟連接至執行個體,請展開「Advanced options」部分,然後執行下列操作:

    1. 展開「磁碟」專區。
    2. 按一下「連接現有的磁碟」
    3. 在「磁碟」清單中,選取要連結至這個執行個體的磁碟。
    4. 在「Attachment Setting」部分,選取磁碟的「Attachment 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_NAMESNAPSHOT_2_NAME:您要還原的非開機磁碟快照名稱
  • DISK_1_NAMEDISK_2_NAME:為此例建立的新非開機磁碟名稱
  • DISK_1_SIZEDISK_2_SIZE:選用:每個新的非開機磁碟大小 (以 GiB 為單位)

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

  • DISK_1_TYPEDISK_2_TYPE:選用:要建立的磁碟類型,例如 pd-ssdhyperdisk-balanced

REST

使用 REST 將非開機快照還原到新執行個體時,會受到以下限制:

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

instances.insert 方法建立 POST 要求,並在 initializeParams 屬性下指定 sourceSnapshot 欄位。您可以為每個要建立的非開機磁碟重複執行 initializeParams 屬性,最多可新增多個非開機磁碟。您可以選擇為您建立的任何磁碟指定 diskSizeGbdiskType 屬性。

例如,要將兩個非開機磁碟快照還原到新執行個體,請發出下列要求:

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-ssdPROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced

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

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

  • DEVICE_NAME:選用:在執行個體的來賓作業系統中顯示的裝置名稱

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