在特定子網路中建立執行個體


根據預設,每個執行個體都會有一個網路介面,用來決定執行個體使用的虛擬私有雲網路。您可以建立具有多個網路介面的執行個體,但每個介面都必須連線至不同的 VPC 網路。每個網路都必須至少有一個子網路,定義可指派給執行個體的 IPv4 或 IPv6 位址範圍。

如要瞭解詳情,請參考下列資源:

根據預設, Google Cloud 會針對每個專案建立名為 default自動模式虛擬私人雲端網路。如要使用在自動模式或自訂模式虛擬私有雲網路中手動建立的其他網路或子網路,您必須在建立執行個體及設定網路介面時指定子網路。

事前準備

  • 如果尚未設定,請先設定驗證機制。驗證是指驗證身分,以便存取 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.subnetworks.use 在專案或所選子網路上
  • 如要在使用虛擬私有雲網路時,將外部 IP 位址指派給執行個體: compute.subnetworks.useExternalIp 專案或所選子網路

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

需求條件

在子網路中建立執行個體時,請考量下列規則:

  • 如果您未指定網路或子網路,Compute Engine 會使用預設虛擬私有雲網路,以及位於執行個體所在地區的自動子網路。
  • 如果您未指定網路,Compute Engine 會從指定的子網路推斷網路。
  • 如果您指定網路,則必須指定子網路,且該子網路必須屬於同一個網路。否則,執行個體建立作業會失敗。

建立執行個體之前,您必須先建立要使用的子網路。詳情請參閱「建立及管理虛擬私有雲網路」。

在特定子網路中建立執行個體

如要在特定子網路中建立執行個體,請按照下列步驟操作:

主控台

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

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

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

    系統隨即會顯示「Create an instance」(建立執行個體) 頁面,並顯示「Machine configuration」(機器設定) 窗格。

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

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

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

    3. 選取執行個體的機器系列。Google Cloud Console 隨後會顯示可用於所選機器系列的機器系列。可用的機器系列選項如下:

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

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

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

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

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

    1. 如要允許執行個體接收 HTTP 或 HTTPS 流量,請前往「防火牆」區段,然後選取「允許 HTTP 流量」或「允許 HTTPS 流量」

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

    2. 如要指定網路介面詳細資料,請前往「Network interfaces」(網路介面) 專區,然後按一下「Add a network interface」(新增網路介面)

      在隨即顯示的「New network interface」專區中,執行下列操作:

      1. 在「Network」(網路) 欄位中,選取包含您所建立之子網路的虛擬私人雲端網路。
      2. 在「Subnetwork」(子網路) 清單中,選取執行個體要使用的子網路。
      3. 在「IP 堆疊類型」欄位中,選取網路介面的 IP 堆疊類型。
      4. 如要確認網路介面詳細資料,請按一下「Done」
  4. 選用:指定其他設定選項。詳情請參閱「建立執行個體時的設定選項」。

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

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. 使用 Google Cloud CLI,按照相同的操作說明透過公開映像檔建立執行個體透過快照建立執行個體,然後在執行 gcloud compute instances create 指令時加入本節所述的網路旗標:

    gcloud compute instances create INSTANCE_NAME \
        --zone=ZONE \
        --machine-type=MACHINE_TYPE \
        --create-disk=boot=yes,image=projects/IMAGE_PROJECT/global/images/IMAGE,size=SIZE \
        --network=NETWORK_NAME \
        --subnet=SUBNET_NAME \
        --stack-type=STACK_TYPE \
        --private-network-ip=INTERNAL_IPV4_ADDRESS \
        --address=EXTERNAL_IPV4_ADDRESS \
        --nic-type=GVNIC
    

    更改下列內容:

    • INSTANCE_NAME:運算執行個體的名稱
    • ZONE:建立執行個體的區域,例如 europe-west1-b。執行個體的地區是從區域推測得出。
    • MACHINE_TYPE:選用:要用於執行個體的機器類型。
    • IMAGE_PROJECT:選用:包含圖片的圖片專案
    • IMAGE:選用:指定下列其中一個:
      • 特定 OS 映像檔版本,例如 rocky-linux-9-optimized-gcp-v20240717
      • 映像檔系列,格式必須為 family/IMAGE_FAMILY。這麼做會使用最新的非淘汰作業系統映像檔建立執行個體。舉例來說,如果您指定 family/rocky-linux-9-optimized-gcp,Compute Engine 會使用 Rocky Linux 9 中最新版本的 OS 映像檔建立執行個體,該映像檔已針對Google Cloud 映像檔系列進行最佳化。如要進一步瞭解如何使用映像檔系列,請參閱「映像檔系列最佳做法」。
    • SIZE:選用:新磁碟的大小。值必須為整數。預設的測量單位為 GiB。
    • NETWORK_NAME:選用:聯播網名稱
    • SUBNET_NAME:與執行個體搭配使用的子網路名稱。

      如要查看網路中的子網路清單,請使用 gcloud compute networks subnets list 指令

    • STACK_TYPE:選用:網路介面的堆疊類型。STACK_TYPE 必須是下列其中一個:IPV4_ONLYIPV4_IPV6IPV6_ONLY (預覽)。預設值為 IPV4_ONLY

    • INTERNAL_IPV4_ADDRESS:選用:您希望計算機執行個體在目標子網路中使用的內部 IPv4 位址。如果不需要特定 IP 位址,請略過這個旗標。

      如要指定內部 IPv6 位址,請改用 --internal-ipv6-address 標記。

    • EXTERNAL_IPV4_ADDRESS:選用:要與網路介面搭配使用的靜態外部 IPv4 位址。您必須先保留外部 IPv4 位址。執行下列其中一個步驟:

      • 指定子網路中的有效 IPv4 位址。
      • 如果不希望網路介面有外部 IP 位址,請改用 --network-interface=no-address 旗標。
      • 如果您希望介面接收臨時外部 IP 位址,請指定 address=''

      如要指定外部 IPv6 位址,請改用 --external-ipv6-address 標記。

