建立共用預留項目

本文說明如何建立共用預留項目 (即多項專案共用的預留項目),以及如何管理組織中哪些專案可以使用共用預留項目。

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

如要瞭解其他建立預留項目的方法,請改為參閱下列頁面:

事前準備

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

    請根據您打算如何使用本頁範例,選取對應的分頁標籤:

    控制台

    使用 Google Cloud 控制台存取 Google Cloud 服務和 API 時,不需要設定驗證機制。

    gcloud

    1. 安裝 Google Cloud CLI,然後使用聯合身分登入 gcloud CLI。 登入後,執行下列指令來初始化 Google Cloud CLI:

      gcloud init
  • 設定預設區域和可用區。
  • Terraform

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

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Go

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

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Java

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

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Node.js

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

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    Python

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

    1. 安裝 Google Cloud CLI。

    2. 設定 gcloud CLI,使用您的聯合身分。

      詳情請參閱「使用聯合身分登入 gcloud CLI」。

    3. 為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果傳回驗證錯誤,請確認您已使用聯合身分登入 gcloud CLI。

    詳情請參閱「為本機開發環境設定驗證機制」。

    REST

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

      安裝 Google Cloud CLI,然後使用聯合身分登入 gcloud CLI。

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

必要的角色

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

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

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

所需權限

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

  • 專案的 compute.reservations.create
  • 如要查看組織政策: orgpolicy.policy.get 在組織上
  • 如要編輯組織政策: orgpolicy.policy.set 組織
  • 如要指定執行個體範本: compute.instanceTemplates.useReadOnly 執行個體範本
  • 如要在 Google Cloud 控制台購買附加承諾使用合約,請按照下列步驟操作: compute.commitments.create 在專案中

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

建立共用預留項目

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

VM 必須具備與該預留項目 完全比對的屬性 ,才能使用該預留項目。如要指定要預留的 VM 屬性,請選取本文中的下列任一節:

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

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

  • 指定現有 VM

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

  • 直接指定屬性

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

根據預設,只要 VM 的屬性與預留項目相符,就能自動使用該預留項目。如要控管預留項目用量,請執行下列一或多項操作:

指定執行個體範本

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

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

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

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

控制台

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

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

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

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

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

  5. 在「Share type」(共用類型) 部分,執行下列操作:

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

    2. 按一下「 Add projects」(新增專案),然後從目前專案的組織中,選取要共用預留項目的專案。最多可選取 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. 在「Resource details」(資源詳細資料) 部分,執行下列操作:

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

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

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

  10. 選用:如要購買與這項共用預留項目相符、依資源計算的承諾使用合約,請按照下列步驟操作:

    1. 如果預留項目包含 GPU 或本機 SSD 磁碟,請確認已取消勾選「Enable auto-delete」(啟用自動刪除功能) 核取方塊。
    2. 在「Maximize savings with a committed use discount」(透過承諾使用折扣盡可能節省費用) 部分,按一下「Purchase a commitment」(購買承諾使用合約)。
    3. 在「Purchase a commitment」(購買承諾使用合約) 窗格中設定承諾使用合約,然後按一下「Attach commitment」(附加承諾使用合約)。承諾使用合約會以草稿形式儲存在頁面上,在您點選「Create」(建立) 之前,系統不會收取任何費用。
    4. 在「揭露事項」部分詳閱條款,然後勾選「按一下下方的『建立』,即表示我同意:」核取方塊。

    如要讓客戶專案獲得這項承諾使用合約的 CUD,請在 Cloud Billing 帳戶啟用 CUD 共用功能。此外,請確認所有消費者專案都使用同一個 Cloud Billing 帳戶。

    如需詳細步驟、需求條件和不相符復原選項,請參閱「在建立預留項目時購買承諾使用合約」。

  11. 如要建立預留項目,請點選「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,以及執行個體範本所在的專案 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-1 和 project-2 共用預留項目,並預留 10 個 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 的預留項目,請加入 --reservation-sharing-policy 旗標,並設為 ALLOW_ALL。

    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,以及執行個體範本所在的專案 ID。

  • ZONE:要預留資源的可用區。

  • RESERVATION_NAME:要建立的預留項目名稱。

  • CONSUMER_PROJECT_ID_1 和 CONSUMER_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 為 10 個 VM 建立預留項目,並與專案 project-1 和 project-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 替換為時間長度 (以秒為單位)。例如,指定 86400 代表 86,400 秒 (1 天)。

