建立共用預訂


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

共用預留項目可供預留項目主機專案 (擁有者專案) 使用,也可供預留項目共用對象專案 (消費者專案) 使用。如果貴機構有多個專案需要預留屬性相同的虛擬機器 (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. After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    2. Set a default region and zone.
    3. Terraform

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

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. 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.

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

      Go

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

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. 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.

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

      Java

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

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. 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.

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

      Node.js

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

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. 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.

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

      Python

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

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. 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.

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

      REST

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

        After installing the Google Cloud CLI, initialize it by running the following command:

        gcloud init

        If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「Authenticate for using REST」。

必要的角色

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

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

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

所需權限

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

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

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

最佳做法

建立共用預訂時,建議採用下列最佳做法。 遵循這些最佳做法,有助於提升貴機構共用預訂項目的管理效率和使用率。

  • 由擁有者專案建立共用預留項目,但不要使用。
    • 如要在各專案之間分散支出,建議只讓用戶專案使用共用預留項目。擁有者專案應僅用於建立共用預留項目。
    • 建立共用預留項目時,擁有者專案必須具備足夠配額,才能預留所有資源。接著,在建立預留項目後,擁有者專案必須有配額,才能使用任何預留資源。詳情請參閱「 共用預留項目的額外配額規定」。
  • 盡量減少機構中可建立共用預訂的專案數量。您可以透過「共用預留項目擁有者專案」(compute.sharedReservationsOwnerProjects) 組織政策限制條件進行控管。
    • 您只能列出各專案建立的預留項目。也就是說,共用預留項目只會列在擁有者專案中,您無法列出與各專案共用的預留項目,也無法列出各機構中的所有共用預留項目。因此,如果擁有者專案數量不多,就能更輕鬆地監控及管理共用預留項目。
    • 將共用預留項目限制為僅與幾個專案共用,即可更輕鬆地管理預留資源的配額。
    • 詳情請參閱「允許及限制專案建立和修改共用預留項目」。
  • 盡量減少 VM 屬性相同的個別共用預留項目數量。
    • 每個不重複的VM 屬性組合,最多可有 100 個共用預訂。因此,盡量減少您建立的共用預訂項目數量,並確保這些項目具有相同的 VM 屬性,有助於減輕這項限制帶來的影響。
    • 減少共用預訂可提升管理效率。
  • 保留項目只能在同一個 Cloud Billing 帳戶的專案之間共用。
    • 每個共用預留項目只能與擁有者專案具有相同 Cloud Billing 帳戶的消費者專案共用。方便您查看預訂是否已使用,以及如何計費。
  • 如果是未來預留要求,請仔細檢查要求的 VM 總數。
    • 如果您要建立未來預留要求,請務必要求VM 總數,其中包含下列所有項目:
      • 未來日期已存在的所有相符預留 VM。
      • 未來日期已存在的所有相符未預留 VM。
      • 未來日期已有的任何相符未用依需求預留項目。
      • 您想在未來日期預留的用量增幅。

      舉例來說,假設您在未來需要 10 部額外 VM,且在未來日期已擁有下列資源:

      • 40 個相符的預留 VM
      • 50 個相符的未預留 VM

      • 40 個相符的預留 VM
      • 50 個相符的未使用隨需預留項目

      由於您在未來日期的現有用量已達到 90 個相符的 VM 和預留項目,且您還需要 10 個 VM,因此您必須在未來預留項目要求中指定總數 100

      詳情請參閱「 計算及佈建預留資源」。

允許及限制專案建立和修改共用預訂

根據預設,機構中的任何專案都無法建立或修改共用預訂項目。將專案新增至「共用預留項目擁有者專案」 (compute.sharedReservationsOwnerProjects) 組織政策限制,允許專案建立及修改共用預留項目。如要進一步瞭解機構政策限制,請參閱機構政策服務簡介

請按照下列步驟查看及編輯「共用預留項目擁有者專案」 (compute.sharedReservationsOwnerProjects) 機構政策限制。

查看共用預留項目機構政策限制

如要查看哪些專案可建立及修改共用預留空間,請使用 Google Cloud 控制台或 gcloud CLI。

主控台

請按照查看機構政策的步驟,使用「共用預留項目擁有者專案」限制。

gcloud

如要查看 compute.sharedReservationsOwnerProjects 限制允許哪些專案建立及修改共用預留項目,請按照下列步驟操作:

  1. 使用 gcloud resource-manager org-policies describe 指令,將貴機構的政策下載為名為 policy.yaml 的檔案:

    gcloud resource-manager org-policies describe compute.sharedReservationsOwnerProjects --organization=ORGANIZATION_ID > policy.yaml
    

    ORGANIZATION_ID 替換為貴機構的機構 ID

  2. 使用文字編輯器開啟 policy.yaml 檔案,並查看 compute.sharedReservationsOwnerProjects 限制條件。允許建立及修改共用保留項目的專案會列在 allowedValues 下方:

    ...
    constraint: constraints/compute.sharedReservationsOwnerProjects
    listPolicy:
      allowedValues:
      - projects/PROJECT_NUMBER_1
      - projects/PROJECT_NUMBER_2
      - projects/PROJECT_NUMBER_3
    ...
    

    其中 PROJECT_NUMBER_1PROJECT_NUMBER_2PROJECT_NUMBER_3 是機構中唯一允許建立共用預訂的專案專案編號

  3. 選用:刪除 policy.yaml 檔案。

    • 如果您使用 Linux 或 macOS 終端機,請使用下列指令:

      rm policy.yaml
      
    • 如果您使用 Windows 終端機,請輸入下列指令:

      del policy.yaml
      

編輯共用預留項目的機構政策限制

如要編輯允許建立及修改共用預留空間的專案,請使用 Google Cloud 控制台或 gcloud CLI。

主控台

按照「自訂清單限制條件政策」一節的步驟,使用「Shared Reservations Owner Projects」限制條件。

gcloud

如要編輯 compute.sharedReservationsOwnerProjects 限制允許建立及修改共用預訂的專案,請使用下列其中一種方法:

  • 如要授予單一專案權限,允許建立及修改共用預留項目,請使用 gcloud resource-manager org-policies allow 指令。 您可以針對要授予這項權限的每個專案,重複執行這項指令。

    gcloud resource-manager org-policies allow compute.sharedReservationsOwnerProjects projects/PROJECT_NUMBER \
        --organization=ORGANIZATION_ID
    

    更改下列內容:

    • PROJECT_NUMBER:您要允許建立及修改共用預約的機構專案專案編號 (而非專案 ID)。
    • ORGANIZATION_ID:貴機構的機構 ID
  • 如要授予或撤銷多個專案的權限,以便建立及修改共用預留項目,請替換機構政策限制:

    1. 如要將貴機構的政策下載為名為 policy.yaml 的檔案,請使用 gcloud resource-manager org-policies describe 指令

      gcloud resource-manager org-policies describe compute.sharedReservationsOwnerProjects --organization=ORGANIZATION_ID > policy.yaml
      

      ORGANIZATION_ID 替換為貴機構的機構 ID

    2. 使用文字編輯器修改 policy.yaml 檔案,讓 compute.sharedReservationsOwnerProjects 限制條件列出所有您要允許在 allowedValues 下建立及修改共用預訂的專案。

      • 針對要授予建立及修改共用預留項目權限的每個專案,請在 allowedValues 下方的新行中新增專案。
      • 如要撤銷建立及修改共用預留項目的權限,請刪除每個專案的對應行。

      完成後,請確認 policy.yaml 檔案與下列內容類似:

      ...
      constraint: constraints/compute.sharedReservationsOwnerProjects
      listPolicy:
        allowedValues:
        - projects/PROJECT_NUMBER_1
        - projects/PROJECT_NUMBER_2
        - projects/PROJECT_NUMBER_3
      ...
      

      其中 PROJECT_NUMBER_1PROJECT_NUMBER_2PROJECT_NUMBER_3 是您要允許建立及修改共用預訂的機構中所有專案的專案編號 (而非專案 ID)。

    3. 儲存 policy.yaml 檔案並關閉文字編輯器。

    4. 如要使用變更更新機構的政策,請使用 gcloud resource-manager org-policies set-policy 指令

      gcloud resource-manager org-policies set-policy --organization=ORGANIZATION_ID policy.yaml
      

      ORGANIZATION_ID 替換為貴機構的機構 ID

    5. 選用:刪除 policy.yaml 檔案。

      • 如果您使用 Linux 或 macOS 終端機,請使用下列指令:

        rm policy.yaml
        
      • 如果您使用 Windows 終端機,請輸入下列指令:

        del policy.yaml
        

編輯內容可能需要幾分鐘才會生效。

建立共用預留項目

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

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

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

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

  • 指定現有 VM

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

  • 直接指定屬性

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

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

指定執行個體範本

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

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

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

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

主控台

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

    前往「預留項目」頁面

    系統隨即會顯示「預訂」頁面。

  2. 點按 「建立預留項目」

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

  3. 在「名稱」部分,輸入預留項目的名稱。

  4. 在「區域」和「可用區」部分,選取要預留資源的位置。

  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. 在「機器設定」部分,選取「使用執行個體範本」,然後選取您要使用的執行個體範本。如果選取區域執行個體範本,您只能在與範本區域相同的區域中預留資源。

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

  11. 如要建立預留項目,請點按「Create」(建立)

    「預留項目」頁面隨即開啟。建立共用預留項目最多可能需要一分鐘。

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=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \
    --vm-count=NUMBER_OF_VMS \
    --zone=ZONE

更改下列內容:

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

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

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

  • LOCATION:執行個體範本的位置。 請指定下列其中一個值:

    • 全域執行個體範本:global

    • 區域執行個體範本:regions/REGION。 將 REGION 替換為執行個體範本所在的區域。如果您指定區域執行個體範本,就只能在與範本區域相同的區域內預留 VM。

  • INSTANCE_TEMPLATE_NAME:現有執行個體範本的名稱。如果執行個體範本指定 A3 Mega、A3 High 或 A3 Edge 機型,則必須加入 --require-specific-reservation 旗標。這表示只有明確指定預留項目的 VM 才能使用。詳情請參閱「從特定預留項目使用 VM」。

  • 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=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \
        --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=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \
        --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=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \
          --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=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \
          --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": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"
  }
}

