建立共用預留項目

本文說明如何建立共用預留項目 (可供多個專案共用的預留項目),以及如何管理機構中可使用共用預留項目的專案。

共用預留項目可供代管預留項目的專案 (擁有者專案) 使用,也可供預留項目共用的專案 (消費者專案) 使用。如果貴機構有多個專案需要預留屬性相同的虛擬機器 (VM) 執行個體,請使用共用預留項目。使用共用預留項目,可提高預留項目的使用率,並減少需要建立及管理的預留項目數量。如要進一步瞭解預留項目,請參閱「Compute Engine 可用區資源的預留項目」。

如要瞭解其他預訂方式,請參閱下列頁面:

事前準備

  • 查看共用預留項目的最佳做法
  • 請參閱共用預訂的 配額規定 限制
  • 確認您用來建立共用預留項目的專案,已由組織政策管理員新增至「共用預留項目擁有者專案」(compute.sharedReservationsOwnerProjects) 組織政策限制的許可清單。根據預設,這份允許清單是空白的,因此貴機構必須先將這項權限授予一或多個專案,您才能建立共用預留項目。如要進一步瞭解如何查看及編輯機構政策限制,請參閱「管理共用預訂建立作業」。
  • 如果尚未設定驗證,請先完成設定。 驗證可確認您的身分,以便存取 Google Cloud 服務和 API。如要從本機開發環境執行程式碼或範例,可以選取下列任一選項,向 Compute Engine 進行驗證:

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

    Console

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

    gcloud

    1. 安裝 Google Cloud CLI。 完成後,執行下列指令來初始化 Google Cloud CLI:

      gcloud init

      若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

    2. Set a default region and zone.

    Terraform

    如要在本機開發環境中使用本頁的 Terraform 範例,請安裝並初始化 gcloud CLI,然後使用您的使用者憑證設定應用程式預設憑證。

      安裝 Google Cloud CLI。

      若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

      If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    詳情請參閱 Set up authentication for a local development environment

    Go

    如要在本機開發環境中使用本頁的 Go 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      安裝 Google Cloud CLI。

      若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

      If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    詳情請參閱 Set up authentication for a local development environment

    Java

    如要在本機開發環境中使用本頁的 Java 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      安裝 Google Cloud CLI。

      若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

      If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    詳情請參閱 Set up authentication for a local development environment

    Node.js

    如要在本機開發環境中使用本頁的 Node.js 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      安裝 Google Cloud CLI。

      若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

      If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    詳情請參閱 Set up authentication for a local development environment

    Python

    如要在本機開發環境中使用本頁的 Python 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      安裝 Google Cloud CLI。

      若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

      If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    詳情請參閱 Set up authentication for a local development environment

    REST

    如要在本機開發環境中使用本頁的 REST API 範例,請使用您提供給 gcloud CLI 的憑證。

      安裝 Google Cloud CLI。

      若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

    詳情請參閱 Google Cloud 驗證說明文件中的「使用 REST 進行驗證」。

必要的角色

如要取得建立共用預留資源所需的權限,請要求管理員授予您下列 IAM 角色:

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

這些預先定義的角色具備建立共用預訂所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

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

  • 專案的 compute.reservations.create
  • 如要查看機構政策: orgpolicy.policy.get 在機構上
  • 如要編輯機構政策: orgpolicy.policy.set 機構
  • 如要指定執行個體範本: compute.instanceTemplates.useReadOnly 執行個體範本中的 compute.instanceTemplates.useReadOnly

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

建立共用預留項目

本節說明如何建立共用預訂。建立共用預留項目後,只有擁有者專案可以修改,但擁有者專案或任何消費者專案都可以使用共用預留項目的資源。

如要使用預留項目,VM 的屬性必須完全符合該預留項目。如要指定要預留的 VM 屬性,請選取本文件中的下列其中一個章節:

  • 建議: 指定執行個體範本

    本節說明如何使用執行個體範本定義共用預留資源的屬性。使用執行個體範本,您可以在同一處定義預留項目的屬性,以及可使用預留項目的 VM。不過,由於範本是專案專屬,因此您無法使用相同範本建立 VM,在建立預留項目的專案外部使用預留項目。對於共用預留項目的專案,您必須在這些專案中建立類似的範本,或直接指定屬性來建立 VM。

  • 指定現有 VM

    本節說明如何使用現有 VM 定義預留項目的屬性。使用現有 VM 的屬性,建立與參考 VM 屬性相符的 VM,即可使用預留資源。

  • 直接指定屬性

    本節說明如何直接定義共用預訂的屬性。使用這個方法時,您必須手動確保 VM 和預留項目的屬性完全相符,否則 屬性不符會導致無法使用

根據預設,凡是符合保留項目屬性的 VM,都會自動使用該保留項目。如要控管預訂用量,請執行下列一或多項操作:

指定執行個體範本

透過指定執行個體範本建立預留項目之前,請確認下列事項:

  • 執行個體範本包含專案專屬設定,因此您只能在同一專案中存取及使用執行個體範本。如果您指定執行個體範本來建立共用預留項目,就無法使用相同範本建立 VM,在建立預留項目的專案外部使用預留項目。

  • 在與執行個體範本中的資源相同的區域和可用區建立預留項目。在執行個體範本中指定的任何區域區域資源 (例如機器類型或永久磁碟磁碟區),都會將範本的使用限制在這些資源所在的區域。舉例來說,如果執行個體範本在 us-central1-a 區域中指定現有的永久磁碟磁碟區,您就只能在同一個區域中建立預留項目。如要檢查現有範本是否指定任何資源,將範本繫結至特定區域或可用區,請查看執行個體範本的詳細資料,並在其中尋找區域或可用區資源的參照。

如要透過指定執行個體範本建立共用預留項目,請選取下列任一選項:

