使用保留項目


本文說明如何在 Compute Engine 中使用預留項目。如要瞭解如何在其他 Google Cloud 產品中使用預訂,請參閱下列說明文件:

建立預留項目後,或 Compute Engine 自動為您建立預留項目以滿足未來預留需求時,Compute Engine 會為您保留預留資源。接著,您可以使用這些預留資源,建立符合預留項目屬性的 Compute Engine 執行個體。這項動作稱為「預訂保留」。在預留容量完全用盡前,您都可以使用預留容量建立執行個體。

限制

您無法使用預留項目建立下列 Compute Engine 資源:

  • Spot VM 或先占執行個體

  • 單一用戶群節點

事前準備

必要的角色

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

這個預先定義的角色具備使用預訂項目所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要使用預留項目,必須具備下列權限:

  • 如要建立預留項目: 專案的 compute.reservations.create
  • 如要建立執行個體,請按照下列步驟操作:
    • 專案的 compute.instances.create 權限
    • 如要使用自訂映像檔建立 VM,請按一下映像檔上的 compute.images.useReadOnly
    • 如要使用快照建立 VM,請按一下快照上的 compute.snapshots.useReadOnly
    • 如要使用執行個體範本建立 VM,請按一下執行個體範本上的 compute.instanceTemplates.useReadOnly
    • 如要將舊版網路指派給 VM:專案的 compute.networks.use
    • 如要為 VM 指定靜態 IP 位址,請在專案中擁有 compute.addresses.use 權限
    • 使用舊版網路時,如要將外部 IP 位址指派給 VM,請在專案中設定 compute.networks.useExternalIp
    • 為 VM 指定子網路:專案或所選子網路的 compute.subnetworks.use
    • 使用虛擬私有雲網路時,如要將外部 IP 位址指派給 VM,請在專案或所選子網路上擁有 compute.subnetworks.useExternalIp 權限
    • 如要為專案中的 VM 設定 VM 執行個體中繼資料,請執行下列指令:compute.instances.setMetadata
    • 如要為 VM 設定標記,請在 VM 上按一下 compute.instances.setTags
    • 如要為 VM 設定標籤,請在 VM 上執行下列步驟:compute.instances.setLabels
    • 如要設定 VM 使用的服務帳戶,請在 VM 上執行 compute.instances.setServiceAccount
    • 如要為 VM 建立新磁碟,請取得專案的 compute.disks.create 權限
    • 如要以唯讀或讀寫模式連接現有磁碟,請對磁碟擁有 compute.disks.use 權限
    • 如要以唯讀模式連接現有磁碟,請對磁碟擁有 compute.disks.useReadOnly 權限
  • 如要建立執行個體範本: 按一下專案上的 compute.instanceTemplates.create

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

使用預留項目

以下各節的範例說明如何建立單一運算執行個體,藉此使用預留項目。您也可以使用其他部署選項建立符合保留項目屬性的執行個體,或是更新現有執行個體的屬性,使其符合自動使用的保留項目,藉此使用保留項目。

如要使用預留項目,請採取下列其中一種做法:

使用自動耗用的預留項目

建立自動耗用的預留項目後,符合預留項目屬性的運算執行個體就會自動耗用該預留項目。這項消耗行為適用於新執行個體和現有執行個體。建立預留項目時,或是 Compute Engine 自動建立預留項目來滿足未來預留項目時,這個預留項目類型是預設設定。

如果單一專案自動預留項目和共用自動預留項目的屬性相符,專案中的執行個體會先使用單一專案預留項目,然後再使用共用預留項目。詳情請參閱「預留項目的消耗順序」。

如要建立及使用範例自動預留項目,請選取下列任一選項:

主控台

以下範例說明如何在區域 us-central1-a 中建立自動保留項目,保留三個 N2 執行個體,每個執行個體有 32 個 vCPU,並以 Intel Cascade Lake 做為最低 CPU 平台。並說明如何建立單一執行個體來使用預留項目。

如要建立範例自動預留項目並加以使用,請按照下列步驟操作:

  1. 如要建立範例預留項目,請完成下列步驟:

    1. 在 Google Cloud 控制台,前往「Reservations」(預留項目) 頁面。

      前往「預留項目」頁面

      其餘步驟會自動顯示在Google Cloud 控制台。

    2. 在「隨需預留項目」分頁 (預設) 中,按一下 「建立預留項目」。「Create a reservation」(建立預留項目) 頁面隨即顯示。

    3. 在「Name」(名稱) 欄位中,輸入預留項目的名稱,例如:輸入 reservation-01

    4. 選取要預留資源的「Region」(區域) 和「Zone」(可用區)。例如,分別選取「us-central1」和「us-central1-a」

    5. 在「分享類型」部分,執行下列任一操作:

      • 如要建立單一專案預留項目,請選取「本機」

      • 如要建立共用預訂,請選取「共用」,然後指定要共用預訂的專案。

    6. 在「Use with VM instance」(搭配 VM 執行個體使用) 區段中,選取「Use reservation automatically」(自動使用保留項目) (如果尚未選取)。

    7. 在「Number of VM instances」(VM 執行個體數量) 欄位中,輸入 3

    8. 在「一般用途」分頁中,選取「N2」

    9. 在「Machine type」(機型) 部分,選取「Preset」(預設) 分頁 (預設),然後選取「n2-standard-32」

    10. 展開「CPU platform and GPU」(CPU 平台和 GPU),然後在「CPU platform」(CPU 平台) 欄位中選取「Intel Cascade Lake or later」(Intel Cascade Lake 以上版本)

    11. 點選「建立」

  2. 如要建立使用範例預留項目的執行個體,請完成下列步驟:

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

      前往「建立執行個體」

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

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

      1. 在「Name」(名稱) 欄位中,輸入執行個體的名稱。在本範例中,請輸入 instance-01

      2. 指定要預留資源的「Region」(區域) 和「Zone」(可用區)。 在本範例中,請分別選取 us-central1us-central1-a

      3. 在「一般用途」分頁中,選取「N2」

      4. 在「Machine type」(機型) 部分,選取「Preset」(預設) 分頁 (預設),然後選取「n2-standard-32」

      5. 展開「Advanced options」(進階選項) 區段,然後在「CPU platform」(CPU 平台) 欄位中,選取「Intel Cascade Lake or later」(Intel Cascade Lake 以上版本)

    3. 選用:根據預設,系統會自動使用相符的預留項目。不過,如要指定這項設定,請按照下列步驟操作:

      1. 在導覽選單中,按一下「進階」。系統會顯示「進階」窗格。

      2. 在「預留項目」部分,選取「使用自動選取功能」

    4. 點選「建立」

gcloud

以下範例說明如何在區域 us-central1-a 中建立自動保留項目,保留三個 N2 執行個體,每個執行個體有 32 個 vCPU,並以 Intel Cascade Lake 做為最低 CPU 平台。並說明如何建立單一執行個體來使用預留項目。

如要建立範例自動預留項目並加以使用,請按照下列步驟操作:

  1. 如要建立範例預留項目,請使用 gcloud compute reservations create 指令

    gcloud compute reservations create reservation-01 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --vm-count=3 \
        --zone=us-central1-a
    
  2. 如要建立使用範例預訂項目的執行個體,請使用 gcloud compute instances create 指令,並將 --reservation-affinity 旗標設為 any。由於 any 是預設設定,因此您也可以省略這個旗標。

    gcloud compute instances create instance-01 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --reservation-affinity=any \
        --zone=us-central1-a
    

Go

如要使用執行個體範本建立範例自動預留項目,並使用相同範本建立執行個體來使用預留項目,請使用下列程式碼範例:

import (
	"context"
	"fmt"
	"io"

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

// consumeAnyReservation creates instance, consuming any available reservation
func consumeAnyReservation(w io.Writer, projectID, zone, instanceName, sourceTemplate string) error {
	// projectID := "your_project_id"
	// zone := "us-west3-a"
	// instanceName := "your_instance_name"
	// sourceTemplate: existing template path. Following formats are allowed:
	//  	- projects/{project_id}/global/instanceTemplates/{template_name}
	//  	- projects/{project_id}/regions/{region}/instanceTemplates/{template_name}
	//  	- https://www.googleapis.com/compute/v1/projects/{project_id}/global/instanceTemplates/instanceTemplate
	//  	- https://www.googleapis.com/compute/v1/projects/{project_id}/regions/{region}/instanceTemplates/instanceTemplate

	ctx := context.Background()

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

	req := &computepb.InsertInstanceRequest{
		Project:                projectID,
		Zone:                   zone,
		SourceInstanceTemplate: proto.String(sourceTemplate),
		InstanceResource: &computepb.Instance{
			Name: proto.String(instanceName),
			// specifies that any matching reservation should be consumed
			ReservationAffinity: &computepb.ReservationAffinity{
				ConsumeReservationType: proto.String("ANY_RESERVATION"),
			},
		},
	}

	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 from reservation\n")

	return nil
}

Java

下列範例說明如何在 us-central1-a 區域中,建立具有四個 vCPU 的 N1 執行個體,並將 Intel Skylake 設為最低 CPU 平台。執行個體會自動使用相符的預留項目。

如要建立範例執行個體,請使用下列程式碼範例:

import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.ANY_RESERVATION;

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
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 com.google.cloud.compute.v1.ReservationAffinity;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ConsumeAnyMatchingReservation {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Zone where the VM instance will be created.
    String zone = "us-central1-a";
    // Name of the VM instance you want to query.
    String instanceName = "YOUR_INSTANCE_NAME";
    // machineType: machine type of the VM being created.
    // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
    String machineTypeName = "n1-standard-4";
    // sourceImage: path to the operating system image to mount.
    // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
    String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
    // diskSizeGb: storage size of the boot disk to attach to the instance.
    long diskSizeGb = 10L;
    // networkName: network interface to associate with the instance.
    String networkName = "default";
    // Minimum CPU platform of the instances.
    String minCpuPlatform = "Intel Skylake";

    createInstanceAsync(projectId, zone, instanceName, machineTypeName, sourceImage,
        diskSizeGb, networkName, minCpuPlatform);
  }

  // Create a virtual machine targeted with the reserveAffinity field.
  // In this consumption model, existing and new VMs automatically consume a reservation
  // if their properties match the VM properties specified in the reservation.
  public static Instance createInstanceAsync(String projectId, String zone,
      String instanceName, String machineTypeName, String sourceImage,
      long diskSizeGb, String networkName, String minCpuPlatform)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    String machineType = String.format("zones/%s/machineTypes/%s", zone, machineTypeName);
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (InstancesClient instancesClient = InstancesClient.create()) {
      AttachedDisk disk =
          AttachedDisk.newBuilder()
              .setBoot(true)
              .setAutoDelete(true)
              .setType(AttachedDisk.Type.PERSISTENT.toString())
              .setDeviceName("disk-1")
              .setInitializeParams(
                  AttachedDiskInitializeParams.newBuilder()
                      .setSourceImage(sourceImage)
                      .setDiskSizeGb(diskSizeGb)
                      .build())
              .build();

      NetworkInterface networkInterface = NetworkInterface.newBuilder()
          .setName(networkName)
          .build();

      ReservationAffinity reservationAffinity =
          ReservationAffinity.newBuilder()
              .setConsumeReservationType(ANY_RESERVATION.toString())
              .build();

      Instance instanceResource =
          Instance.newBuilder()
              .setName(instanceName)
              .setMachineType(machineType)
              .addDisks(disk)
              .addNetworkInterfaces(networkInterface)
              .setMinCpuPlatform(minCpuPlatform)
              .setReservationAffinity(reservationAffinity)
              .build();

      InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setInstanceResource(instanceResource)
          .build();

      OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
          insertInstanceRequest);

      Operation response = operation.get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        return null;
      }
      return instancesClient.get(projectId, zone, instanceName);
    }
  }
}

Node.js

下列範例說明如何在 us-central1-a 區域中,建立具有四個 vCPU 的 N1 執行個體,並將 Intel Skylake 設為最低 CPU 平台。執行個體會自動使用相符的預留項目。

如要建立範例執行個體,請使用下列程式碼範例:

// Import the Compute library
const computeLib = require('@google-cloud/compute');
const compute = computeLib.protos.google.cloud.compute.v1;

// Instantiate a reservationsClient
const instancesClient = new computeLib.InstancesClient();
// Instantiate a zoneOperationsClient
const zoneOperationsClient = new computeLib.ZoneOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The ID of the project where you want to create instance.
const projectId = await instancesClient.getProjectId();
// The zone in which to create instance.
const zone = 'us-central1-a';
// The name of the instance to create.
// const instanceName = 'instance-01';
// Machine type to use for VM.
const machineType = 'n1-standard-4';

// Create instance to consume reservation if their properties match the VM properties
async function callCreateInstanceToConsumeAnyReservation() {
  // Describe the size and source image of the boot disk to attach to the instance.
  const disk = new compute.Disk({
    boot: true,
    autoDelete: true,
    type: 'PERSISTENT',
    initializeParams: {
      diskSizeGb: '10',
      sourceImage: 'projects/debian-cloud/global/images/family/debian-12',
    },
  });

  //  Define networkInterface
  const networkInterface = new compute.NetworkInterface({
    name: 'global/networks/default',
  });

  // Define reservationAffinity
  const reservationAffinity = new compute.ReservationAffinity({
    consumeReservationType: 'ANY_RESERVATION',
  });

  // Create an instance
  const instance = new compute.Instance({
    name: instanceName,
    machineType: `zones/${zone}/machineTypes/${machineType}`,
    minCpuPlatform: 'Intel Skylake',
    disks: [disk],
    networkInterfaces: [networkInterface],
    reservationAffinity,
  });

  const [response] = await instancesClient.insert({
    project: projectId,
    instanceResource: instance,
    zone,
  });

  let operation = response.latestResponse;

  // Wait for the create instance operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await zoneOperationsClient.wait({
      operation: operation.name,
      project: projectId,
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log(`Instance ${instanceName} created.`);
}

await callCreateInstanceToConsumeAnyReservation();

Python

以下範例說明如何在區域 us-central1-a 中建立自動預留項目,供三個 N1 執行個體使用,每個執行個體有一個 vCPU,且最低 CPU 平台為 Intel Ivy。並說明如何建立單一執行個體來使用預留項目。