Terraform

如要在特定子網路中建立執行個體,您可以使用 google_compute_instance 資源


# Create a VM in a custom VPC network and subnet

resource "google_compute_instance" "custom_subnet" {
  name         = "my-vm-instance"
  tags         = ["allow-ssh"]
  zone         = "europe-west1-b"
  machine_type = "e2-small"
  network_interface {
    network    = google_compute_network.custom.id
    subnetwork = google_compute_subnetwork.custom.id
  }
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-12"
    }
  }
}

如要瞭解如何套用或移除 Terraform 設定,請參閱「基本 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"
)

// createInstanceWithSubnet creates a new VM instance with Debian 10 operating system in specified network and subnetwork.
func createInstanceWithSubnet(w io.Writer, projectID, zone, instanceName, networkLink, subnetworkLink string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// networkLink := "global/networks/default"
	// subnetworkLink := "regions/region/subnetworks/subnetwork_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()),
				},
			},
			MachineType: proto.String(fmt.Sprintf("zones/%s/machineTypes/n1-standard-1", zone)),
			NetworkInterfaces: []*computepb.NetworkInterface{
				{
					Name:       proto.String(networkLink),
					Subnetwork: proto.String(subnetworkLink),
				},
			},
		},
	}

	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;
  }


  /**
   * 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);
    }
  }

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 networkLink = 'global/networks/default';
// const subnetworkLink = 'regions/europe-central2/subnetworks/default';

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

// Creates a new VM instance with Debian 10 operating system in specified network and subnetwork.
async function createInstanceWithSubnet() {
  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',
        },
      ],
      machineType: `zones/${zone}/machineTypes/n1-standard-1`,
      networkInterfaces: [
        {
          name: networkLink,
          subnetwork: subnetworkLink,
        },
      ],
    },
  });
  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.');
}

createInstanceWithSubnet();

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 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_subnet(
    project_id: str, zone: str, instance_name: str, network_link: str, subnet_link: str
) -> compute_v1.Instance:
    """
    Create a new VM instance with Debian 10 operating system in specified network and subnetwork.

    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.
        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}"

    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, 10, True, newest_debian.self_link)]
    instance = create_instance(
        project_id,
        zone,
        instance_name,
        disks,
        network_link=network_link,
        subnetwork_link=subnet_link,
    )
    return instance

REST

請按照 REST 操作說明從公開映像檔或快照建立執行個體,但須在要求主體中指定 subnet 欄位。

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
      }
   ],
   
   
   "networkInterfaces":[
      {
         "network":"global/networks/NETWORK_NAME",
         "subnetwork":"regions/REGION/subnetworks/SUBNET_NAME",
         "stackType":"STACK_TYPE"
      }
   ],
   
  
   "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。

  • NETWORK_NAME:選用:您要用於 VM 的 VPC 網路。您可以指定 default 使用預設網路。
  • REGION:指定子網路所在的區域。必須與 VM 位於相同的區域。
  • SUBNET_NAME:要使用的子網路名稱
  • STACK_TYPE:選用:網路介面的堆疊類型。您可以指定 IPV4_ONLYIPV4_IPV6IPV6_ONLY 其中之一 (預覽)。預設值為 IPV4_ONLY
  • ENABLE_SECURE_BOOT:選用:如果您選擇支援受防護 VM 功能的映像檔,Compute Engine 預設會啟用虛擬信任平台模組 (vTPM)完整性監控。Compute Engine 預設不會啟用安全啟動

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

後續步驟