控制台

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

    前往「Reservations」(預留項目) 頁面

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

  3. 在「Name」(名稱) 欄位中,輸入預留項目的名稱。

  4. 在「Region」(區域) 和「Zone」(可用區) 清單中,選取要預留資源的位置。

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

    1. 如要與其他專案共用預留項目,請選取「已共用」

    2. 按一下「新增專案」,然後選取要共用預留項目的專案 (來自目前專案的機構)。最多可選取 100 個消費性專案。

  6. 選用步驟:如要允許 Vertex AI 中的自訂訓練工作預測工作使用 GPU VM 的預留項目,請在「Google Cloud services」(Google Cloud 服務) 部分,選取「Share reservation」(共用預留項目)

  7. 在「Use with VM instance」(用於 VM 執行個體) 部分,選取下列任一選項:

    • 如要允許相符的 VM 自動使用這個預留項目,請選取「Use reservation automatically」(自動使用預留項目)

    • 如要只在建立明確指定預留項目名稱的相符 VM 時,才使用這個預留項目的資源,請選用「Select specific reservation」(選取特定預留項目)

  8. 在「資源詳細資料」部分,執行下列操作:

    • 在「Number of VM instances」(VM 執行個體數量) 欄位中,輸入要預留的 VM 數量。

    • 如要使用執行個體範本指定 VM 設定,請選取「使用執行個體範本」,然後在顯示的清單中選取執行個體範本。

  9. 在「Auto-delete」(自動刪除) 區段中,您可以啟用自動刪除選項,讓 Compute Engine 在特定日期和時間自動刪除預留項目。如果您在停止使用預留資源時自動刪除預留項目,可有助於避免不必要的費用。

  10. 如要建立預留項目,請點選「Create」(建立)。「Reservations」(預留項目) 頁面隨即顯示。預留項目會在一分鐘內建立完畢。 如要確認 Compute Engine 何時完成建立作業,請查看預留項目

gcloud

如要建立共用預留項目,請使用 gcloud compute reservations create 指令搭配 --share-setting=projects--share-with 旗標。

如要建立共用預留項目,請指定執行個體範本,並執行下列指令,不含任何選用旗標:

gcloud compute reservations create RESERVATION_NAME \
    --share-setting=projects \
    --share-with=CONSUMER_PROJECT_IDS \
    --source-instance-template=INSTANCE_TEMPLATE_URL \
    --vm-count=NUMBER_OF_VMS \
    --zone=ZONE

更改下列內容:

  • RESERVATION_NAME:要建立的預訂名稱。

  • PROJECT_ID:您要預留資源的專案 ID,也是執行個體範本所在的專案。

  • CONSUMER_PROJECT_IDS:以半形逗號分隔的專案 ID 清單,這些專案可使用這項預留資源,例如 project-1,project-2。最多可加入 100 個消費性專案。這些專案必須與擁有者專案位於同一個機構。 請勿加入擁有者專案。預設情況下,系統已允許使用預訂。

  • INSTANCE_TEMPLATE_URL:現有執行個體範本的網址,該範本必須存在於專案中。請指定下列其中一個值:

    • 如果是區域性執行個體範本: projects/PROJECT_ID/regions/REGION/instanceTemplates/INSTANCE_TEMPLATE_NAME

    • 全域執行個體範本: INSTANCE_TEMPLATE_NAME

  • NUMBER_OF_VMS:要預留的 VM 數量。

  • ZONE:預留資源的所在區域。

舉例來說,如要在 us-central1-a 區域中指定全域執行個體範本來建立預留項目,並與專案 project-1project-2 共用預留項目,以及預留十部 VM,每部 VM 都使用具有 4 個 vCPU 的 N2 預先定義機器類型,請執行下列指令:

gcloud compute reservations create my-reservation \
    --share-setting=projects \
    --share-with=project-1,project-2 \
    --source-instance-template=projects/example-project/global/example-instance-template \
    --vm-count=10 \
    --zone=us-central1-a

您也可以採取下列做法:

  • 如要指定只有明確指定這個預留項目的 VM 才能使用,請加入 --require-specific-reservation 旗標。

    gcloud compute reservations create RESERVATION_NAME \
        --require-specific-reservation \
        --share-setting=projects \
        --share-with=CONSUMER_PROJECT_IDS \
        --source-instance-template=INSTANCE_TEMPLATE_URL \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    
  • 如要讓 Vertex AI 中的自訂訓練工作預測工作使用 GPU VM 的預留項目,請加入設為 ALLOW_ALL--reservation-sharing-policy 標記。

    gcloud compute reservations create RESERVATION_NAME \
        --reservation-sharing-policy=ALLOW_ALL \
        --share-setting=projects \
        --share-with=CONSUMER_PROJECT_IDS \
        --source-instance-template=INSTANCE_TEMPLATE_URL \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    
  • 如要啟用 Compute Engine,自動刪除預留項目,請選用下列任一方法:

    • 如要刪除特定日期和時間的預約,請使用 gcloud beta compute reservations create 指令並搭配 --delete-at-time 旗標。

      gcloud beta compute reservations create RESERVATION_NAME \
          --delete-at-time=DELETE_AT_TIME \
          --share-setting=projects \
          --share-with=CONSUMER_PROJECT_IDS \
          --source-instance-template=INSTANCE_TEMPLATE_URL \
          --vm-count=NUMBER_OF_VMS \
          --zone=ZONE
      

      DELETE_AT_TIME 替換為以 RFC 3339 時間戳記格式設定的日期和時間,且必須符合下列條件:

      YYYY-MM-DDTHH:MM:SSOFFSET
      

      更改下列內容:

      • YYYY-MM-DD:日期格式為 4 位數年份、2 位數月份和 2 位數日期,並以連字號 (-) 分隔。

      • HH:MM:SS:時間格式為 2 位數的小時 (採用 24 小時制)、2 位數的分鐘和 2 位數的秒數,並以半形冒號 (:) 分隔。

      • OFFSET:時區格式為世界標準時間 (UTC) 的偏移量。舉例來說,如要使用太平洋標準時間 (PST),請指定 -08:00。或者,如要不使用位移,請指定 Z

    • 如要在特定時間後刪除預訂項目,請使用 gcloud beta compute reservations create 指令搭配 --delete-after-duration 旗標。

      gcloud beta compute reservations create RESERVATION_NAME \
          --delete-after-duration=DELETE_AFTER_DURATION \
          --share-setting=projects \
          --share-with=CONSUMER_PROJECT_IDS \
          --source-instance-template=INSTANCE_TEMPLATE_URL \
          --vm-count=NUMBER_OF_VMS \
          --zone=ZONE
      

      DELETE_AFTER_DURATION 替換為天數、小時數、分鐘數或秒數。舉例來說,指定 30m 代表 30 分鐘,指定 1d2h3m4s 則代表 1 天 2 小時 3 分鐘 4 秒。