如要建立範例自動預留項目並加以使用,請按照下列步驟操作:

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def consume_any_project_reservation(
    project_id: str,
    zone: str,
    reservation_name: str,
    instance_name: str,
    machine_type: str = "n1-standard-1",
    min_cpu_platform: str = "Intel Ivy Bridge",
) -> compute_v1.Instance:
    """
    Creates a specific reservation in a single project and launches a VM
    that consumes the newly created reservation.
    Args:
        project_id (str): The ID of the Google Cloud project.
        zone (str): The zone to create the reservation.
        reservation_name (str): The name of the reservation to create.
        instance_name (str): The name of the instance to create.
        machine_type (str): The machine type for the instance.
        min_cpu_platform (str): The minimum CPU platform for the instance.
    """
    instance_properties = (
        compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
            machine_type=machine_type,
            min_cpu_platform=min_cpu_platform,
        )
    )

    reservation = compute_v1.Reservation(
        name=reservation_name,
        specific_reservation=compute_v1.AllocationSpecificSKUReservation(
            count=3,
            instance_properties=instance_properties,
        ),
    )

    # Create a reservation client
    client = compute_v1.ReservationsClient()
    operation = client.insert(
        project=project_id,
        zone=zone,
        reservation_resource=reservation,
    )
    wait_for_extended_operation(operation, "Reservation creation")

    instance = compute_v1.Instance()
    instance.name = instance_name
    instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
    instance.min_cpu_platform = min_cpu_platform
    instance.zone = zone

    # Set the reservation affinity to target any matching reservation
    instance.reservation_affinity = compute_v1.ReservationAffinity(
        consume_reservation_type="ANY_RESERVATION",  # Type of reservation to consume
    )
    # Define the disks for the instance
    instance.disks = [
        compute_v1.AttachedDisk(
            boot=True,  # Indicates that this is a boot disk
            auto_delete=True,  # The disk will be deleted when the instance is deleted
            initialize_params=compute_v1.AttachedDiskInitializeParams(
                source_image="projects/debian-cloud/global/images/family/debian-11",
                disk_size_gb=10,
            ),
        )
    ]
    instance.network_interfaces = [
        compute_v1.NetworkInterface(
            network="global/networks/default",  # The network to use
            access_configs=[
                compute_v1.AccessConfig(
                    name="External NAT",  # Name of the access configuration
                    type="ONE_TO_ONE_NAT",  # Type of access configuration
                )
            ],
        )
    ]
    # Create a request to insert the instance
    request = compute_v1.InsertInstanceRequest()
    request.zone = zone
    request.project = project_id
    request.instance_resource = instance

    vm_client = compute_v1.InstancesClient()
    operation = vm_client.insert(request)
    wait_for_extended_operation(operation, "instance creation")
    print(f"Instance {instance_name} that targets any open reservation created.")

    return vm_client.get(project=project_id, zone=zone, instance=instance_name)

REST

以下範例說明如何在區域 us-central1-a 中建立自動保留項目,保留三個 N2 執行個體,每個執行個體有 32 個 vCPU,並以 Intel Cascade Lake 做為最低 CPU 平台。並說明如何建立單一執行個體來使用預留項目。

如要建立範例自動預留項目並加以使用,請按照下列步驟操作:

  1. 如要建立範例預留項目,請對 reservations.insert 方法發出 POST 要求:

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations
    
    {
      "name": "reservation-01",
      "specificReservation": {
        "count": "3",
        "instanceProperties": {
          "machineType": "n2-standard-32",
          "minCpuPlatform": "Intel Cascade Lake",
        }
      }
    }
    
  2. 如要建立使用範例預留項目的執行個體,請對 instances.insert 方法發出 POST 要求。在要求主體中,加入設為 ANY_RESERVATIONconsumeReservationType 欄位。不過,由於 ANY_RESERVATION 是預設設定,您也可以省略這個欄位。

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/instances
    
    {
      "name": "instance-01",
      "machineType": "zones/us-central1-a/machineTypes/n2-standard-32",
      "minCpuPlatform": "Intel Cascade Lake",
      "disks": [
        {
          "boot": true,
          "initializeParams": {
            "sourceImage": "projects/debian-cloud/global/images/family/debian-12"
          }
        }
      ],
      "networkInterfaces": [
        {
          "network": "global/networks/default"
        }
      ],
      "reservationAffinity": {
        "consumeReservationType": "ANY_RESERVATION"
      }
    }
    

使用明確指定的預留項目

明確指定的預留項目允許新的運算執行個體使用相符的預留項目,但前提是執行個體必須指定該預留項目。只有在執行個體的屬性與預留項目屬性相符時,系統才會成功建立執行個體。否則會發生錯誤。

根據您要使用的建立方法,建立特定保留項目和指定這些項目的執行個體,方法如下:

建立方式 建立預留項目時 建立執行個體時
Google Cloud 控制台 在「Use with VM instance」(搭配 VM 執行個體使用) 部分,選取「Select specific reservation」(選取特定保留項目) 在「進階」窗格的「預留項目」部分,選取「選擇預留項目」
Google Cloud CLI 加上 --require-specific-reservation 旗標。 請加入下列旗標:
  • --reservation-affinity 旗標設為 specific
  • --reservation 旗標設為預訂的網址。
Go 加入設為 trueSpecificReservationRequired 欄位。 ReservationAffinity 欄位中,加入下列欄位:
  • ConsumeReservationType 欄位設為 SPECIFIC_RESERVATION
  • Key 欄位設為 compute.googleapis.com/reservation-name
  • Values 欄位設為預訂網址。
Java 加入設為 truesetSpecificReservationRequired 欄位。 ReservationAffinity 欄位中,加入下列欄位:
  • setConsumeReservationType 欄位設為 SPECIFIC_RESERVATION
  • setKey 欄位設為 compute.googleapis.com/reservation-name
  • addValues 欄位設為預訂網址。
Node.js 和 REST API 加入設為 truespecificReservationRequired 欄位。 reservationAffinity 欄位中,加入下列欄位:
  • consumeReservationType 欄位設為 SPECIFIC_RESERVATION
  • key 欄位設為 compute.googleapis.com/reservation-name
  • values 欄位設為預訂網址。
Python 和 Terraform 加入設為 truespecific_reservation_required 欄位。 reservation_affinity 欄位中,加入下列欄位:
  • consume_reservation_type 欄位設為 SPECIFIC_RESERVATION
  • key 欄位設為 compute.googleapis.com/reservation-name
  • values 欄位設為預訂網址。

如要建立範例專屬預留項目和使用該項目的執行個體,請選取下列任一選項:

主控台

以下範例說明如何在 us-central1-a 區域中,為三個 N2 執行個體建立特定預訂,這些執行個體具有 32 個 vCPU,且最低 CPU 平台為 Intel Cascade Lake。並說明如何建立單一執行個體來使用預留項目。

如要建立範例專屬預留項目並加以使用,請按照下列步驟操作:

  1. 如要建立範例預留項目,請完成下列步驟:

    1. 在 Google Cloud 控制台,前往「Reservations」(預留項目) 頁面。

      前往「預留項目」頁面

      其餘步驟會自動顯示在Google Cloud 控制台。

    2. 在「隨需預留項目」分頁 (預設) 中,按一下 「建立預留項目」。「Create a reservation」(建立預留項目) 頁面隨即顯示。

    3. 在「Name」(名稱) 欄位中,輸入預留項目的名稱,例如:輸入 reservation-02

    4. 指定要預留資源的「區域」和「可用區」。在本範例中,請分別選取「us-central1」和「us-central1-a」

    5. 在「分享類型」部分,執行下列任一操作:

      • 如要建立單一專案預留項目,請選取「本機」

      • 如要建立共用預訂,請選取「共用」,然後指定要共用預訂的專案。

    6. 在「Use with VM instance」(搭配 VM 執行個體使用) 部分,選取「Select specific reservation」(選取特定保留項目)

    7. 在「Number of VM instances」(VM 執行個體數量) 欄位中,輸入 3

    8. 在「一般用途」分頁中,選取「N2」

    9. 在「Machine type」(機型) 部分,選取「Preset」(預設) 分頁 (預設),然後選取「n2-standard-32」

    10. 展開「CPU platform and GPU」(CPU 平台和 GPU),然後在「CPU platform」(CPU 平台) 欄位中選取「Intel Cascade Lake or later」(Intel Cascade Lake 以上版本)

    11. 點選「建立」

  2. 如要建立使用範例預留項目的執行個體,請完成下列步驟:

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

      前往「建立執行個體」

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

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

      1. 在「Name」(名稱) 欄位中,輸入執行個體的名稱。在本範例中,請輸入 instance-02

      2. 指定要預留資源的「區域」和「可用區」。在本範例中,請分別選取「us-central1」和「us-central1-a」

      3. 在「一般用途」分頁中,選取「N2」

      4. 在「Machine type」(機型) 部分,選取「Preset」(預設) 分頁 (預設),然後選取「n2-standard-32」

      5. 展開「Advanced options」(進階選項) 區段,然後在「CPU platform」(CPU 平台) 欄位中,選取「Intel Cascade Lake or later」(Intel Cascade Lake 以上版本)

    3. 在導覽選單中,按一下「進階」。系統會顯示「進階」窗格。

    4. 在「Reservations」(預留項目) 部分,選取「Choose a reservation」(選取預留項目),然後點選「Choose reservation」(選取預留項目)

    5. 在隨即顯示的「選擇預留項目」窗格中,執行下列操作:

      1. 選取您在前述步驟中建立的特定預留項目。如要使用其他專案中的共用預留項目,請在「專案」清單中選取預留項目所在的專案。

      2. 按一下「選擇」

    6. 點選「建立」

