使用保留項目


本文說明如何在 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: compute.instances.setMetadata 設定 VM 執行個體中繼資料
    • 如何為 VM 設定標記:compute.instances.setTags
    • 如何為 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」(預留項目) 頁面。

      前往「預留項目」

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

    3. 在「名稱」欄位中,輸入預訂名稱。例如輸入 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 平台和 GPU」,然後在「CPU 平台」欄位中選取「Intel Cascade Lake 或以上版本」

    11. 按一下 [建立]。

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

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

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

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

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

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

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

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

      4. 在「Machine type」部分的「Preset」分頁中 (預設),選取「n2-standard-32」

      5. 展開「進階選項」部分,然後在「CPU 平台」欄位中選取「Intel Cascade Lake 或更新版本」

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

    4. 在「進階」窗格中的「預訂」部分,選取「使用自動選取」(如果尚未選取)。

    5. 按一下 [建立]。

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 和 Intel Skylake 做為最低 CPU 平台的 N1 執行個體。執行個體會自動使用相符的預留項目。

如要建立範例例項,請使用以下程式碼範例:

// 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,Intel Ivy 做為最低 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_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 要求。在要求主體中加入 consumeReservationType 欄位,並將其設為 ANY_RESERVATION。不過,由於 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 SpecificReservationRequired 欄位設為 true ReservationAffinity 欄位中加入下列欄位:
  • ConsumeReservationType 欄位設為 SPECIFIC_RESERVATION
  • Key 欄位設為 compute.googleapis.com/reservation-name
  • Values 欄位設為預訂項目的網址。
Java setSpecificReservationRequired 欄位設為 true ReservationAffinity 欄位中加入下列欄位:
  • setConsumeReservationType 欄位設為 SPECIFIC_RESERVATION
  • setKey 欄位設為 compute.googleapis.com/reservation-name
  • addValues 欄位設為預訂項目的網址。
Node.js 和 REST API specificReservationRequired 欄位設為 true reservationAffinity 欄位中加入下列欄位:
  • consumeReservationType 欄位設為 SPECIFIC_RESERVATION
  • key 欄位設為 compute.googleapis.com/reservation-name
  • values 欄位設為預訂項目的網址。
Python 和 Terraform specific_reservation_required 欄位設為 true reservation_affinity 欄位中加入下列欄位:
  • consume_reservation_type 欄位設為 SPECIFIC_RESERVATION
  • key 欄位設為 compute.googleapis.com/reservation-name
  • values 欄位設為預訂項目的網址。

如要建立示例特定保留項目和要使用該項目的執行個體,請選取下列任一選項:

主控台

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

如要建立示例特定保留項目並加以使用,請執行下列步驟:

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

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

      前往「預留項目」

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

    3. 在「名稱」欄位中,輸入預訂名稱。例如輸入 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 平台和 GPU」,然後在「CPU 平台」欄位中選取「Intel Cascade Lake 或以上版本」

    11. 按一下 [建立]。

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

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

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

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

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

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

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

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

      4. 在「Machine type」部分的「Preset」分頁中 (預設),選取「n2-standard-32」

      5. 展開「進階選項」部分,然後在「CPU 平台」欄位中選取「Intel Cascade Lake 或以上版本」

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

    4. 在「進階」窗格中的「預訂」部分,選取「選擇預訂」,然後按一下「選擇預訂」

    5. 在隨即顯示的「Choose a reservation」窗格中,執行下列操作:

      1. 選取您在先前步驟中建立的特定保留項目。如果您想使用位於其他專案中的共用預留項目,請在「專案」清單中選取該預留項目所在的專案。

      2. 按一下「選擇」

    6. 按一下 [建立]。

gcloud

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

如要建立示例特定保留項目並加以使用,請執行下列步驟:

  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 和 Intel Skylake 做為最低 CPU 平台的 N1 執行個體,以便使用特定的符合條件保留項目:

// 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,並將 Intel Cascade Lake 做為最低 CPU 平台。並說明如何建立單一執行個體來使用保留項目。

如要建立示例特定保留項目並加以使用,請執行下列步驟:

  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 執行個體的屬性是否與自動消耗的保留項目相符,請執行下列操作:

  1. 建立保留項目的副本,做為單一執行個體的特定指定保留項目。

  2. 建立測試用例,以便使用保留項目。

如果您可以建立測試例項,則其屬性會與測試保留項目的屬性相符。否則建立執行個體會失敗。

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

驗證保留項目用量

如要驗證預訂使用情形,您可以執行下列一或多項操作:

  • 如要查看目前有多少 Compute 執行個體正在使用保留項目,以及還有多少執行個體可以使用保留項目,請查看保留項目

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

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

    • 如要查看過去和預測的預留容量使用量,以便分析使用量趨勢並規劃未來的容量需求,請使用容量規劃工具

後續步驟