Go

import (
	"context"
	"fmt"
	"io"

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

// Creates shared reservation from given template in particular zone
func createSharedReservation(w io.Writer, client ClientInterface, projectID, baseProjectId, zone, reservationName, sourceTemplate string) error {
	// client, err := compute.NewReservationsRESTClient(ctx)
	// projectID := "your_project_id". Destination of sharing.
	// baseProjectId := "your_project_id2". Project where the reservation will be created.
	// zone := "us-west3-a"
	// reservationName := "your_reservation_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()

	shareSettings := map[string]*computepb.ShareSettingsProjectConfig{
		projectID: {ProjectId: proto.String(projectID)},
	}

	req := &computepb.InsertReservationRequest{
		Project: baseProjectId,
		ReservationResource: &computepb.Reservation{
			Name: proto.String(reservationName),
			Zone: proto.String(zone),
			SpecificReservation: &computepb.AllocationSpecificSKUReservation{
				Count:                  proto.Int64(2),
				SourceInstanceTemplate: proto.String(sourceTemplate),
			},
			ShareSettings: &computepb.ShareSettings{
				ProjectMap: shareSettings,
				ShareType:  proto.String("SPECIFIC_PROJECTS"),
			},
		},
		Zone: zone,
	}

	op, err := client.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create reservation: %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, "Reservation created\n")

	return nil
}

Java

import com.google.cloud.compute.v1.AllocationSpecificSKUReservation;
import com.google.cloud.compute.v1.InsertReservationRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.Reservation;
import com.google.cloud.compute.v1.ReservationsClient;
import com.google.cloud.compute.v1.ShareSettings;
import com.google.cloud.compute.v1.ShareSettingsProjectConfig;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateSharedReservation {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // The ID of the project where you want to reserve resources
    // and where the instance template exists.
    // By default, no projects are allowed to create or modify shared reservations
    // in an organization. Add projects to the Shared Reservations Owner Projects
    // (compute.sharedReservationsOwnerProjects) organization policy constraint
    // to allow them to create and modify shared reservations.
    // For more information visit this page:
    // https://cloud.google.com/compute/docs/instances/reservations-shared#shared_reservation_constraint
    String projectId = "YOUR_PROJECT_ID";
    // Zone in which to reserve resources.
    String zone = "us-central1-a";
    // Name of the reservation to be created.
    String reservationName = "YOUR_RESERVATION_NAME";
    // The URI of the global instance template to be used for creating the reservation.
    String instanceTemplateUri = String.format(
        "projects/%s/global/instanceTemplates/%s", projectId, "YOUR_INSTANCE_TEMPLATE_NAME");
    // Number of instances for which capacity needs to be reserved.
    int vmCount = 3;

    createSharedReservation(projectId, zone, reservationName, instanceTemplateUri, vmCount);
  }

  // Creates a shared reservation with the given name in the given zone.
  public static Status createSharedReservation(
          String projectId, String zone,
          String reservationName, String instanceTemplateUri, int vmCount)
          throws ExecutionException, InterruptedException, TimeoutException, IOException {

    // 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 (ReservationsClient reservationsClient = ReservationsClient.create()) {
      ShareSettings shareSettings = ShareSettings.newBuilder()
              .setShareType(String.valueOf(ShareSettings.ShareType.SPECIFIC_PROJECTS))
              // The IDs of projects that can consume this reservation. You can include up to
              // 100 consumer projects. These projects must be in the same organization as
              // the owner project. Don't include the owner project.
              // By default, it is already allowed to consume the reservation.
              .putProjectMap("CONSUMER_PROJECT_1", ShareSettingsProjectConfig.newBuilder().build())
              .putProjectMap("CONSUMER_PROJECT_2", ShareSettingsProjectConfig.newBuilder().build())
              .build();

      Reservation reservationResource =
              Reservation.newBuilder()
                      .setName(reservationName)
                      .setZone(zone)
                      .setSpecificReservationRequired(true)
                      .setShareSettings(shareSettings)
                      .setSpecificReservation(
                              AllocationSpecificSKUReservation.newBuilder()
                                      .setCount(vmCount)
                                      .setSourceInstanceTemplate(instanceTemplateUri)
                                      .build())
                      .build();

      InsertReservationRequest request =
              InsertReservationRequest.newBuilder()
                      .setProject(projectId)
                      .setZone(zone)
                      .setReservationResource(reservationResource)
                      .build();

      Operation response = reservationsClient.insertAsync(request)
              .get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        throw new Error("Reservation creation failed!!" + response);
      }
      return response.getStatus();
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment reservationsClient and zoneOperationsClient before running the sample.
 */
// Instantiate a reservationsClient
// reservationsClient = new computeLib.ReservationsClient();
// Instantiate a zoneOperationsClient
// zoneOperationsClient = new computeLib.ZoneOperationsClient();

/**
 * TODO(developer): Update these variables before running the sample.
 */
// The ID of the project where you want to reserve resources and where the instance template exists.
const projectId = await reservationsClient.getProjectId();
// The zone in which to reserve resources.
const zone = 'us-central1-a';
// The name of the reservation to create.
const reservationName = 'reservation-01';
// The number of VMs to reserve.
const vmsNumber = 3;
// The name of an existing instance template.
const instanceTemplateName = 'global-instance-template-name';
// The location of the instance template.
const location = 'global';

async function callCreateComputeSharedReservation() {
  // Create reservation for 3 VMs in zone us-central1-a by specifying a instance template.
  const specificReservation = new compute.AllocationSpecificSKUReservation({
    count: vmsNumber,
    sourceInstanceTemplate: `projects/${projectId}/${location}/instanceTemplates/${instanceTemplateName}`,
  });

  // Create share settings. Share reservation with one customer project.
  const shareSettings = new compute.ShareSettings({
    shareType: 'SPECIFIC_PROJECTS',
    projectMap: {
      // The IDs of projects that can consume this reservation. You can include up to 100 consumer projects.
      // These projects must be in the same organization as the owner project.
      // Don't include the owner project. By default, it is already allowed to consume the reservation.
      consumer_project_id: {
        projectId: 'consumer_project_id',
      },
    },
  });

  // Create a reservation.
  const reservation = new compute.Reservation({
    name: reservationName,
    specificReservation,
    specificReservationRequired: true,
    shareSettings,
  });

  const [response] = await reservationsClient.insert({
    project: projectId,
    reservationResource: reservation,
    zone,
  });

  let operation = response.latestResponse;

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

  console.log(`Reservation: ${reservationName} created.`);
  return response;
}