gcloud

以下範例說明如何在 us-central1-a 區域中,為三個 N2 執行個體建立特定預訂,這些執行個體具有 32 個 vCPU,且最低 CPU 平台為 Intel Cascade Lake。並說明如何建立單一執行個體來使用預留項目。

如要建立範例專屬預留項目並加以使用,請按照下列步驟操作:

  1. 如要建立範例預訂,請使用 gcloud compute reservations create 指令搭配 --require-specific-reservation 旗標:

    gcloud compute reservations create reservation-02 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --require-specific-reservation \
        --vm-count=3 \
        --zone=us-central1-a
    
  2. 如要建立使用範例預留項目的執行個體,請使用 gcloud compute instances create 指令搭配 --reservation--reservation-affinity=specific 旗標:

    gcloud compute instances create instance-02 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --reservation-affinity=specific \
        --reservation=RESERVATION_URL \
        --zone=us-central1-a
    

    RESERVATION_URL 替換為預訂的網址。請指定下列其中一個值:

    • 如果您在同一個專案中建立預留項目: reservation-02

    • 如果保留項目位於其他專案: projects/PROJECT_ID/reservations/reservation-02

Go

以下範例說明如何在 us-central1-a 區域中建立具有 32 個 vCPU 的 N2 執行個體,並將 Intel Cascade Lake 設為最低 CPU 平台,以使用相符的特定預訂項目:

  • 如要建立範例執行個體,以使用單一專案的特定預留項目,請使用下列程式碼範例:

    import (
    	"context"
    	"fmt"
    	"io"
    
    	compute "cloud.google.com/go/compute/apiv1"
    	computepb "cloud.google.com/go/compute/apiv1/computepb"
    	"google.golang.org/protobuf/proto"
    )
    
    // consumeSpecificReservation creates instance, consuming specific reservation
    // Note: respective reservation should have SpecificReservationRequired: true
    func consumeSpecificReservation(w io.Writer, projectID, zone, instanceName, reservationName string) error {
    	// projectID := "your_project_id"
    	// zone := "us-west3-a"
    	// reservationName := "your_reservation_name"
    	// instanceName := "your_instance_name"
    
    	ctx := context.Background()
    	machineType := fmt.Sprintf("zones/%s/machineTypes/%s", zone, "n2-standard-32")
    	sourceImage := "projects/debian-cloud/global/images/family/debian-12"
    
    	instancesClient, err := compute.NewInstancesRESTClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewInstancesRESTClient: %w", err)
    	}
    	defer instancesClient.Close()
    
    	req := &computepb.InsertInstanceRequest{
    		Project: projectID,
    		Zone:    zone,
    		InstanceResource: &computepb.Instance{
    			Disks: []*computepb.AttachedDisk{
    				{
    					InitializeParams: &computepb.AttachedDiskInitializeParams{
    						DiskSizeGb:  proto.Int64(10),
    						SourceImage: proto.String(sourceImage),
    					},
    					AutoDelete: proto.Bool(true),
    					Boot:       proto.Bool(true),
    					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
    				},
    			},
    			MachineType:    proto.String(machineType),
    			MinCpuPlatform: proto.String("Intel Cascade Lake"),
    			Name:           proto.String(instanceName),
    			NetworkInterfaces: []*computepb.NetworkInterface{
    				{
    					Name: proto.String("global/networks/default"),
    				},
    			},
    			// specifies particular reservation, which should be consumed
    			ReservationAffinity: &computepb.ReservationAffinity{
    				ConsumeReservationType: proto.String("SPECIFIC_RESERVATION"),
    				Key:                    proto.String("compute.googleapis.com/reservation-name"),
    				Values:                 []string{reservationName},
    			},
    		},
    	}
    
    	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 from reservation\n")
    
    	return nil
    }
    
  • 如要建立範例執行個體來使用共用的特定預留項目,請使用下列程式碼範例:

    import (
    	"context"
    	"fmt"
    	"io"
    
    	computepb "cloud.google.com/go/compute/apiv1/computepb"
    	"google.golang.org/protobuf/proto"
    )
    
    // consumeSpecificSharedReservation consumes specific shared reservation in particular zone
    func consumeSpecificSharedReservation(w io.Writer, client InstanceClientInterface, projectID, baseProjectId, zone, instanceName, reservationName string) error {
    	// client, err := compute.NewInstancesRESTClient(ctx)
    	// projectID := "your_project_id". Project where reservation is created.
    	// baseProjectId := "shared_project_id". Project where instance will be consumed and created.
    	// zone := "us-west3-a"
    	// reservationName := "your_reservation_name"
    	// instanceName := "your_instance_name"
    
    	ctx := context.Background()
    	machineType := fmt.Sprintf("zones/%s/machineTypes/%s", zone, "n2-standard-32")
    	sourceImage := "projects/debian-cloud/global/images/family/debian-12"
    	sharedReservation := fmt.Sprintf("projects/%s/reservations/%s", baseProjectId, reservationName)
    
    	req := &computepb.InsertInstanceRequest{
    		Project: projectID,
    		Zone:    zone,
    		InstanceResource: &computepb.Instance{
    			Disks: []*computepb.AttachedDisk{
    				{
    					InitializeParams: &computepb.AttachedDiskInitializeParams{
    						DiskSizeGb:  proto.Int64(10),
    						SourceImage: proto.String(sourceImage),
    					},
    					AutoDelete: proto.Bool(true),
    					Boot:       proto.Bool(true),
    					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
    				},
    			},
    			MachineType:    proto.String(machineType),
    			MinCpuPlatform: proto.String("Intel Cascade Lake"),
    			Name:           proto.String(instanceName),
    			NetworkInterfaces: []*computepb.NetworkInterface{
    				{
    					Name: proto.String("global/networks/default"),
    				},
    			},
    			// specifies particular reservation, which should be consumed
    			ReservationAffinity: &computepb.ReservationAffinity{
    				ConsumeReservationType: proto.String("SPECIFIC_RESERVATION"),
    				Key:                    proto.String("compute.googleapis.com/reservation-name"),
    				Values:                 []string{sharedReservation},
    			},
    		},
    	}
    
    	op, err := client.Insert(ctx, req)
    	if err != nil {
    		return fmt.Errorf("unable to create instance: %w", err)
    	}
    
    	if op != nil {
    		if err = op.Wait(ctx); err != nil {
    			return fmt.Errorf("unable to wait for the operation: %w", err)
    		}
    	}
    	fmt.Fprintf(w, "Instance created from shared reservation\n")
    
    	return nil
    }
    

Java