指定現有 VM

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

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

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

    1. 依據參照 VM 建立執行個體範本,而不覆寫參照 VM 的屬性。

    2. 使用新建立的範本建立 VM,方法是執行下列其中一項或兩項操作:

  • 建立 VM,其屬性必須與參照 VM 完全相符,如下所示:

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

    • 在用戶專案中建立 VM,並手動確保其屬性與參照 VM 的屬性相符。

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

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

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

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

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

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

  5. 在「Share type」(共用類型) 部分,執行下列操作:

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

    2. 按一下「 Add projects」(新增專案),然後從目前專案的組織中,選取要共用預留項目的專案。最多可選取 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. 在「Resource details」(資源詳細資料) 部分,執行下列操作:

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

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

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

  10. 選用:如要購買與這項共用預留項目相符、依資源計算的承諾使用合約,請按照下列步驟操作:

    1. 如果預留項目包含 GPU 或本機 SSD 磁碟,請確認已取消勾選「Enable auto-delete」(啟用自動刪除功能) 核取方塊。
    2. 在「Maximize savings with a committed use discount」(透過承諾使用折扣盡可能節省費用) 部分,按一下「Purchase a commitment」(購買承諾使用合約)。
    3. 在「Purchase a commitment」(購買承諾使用合約) 窗格中設定承諾使用合約,然後按一下「Attach commitment」(附加承諾使用合約)。承諾使用合約會以草稿形式儲存在頁面上,在您點選「Create」(建立) 之前,系統不會收取任何費用。
    4. 在「揭露事項」部分詳閱條款,然後勾選「按一下下方的『建立』,即表示我同意:」核取方塊。

    如要讓客戶專案獲得這項承諾使用合約的 CUD,請在 Cloud Billing 帳戶啟用 CUD 共用功能。此外,請確認所有消費者專案都使用同一個 Cloud Billing 帳戶。

    如需詳細步驟、需求條件和不相符復原選項,請參閱「在建立預留項目時購買承諾使用合約」。

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

直接指定屬性

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

控制台

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

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

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

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

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

  5. 在「Share type」(共用類型) 部分,執行下列操作:

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

    2. 按一下「 Add projects」(新增專案),然後從目前專案的組織中,選取要共用預留項目的專案。最多可選取 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. 在「Resource details」(資源詳細資料) 部分,執行下列操作:

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

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

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

  10. 選用:如要購買與這項共用預留項目相符、依資源計算的承諾使用合約,請按照下列步驟操作:

    1. 如果預留項目包含 GPU 或本機 SSD 磁碟,請確認已取消勾選「Enable auto-delete」(啟用自動刪除功能) 核取方塊。
    2. 在「Maximize savings with a committed use discount」(透過承諾使用折扣盡可能節省費用) 部分,按一下「Purchase a commitment」(購買承諾使用合約)。
    3. 在「Purchase a commitment」(購買承諾使用合約) 窗格中設定承諾使用合約,然後按一下「Attach commitment」(附加承諾使用合約)。承諾使用合約會以草稿形式儲存在頁面上,在您點選「Create」(建立) 之前,系統不會收取任何費用。
    4. 在「揭露事項」部分詳閱條款,然後勾選「按一下下方的『建立』,即表示我同意:」核取方塊。

    如要讓客戶專案獲得這項承諾使用合約的 CUD,請在 Cloud Billing 帳戶啟用 CUD 共用功能。此外,請確認所有消費者專案都使用同一個 Cloud Billing 帳戶。

    如需詳細步驟、需求條件和不相符復原選項,請參閱「在建立預留項目時購買承諾使用合約」。

  11. 如要建立預留項目,請點選「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-1 和 project-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_1 和 CONSUMER_PROJECT_ID_2:可使用這項預留項目的專案 ID。最多可加入 100 項消費者專案。這些專案必須與擁有者專案位於同一個組織。請勿加入擁有者專案。根據預設,系統已允許使用預留項目。

  • NUMBER_OF_VMS:要預留的 VM 數量。

  • MACHINE_TYPE:各 VM 要使用的機型。

舉例來說,如要建立預留項目,請在可用區 us-central1-a 指定全域執行個體範本,與專案 project-1 和 project-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 替換為時間長度 (以秒為單位)。例如,指定 86400 代表 86,400 秒 (1 天)。

後續步驟