更改下列內容:

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

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

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

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

  • NUMBER_OF_VMS:要預留的 VM 數量。

  • LOCATION:執行個體範本的位置。 請指定下列其中一個值:

    • 全域執行個體範本:global

    • 區域執行個體範本:regions/REGION。 將 REGION 替換為執行個體範本所在的區域。如果您指定區域執行個體範本,就只能在與範本區域相同的區域內預留 VM。

  • INSTANCE_TEMPLATE_NAME:現有執行個體範本的名稱。如果執行個體範本指定 A3 Mega、A3 High 或 A3 Edge 機型,您必須在要求主體中加入 specificReservationRequired 欄位,並將該欄位設為 true。這表示只有明確指定這個預留項目的 VM 才能使用。詳情請參閱「從特定預留項目使用 VM」一文。

舉例來說,如要在可用區 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": "projects/example-project/global/instanceTemplates/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": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"
      },
      "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": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"
      }
    }
    
  • 如要讓 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": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"
        }
      }
      

      請將 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": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"
        }
      }
      

      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」(預留項目) 頁面。

    前往「預留項目」頁面

  2. 在「隨需預留項目」分頁 (預設) 中,按一下 「建立預留項目」

    「Create a reservation」(建立預留項目) 頁面會隨即開啟。

  3. 在「名稱」部分,輸入預留項目的名稱。

  4. 在「區域」和「可用區」部分,選取要預留資源的位置。

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

    1. 如要指定共用預訂,請選取「共用」

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

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

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

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

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

  8. 在「機器設定」專區中,執行下列操作:

    1. 選取「使用現有 VM」

    2. 如果是「現有 VM」,請選取要用來建立預留項目的 VM 屬性。

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

  10. 如要建立預留項目,請點按「Create」(建立)

    「預留項目」頁面隨即開啟。預留項目會在一分鐘內建立完畢。

