建立含有額外非開機磁碟的執行個體

本文說明如何在建立執行個體時,建立額外的非開機磁碟並連結至 Compute Engine 執行個體。

本文資訊適用於建立具有區域磁碟的運算執行個體,這些磁碟不在 Hyperdisk 集區中。下表列出相關工作和說明文件。

事前準備

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

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

    控制台

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

    gcloud

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

      gcloud init

      如果您使用外部識別資訊提供者 (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.instances.create
  • 為執行個體建立磁碟: compute.disks.create 在專案中
  • 如要從映像檔建立磁碟: compute.images.useReadOnly 來源映像檔
  • 如要從標準或封存快照建立磁碟,請按照下列步驟操作: compute.snapshots.useReadOnly 來源快照
  • 如要從即時快照建立磁碟,請按照下列步驟操作: compute.instantSnapshots.useReadOnly 在來源即時快照上
  • 如要從現有磁碟建立磁碟,請按照下列步驟操作: compute.disks.useReadOnly 在來源磁碟上

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

限制

可附加至執行個體的磁碟數量、總大小和類型,取決於執行個體的機型。

舉例來說,C4 執行個體不支援永久磁碟。此外,連至 c4-standard-2 執行個體的所有磁碟加總大小不得超過 257 TiB,但 c4-standard-192 執行個體的限制為 512 TiB。

如要瞭解各機器系列的詳細限制,請參閱機器系列說明文件中的「支援的磁碟類型」一節。如要查看新執行個體機器系列的限制,請參閱下表中的對應連結。

一般用途
機型
運算最佳化
機器類型
記憶體最佳化
機型
加速器最佳化
機器類型
儲存空間最佳化
機型

磁碟大小限制和參照名稱

為區域磁碟指定的大小必須在下表列出的範圍內。

使用 Google Cloud CLI、REST 或 Compute Engine 適用的 Cloud Client Libraries 建立磁碟時,請在下表指定「參考名稱」欄的對應值,藉此指定要建立的磁碟類型。

磁碟類型 參照名稱 大小下限 大小上限 預設大小
Hyperdisk Balanced hyperdisk-balanced 4 GiB 64 TiB1 100 GiB
Hyperdisk Balanced High Availability hyperdisk-balanced-high-availability 4 GiB 64 TiB 100 GiB
Hyperdisk Extreme hyperdisk-extreme 64 GiB 64 TiB 1 TiB
Hyperdisk Throughput hyperdisk-throughput 2 TiB 32 TiB 2 TiB
Hyperdisk ML hyperdisk-ml 4 GiB 64 TiB 100 GiB
平衡型永久磁碟 pd-balanced 區域:10 GiB
區域:10 GiB
64 TiB 100 GiB
效能型 (SSD) 永久磁碟 pd-ssd 區域:10 GiB
區域:10 GiB
64 TiB 100 GiB
標準永久磁碟 pd-standard 區域:10 GiB
區域:200 GiB
64 TiB 500 GiB
極端永久磁碟 pd-extreme 500 GiB 64 TiB 1 TiB
1 預先發布版: C4 支援的最大磁碟大小為 128 TiB。如要存取這項功能,請聯絡 hyperdisk-questions@google.com。

建立執行個體,並新增非開機磁碟

如要建立執行個體,並建立及附加額外的非開機磁碟,請按照下列步驟操作:

控制台

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

    前往「建立執行個體」

    如果出現系統提示,請選取您的專案,然後按一下 [Continue] (繼續)。

    「建立執行個體」頁面隨即顯示,並顯示「機器設定」窗格。

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

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

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

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

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

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

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

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

  3. 在導覽選單中,按一下「OS 和儲存空間」。系統會顯示「作業系統和儲存空間」窗格。

  4. 如要設定開機磁碟,請按一下「變更」。 系統會顯示「開機磁碟」窗格和「公開映像檔」分頁。

  5. 透過下列任一方式設定開機磁碟的資料來源:

    • 如要選擇公開映像檔做為開機磁碟的資料來源,請在「Public images」(公開映像檔) 分頁中指定下列項目:
      1. 在「Operating system」(作業系統) 清單中,選取作業系統類型。
      2. 在「Version」清單中,選取作業系統版本。
      3. 在「Boot disk type」(開機磁碟類型) 清單中,選取開機磁碟類型。
      4. 在「Size (GB)」(大小 (GB)) 欄位中,指定開機磁碟大小。
    • 如要選擇自訂映像檔做為開機磁碟的資料來源,請按一下「自訂映像檔」,然後在隨即顯示的「自訂映像檔」分頁中,指定下列項目:
      1. 如要選取圖片專案,請按一下「變更」,然後選取含有圖片的專案。
      2. 在「圖片」清單中,選取要匯入的圖片。
      3. 在「Boot disk type」(開機磁碟類型) 清單中,選取開機磁碟類型。
      4. 在「Size (GB)」(大小 (GB)) 欄位中,指定開機磁碟大小。
    • 如要選擇標準快照做為開機磁碟的資料來源,請按一下「快照」,然後在隨即顯示的「快照」分頁中,指定下列項目:
      1. 在「Snapshot」(快照) 清單中選取快照。
      2. 在「Boot disk type」(開機磁碟類型) 清單中,選取開機磁碟類型。
      3. 在「Size (GB)」(大小 (GB)) 欄位中,指定開機磁碟大小。
    • 如要選擇封存快照做為開機磁碟的資料來源,請按一下「封存快照」,然後在隨即顯示的「封存快照」分頁中,指定下列項目:
      1. 在「封存快照」清單中,選取封存快照。
      2. 在「Boot disk type」(開機磁碟類型) 清單中,選取開機磁碟類型。
      3. 在「Size (GB)」(大小 (GB)) 欄位中,指定開機磁碟大小。
    • 如要選擇現有磁碟做為開機磁碟,請按一下「現有磁碟」。然後在隨即顯示的「現有磁碟」分頁中,選取「磁碟」清單中的現有磁碟。這個選項會使用現有磁碟做為開機磁碟,不會建立新磁碟。

  6. 選用:如果開機磁碟是 Hyperdisk Balanced 磁碟區,您可以為新磁碟設定效能限制。指定的值必須在支援的值範圍內。

  7. 選用:如要查看進階設定選項,請展開「顯示進階設定」部分。

    • 在「模式」欄位中選取磁碟連接模式。
    • 在「刪除規則」欄位中選取選項,即可選擇在刪除執行個體時保留或刪除磁碟。
    • 如要方便從客體 OS 識別磁碟,請指定自訂裝置名稱。 在「裝置名稱」標題下方,選取「使用自訂裝置名稱」選項。在「裝置名稱」欄位中,輸入要用做磁碟符號連結的字串。

  8. 如要確認開機磁碟選項並返回「OS and storage」(OS 與儲存空間) 窗格,請按一下「Select」(選取)。

  9. 如要建立新的非開機磁碟並連結至執行個體,請針對要新增的每個磁碟,按照下列步驟操作。

    1. 在「Additional disks」(其他磁碟) 部分中,點選「Add new disk」(增加新磁碟)。 系統會顯示「新增磁碟」窗格。

    2. 在「Disk configuration」(磁碟設定) 區段的「Name」(名稱) 欄位中,指定非開機磁碟的名稱。

    3. 選用:在「Description」(說明) 欄位中,指定磁碟的說明。

    4. 選取新磁碟的資料來源:

      • 如要建立空白且未格式化的磁碟,請在「Disk source type」(磁碟來源類型) 清單中選取「Blank disk」(空白磁碟)。
      • 如要複製現有資料,請選取非開機磁碟的來源類型。
    5. 在「Disk type」(磁碟類型) 清單中,選取非開機磁碟的類型。 機型必須支援磁碟類型。

    6. 在「大小」欄位中,指定非開機磁碟的大小。

    7. 選用:如果新磁碟是 Hyperdisk 磁碟區,您可以為新磁碟設定效能限制。指定的值必須在支援的值範圍內,且取決於 Hyperdisk 類型,如下所示:

      • Hyperdisk Balanced。您可以變更磁碟的大小、佈建的 IOPS 和佈建輸送量
      • Hyperdisk Extreme。您可以變更磁碟的大小和佈建的 IOPS。
      • Hyperdisk ML。您可以變更磁碟的大小和佈建輸送量。
      • Hyperdisk Throughput。您可以變更磁碟的大小和佈建輸送量。
    8. 選用:如要查看進階設定選項,請展開「Show advanced configurations」(顯示進階設定) 部分。

      • 在「模式」欄位中選取磁碟連接模式。
      • 在「刪除規則」欄位中選取選項,即可選擇在刪除執行個體時保留或刪除磁碟。
      • 如要方便從客體 OS 識別磁碟,請指定自訂裝置名稱。 在「裝置名稱」標題下方,選取「使用自訂裝置名稱」選項。在「裝置名稱」欄位中,輸入要用做磁碟符號連結的字串。

    9. 如要確認選項並返回「OS 和儲存空間」窗格,請按一下「儲存」。

    針對要建立並附加至執行個體的每個非開機磁碟,重複執行這個步驟。

  10. 選用:為運算執行個體指定備份和複製選項。在導覽選單中,按一下「資料保護」。 在隨即顯示的「資料保護」窗格中,完成下列步驟,指定要如何備份及複製運算執行個體的資料。

    1. 如要指定資料備份方式,請選取「Back up your data」(備份資料) 的選項。
    2. 如要指定資料的複製方式,請按照下列步驟操作:

      1. 如要使用區域磁碟類型,在第二個可用區中同步複製執行個體的新磁碟,請選取「區域磁碟」核取方塊。
      1. 如要使用非同步複製功能,在第二個區域中複製執行個體的磁碟,請選取「非同步複製」核取方塊。
    3. 如要只在非開機磁碟上使用指定的資料保護選項,請勾選「排除開機磁碟」核取方塊。

  11. 點選導覽選單中的「Networking」(網路)。在隨即顯示的「Networking」(網路) 窗格中,執行下列操作:

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

      Compute Engine 會在執行個體中新增網路標記,並建立對應的輸入防火牆規則,允許所有傳入的 tcp:80 (HTTP) 或 tcp:443 (HTTPS) 流量。網路標記會將防火牆規則與執行個體建立關聯。詳情請參閱 Cloud Next Generation Firewall 說明文件中的「防火牆規則總覽」。

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

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

gcloud

  1. 在 Google Cloud 控制台中啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

  2. 執行 gcloud compute instances create 指令,建立含有額外非開機磁碟的執行個體。

    建立執行個體時,最多可以新增 127 個非開機磁碟。為您建立的每個非開機磁碟指定 --create-disk 旗標。

    如要從公開或預設映像檔建立非開機磁碟,請使用 --create-disk 旗標指定 image 或 image-family 和 image-project 屬性。如要建立空白磁碟,請勿加入這些屬性。

    您可以選擇性地加入下列屬性的值:

    • 磁碟大小:使用 --size 屬性。
    • 磁碟類型:使用 --type 屬性。
    • 區域性磁碟:包含 replica-zones 屬性。
    gcloud compute instances create INSTANCE_NAME \
        --zone=ZONE \
        --machine-type=MACHINE_TYPE \
        --image-project=BOOT_DISK_IMAGE_PROJECT \
        BOOT_DISK_IMAGE_FLAG \
        --create-disk name=DISK_NAME,device-name=DISK_DEVICE_NAME,size=SIZE_GB,type=DISK_TYPE,image=DISK_IMAGE,image-project=DISK_IMAGE_PROJECT,replica-zones=^:^ZONE:REMOTE_ZONE,boot=false
    

    更改下列內容:

    • INSTANCE_NAME:新執行個體的名稱。
    • ZONE:要在哪個可用區建立執行個體。
    • MACHINE_TYPE:執行個體的機型。例如:c3-standard-4。
    • BOOT_DISK_IMAGE_PROJECT: 包含圖片的專案。舉例來說,如果是 Debian,請輸入 debian-cloud。如要尋找公開映像檔的映像檔專案,請前往「作業系統詳細資料」頁面。在作業系統的「正式版」部分,「一般資訊」分頁的「映像檔專案」欄會列出映像檔專案。
    • BOOT_DISK_IMAGE_FLAG:指定下列其中一個值:

      • 使用 --image IMAGE_NAME 旗標指定公開或自訂映像檔的特定版本。例如:--image debian-12-bookworm-v20241112。

      • 使用 --image-family IMAGE_FAMILY_NAME 旗標指定映像檔系列。這樣一來,系統就會建立執行個體,並使用映像檔系列中未淘汰的最新 OS 映像檔。舉例來說,如果您指定 --image-family debian-12,Compute Engine 在建立執行個體時,就會使用 Debian 12 映像檔系列中最新的 OS 映像檔版本。

    • 如要使用其他磁碟,請替換下列項目:

      • DISK_NAME:選用:非開機磁碟的名稱。
      • SIZE_GB:選用:非開機磁碟的大小。
      • DISK_TYPE:磁碟的類型。例如:hyperdisk-balanced。機型必須支援磁碟類型。
      • DISK_DEVICE_NAME:選用:執行個體建立後,顯示給客體 OS 的磁碟名稱。
      • DISK_IMAGE:選用:如要從現有映像檔建立磁碟,請指定下列其中一項:
        • image=DISK_IMAGE_NAME:要用於建立非開機磁碟的映像檔名稱,例如 debian-12-bookworm-v20260210。
        • image-family=DISK_IMAGE_FAMILY:建立非開機磁碟時要使用的映像檔系列,例如 debian-12。
      • DISK_IMAGE_PROJECT:選用:如要從現有映像檔建立非開機磁碟,請指定包含該映像檔的映像檔專案。
      • REMOTE_ZONE:選用:如要建立區域磁碟,請指定磁碟應複製到的可用區,例如 us-central1-b。

      如為空白磁碟,請勿指定 image、image-project 或 image-family 參數。

      如果是區域磁碟,請勿指定磁碟屬性 replica-zones。

Terraform

如要產生 Terraform 程式碼,請使用 Google Cloud 控制台中的「對等程式碼」元件。
  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面。

    前往 VM 執行個體

  2. 點選「建立執行個體」。
  3. 指定所需參數。
  4. 按一下頁面頂端或底部的「對等程式碼」,然後點選「Terraform」分頁標籤,即可查看 Terraform 程式碼。

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

// createWithAdditionalDisk create a new VM instance with Debian 10 operating system and a 11 GB additional empty disk.
func createWithAdditionalDisk(w io.Writer, projectID, zone, instanceName string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"

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

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

	// List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details.
	newestDebianReq := &computepb.GetFromFamilyImageRequest{
		Project: "debian-cloud",
		Family:  "debian-12",
	}
	newestDebian, err := imagesClient.GetFromFamily(ctx, newestDebianReq)
	if err != nil {
		return fmt.Errorf("unable to get image from family: %w", err)
	}

	req := &computepb.InsertInstanceRequest{
		Project: projectID,
		Zone:    zone,
		InstanceResource: &computepb.Instance{
			Name: proto.String(instanceName),
			Disks: []*computepb.AttachedDisk{
				{
					InitializeParams: &computepb.AttachedDiskInitializeParams{
						DiskSizeGb:  proto.Int64(10),
						SourceImage: newestDebian.SelfLink,
						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()),
				},
				{
					InitializeParams: &computepb.AttachedDiskInitializeParams{
						DiskSizeGb: proto.Int64(11),
						DiskType:   proto.String(fmt.Sprintf("zones/%s/diskTypes/pd-standard", zone)),
					},
					AutoDelete: proto.Bool(true),
					Boot:       proto.Bool(false),
					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

在試用這個範例之前,請先按照「使用用戶端程式庫的 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 {

  /**
   * Create an AttachedDisk object to be used in VM instance creation. Uses an image as the source
   * for the new disk.
   *
   * @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 sourceImage source image to use when creating this disk. You must have read access to
   * this disk. This can be one of the publicly available images or an image from one of your
   * projects. This value uses the following format:
   * "projects/{project_name}/global/images/{image_name}"
   * @return AttachedDisk object configured to be created using the specified image.
   */
  private static AttachedDisk diskFromImage(String diskType, int diskSizeGb, boolean boot,
      String sourceImage) {
    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()
                    .setSourceImage(sourceImage)
                    .setDiskSizeGb(diskSizeGb)
                    .setDiskType(diskType)
                    .build())
            .build();
    return disk;
  }


  /**
   * Create an AttachedDisk object to be used in VM instance creation. The created disk contains no
   * data and requires formatting before it can be used.
   *
   * @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
   * @return AttachedDisk object configured to be created as an empty disk.
   */
  private static AttachedDisk emptyDisk(String diskType, int diskSizeGb) {
    AttachedDisk disk =
        AttachedDisk.newBuilder()
            .setBoot(false)
            // 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()
                    .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 Debian 13 operating system and a 11 GB additional empty disk.
   *
   * @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.
   * @return Instance object.
   */
  public static Instance createWithAdditionalDisk(String project, String zone, String instanceName)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (ImagesClient imagesClient = ImagesClient.create()) {
      // List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
      Image image = imagesClient.getFromFamily("debian-cloud", "debian-13");
      String diskType = String.format("zones/%s/diskTypes/pd-standard", zone);
      Vector<AttachedDisk> disks = new Vector<>();
      disks.add(diskFromImage(diskType, 10, true, image.getSelfLink()));
      disks.add(emptyDisk(diskType, 11));
      return createWithDisks(project, zone, instanceName, disks, "n1-standard-1",
          "global/networks/default", null);
    }
  }

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 compute = require('@google-cloud/compute');

// Create a new VM instance with Debian 10 operating system and a 11 GB additional empty disk.
async function createWithAdditionalDisk() {
  const instancesClient = new compute.InstancesClient();
  const imagesClient = new compute.ImagesClient();

  // List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details.
  const [newestDebian] = await imagesClient.getFromFamily({
    project: 'debian-cloud',
    family: 'debian-11',
  });

  const [response] = await instancesClient.insert({
    project: projectId,
    zone,
    instanceResource: {
      name: instanceName,
      disks: [
        {
          initializeParams: {
            diskSizeGb: '10',
            sourceImage: newestDebian.selfLink,
            diskType: `zones/${zone}/diskTypes/pd-standard`,
          },
          autoDelete: true,
          boot: true,
          type: 'PERSISTENT',
        },
        {
          initializeParams: {
            diskSizeGb: '11',
            diskType: `zones/${zone}/diskTypes/pd-standard`,
          },
          autoDelete: true,
          boot: false,
          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.');
}

createWithAdditionalDisk();

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_image_from_family(project: str, family: str) -> compute_v1.Image:
    """
    Retrieve the newest image that is part of a given family in a project.

    Args:
        project: project ID or project number of the Cloud project you want to get image from.
        family: name of the image family you want to get image from.

    Returns:
        An Image object.
    """
    image_client = compute_v1.ImagesClient()
    # List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
    newest_image = image_client.get_from_family(project=project, family=family)
    return newest_image


def disk_from_image(
    disk_type: str,
    disk_size_gb: int,
    boot: bool,
    source_image: str,
    auto_delete: bool = True,
) -> compute_v1.AttachedDisk:
    """
    Create an AttachedDisk object to be used in VM instance creation. Uses an image 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_image: source image to use when creating this disk. You must have read access to this disk. This can be one
            of the publicly available images or an image from one of your projects.
            This value uses the following format: "projects/{project_name}/global/images/{image_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 image.
    """
    boot_disk = compute_v1.AttachedDisk()
    initialize_params = compute_v1.AttachedDiskInitializeParams()
    initialize_params.source_image = source_image
    initialize_params.disk_size_gb = disk_size_gb
    initialize_params.disk_type = disk_type
    boot_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.
    boot_disk.auto_delete = auto_delete
    boot_disk.boot = boot
    return boot_disk


def empty_disk(
    disk_type: str, disk_size_gb: int, boot: bool = False, auto_delete: bool = True
) -> compute_v1.AttachedDisk():
    """
    Create an AttachedDisk object to be used in VM instance creation. The created disk contains
    no data and requires formatting before it can be used.

    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
        auto_delete: boolean flag indicating whether this disk should be deleted with the VM that uses it

    Returns:
        AttachedDisk object configured to be created as an empty disk.
    """
    disk = compute_v1.AttachedDisk()
    initialize_params = compute_v1.AttachedDiskInitializeParams()
    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_with_additional_disk(
    project_id: str, zone: str, instance_name: str
) -> compute_v1.Instance:
    """
    Create a new VM instance with Debian 10 operating system on a 20 GB disk
    and a 25 GB additional empty 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.

    Returns:
        Instance object.
    """
    newest_debian = get_image_from_family(project="debian-cloud", family="debian-12")
    disk_type = f"zones/{zone}/diskTypes/pd-standard"
    disks = [
        disk_from_image(disk_type, 20, True, newest_debian.self_link),
        empty_disk(disk_type, 25),
    ]
    instance = create_instance(project_id, zone, instance_name, disks)
    return instance

REST

建立執行個體時,您最多可使用每個額外磁碟的 initializeParams 屬性,建立 127 個非開機磁碟。請使用公開或私人映像檔建立額外磁碟。如要新增空白磁碟,請不要使用 sourceImage 值定義 initializeParams 項目。 加入磁碟屬性 replicaZones,即可建立區域磁碟,而非可用區磁碟。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances

{
   "machineType":"zones/MACHINE_TYPE_ZONE/machineTypes/MACHINE_TYPE",
   "name":"VM_NAME",
   
   "disks":[
      {
         "initializeParams":{
            "sourceImage":"projects/IMAGE_PROJECT/global/images/IMAGE"
         },
         "boot":true
      },
      {
         "initializeParams":{
            "diskSizeGb":"SIZE_GB",
            "sourceImage":"projects/DISK_IMAGE_PROJECT/global/images/DISK_IMAGE",
            "diskType":"DISK_TYPE"
         }
      },
      {
         "initializeParams":{
            "diskSizeGb":"SIZE_GB",
            "diskType":"DISK_TYPE"
         },
      },
      {
         "boot": false,
         "deviceName":"DISK_NAME",
         "initializeParams": {
            "diskType": "DISK_TYPE",
            "replicaZones": [
               "projects/PROJECT_ID/zones/ZONE",
               "projects/PROJECT_ID/zones/REMOTE_ZONE"
            ]
         }
      }
   ],
   
   
   "networkInterfaces":[
      {
         "network":"global/networks/NETWORK_NAME"
      }
   ],
   
  
   "shieldedInstanceConfig":{
      "enableSecureBoot":"ENABLE_SECURE_BOOT"
   }
}

更改下列內容:

  • PROJECT_ID:要在其中建立 VM 的專案 ID
  • ZONE:要在其中建立 VM 的可用區
  • MACHINE_TYPE_ZONE:包含要用於新 VM 的機型的可用區
  • MACHINE_TYPE:新 VM 的機型,預先定義或自訂
  • VM_NAME:新 VM 的名稱
  • IMAGE_PROJECT:包含映像檔的專案
    。舉例來說,如果您指定 debian-10 做為映像檔系列,請指定 debian-cloud 做為映像檔專案。
  • IMAGE:請指定下列其中一個值:
    • IMAGE:公開映像檔的特定版本

      例如: "sourceImage": "projects/debian-cloud/global/images/debian-10-buster-v20200309"

    • IMAGE_FAMILY:映像檔系列

      系統會使用最新的非已淘汰 OS 映像檔建立 VM。舉例來說,如果您指定 "sourceImage": "projects/debian-cloud/global/images/family/debian-10",Compute Engine 會從 Debian 10 映像檔系列中,建立最新版本的 OS 映像檔 VM。

  • 如要使用其他磁碟,請替換下列項目:

    • SIZE_GB:磁碟大小
    • DISK_IMAGE 或
    • DISK_IMAGE_FAMILY:為非開機磁碟指定來源映像檔或映像檔系列:
      • DISK_IMAGE:要當做非開機磁碟使用的映像檔名稱。例如:"sourceImage": "projects/DISK_IMAGE_PROJECT/global/images/DISK_IMAGE"。
      • DISK_IMAGE_FAMILY:做為非開機磁碟的映像檔系列。 例如:"sourceImage": "projects/DISK_IMAGE_PROJECT/global/images/family/DISK_IMAGE_FAMILY"。
    • DISK_TYPE:磁碟類型類型的完整或部分網址。例如:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced。 機型必須支援磁碟類型。
    • DISK_NAME:選用。VM 建立完成後,訪客 OS 顯示的磁碟名稱。
    • REMOTE_ZONE:要將區域磁碟複製到的可用區

    如果是空白磁碟,請勿指定 sourceImage 屬性。

    如果是區域磁碟,請勿指定 replicaZones 屬性。

  • NETWORK_NAME:您要用於 VM 的虛擬私有雲網路。您可以指定 default 使用預設網路。
  • ENABLE_SECURE_BOOT:選用:如果您選擇的映像檔支援 Shielded VM 功能,Compute Engine 預設會啟用虛擬信任平台模組 (vTPM) 和完整性監控。Compute Engine 預設不會啟用安全啟動。

    如果您為 enableSecureBoot 指定 true,Compute Engine 會建立 VM,並啟用所有三項 Shielded VM 功能。Compute Engine 啟動 VM 後,如要修改 Shielded VM 選項,必須先停止 VM。

建立執行個體後,您必須格式化所有空白磁碟並掛接所有磁碟,才能使用這些磁碟。