建立共用預訂


本文將說明如何建立共用預留項目,也就是在多個專案中共用的預留項目,以及如何管理機構中可使用共用預留項目的專案。

共用預留項目可供主機專案 (擁有者專案) 和共用預留項目的專案 (使用者專案) 使用。如果貴機構有多個專案需要預留屬性相同的虛擬機器 (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.

    Terraform

    To use the Terraform samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    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.

    For more information, see Set up authentication for a local development environment.

    Go

    To use the Go samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    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.

    For more information, see Set up authentication for a local development environment.

    Java

    To use the Java samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    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.

    For more information, see Set up authentication for a local development environment.

    Node.js

    To use the Node.js samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    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.

    For more information, see Set up authentication for a local development environment.

    Python

    To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    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.

    For more information, see Set up authentication for a local development environment.

    REST

    To use the REST API samples on this page in a local development environment, you use the credentials you provide to the 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.

    For more information, see Authenticate for using REST in the Google Cloud authentication documentation.

必要的角色

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

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

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

所需權限

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

  • compute.reservations.create 專案
  • 如要查看機構政策,請按照下列步驟操作: orgpolicy.policy.get 機構
  • 如要編輯機構政策,請按照下列步驟操作: orgpolicy.policy.set 機構
  • 如要指定執行個體範本: 在執行個體範本中使用 compute.instanceTemplates.useReadOnly

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

最佳做法

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

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

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

      • 40 個相符的預留 VM
      • 50 個符合條件的未保留 VM

      • 40 個相符的預留 VM
      • 50 個符合條件的未使用的隨選預留項目

      由於您在未來日期的現有用量已累積為 90 個相符的 VM 和預留項目,且您需要額外增加十個 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。

主控台

請按照自訂清單限制條件政策的步驟,使用「共用預訂項目擁有者專案」限制條件。

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

    前往「預留項目」

    系統隨即會顯示「Reservations」(保留項目) 頁面。

  2. 點按 「Create reservation」(建立預留項目)

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

  3. 在「名稱」部分,輸入預訂名稱。

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

  5. 在「分享類型」專區,執行以下操作:

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

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

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

  7. 在「Use with VM instance」部分中,選取下列任一選項:

    • 如要讓相符的 VM 執行個體自動使用這個保留項目,請選取「Use reservation automatically」(自動使用保留項目) (如果尚未選取)。

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

  8. 在「VM 執行個體數量」中,輸入要預留的 VM 數量。

  9. 在「Machine configuration」(機器設定) 部分中,選取「Use instance template」(使用執行個體範本),然後選取所需的執行個體範本。如果您選取區域執行個體範本,則只能預留與範本區域相同的區域內資源。

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

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

    「Reservations」(保留項目) 頁面隨即開啟。建立共用預留項目可能需要一分鐘的時間。

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 專案共用保留項目,以及預留 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=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \
        --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=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:以 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 替換為以天、小時、分鐘或秒為單位的時間長度。舉例來說,如果要指定 30 分鐘,請指定 30m;如果要指定 1 天 2 小時 3 分鐘 4 秒,請指定 1d2h3m4s

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:以 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 替換為秒數。例如,將 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」(預留項目) 頁面。

    前往「預留項目」

  2. 在「On-demand reservations」(隨需預留項目) 分頁 (預設) 中,按一下 「Create reservation」(建立預留項目)

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

  3. 在「名稱」部分,輸入預訂名稱。

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

  5. 在「分享類型」專區,執行以下操作:

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

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

  6. 在「Use with VM instance」部分中,選取下列任一選項:

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

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

  7. 在「VM 執行個體數量」中,輸入要預留的 VM 數量。

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

    1. 選取「Use existing VM」

    2. 針對「現有 VM」,選取要用來建立預留項目的 VM 屬性。

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

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

    「Reservations」(保留項目) 頁面隨即開啟。預留項目建立作業可能需要一分鐘才能完成。

直接指定屬性

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

主控台

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

    前往「預留項目」

  2. 在「On-demand reservations」(隨需預留項目) 分頁 (預設) 中,按一下 「Create reservation」(建立預留項目)

  3. 按一下 「Create reservation」(建立預留項目)

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

  4. 在「名稱」部分,輸入預訂名稱。

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

  6. 在「分享類型」專區,執行以下操作:

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

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

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

  8. 在「Use with VM instance」部分中,選取下列任一選項:

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

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

  9. 在「VM 執行個體數量」中,輸入要預留的 VM 數量。

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

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

    2. 選用:如要指定 CPU 平台基本要求,或將 GPU 連結至 N1 VM,請執行下列操作:

      1. 如要展開「CPU Platform and GPU」部分,請按一下 展開箭頭。

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

      3. 選用步驟:如要將 GPU 附加至 N1 VM,請按一下 「Add GPU」。接著,針對「GPU 類型」和「GPU 數量」,選取要附加至每個 N1 VM 的 GPU 類型和數量。

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

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

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

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

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

    「Reservations」(保留項目) 頁面隨即開啟。建立共用預留項目可能需要一分鐘的時間。

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 為 10 個 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 的預留項目,請將 --reservation-sharing-policy 標記設為 ALLOW_ALL

    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:以 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 替換為以天、小時、分鐘或秒為單位的時間長度。舉例來說,如果要指定 30 分鐘,請指定 30m;如果要指定 1 天 2 小時 3 分鐘 4 秒,請指定 1d2h3m4s

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 專案共用保留項目,並預留 10 個 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:以 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 天)。

疑難排解

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

後續步驟