return await callCreateComputeSharedReservation();

Python

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 create_compute_shared_reservation(
    project_id: str,
    zone: str = "us-central1-a",
    reservation_name="your-reservation-name",
    shared_project_id: str = "shared-project-id",
) -> compute_v1.Reservation:
    """Creates a compute reservation in GCP.
    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.
        shared_project_id (str): The ID of the project that the reservation is shared with.
    Returns:
        Reservation object that represents the new reservation.
    """

    instance_properties = compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
        machine_type="n1-standard-1",
        # Optional. Specifies amount of local ssd to reserve with each instance.
        local_ssds=[
            compute_v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk(
                disk_size_gb=375, interface="NVME"
            ),
        ],
    )

    reservation = compute_v1.Reservation(
        name=reservation_name,
        specific_reservation=compute_v1.AllocationSpecificSKUReservation(
            count=3,  # Number of resources that are allocated.
            # If you use source_instance_template, you must exclude the instance_properties field.
            # It can be a full or partial URL.
            # source_instance_template="projects/[PROJECT_ID]/global/instanceTemplates/my-instance-template",
            instance_properties=instance_properties,
        ),
        share_settings=compute_v1.ShareSettings(
            share_type="SPECIFIC_PROJECTS",
            project_map={
                shared_project_id: compute_v1.ShareSettingsProjectConfig(
                    project_id=shared_project_id
                )
            },
        ),
    )

    # Create a client
    client = compute_v1.ReservationsClient()

    operation = client.insert(
        project=project_id,
        zone=zone,
        reservation_resource=reservation,
    )
    wait_for_extended_operation(operation, "Reservation creation")

    reservation = client.get(
        project=project_id, zone=zone, reservation=reservation_name
    )
    shared_project = next(iter(reservation.share_settings.project_map.values()))

    print("Name: ", reservation.name)
    print("STATUS: ", reservation.status)
    print("SHARED PROJECT: ", shared_project)
    # Example response:
    # Name:  your-reservation-name
    # STATUS:  READY
    # SHARED PROJECT:  project_id: "123456789012"

    return reservation

REST

如要建立共用預留項目,請對 reservations.insert 方法發出 POST 要求。在要求主體中加入下列內容:

  • projectMap 欄位。

  • shareType 欄位設為 SPECIFIC_PROJECTS

舉例來說,如要建立共用保留項目,請指定執行個體範本,但不納入任何選用欄位,並與兩個消費者專案共用保留項目,請發出下列 POST 要求:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations

{
  "name": "RESERVATION_NAME",
  "shareSettings": {
    "shareType": "SPECIFIC_PROJECTS",
    "projectMap": {
      "CONSUMER_PROJECT_ID_1": {
        "projectId": "CONSUMER_PROJECT_ID_1"
      },
      "CONSUMER_PROJECT_ID_2": {
        "projectId": "CONSUMER_PROJECT_ID_2"
      }
    }
  },
  "specificReservation": {
    "count": "NUMBER_OF_VMS",
    "sourceInstanceTemplate": "INSTANCE_TEMPLATE_URL"
  }
}

更改下列內容:

  • PROJECT_ID:您要預留資源的專案 ID,也是執行個體範本所在的專案。

  • ZONE:預留資源的所在區域。

  • RESERVATION_NAME:要建立的預訂名稱。

  • CONSUMER_PROJECT_ID_1CONSUMER_PROJECT_ID_2:可使用這項預留項目的專案 ID。最多可加入 100 個消費者專案。這些專案必須與擁有者專案位於同一個機構。請勿加入擁有者專案。根據預設,系統已允許使用預留項目。

  • NUMBER_OF_VMS:要預留的 VM 數量。

  • INSTANCE_TEMPLATE_URL:現有執行個體範本的網址,該範本必須存在於專案中。請指定下列其中一個值:

    • 如果是區域性執行個體範本: projects/PROJECT_ID/regions/REGION/instanceTemplates/INSTANCE_TEMPLATE_NAME

    • 全域執行個體範本: INSTANCE_TEMPLATE_NAME

舉例來說,如要在可用區 us-central1-a 中為十部 VM 建立預留項目 (指定全域執行個體範本),並與專案 project-1project-2 共用預留項目,請發出下列 POST 要求:

POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations

{
  "name": "my-reservation",
  "shareSettings": {
    "shareType": "SPECIFIC_PROJECTS",
    "projectMap": {
      "project-1": {
        "projectId": "project-1"
      },
      "project-2": {
        "projectId": "project-2"
      }
    }
  },
  "specificReservation": {
    "count": "10",
    "sourceInstanceTemplate": "example-instance-template"
  }
}