下列範例說明如何在 us-central1-a 區域中建立 N1 執行個體,並指定四個 vCPU 和 Intel Skylake 做為最低 CPU 平台,以使用相符的特定預訂項目:

  • 如要建立範例預留項目做為單一專案預留項目,並建立執行個體來使用該預留項目,請使用下列程式碼範例:

    import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.SPECIFIC_RESERVATION;
    
    import com.google.api.gax.longrunning.OperationFuture;
    import com.google.cloud.compute.v1.AttachedDisk;
    import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
    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 com.google.cloud.compute.v1.ReservationAffinity;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class ConsumeSingleProjectReservation {
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(developer): Replace these variables before running the sample.
        // Project ID or project number of the Cloud project you want to use.
        String projectId = "YOUR_PROJECT_ID";
        // Name of the zone where the reservation is located.
        String zone = "us-central1-a";
        // Name of the reservation you want to query.
        String reservationName = "YOUR_RESERVATION_NAME";
        // Name of the VM instance you want to query.
        String instanceName = "YOUR_INSTANCE_NAME";
        // machineType: machine type of the VM being created.
        // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
        String machineTypeName = "n1-standard-4";
        // sourceImage: path to the operating system image to mount.
        // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
        String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
        // diskSizeGb: storage size of the boot disk to attach to the instance.
        long diskSizeGb = 10L;
        // networkName: network interface to associate with the instance.
        String networkName = "default";
        // Minimum CPU platform of the instances.
        String minCpuPlatform = "Intel Skylake";
    
        createInstanceAsync(projectId, zone, instanceName, reservationName, machineTypeName,
            sourceImage, diskSizeGb, networkName, minCpuPlatform);
      }
    
      // Create a virtual machine targeted with the reserveAffinity field.
      // Ensure that the VM's properties match the reservation's VM properties.
      public static Instance createInstanceAsync(String projectId, String zone, String instanceName,
          String reservationName, String machineTypeName, String sourceImage, long diskSizeGb,
          String networkName, String minCpuPlatform)
          throws IOException, InterruptedException, ExecutionException, TimeoutException {
        String machineType = String.format("zones/%s/machineTypes/%s", zone, machineTypeName);
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (InstancesClient instancesClient = InstancesClient.create()) {
          AttachedDisk disk =
              AttachedDisk.newBuilder()
                  .setBoot(true)
                  .setAutoDelete(true)
                  .setType(AttachedDisk.Type.PERSISTENT.toString())
                  .setDeviceName("disk-1")
                  .setInitializeParams(
                      AttachedDiskInitializeParams.newBuilder()
                          .setSourceImage(sourceImage)
                          .setDiskSizeGb(diskSizeGb)
                          .build())
                  .build();
    
          NetworkInterface networkInterface = NetworkInterface.newBuilder()
              .setName(networkName)
              .build();
    
          ReservationAffinity reservationAffinity =
              ReservationAffinity.newBuilder()
                  .setConsumeReservationType(SPECIFIC_RESERVATION.toString())
                  .setKey("compute.googleapis.com/reservation-name")
                  // Set specific reservation
                  .addValues(reservationName)
                  .build();
    
          Instance instanceResource =
              Instance.newBuilder()
                  .setName(instanceName)
                  .setMachineType(machineType)
                  .addDisks(disk)
                  .addNetworkInterfaces(networkInterface)
                  .setMinCpuPlatform(minCpuPlatform)
                  .setReservationAffinity(reservationAffinity)
                  .build();
    
          InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
              .setProject(projectId)
              .setZone(zone)
              .setInstanceResource(instanceResource)
              .build();
    
          OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
              insertInstanceRequest);
          Operation response = operation.get(3, TimeUnit.MINUTES);
    
          if (response.hasError()) {
            return null;
          }
          return instancesClient.get(projectId, zone, instanceName);
        }
      }
    }
  • 如要建立範例預留項目做為共用預留項目,並建立執行個體來使用該預留項目,請使用下列程式碼範例:

    import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.SPECIFIC_RESERVATION;
    
    import com.google.api.gax.longrunning.OperationFuture;
    import com.google.cloud.compute.v1.AttachedDisk;
    import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
    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 com.google.cloud.compute.v1.ReservationAffinity;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class ConsumeSpecificSharedReservation {
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(developer): Replace these variables before running the sample.
        // Project ID or project number of the Cloud project you want to use.
        String projectId = "YOUR_PROJECT_ID";
        // Name of the zone the reservation is located.
        String zone = "us-central1-a";
        // Name of the reservation you want to query.
        String reservationName = "YOUR_RESERVATION_NAME";
        // Name of the VM instance you want to query.
        String instanceName = "YOUR_INSTANCE_NAME";
        // machineType: machine type of the VM being created.
        // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
        String machineTypeName = "n1-standard-4";
        // sourceImage: path to the operating system image to mount.
        // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
        String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
        // diskSizeGb: storage size of the boot disk to attach to the instance.
        long diskSizeGb = 10L;
        // networkName: network interface to associate with the instance.
        String networkName = "default";
        // Minimum CPU platform of the instances.
        String minCpuPlatform = "Intel Skylake";
    
        createInstanceAsync(projectId, zone, instanceName, reservationName, machineTypeName,
            sourceImage, diskSizeGb, networkName, minCpuPlatform);
      }
    
      // Create a virtual machine targeted with the reserveAffinity field.
      // Ensure that the VM's properties match the reservation's VM properties.
      public static Instance createInstanceAsync(String projectId, String zone, String instanceName,
          String reservationName, String machineTypeName, String sourceImage, long diskSizeGb,
          String networkName, String minCpuPlatform)
          throws IOException, InterruptedException, ExecutionException, TimeoutException {
        String machineType = String.format("zones/%s/machineTypes/%s", zone, machineTypeName);
        // To consume this reservation from any consumer projects that this reservation is shared with,
        // you must also specify the owner project of the reservation - the path to the reservation.
        String reservationPath =
            String.format("projects/%s/reservations/%s", projectId, reservationName);
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (InstancesClient instancesClient = InstancesClient.create()) {
          AttachedDisk disk =
              AttachedDisk.newBuilder()
                  .setBoot(true)
                  .setAutoDelete(true)
                  .setType(AttachedDisk.Type.PERSISTENT.toString())
                  .setDeviceName("disk-1")
                  .setInitializeParams(
                      AttachedDiskInitializeParams.newBuilder()
                          .setSourceImage(sourceImage)
                          .setDiskSizeGb(diskSizeGb)
                          .build())
                  .build();
    
          NetworkInterface networkInterface = NetworkInterface.newBuilder()
              .setName(networkName)
              .build();
    
          ReservationAffinity reservationAffinity =
              ReservationAffinity.newBuilder()
                  .setConsumeReservationType(SPECIFIC_RESERVATION.toString())
                  .setKey("compute.googleapis.com/reservation-name")
                  // Set specific reservation
                  .addValues(reservationPath)
                  .build();
    
          Instance instanceResource =
              Instance.newBuilder()
                  .setName(instanceName)
                  .setMachineType(machineType)
                  .addDisks(disk)
                  .addNetworkInterfaces(networkInterface)
                  .setMinCpuPlatform(minCpuPlatform)
                  .setReservationAffinity(reservationAffinity)
                  .build();
    
          InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
              .setProject(projectId)
              .setZone(zone)
              .setInstanceResource(instanceResource)
              .build();
    
          OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
              insertInstanceRequest);
          Operation response = operation.get(3, TimeUnit.MINUTES);
    
          if (response.hasError()) {
            return null;
          }
          return instancesClient.get(projectId, zone, instanceName);
        }
      }
    }

Node.js

下列範例說明如何在 us-central1-a 區域中建立具有 4 個 vCPU 的 N1 執行個體,並將 Intel Skylake 設為最低 CPU 平台,以使用特定相符的預訂項目:

// Import the Compute library
const computeLib = require('@google-cloud/compute');
const compute = computeLib.protos.google.cloud.compute.v1;

// Instantiate a reservationsClient
const instancesClient = new computeLib.InstancesClient();
// Instantiate a zoneOperationsClient
const zoneOperationsClient = new computeLib.ZoneOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The ID of the project where you want to create instance.
const projectId = await instancesClient.getProjectId();
// The zone in which to create instance.
const zone = 'us-central1-a';
// The name of the instance to create.
// const instanceName = 'instance-01';
// The name of the reservation to consume.
// Ensure that the specificReservationRequired field in reservation properties is set to true.
// const reservationName = 'reservation-01';
// Machine type to use for VM.
const machineType = 'n1-standard-4';