直接指定屬性

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

主控台

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

    前往「預留項目」頁面

  2. 在「隨需預留項目」分頁 (預設) 中,按一下 「建立預留項目」

  3. 點按 「建立預留項目」

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

  4. 在「名稱」部分,輸入預留項目的名稱。

  5. 在「區域」和「可用區」部分,選取要預留資源的位置。

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

    1. 如要指定共用預訂,請選取「共用」

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

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

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

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

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

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

  10. 在「機器設定」專區中,選取「指定機器類型」,然後指定下列項目:

    1. 在「機器系列」、「系列」和「機器類型」部分,選取機器系列、系列和機器類型。

    2. 選用:如要指定最低 CPU 平台或將 GPU 附加至 N1 VM,請執行下列操作:

      1. 如要展開「CPU Platform and GPU」(CPU 平台和 GPU) 區段,請按一下 展開箭頭。

      2. 選用:如要指定最低 CPU 平台,請選取「CPU Platform」(CPU 平台) 的選項。

      3. 選用:如要將 GPU 附加至 N1 VM,請按一下 「新增 GPU」。然後,針對「GPU type」(GPU 類型) 和「Number of GPUs」(GPU 數量),選取要附加至每個 N1 VM 的 GPU 類型和數量。

    3. 選用:如要將本機 SSD 磁碟連接至預設不含本機 SSD 磁碟的機器類型,請按照下列步驟操作:

      1. 在「磁碟數量」中,選取要附加的本機 SSD 磁碟數量。

      2. 在「介面類型」部分,選取本機 SSD 磁碟的磁碟介面。

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

  12. 如要建立預留項目,請點按「Create」(建立)

    「預留項目」頁面隨即開啟。建立共用預留項目可能需要一分鐘。

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 要使用的機器類型。如果您指定 A3 Mega、A3 High 或 A3 Edge 機型,則必須加入 --require-specific-reservation 旗標。這表示只有明確指定預留項目的 VM 才能使用。詳情請參閱「從特定預留項目使用 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 要使用的機器類型。如果您指定 A3 Mega、A3 High 或 A3 Edge 機型,則必須在要求主體中加入 specificReservationRequired 欄位,並將該欄位設為 true。這表示只有明確指定該預留項目的 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

疑難排解

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

後續步驟