您也可以採取下列做法:

  • 如要指定只有明確指定這個預留項目的 VM 才能使用,請在要求主體中加入 specificReservationRequired 欄位,並將該欄位設為 true

    舉例來說,如要透過指定執行個體範本建立特定保留項目,並與兩個消費者專案共用該保留項目,請提出下列要求:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "shareSettings": {
        "shareType": "SPECIFIC_PROJECTS",
        "projectMap": {
          "CONSUMER_PROJECT_ID_1": {
            "projectId": "CONSUMER_PROJECT_ID_1"
          },
          "CONSUMER_PROJECT_ID_2": {
            "projectId": "CONSUMER_PROJECT_ID_2"
          }
        }
      },
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "sourceInstanceTemplate": "INSTANCE_TEMPLATE_URL"
      },
      "specificReservationRequired": true
    }
    
  • 如要讓 Vertex AI 中的自訂訓練工作預測工作使用 GPU VM 的預留項目,請加入 serviceShareType 欄位並設為 ALLOW_ALL

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "reservationSharingPolicy": {
        "serviceShareType": "ALLOW_ALL"
      },
      "shareSettings": {
        "shareType": "SPECIFIC_PROJECTS",
        "projectMap": {
          "CONSUMER_PROJECT_ID_1": {
            "projectId": "CONSUMER_PROJECT_ID_1"
          },
          "CONSUMER_PROJECT_ID_2": {
            "projectId": "CONSUMER_PROJECT_ID_2"
          }
        }
      },
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "sourceInstanceTemplate": "INSTANCE_TEMPLATE_URL"
      }
    }
    
  • 如要啟用 Compute Engine,自動刪除預留項目,請選用下列任一方法:

    • 如要在特定日期和時間刪除預留項目,請對 beta.reservations.insert 方法發出 POST 要求。在要求主體中,請納入 deleteAtTime 欄位。

      舉例來說,如要透過指定執行個體範本建立預留項目、在特定日期和時間自動刪除預留項目,並與兩個消費者專案共用預留項目,請發出下列要求:

      POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations
      
      {
        "deleteAtTime": "DELETE_AT_TIME",
        "name": "RESERVATION_NAME",
        "shareSettings": {
          "shareType": "SPECIFIC_PROJECTS",
          "projectMap": {
            "CONSUMER_PROJECT_ID_1": {
              "projectId": "CONSUMER_PROJECT_ID_1"
            },
            "CONSUMER_PROJECT_ID_2": {
              "projectId": "CONSUMER_PROJECT_ID_2"
            }
          }
        },
        "specificReservation": {
          "count": "NUMBER_OF_VMS",
          "sourceInstanceTemplate": "INSTANCE_TEMPLATE_URL"
        }
      }
      

      DELETE_AT_TIME 替換為以 RFC 3339 時間戳記格式設定的日期和時間,且必須符合下列條件:

      YYYY-MM-DDTHH:MM:SSOFFSET
      

      更改下列內容:

      • YYYY-MM-DD:日期格式為 4 位數年份、2 位數月份和 2 位數日期,並以連字號 (-) 分隔。

      • HH:MM:SS:時間格式為 2 位數的小時 (採用 24 小時制)、2 位數的分鐘和 2 位數的秒數,並以半形冒號 (:) 分隔。

      • OFFSET:時區格式為世界標準時間 (UTC) 的偏移量。舉例來說,如要使用太平洋標準時間 (PST),請指定 -08:00。或者,如要不使用位移,請指定 Z

    • 如要在特定時間後刪除預留項目,請對 beta.reservations.insert 方法發出 POST 要求。在要求主體中,請納入 deleteAfterDuration 欄位。

      舉例來說,如要透過指定執行個體範本建立預留項目、在特定時間長度後自動刪除預留項目,以及與兩個消費者專案共用預留項目,請發出下列要求:

      POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations
      
      {
        "deleteAfterDuration": {
          "seconds": "DELETE_AFTER_DURATION"
        },
        "name": "RESERVATION_NAME",
        "shareSettings": {
          "shareType": "SPECIFIC_PROJECTS",
          "projectMap": {
            "CONSUMER_PROJECT_ID_1": {
              "projectId": "CONSUMER_PROJECT_ID_1"
            },
            "CONSUMER_PROJECT_ID_2": {
              "projectId": "CONSUMER_PROJECT_ID_2"
            }
          }
        },
        "specificReservation": {
          "count": "NUMBER_OF_VMS",
          "sourceInstanceTemplate": "INSTANCE_TEMPLATE_URL"
        }
      }
      

      DELETE_AFTER_DURATION 改為以秒為單位的時間長度。舉例來說,如要指定 86,400 秒 (1 天),請輸入 86400

指定現有 VM

您只能根據與 VM 位於相同專案和區域的現有 VM,建立共用預留項目。

建立預留項目後,您可以建立屬性與參考 VM 相符的 VM,藉此使用預留項目。方法如下:

  • 請按照下列步驟建立及使用執行個體範本:

    1. 根據參考 VM 建立執行個體範本,但不覆寫參考 VM 的屬性。

    2. 使用新建立的範本建立 VM,方法如下:

  • 建立 VM,且屬性完全符合參考 VM,如下所示:

    • 在擁有者專案中,根據參照 VM 建立 VM,且不變更所建立 VM 的屬性。

    • 在用戶專案中建立 VM,同時手動確保 VM 的屬性和參照 VM 的屬性相符。

如要建立共用預留項目,並使用現有 VM 的屬性,請按照下列步驟操作:

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

    前往「Reservations」(預留項目) 頁面

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

  3. 在「Name」(名稱) 欄位中,輸入預留項目的名稱。

  4. 在「Region」(區域) 和「Zone」(可用區) 清單中,選取要預留資源的位置。

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

    1. 如要與其他專案共用預留項目,請選取「已共用」

    2. 按一下「新增專案」,然後從目前專案的機構中選取要共用預留項目的專案。最多可選取 100 個消費者專案。

  6. 選用步驟:如要允許 Vertex AI 中的自訂訓練工作預測工作使用 GPU VM 的預留項目,請在「Google Cloud services」(Google Cloud 服務) 部分,選取「Share reservation」(共用預留項目)

  7. 在「Use with VM instance」(用於 VM 執行個體) 部分,選取下列任一選項:

    • 如要允許相符的 VM 自動使用這個預留項目,請選取「Use reservation automatically」(自動使用預留項目)

    • 如要只在建立明確指定預留項目名稱的相符 VM 時,才使用這個預留項目的資源,請選用「Select specific reservation」(選取特定預留項目)

  8. 在「資源詳細資料」部分,執行下列操作:

    • 在「Number of VM instances」(VM 執行個體數量) 欄位中,輸入要預留的 VM 數量。

    • 如要使用參考 VM 指定 VM 設定,請選取「使用現有 VM」,然後在顯示的清單中選取 VM。

  9. 在「Auto-delete」(自動刪除) 區段中,您可以啟用自動刪除選項,讓 Compute Engine 在特定日期和時間自動刪除預留項目。如果在停止使用預留資源時自動刪除預留項目,可有助於避免不必要的費用。

  10. 如要建立預留項目,請點選「Create」(建立)。「Reservations」(預留項目) 頁面隨即顯示。預留項目會在一分鐘內建立完畢。如要確認 Compute Engine 何時完成建立作業,請查看預留項目

直接指定屬性

如要直接指定屬性來建立共用預留項目,請選取下列其中一個選項:

控制台

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

    前往「Reservations」(預留項目) 頁面

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

  3. 在「Name」(名稱) 欄位中,輸入預留項目的名稱。

  4. 在「Region」(區域) 和「Zone」(可用區) 清單中,選取要預留資源的位置。

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

    1. 如要與其他專案共用預留項目,請選取「已共用」

    2. 按一下「新增專案」,然後選取要共用預留項目的專案 (來自目前專案的機構)。最多可選取 100 個消費性專案。

  6. 選用步驟:如要允許 Vertex AI 中的自訂訓練工作預測工作使用 GPU VM 的預留項目,請在「Google Cloud services」(Google Cloud 服務) 部分,選取「Share reservation」(共用預留項目)

  7. 在「Use with VM instance」(用於 VM 執行個體) 部分,選取下列任一選項:

    • 如要允許相符的 VM 自動使用這個預留項目,請選取「Use reservation automatically」(自動使用預留項目)

    • 如要只在建立明確指定預留項目名稱的相符 VM 時,才使用這個預留項目的資源,請選用「Select specific reservation」(選取特定預留項目)

  8. 在「資源詳細資料」部分,執行下列操作:

    • 在「Number of VM instances」(VM 執行個體數量) 欄位中,輸入要預留的 VM 數量。

    • 指定要預留的機器系列和類型。

  9. 在「Auto-delete」(自動刪除) 區段中,您可以啟用自動刪除選項,讓 Compute Engine 在特定日期和時間自動刪除預留項目。如果您在停止使用預留資源時自動刪除預留項目,可有助於避免不必要的費用。

  10. 如要建立預留項目,請點選「Create」(建立)。「Reservations」(預留項目) 頁面隨即顯示。預留項目會在一分鐘內建立完畢。 如要確認 Compute Engine 何時完成建立作業,請查看預留項目

gcloud

如要建立共用預留項目,請使用 gcloud compute reservations create 指令搭配 --share-setting=projects--share-with 旗標。

如要直接指定屬性來建立共用預留空間,且不含任何選用標記,請執行下列指令:

gcloud compute reservations create RESERVATION_NAME \
    --machine-type=MACHINE_TYPE \
    --share-setting=projects \
    --share-with=CONSUMER_PROJECT_IDS \
    --vm-count=NUMBER_OF_VMS \
    --zone=ZONE

更改下列內容:

  • RESERVATION_NAME:要建立的預訂名稱。

  • MACHINE_TYPE:每個 VM 要使用的機器類型。

  • CONSUMER_PROJECT_IDS:以半形逗號分隔的專案 ID 清單,這些專案可使用這項預留資源,例如 project-1,project-2。最多可加入 100 個消費性專案。這些專案必須與擁有者專案位於同一個機構。 請勿加入擁有者專案。預設情況下,系統已允許使用預訂。

  • NUMBER_OF_VMS:要預留的 VM 數量。

  • ZONE:預留資源的所在區域。

舉例來說,如要在 us-central1-a 地區中為十部 VM 建立預留項目,每部 VM 都使用具有 4 個 vCPU 的 N2 預先定義機器類型,並與專案 project-1project-2 共用預留項目,請執行下列指令:

gcloud compute reservations create my-reservation \
    --machine-type=n2-standard-4 \
    --share-setting=projects \
    --share-with=project-1,project-2 \
    --vm-count=10 \
    --zone=us-central1-a

您也可以採取下列做法:

  • 如要將 GPU 附加至預留的 N1 VM,請加入 --accelerator 旗標。

    gcloud compute reservations create RESERVATION_NAME \
        --accelerator=count=NUMBER_OF_ACCELERATORS,type=ACCELERATOR_TYPE
        --machine-type=MACHINE_TYPE \
        --share-setting=projects \
        --share-with=CONSUMER_PROJECT_IDS \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    

    更改下列內容:

  • 如要將本機 SSD 磁碟連接至預設不含本機 SSD 磁碟的機器類型,請加入 --local-ssd 旗標。您只能連接 375 GB 的本機 SSD 磁碟。

    gcloud compute reservations create RESERVATION_NAME \
        --local-ssd=count=NUMBER_OF_LOCAL_SSD_DISKS,size=375,interface=INTERFACE_TYPE \
        --machine-type=MACHINE_TYPE \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    

    更改下列內容:

    • NUMBER_OF_LOCAL_SSD_DISKS:要附加的本機 SSD 磁碟數量。

    • INTERFACE_TYPE:您希望每個本機 SSD 磁碟使用的磁碟介面類型,且您指定的機器類型支援該類型。請指定下列其中一個值:

      • NVME 磁碟介面:nvme

      • SCSI 磁碟介面:scsi

  • 如要讓保留的 VM 使用特定最低 CPU 平台,而非區域的預設 CPU 平台,請加入 --min-cpu-platform 旗標。

    gcloud compute reservations create RESERVATION_NAME \
        --machine-type=MACHINE_TYPE \
        --min-cpu-platform="MIN_CPU_PLATFORM" \
        --share-setting=projects \
        --share-with=CONSUMER_PROJECT_IDS \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    

    MIN_CPU_PLATFORM 替換為最低 CPU 平台。 如要確認 CPU 平台在您預留資源的區域是否可用,請查看各區域可用的 CPU 平台

  • 如要指定只有明確指定這個預留項目的 VM 才能使用,請加入 --require-specific-reservation 旗標。

    gcloud compute reservations create RESERVATION_NAME \
        --machine-type=MACHINE_TYPE \
        --require-specific-reservation \
        --share-setting=projects \
        --share-with=CONSUMER_PROJECT_IDS \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    
  • 如要讓 Vertex AI 中的自訂訓練工作預測工作使用 GPU VM 的預留項目,請加入設為 ALLOW_ALL--reservation-sharing-policy 旗標。

    gcloud compute reservations create RESERVATION_NAME \
        --machine-type=MACHINE_TYPE \
        --reservation-sharing-policy=ALLOW_ALL \
        --share-setting=projects \
        --share-with=CONSUMER_PROJECT_IDS \
        --vm-count=NUMBER_OF_VMS \
        --zone=ZONE
    
  • 如要啟用 Compute Engine,自動刪除預留項目,請選用下列任一方法:

    • 如要刪除特定日期和時間的預約,請使用 gcloud beta compute reservations create 指令並搭配 --delete-at-time 旗標。

      gcloud beta compute reservations create RESERVATION_NAME \
          --delete-at-time=DELETE_AT_TIME \
          --machine-type=MACHINE_TYPE \
          --share-setting=projects \
          --share-with=CONSUMER_PROJECT_IDS \
          --vm-count=NUMBER_OF_VMS \
          --zone=ZONE
      

      DELETE_AT_TIME 替換為以 RFC 3339 時間戳記格式設定的日期和時間,且必須符合下列條件:

      YYYY-MM-DDTHH:MM:SSOFFSET
      

      更改下列內容:

      • YYYY-MM-DD:日期格式為 4 位數年份、2 位數月份和 2 位數日期,並以連字號 (-) 分隔。

      • HH:MM:SS:時間格式為 2 位數的小時 (採用 24 小時制)、2 位數的分鐘和 2 位數的秒數,並以半形冒號 (:) 分隔。

      • OFFSET:時區格式為世界標準時間 (UTC) 的偏移量。舉例來說,如要使用太平洋標準時間 (PST),請指定 -08:00。或者,如要不使用位移,請指定 Z

    • 如要在特定時間後刪除預訂項目,請使用 gcloud beta compute reservations create 指令搭配 --delete-after-duration 旗標。

      gcloud beta compute reservations create RESERVATION_NAME \
          --delete-after-duration=DELETE_AFTER_DURATION \
          --machine-type=MACHINE_TYPE \
          --share-setting=projects \
          --share-with=CONSUMER_PROJECT_IDS \
          --vm-count=NUMBER_OF_VMS \
          --zone=ZONE
      

      DELETE_AFTER_DURATION 替換為天數、小時數、分鐘數或秒數。舉例來說,指定 30m 代表 30 分鐘,指定 1d2h3m4s 則代表 1 天 2 小時 3 分鐘 4 秒。