// Create instance to consume a specific single-project reservation
async function callCreateInstanceToConsumeSingleProjectReservation() {
  // Describe the size and source image of the boot disk to attach to the instance.
  // Ensure that the VM's properties match the reservation's VM properties,
  // including the zone, machine type (machine family, vCPUs, and memory),
  // minimum CPU platform, GPU amount and type, and local SSD interface and size
  const disk = new compute.Disk({
    boot: true,
    autoDelete: true,
    type: 'PERSISTENT',
    initializeParams: {
      diskSizeGb: '10',
      sourceImage: 'projects/debian-cloud/global/images/family/debian-12',
    },
  });

  //  Define networkInterface
  const networkInterface = new compute.NetworkInterface({
    name: 'global/networks/default',
  });

  // Define reservationAffinity
  const reservationAffinity = new compute.ReservationAffinity({
    consumeReservationType: 'SPECIFIC_RESERVATION',
    key: 'compute.googleapis.com/reservation-name',
    values: [reservationName],
  });

  // Create an instance
  const instance = new compute.Instance({
    name: instanceName,
    machineType: `zones/${zone}/machineTypes/${machineType}`,
    minCpuPlatform: 'Intel Skylake',
    disks: [disk],
    networkInterfaces: [networkInterface],
    reservationAffinity,
  });

  const [response] = await instancesClient.insert({
    project: projectId,
    instanceResource: instance,
    zone,
  });

  let operation = response.latestResponse;

  // Wait for the create instance operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await zoneOperationsClient.wait({
      operation: operation.name,
      project: projectId,
      zone: operation.zone.split('/').pop(),
    });
  }

  console.log(`Instance ${instanceName} created.`);
}

await callCreateInstanceToConsumeSingleProjectReservation();

Python

以下範例說明如何在 us-central1-a 區域中建立具有 32 個 vCPU 的 N2 執行個體,並將 Intel Cascade Lake 設為最低 CPU 平台,以使用相符的特定預訂項目:

如要建立範例專屬預留項目並加以使用,請按照下列步驟操作:

  • 如要建立及使用範例預留項目做為單一專案預留項目,請使用下列程式碼範例:

    from __future__ import annotations
    
    import sys
    from typing import Any
    
    from google.api_core.extended_operation import ExtendedOperation
    from google.cloud import compute_v1
    
    
    def wait_for_extended_operation(
        operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
    ) -> Any:
        """
        Waits for the extended (long-running) operation to complete.
    
        If the operation is successful, it will return its result.
        If the operation ends with an error, an exception will be raised.
        If there were any warnings during the execution of the operation
        they will be printed to sys.stderr.
    
        Args:
            operation: a long-running operation you want to wait on.
            verbose_name: (optional) a more verbose name of the operation,
                used only during error and warning reporting.
            timeout: how long (in seconds) to wait for operation to finish.
                If None, wait indefinitely.
    
        Returns:
            Whatever the operation.result() returns.
    
        Raises:
            This method will raise the exception received from `operation.exception()`
            or RuntimeError if there is no exception set, but there is an `error_code`
            set for the `operation`.
    
            In case of an operation taking longer than `timeout` seconds to complete,
            a `concurrent.futures.TimeoutError` will be raised.
        """
        result = operation.result(timeout=timeout)
    
        if operation.error_code:
            print(
                f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
                file=sys.stderr,
                flush=True,
            )
            print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
            raise operation.exception() or RuntimeError(operation.error_message)
    
        if operation.warnings:
            print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
            for warning in operation.warnings:
                print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)
    
        return result
    
    
    def consume_specific_single_project_reservation(
        project_id: str,
        zone: str,
        reservation_name: str,
        instance_name: str,
        machine_type: str = "n1-standard-1",
        min_cpu_platform: str = "Intel Ivy Bridge",
    ) -> compute_v1.Instance:
        """
        Creates a specific reservation in a single project and launches a VM
        that consumes the newly created reservation.
        Args:
            project_id (str): The ID of the Google Cloud project.
            zone (str): The zone to create the reservation.
            reservation_name (str): The name of the reservation to create.
            instance_name (str): The name of the instance to create.
            machine_type (str): The machine type for the instance.
            min_cpu_platform (str): The minimum CPU platform for the instance.
        """
        instance_properties = (
            compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
                machine_type=machine_type,
                min_cpu_platform=min_cpu_platform,
            )
        )
    
        reservation = compute_v1.Reservation(
            name=reservation_name,
            specific_reservation=compute_v1.AllocationSpecificSKUReservation(
                count=3,
                instance_properties=instance_properties,
            ),
            # Only VMs that target the reservation by name can consume from this reservation
            specific_reservation_required=True,
        )
    
        # Create a reservation client
        client = compute_v1.ReservationsClient()
        operation = client.insert(
            project=project_id,
            zone=zone,
            reservation_resource=reservation,
        )
        wait_for_extended_operation(operation, "Reservation creation")
    
        instance = compute_v1.Instance()
        instance.name = instance_name
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
        instance.min_cpu_platform = min_cpu_platform
        instance.zone = zone
    
        # Set the reservation affinity to target the specific reservation
        instance.reservation_affinity = compute_v1.ReservationAffinity(
            consume_reservation_type="SPECIFIC_RESERVATION",  # Type of reservation to consume
            key="compute.googleapis.com/reservation-name",  # Key for the reservation
            values=[reservation_name],  # Reservation name to consume
        )
        # Define the disks for the instance
        instance.disks = [
            compute_v1.AttachedDisk(
                boot=True,  # Indicates that this is a boot disk
                auto_delete=True,  # The disk will be deleted when the instance is deleted
                initialize_params=compute_v1.AttachedDiskInitializeParams(
                    source_image="projects/debian-cloud/global/images/family/debian-11",
                    disk_size_gb=10,
                ),
            )
        ]
        instance.network_interfaces = [
            compute_v1.NetworkInterface(
                network="global/networks/default",  # The network to use
                access_configs=[
                    compute_v1.AccessConfig(
                        name="External NAT",  # Name of the access configuration
                        type="ONE_TO_ONE_NAT",  # Type of access configuration
                    )
                ],
            )
        ]
        # Create a request to insert the instance
        request = compute_v1.InsertInstanceRequest()
        request.zone = zone
        request.project = project_id
        request.instance_resource = instance
    
        vm_client = compute_v1.InstancesClient()
        operation = vm_client.insert(request)
        wait_for_extended_operation(operation, "instance creation")
        print(f"Instance {instance_name} with specific reservation created successfully.")
    
        return vm_client.get(project=project_id, zone=zone, instance=instance_name)
    
    
  • 如要建立及使用範例預留項目做為共用預留項目,請使用下列程式碼範例:

    from __future__ import annotations
    
    import sys
    from typing import Any
    
    from google.api_core.extended_operation import ExtendedOperation
    from google.cloud import compute_v1
    
    
    def wait_for_extended_operation(
        operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
    ) -> Any:
        """
        Waits for the extended (long-running) operation to complete.
    
        If the operation is successful, it will return its result.
        If the operation ends with an error, an exception will be raised.
        If there were any warnings during the execution of the operation
        they will be printed to sys.stderr.
    
        Args:
            operation: a long-running operation you want to wait on.
            verbose_name: (optional) a more verbose name of the operation,
                used only during error and warning reporting.
            timeout: how long (in seconds) to wait for operation to finish.
                If None, wait indefinitely.
    
        Returns:
            Whatever the operation.result() returns.
    
        Raises:
            This method will raise the exception received from `operation.exception()`
            or RuntimeError if there is no exception set, but there is an `error_code`
            set for the `operation`.
    
            In case of an operation taking longer than `timeout` seconds to complete,
            a `concurrent.futures.TimeoutError` will be raised.
        """
        result = operation.result(timeout=timeout)
    
        if operation.error_code:
            print(
                f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
                file=sys.stderr,
                flush=True,
            )
            print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
            raise operation.exception() or RuntimeError(operation.error_message)
    
        if operation.warnings:
            print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
            for warning in operation.warnings:
                print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)
    
        return result
    
    
    def consume_specific_shared_project_reservation(
        owner_project_id: str,
        shared_project_id: str,
        zone: str,
        reservation_name: str,
        instance_name: str,
        machine_type: str = "n1-standard-1",
        min_cpu_platform: str = "Intel Ivy Bridge",
    ) -> compute_v1.Instance:
        """
        Creates a specific reservation in a single project and launches a VM
        that consumes the newly created reservation.
        Args:
            owner_project_id (str): The ID of the Google Cloud project.
            shared_project_id: The ID of the owner project of the reservation in the same zone.
            zone (str): The zone to create the reservation.
            reservation_name (str): The name of the reservation to create.
            instance_name (str): The name of the instance to create.
            machine_type (str): The machine type for the instance.
            min_cpu_platform (str): The minimum CPU platform for the instance.
        """
        instance_properties = (
            compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
                machine_type=machine_type,
                min_cpu_platform=min_cpu_platform,
            )
        )
    
        reservation = compute_v1.Reservation(
            name=reservation_name,
            specific_reservation=compute_v1.AllocationSpecificSKUReservation(
                count=3,
                instance_properties=instance_properties,
            ),
            # Only VMs that target the reservation by name can consume from this reservation
            specific_reservation_required=True,
            share_settings=compute_v1.ShareSettings(
                share_type="SPECIFIC_PROJECTS",
                project_map={
                    shared_project_id: compute_v1.ShareSettingsProjectConfig(
                        project_id=shared_project_id
                    )
                },
            ),
        )
    
        # Create a reservation client
        client = compute_v1.ReservationsClient()
        operation = client.insert(
            project=owner_project_id,
            zone=zone,
            reservation_resource=reservation,
        )
        wait_for_extended_operation(operation, "Reservation creation")
    
        instance = compute_v1.Instance()
        instance.name = instance_name
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
        instance.min_cpu_platform = min_cpu_platform
        instance.zone = zone
    
        # Set the reservation affinity to target the specific reservation
        instance.reservation_affinity = compute_v1.ReservationAffinity(
            consume_reservation_type="SPECIFIC_RESERVATION",  # Type of reservation to consume
            key="compute.googleapis.com/reservation-name",
            # To consume this reservation from any consumer projects, specify the owner project of the reservation
            values=[f"projects/{owner_project_id}/reservations/{reservation_name}"],
        )
        # Define the disks for the instance
        instance.disks = [
            compute_v1.AttachedDisk(
                boot=True,  # Indicates that this is a boot disk
                auto_delete=True,  # The disk will be deleted when the instance is deleted
                initialize_params=compute_v1.AttachedDiskInitializeParams(
                    source_image="projects/debian-cloud/global/images/family/debian-11",
                    disk_size_gb=10,
                ),
            )
        ]
        instance.network_interfaces = [
            compute_v1.NetworkInterface(
                network="global/networks/default",  # The network to use
                access_configs=[
                    compute_v1.AccessConfig(
                        name="External NAT",  # Name of the access configuration
                        type="ONE_TO_ONE_NAT",  # Type of access configuration
                    )
                ],
            )
        ]
        # Create a request to insert the instance
        request = compute_v1.InsertInstanceRequest()
        request.zone = zone
        # The instance will be created in the shared project
        request.project = shared_project_id
        request.instance_resource = instance
    
        vm_client = compute_v1.InstancesClient()
        operation = vm_client.insert(request)
        wait_for_extended_operation(operation, "instance creation")
        print(f"Instance {instance_name} from project {owner_project_id} created.")
        # The instance is created in the shared project, so we return it from there.
        return vm_client.get(project=shared_project_id, zone=zone, instance=instance_name)
    
    

