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


建立運算執行個體時,您可以同時建立其他非開機磁碟,並附加至執行個體。您也可以選擇要附加為非開機磁碟的現有磁碟

如要以多重寫入模式建立磁碟,您無法在建立執行個體的同時建立磁碟。您必須先建立磁碟,然後才能將磁碟連接至執行個體。

事前準備

  • 如果尚未設定驗證,請先完成設定。 「驗證」是指驗證身分的程序,確認您有權存取 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.
    3. REST

      如要在本機開發環境中使用本頁的 REST API 範例,請使用您提供給 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.

      詳情請參閱 Google Cloud 驗證說明文件中的「Authenticate for using REST」。

必要的角色

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

這個預先定義的角色具備建立執行個體所需的權限,且執行個體已新增非開機磁碟。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要建立執行個體並新增非開機磁碟,必須具備下列權限:

  • 專案的 compute.instances.create
  • 為執行個體建立新磁碟: 專案的 compute.disks.create

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

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

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

主控台

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

    前往「建立執行個體」

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

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

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

        1. 如要選取圖片專案,請按一下「變更」,然後選取含有圖片的專案。
        2. 在「圖片」清單中,選取要匯入的圖片。
        3. 在「Boot disk type」(開機磁碟類型) 清單中,選取開機磁碟類型。
        4. 在「Size (GB)」(大小 (GB)) 欄位中,指定開機磁碟的大小。
      • 如要選擇標準快照做為開機磁碟的資料來源,請按一下「快照」,然後在隨即顯示的「快照」分頁中,指定下列項目:

        1. 在「快照」清單中選取快照。
        2. 在「Boot disk type」(開機磁碟類型) 清單中,選取開機磁碟類型。
        3. 在「Size (GB)」(大小 (GB)) 欄位中,指定開機磁碟的大小。
      • 如要選擇封存快照做為開機磁碟的資料來源,請按一下「封存快照」,然後在隨即顯示的「封存快照」分頁中,指定下列項目:

        1. 在「封存快照」清單中,選取封存快照。
        2. 在「Boot disk type」(開機磁碟類型) 清單中,選取開機磁碟類型。
        3. 在「Size (GB)」(大小 (GB)) 欄位中,指定開機磁碟的大小。
      • 如要選擇現有磁碟做為開機磁碟,請按一下「現有磁碟」。然後在隨即顯示的「現有磁碟」分頁中,從「磁碟」清單選取現有的區域性 Persistent Disk 或 Hyperdisk Balanced High Availability 磁碟區。

    3. 選用:如需進階設定選項,請展開「Show advanced configurations」(顯示進階設定) 部分。

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

    5. 如要建立新的非開機磁碟並連結至執行個體,請在「額外儲存空間和 VM 備份」部分點選「新增磁碟」

      在隨即顯示的「Add new disk」(新增磁碟) 窗格中,執行下列操作:

      1. 在「Name」(名稱) 欄位中,指定非啟動磁碟的名稱。
      2. 在「Disk source type」(磁碟來源類型) 清單中,選取非開機磁碟的來源類型。
      3. 在「Disk type」(磁碟類型) 清單中,選取非開機磁碟的類型。
      4. 在「Size」(大小) 欄位中,指定非開機磁碟的大小。
      5. 在「附件設定」部分,執行下列操作:
      6. 在「模式」欄位中,選取磁碟附加模式。
      7. 在「Deletion rule」(刪除規則) 欄位中選取選項,指定刪除執行個體時磁碟的處理方式。

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

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

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

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

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

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

      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

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

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/protobuf/proto"
)

// 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

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

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

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const 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

在試用這個範例之前,請先按照Python使用用戶端程式庫的 Compute Engine 快速入門」中的操作說明進行設定。詳情請參閱 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:磁碟類型類型的完整或部分網址。例如: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 的 VPC 網路。如要使用預設網路,請指定 default
  • ENABLE_SECURE_BOOT:選用:如果您選擇支援受防護 VM 功能的映像檔,Compute Engine 預設會啟用虛擬信任平台模組 (vTPM)完整性監控。Compute Engine 預設不會啟用安全啟動

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

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