Terraform

如要建立預留項目,請使用 google_compute_reservation Terraform 資源。如要與其他專案共用預留項目,請定義 share_settings 區塊:

  • share_type 欄位設為 SPECIFIC_PROJECTS
  • project_map 區塊中,指定要共用這個預留項目的專案專案 ID

如要進一步瞭解如何使用 Terraform,請參閱「搭配使用 Terraform 與 Google Cloud」。

REST

如要建立共用預留項目,請對 reservations.insert 方法發出 POST 要求。在要求主體中加入下列內容:

  • projectMap 欄位。

  • shareType 欄位設為 SPECIFIC_PROJECTS

舉例來說,如要建立共用預留項目,但不包含任何選用欄位,並與兩個消費者專案共用預留項目,請發出下列 POST 要求:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations

{
  "name": "RESERVATION_NAME",
  "shareSettings": {
    "shareType": "SPECIFIC_PROJECTS",
    "projectMap": {
      "CONSUMER_PROJECT_ID_1": {
        "projectId": "CONSUMER_PROJECT_ID_1"
      },
      "CONSUMER_PROJECT_ID_2": {
        "projectId": "CONSUMER_PROJECT_ID_2"
      }
    }
  },
  "specificReservation": {
    "count": "NUMBER_OF_VMS",
    "instanceProperties": {
      "machineType": "MACHINE_TYPE"
    }
  }
}

更改下列內容:

  • PROJECT_ID:要預留資源的專案 ID。

  • ZONE:預留資源的所在區域。

  • RESERVATION_NAME:要建立的預訂名稱。

  • CONSUMER_PROJECT_ID_1CONSUMER_PROJECT_ID_2:可使用這項預留項目的專案 ID。最多可加入 100 個消費者專案。這些專案必須與擁有者專案位於同一個機構。請勿加入擁有者專案。根據預設,系統已允許使用預留項目。

  • NUMBER_OF_VMS:要預留的 VM 數量。

  • MACHINE_TYPE:每個 VM 要使用的機器類型。

舉例來說,如要在 us-central1-a 區域中指定全域執行個體範本來建立預留項目,並與專案 project-1project-2 共用預留項目,以及預留十部 VM,每部 VM 都使用具有 4 個 vCPU 的 N2 預先定義機器類型,請發出下列 POST 要求:

POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations

{
  "name": "my-reservation",
  "shareSettings": {
    "shareType": "SPECIFIC_PROJECTS",
    "projectMap": {
      "project-1": {
        "projectId": "project-1"
      },
      "project-2": {
        "projectId": "project-2"
      }
    }
  },
  "specificReservation": {
    "count": "10",
    "instanceProperties": {
      "machineType": "n2-standard-4",
    }
  }
}