REST

以下範例說明如何在 us-central1-a 區域中,為三個 N2 執行個體建立特定預訂,這些執行個體具有 32 個 vCPU,且最低 CPU 平台為 Intel Cascade Lake。並說明如何建立單一執行個體來使用預留項目。

如要建立範例專屬預留項目並加以使用,請按照下列步驟操作:

  1. 如要建立範例預留項目,請對 instances.insert 方法發出 POST 要求。在要求主體中,加入設為 truespecificReservationRequired 欄位:

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations
    
    {
      "name": "reservation-02",
      "specificReservation": {
        "count": "3",
        "instanceProperties": {
          "machineType": "n2-standard-32",
          "minCpuPlatform": "Intel Cascade Lake",
        }
      },
      "specificReservationRequired": true
    }
    
  2. 如要建立使用範例預留項目的執行個體,請對 instances.insert 方法發出 POST 要求。在要求主體的 reservationAffinity 欄位中,加入下列項目:

    • consumeReservationType 欄位設為 SPECIFIC_RESERVATION

    • key 欄位設為 compute.googleapis.com/reservation-name

    • values 欄位設為預訂網址。

    要求類似於下列內容:

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/instances
    
    {
      "name": "instance-02",
      "machineType": "zones/us-central1-a/machineTypes/n2-standard-32",
      "minCpuPlatform": "Intel Cascade Lake",
      "disks": [
        {
          "boot": true,
          "initializeParams": {
            "sourceImage": "projects/debian-cloud/global/images/family/debian-12"
          }
        }
      ],
      "networkInterfaces": [
        {
          "network": "global/networks/default"
        }
      ],
      "reservationAffinity": {
        "consumeReservationType": "SPECIFIC_RESERVATION",
        "key": "compute.googleapis.com/reservation-name",
        "values": [
          "RESERVATION_URL"
        ]
      }
    }
    

    RESERVATION_URL 替換為預訂的網址。請指定下列其中一個值:

    • 如果您在同一個專案中建立預留項目: reservation-02

    • 如果保留項目位於其他專案: projects/PROJECT_ID/reservations/reservation-02

在日曆模式中,針對要求耗用自動建立的預留項目

這類預留項目可供新的運算執行個體耗用,而 Compute Engine 會自動建立預留項目,以滿足日曆模式中的未來預留項目

如要使用這類預留項目,請按照下列方式建立執行個體:

  • 執行個體必須明確指定保留項目

  • 執行個體必須在預留項目結束時間前停止或刪除

  • 執行個體必須使用取決於預留項目佈建模式。建立執行個體時,您可以指定這個模型,如下所示:

    • 在 Google Cloud 控制台中,如果您在日曆模式中為未來預留項目指定支援的機器類型,系統會自動選取與預留項目綁定的模型。

    • 在 gcloud CLI 中,加入設為 reservation-bound--provisioning-model 旗標。

    • 在 REST API 中,加入設為 RESERVATION_BOUNDprovisioningModel 欄位。

以下範例會在日曆模式中建立 A3 Ultra 執行個體的未來預留要求。這個範例也顯示建立獨立 A3 Ultra 執行個體時要指定的欄位,以便使用系統為要求自動建立的預訂項目。

如要使用自動建立的範例預留項目,請選取下列其中一個選項:

