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


您也可以選擇要附加的現有磁碟,做為非開機磁碟

如果您想以多重寫入模式建立磁碟,就無法在建立執行個體時一併建立磁碟。您必須先建立磁碟,才能將磁碟連結至執行個體。

事前準備

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

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    1. After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    2. Set a default region and zone.

    REST

    To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.

      After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    For more information, see Authenticate for using REST in the Google Cloud authentication documentation.

必要的角色

如要取得建立含有新增非開機磁碟的執行個體所需的權限,請要求管理員為您授予專案的 Compute 執行個體管理員 (v1) (roles/compute.instanceAdmin.v1) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

這個預先定義的角色包含建立含有額外非啟動磁碟的執行個體所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要建立含有新增非啟動磁碟的執行個體,您必須具備下列權限:

  • compute.instances.create 專案
  • 如要為執行個體建立新磁碟,請按照下列步驟操作: compute.disks.create 專案

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

使用新的額外非開機磁碟建立執行個體

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

主控台

  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」(作業系統和儲存空間) 窗格中,完成下列步驟。

    如要進一步瞭解新增磁碟時可設定的參數,請參閱「關於永久磁碟」和「關於 Google Cloud Hyperdisk」。

    1. 如要設定開機磁碟,請按一下「變更」。系統會顯示「Boot disk」窗格,並顯示「Public images」分頁。

    2. 使用下列其中一種方式設定開機磁碟的資料來源:

      • 如要選擇公開映像檔做為開機磁碟的資料來源,請在「Public images」(公開映像檔) 分頁中指定下列項目:

        1. 在「Operating system」(作業系統) 清單中選取 OS 類型。
        2. 在「Version」清單中,選取 OS 版本。
        3. 在「Boot disk type」(開機磁碟類型)清單中,選取開機磁碟類型。
        4. 在「Size (GB)」(大小 (GB)) 欄位中,指定開機磁碟的大小。
      • 如要選擇自訂映像檔做為開機磁碟的資料來源,請按一下「Custom images」,然後在隨即顯示的「Custom images」分頁中指定下列項目:

        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)) 欄位中,指定開機磁碟的大小。
      • 如要選擇現有磁碟做為開機磁碟,請按一下「Existing disks」。接著,在隨即顯示的「現有磁碟」分頁中,選取「磁碟」清單中的現有地區性永久磁碟或 Hyperdisk 平衡高可用性磁碟區。

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

    4. 如要確認開機磁碟選項並返回「Operating system and storage」(作業系統和儲存空間) 窗格,請按一下「Select」(選取)

    5. 如要建立新的非開機磁碟並連接至執行個體,請在「額外儲存空間和 VM 備份」區段中,按一下「新增磁碟」

      在隨即顯示的「Add new disk」窗格中,執行下列操作:

      1. 在「Name」欄位中,指定非開機磁碟的名稱。
      2. 在「Disk source type」(磁碟來源類型) 清單中,選取非開機磁碟的來源類型。
      3. 在「磁碟類型」清單中,選取非開機磁碟的類型。
      4. 在「Size」欄位中,指定非開機磁碟的大小。
      5. 在「附件設定」專區,執行以下操作:
      6. 在「Mode」欄位中,選取磁碟連結模式。
      7. 在「Deletion rule」欄位中,選取一個選項,指定在刪除執行個體時,磁碟會發生什麼事。

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

  4. 在導覽選單中,按一下「資料保護」。在隨即顯示的「資料保護」窗格中,按照下列步驟指定要如何備份及複製執行個體的資料。

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

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

  5. 在導覽選單中,按一下「Networking」。在隨即顯示的「Networking」窗格中,執行下列操作:

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

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

  6. 選用:指定其他設定選項。詳情請參閱「建立執行個體時的設定選項」。

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

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

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

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

    如要透過公開或庫存映像檔建立非開機磁碟,請使用 --create-disk 標記指定 imageimage-familyimage-project 屬性。如要建立空白磁碟,請勿加入這些屬性。

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

    • 磁碟大小:使用 --size 屬性。
    • 磁碟類型:使用 --type 屬性。
    • 區域磁碟:納入 replica-zones 屬性。
    gcloud compute instances create INSTANCE_NAME \
        --zone=ZONE \
        --image-project=IMAGE_PROJECT \
        IMAGE_FLAG \
        --create-disk DISK_IMAGE,image-project=DISK_IMAGE_PROJECT,size=SIZE_GB,type=DISK_TYPE \
        --create-disk device-name=DISK_NAME,replica-zones=^:^ZONE:REMOTE-ZONE,boot=false
    

    更改下列內容:

    • INSTANCE_NAME:新執行個體的名稱
    • ZONE:要建立執行個體的可用區
    • IMAGE_PROJECT:包含圖片的專案
    • 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_IMAGE:請指定下列其中一個值:
        • image=DISK_IMAGE_NAME:建立非開機磁碟時要使用的映像檔名稱
        • image-family=DISK_IMAGE_FAMILY>:建立非開機磁碟時要使用的映像檔系列
      • DISK_IMAGE_PROJECT:磁碟映像檔所屬的映像檔專案
      • SIZE_GB:選用:非開機磁碟的大小
      • DISK_TYPE:選用:磁碟的類型完整或部分網址

        例如,https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced。如要查看一或多個區域的可用磁碟類型,請使用 gcloud compute disk-types list --zones=ZONE_LIST 指令。將 ZONE_LIST 替換為以半形逗號分隔的區域清單。

      • DISK_NAME:選用:在建立執行個體後,向客體 OS 顯示的磁碟名稱。

      • REMOTE_ZONE:磁碟應複製至的區域

      如果是空白磁碟,請勿指定 imageimage-projectimage-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 11 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-11");
      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圖片系列

      這會根據最新的非淘汰作業系統映像檔建立 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:磁碟類型的type 完整或部分網址。例如:https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/diskTypes/hyperdisk-balanced
    • DISK_NAME:選用。在建立 VM 後,向客體作業系統顯示的磁碟名稱。
    • REMOTE_ZONE:要複製區域磁碟的區域

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

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

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

    如果您為 enableSecureBoot 指定 true,Compute Engine 會建立 VM,並啟用所有三種受防護的 VM 功能。在 Compute Engine 啟動 VM 後,您必須停止 VM,才能修改受防護的 VM 選項。

請在使用前先格式化及掛接磁碟。