您也可以採取下列做法:

  • 如要將 GPU 附加至預留的 N1 VM,請在要求主體中加入 guestAccelerators 欄位。

    舉例來說,如要建立與兩個消費者專案共用的預留項目,並將 GPU 連接至任何預留的 N1 VM,請提出下列要求:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "shareSettings": {
        "shareType": "SPECIFIC_PROJECTS",
        "projectMap": {
          "CONSUMER_PROJECT_ID_1": {
            "projectId": "CONSUMER_PROJECT_ID_1"
          },
          "CONSUMER_PROJECT_ID_2": {
            "projectId": "CONSUMER_PROJECT_ID_2"
          }
        }
      },
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "instanceProperties": {
          "guestAccelerators": [
            {
              "acceleratorCount": NUMBER_OF_ACCELERATORS,
              "acceleratorType": "ACCELERATOR_TYPE"
            }
          ],
          "machineType": "MACHINE_TYPE"
        }
      }
    }
    

    更改下列內容:

  • 如要將本機 SSD 磁碟連接至預設不含本機 SSD 磁碟的機器類型,請在要求主體中加入 localSsds 欄位。您只能連接 375 GB 的本機 SSD 磁碟。

    舉例來說,如要將兩個本機 SSD 磁碟連接至要預留的機器類型,同時指定兩個消費者專案,請提出下列要求:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "shareSettings": {
        "shareType": "SPECIFIC_PROJECTS",
        "projectMap": {
          "CONSUMER_PROJECT_ID_1": {
            "projectId": "CONSUMER_PROJECT_ID_1"
          },
          "CONSUMER_PROJECT_ID_2": {
            "projectId": "CONSUMER_PROJECT_ID_2"
          }
        }
      },
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "instanceProperties": {
          "localSsds": [
            {
              "diskSizeGb": "375",
              "interface": "INTERFACE_TYPE"
            },
            {
              "diskSizeGb": "375",
              "interface": "INTERFACE_TYPE"
            }
          ],
          "machineType": "MACHINE_TYPE"
        }
      }
    }
    

    INTERFACE_TYPE 替換為您希望每個本機 SSD 磁碟使用的磁碟介面類型,且您指定的機型支援該類型。請指定下列其中一個值:

    • NVME 磁碟介面:NVME

    • SCSI 磁碟介面:SCSI

  • 如要讓保留的 VM 使用特定最低 CPU 平台,而非區域的預設 CPU 平台,請在要求主體中加入 minCpuPlatform 欄位。

    舉例來說,如要建立共用預留項目,同時指定最低 CPU 平台和兩個用戶專案,請提出下列要求:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "shareSettings": {
        "shareType": "SPECIFIC_PROJECTS",
        "projectMap": {
          "CONSUMER_PROJECT_ID_1": {
            "projectId": "CONSUMER_PROJECT_ID_1"
          },
          "CONSUMER_PROJECT_ID_2": {
            "projectId": "CONSUMER_PROJECT_ID_2"
          }
        }
      },
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "instanceProperties": {
          "machineType": "MACHINE_TYPE",
          "minCpuPlatform": "MIN_CPU_PLATFORM"
        }
      }
    }
    

    MIN_CPU_PLATFORM 替換為最低 CPU 平台。 如要確認 CPU 平台在您預留資源的區域是否可用,請查看各區域可用的 CPU 平台

  • 如要指定只有明確指定這個預留項目的 VM 才能使用,請在要求主體中加入 specificReservationRequired 欄位,並將該欄位設為 true

    舉例來說,如要建立特定保留項目並與兩個消費者專案共用,請提出下列要求:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "shareSettings": {
        "shareType": "SPECIFIC_PROJECTS",
        "projectMap": {
          "CONSUMER_PROJECT_ID_1": {
            "projectId": "CONSUMER_PROJECT_ID_1"
          },
          "CONSUMER_PROJECT_ID_2": {
            "projectId": "CONSUMER_PROJECT_ID_2"
          }
        }
      },
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "instanceProperties": {
          "machineType": "MACHINE_TYPE"
        }
      },
      "specificReservationRequired": true
    }
    
  • 如要讓 Vertex AI 中的自訂訓練工作預測工作使用 GPU VM 的預留項目,請加入 serviceShareType 欄位並設為 ALLOW_ALL

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations
    
    {
      "name": "RESERVATION_NAME",
      "reservationSharingPolicy": {
        "serviceShareType": "ALLOW_ALL"
      },
      "shareSettings": {
        "shareType": "SPECIFIC_PROJECTS",
        "projectMap": {
          "CONSUMER_PROJECT_ID_1": {
            "projectId": "CONSUMER_PROJECT_ID_1"
          },
          "CONSUMER_PROJECT_ID_2": {
            "projectId": "CONSUMER_PROJECT_ID_2"
          }
        }
      },
      "specificReservation": {
        "count": "NUMBER_OF_VMS",
        "instanceProperties": {
          "machineType": "MACHINE_TYPE"
        }
      }
    }
    
  • 如要啟用 Compute Engine,自動刪除預留項目,請選用下列任一方法:

    • 如要在特定日期和時間刪除預留項目,請對 beta.reservations.insert 方法發出 POST 要求。在要求主體中,請納入 deleteAtTime 欄位。

      舉例來說,如要建立預留項目,同時指定刪除預留項目的日期和時間,並與兩個消費者專案共用預留項目,請發出下列要求:

      POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations
      
      {
        "deleteAtTime": "DELETE_AT_TIME",
        "name": "RESERVATION_NAME",
        "shareSettings": {
          "shareType": "SPECIFIC_PROJECTS",
          "projectMap": {
            "CONSUMER_PROJECT_ID_1": {
              "projectId": "CONSUMER_PROJECT_ID_1"
            },
            "CONSUMER_PROJECT_ID_2": {
              "projectId": "CONSUMER_PROJECT_ID_2"
            }
          }
        },
        "specificReservation": {
          "count": "NUMBER_OF_VMS",
          "instanceProperties": {
            "machineType": "MACHINE_TYPE"
          }
        }
      }
      

      DELETE_AT_TIME 替換為以 RFC 3339 時間戳記格式設定的日期和時間,且必須符合下列條件:

      YYYY-MM-DDTHH:MM:SSOFFSET
      

      更改下列內容:

      • YYYY-MM-DD:日期格式為 4 位數年份、2 位數月份和 2 位數日期,並以連字號 (-) 分隔。

      • HH:MM:SS:時間格式為 2 位數的小時 (採用 24 小時制)、2 位數的分鐘和 2 位數的秒數,並以半形冒號 (:) 分隔。

      • OFFSET:時區格式為世界標準時間 (UTC) 的偏移量。舉例來說,如要使用太平洋標準時間 (PST),請指定 -08:00。或者,如要不使用位移,請指定 Z

    • 如要在特定時間後刪除預留項目,請對 beta.reservations.insert 方法發出 POST 要求。在要求主體中,請納入 deleteAfterDuration 欄位。

      舉例來說,如要建立保留項目,讓 Compute Engine 在特定時間長度後刪除,並與兩個消費者專案共用保留項目,請提出下列要求:

      POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations
      
      {
        "deleteAfterDuration": {
          "seconds": "DELETE_AFTER_DURATION"
        },
        "name": "RESERVATION_NAME",
        "shareSettings": {
          "shareType": "SPECIFIC_PROJECTS",
          "projectMap": {
            "CONSUMER_PROJECT_ID_1": {
              "projectId": "CONSUMER_PROJECT_ID_1"
            },
            "CONSUMER_PROJECT_ID_2": {
              "projectId": "CONSUMER_PROJECT_ID_2"
            }
          }
        },
        "specificReservation": {
          "count": "NUMBER_OF_VMS",
          "instanceProperties": {
            "machineType": "MACHINE_TYPE"
          }
        }
      }
      

      DELETE_AFTER_DURATION 改為以秒為單位的時間長度。舉例來說,如要指定 86,400 秒 (1 天),請輸入 86400

疑難排解

瞭解如何排解預訂建立問題

後續步驟