主控台

  1. 建立五個 A3 Ultra 執行個體的範例要求,並提交審查:

    1. 在 Google Cloud 控制台,前往「Reservations」(預留項目) 頁面。

      前往「預留項目」頁面

    2. 點按「Future reservations」(未來預留項目) 分頁標籤。

    3. 點按 「Create future reservation」(建立未來預留項目)。「Create a future reservation」(建立未來預留項目) 頁面隨即顯示。

    4. 在「硬體設定」部分,選取「指定機器類型」,然後指定 A3 Ultra 執行個體。

    5. 在「Obtainability method」(取得方法) 區段中,完成下列步驟:

      1. 選取「搜尋最多 90 天的運算資源」

      2. 在「Region」(區域) 和「Zone」(可用區) 清單中,指定要預留資源的區域和可用區。在本範例中,請分別選取 us-central1us-central1-a

      3. 在「Total capacity needed」(所需總容量) 欄位中輸入 5

      4. 在「預留期間」部分,指定預留項目的預留期間。

    6. 指定其餘欄位,然後按一下「提交」

  2. 在要求開始時間,如要建立 A3 Ultra 執行個體來使用範例自動建立的預留項目,請按照下列步驟操作:

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

      前往「建立執行個體」

    2. 在「Name」(名稱) 欄位中,輸入執行個體的名稱。在本範例中,請輸入 example-instance

    3. 指定要預留資源的「Region」(區域) 和「Zone」(可用區)。在本範例中,請分別選取 us-central1us-central1-a

    4. 按一下「GPU」分頁標籤,然後在「GPU type」(GPU 類型) 清單中,選取「NVIDIA H200 141GB」。這項動作會指定 A3 Ultra 執行個體,並將佈建模式設為「取決於預留項目」

    5. 在導覽選單中,按一下「進階」

    6. 在「Reservations」(預留項目) 部分,選取「Choose a reservation」(選取預留項目),然後點選「Choose a reservation」(選取預留項目)

    7. 在「Choose a reservation」(選擇預留項目) 窗格中,執行下列操作:

      1. 選取特定預留項目。如要使用其他專案中的共用預留項目,請在「專案」清單中選取預留項目所在的專案。

      2. 按一下「選擇」

    8. 在「佈建模式」部分,展開「VM 佈建模式進階設定」部分。

    9. 在「On VM termination」(VM 終止時) 清單中,選取「Stop」(停止) (預設) 或「Delete」(刪除)

    10. 點選「建立」

gcloud

  1. 如要建立五個 A3 Ultra VM 的範例要求,並提交審查,請使用 gcloud beta compute future-reservations create 指令

    gcloud beta compute future-reservations create example-fr \
        --auto-delete-auto-created-reservations \
        --deployment-type=DENSE \
        --planning-status=SUBMITTED \
        --require-specific-reservation \
        --reservation-mode=CALENDAR \
        --reservation-name=example-reservation \
        --share-type=local \
        --start-time=2025-10-05T00:00:00Z \
        --end-time=2025-10-19T00:00:00Z \
        --machine-type=a3-ultragpu-8g \
        --total-count=5 \
        --zone=us-central1-a
    

    假設 Google Cloud 核准要求,Compute Engine 會自動建立空白預留項目。在 2025 年 10 月 5 日的要求開始時間,Compute Engine 會增加預留項目中的預留 GPU VM 數量。然後即可使用預留項目。

  2. 在要求開始時間,如要建立 A3 Ultra 執行個體來使用範例自動建立的預訂項目,請使用 gcloud compute instances create 指令搭配下列旗標:

    • --instance-termination-action 標記。

    • --provisioning-model 旗標設為 RESERVATION_BOUND

    • --reservation 標記。

    • --reservation-affinity 旗標設為 specific

    指令類似於下列內容。如要瞭解建立 A3 Ultra 執行個體的完整需求,請參閱「建立 A3 Ultra 或 A4 執行個體」。

    gcloud compute instance create example-instance  \
        --machine-type=a3-ultragpu-8g \
        --instance-termination-action=TERMINATION_ACTION \
        --provisioning-model=RESERVATION_BOUND \
        --reservation-affinity=specific \
        --reservation=RESERVATION_URL \
        --zone=us-central1-a \
        ...
    

    這項指令包含下列值:

    • TERMINATION_ACTION:Compute Engine 在預訂期結束時,是停止 (STOP) 還是刪除 (DELETE) VM。

    • RESERVATION_URL:預訂網址,格式如下:

      • 如果專案中已有自動建立的預留項目: example-reservation

      • 如果自動建立的預留項目位於其他專案: projects/PROJECT_ID/reservations/example-reservation

REST

  1. 如要建立五個 A3 Ultra 執行個體的要求範例,並提交審查,請對 Beta 版 futureReservations.insert 方法發出 POST 要求:

    POST https://compute.googleapis.com/compute/beta/projects/example-project/zones/us-central1-a/futureReservations
    
    {
      "name": "example-request-calendar-mode",
      "autoDeleteAutoCreatedReservations": true,
      "deploymentType": "DENSE",
      "planningStatus": "SUBMITTED",
      "reservationMode": "CALENDAR",
      "reservationName": "example-reservation",
      "shareSettings": {
        "shareType": "LOCAL"
      },
      "specificReservationRequired": true,
      "specificSkuProperties": {
        "machineType": "a3-ultragpu-8g",
        "totalCount": 5
      },
      "timeWindow": {
        "startTime": "2025-10-05T00:00:00Z",
        "endTime": "2025-10-19T00:00:00Z"
      }
    }
    

    假設 Google Cloud 核准要求,Compute Engine 會自動建立空白預留項目。在 2025 年 10 月 5 日的要求開始時間,Compute Engine 會增加預留項目中的預留 GPU VM 數量。然後即可使用預留項目。

  2. 在要求開始時間,如要建立 A3 Ultra 執行個體來使用範例自動建立的預留項目,請對 instances.insert 方法提出 POST 要求。在要求主體中加入下列欄位:

    • reservationAffinity.consumeReservationType 欄位設為 SPECIFIC_RESERVATION

    • reservationAffinity.key 欄位設為 compute.googleapis.com/reservation-name

    • reservationAffinity.values」欄位設為預訂網址。

    • scheduling.instanceTerminationAction 欄位。

    • scheduling.provisioningModel 欄位設為 RESERVATION_BOUND

    要求類似如下。如要瞭解建立 A3 Ultra 執行個體的完整需求,請參閱「建立 A3 Ultra 或 A4 執行個體」。

    POST https://compute.googleapis.com/compute/beta/projects/example-project/zones/us-central1-a/
    
    {
      {
        "machineType": "projects/example-project/zones/us-central1-a/machineTypes/a3-ultragpu-8g",
        "name": "example-instance",
        "reservationAffinity": {
          "consumeReservationType": "SPECIFIC_RESERVATION",
          "key": "compute.googleapis.com/reservation-name",
          "values":[
            "RESERVATION_URL"
          ],
        },
        "scheduling": {
          "instanceTerminationAction": "TERMINATION_ACTION",
          "provisioningModel": "RESERVATION_BOUND"
        },
        ...
      }
    }
    

    要求主體包含下列值:

    • RESERVATION_URL:預訂網址,格式如下:

      • 如果專案中已有自動建立的預留項目: example-reservation

      • 如果自動建立的預留項目位於其他專案: projects/PROJECT_ID/reservations/example-reservation

    • TERMINATION_ACTION:Compute Engine 在預訂期結束時,是停止 (STOP) 還是刪除 (DELETE) VM。

測試執行個體屬性是否與自動耗用的預留項目相符

如要測試運算執行個體的屬性是否與自動耗用的預留項目相符,請按照下列步驟操作:

  1. 將預留項目複製為單一執行個體的明確指定預留項目。

  2. 建立測試執行個體,以使用預留項目。

如果可以建立測試執行個體,表示其屬性與測試保留項目的屬性相符。否則會發生錯誤。

確認測試執行個體和測試保留項目的屬性相符後,請刪除保留項目測試執行個體

確認預留項目使用情形

如要驗證預訂項目用量,請採取下列一或多項做法:

  • 如要查看目前使用預留項目的運算執行個體數量,以及還能使用預留項目的執行個體數量,請查看預留項目

  • 如要監控每 30 分鐘更新一次的預訂用量資料,並在預訂用完或未使用時收到快訊,請監控預訂用量

  • 如要查看每 24 小時更新的預訂項目用量資料,請執行下列任一操作:

    • 如要在 Cloud Storage bucket 中接收用量報表,以便分析用量趨勢及找出未使用的預訂項目,請查看預訂項目用量報表
    • 如要查看過去和預測的預留項目用量,以便分析用量趨勢及規劃日後的容量需求,請使用 Capacity Planner

後續步驟