予約を使用する


このドキュメントでは、Compute Engine で予約を消費する方法について説明します。他の Google Cloud プロダクトで予約を消費する方法については、次のドキュメントをご覧ください。

予約を作成した後、または将来の予約内容を遂行するために Compute Engine が自動的に予約を作成した後、Compute Engine は予約されたリソースを保持します。これらの予約済みリソースを使用して、予約のプロパティに一致する Compute Engine インスタンスを作成できます。このアクションは、予約の消費と呼ばれます。予約済み容量は、予約がすべて消費されるまで、インスタンスの作成に使用できます。

制限事項

予約を消費して、次の Compute Engine リソースを作成することはできません。

  • Spot VM またはプリエンプティブル インスタンス

  • 単一テナントノード

始める前に

  • まだ設定していない場合は、認証を設定します。認証とは、 Google Cloud サービスと API にアクセスするために ID を確認するプロセスです。ローカル開発環境からコードまたはサンプルを実行するには、次のいずれかのオプションを選択して 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. 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.

        詳細については 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.

        詳細については 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.

        詳細については 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.

        詳細については 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 認証ドキュメントの REST を使用して認証するをご覧ください。

必要なロール

予約を消費するために必要な権限を取得するには、プロジェクトに対する Compute インスタンス管理者(v1)roles/compute.instanceAdmin.v1)の IAM ロールを付与するよう管理者に依頼します。ロールの付与については、プロジェクト、フォルダ、組織へのアクセス権の管理をご覧ください。

この事前定義ロールには、予約の使用に必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

予約を使用するには、次の権限が必要です。

  • 予約を作成する権限: プロジェクトに対する compute.reservations.create
  • インスタンスを作成する:
    • プロジェクトに対する compute.instances.create
    • カスタム イメージを使用して VM を作成する: イメージに対する compute.images.useReadOnly
    • スナップショットを使用して VM を作成する: スナップショットに対する compute.snapshots.useReadOnly
    • インスタンス テンプレートを使用して VM を作成する: インスタンス テンプレートに対する compute.instanceTemplates.useReadOnly
    • レガシー ネットワークを VM に割り当てる: プロジェクトに対する compute.networks.use
    • VM の静的 IP アドレスを指定する: プロジェクトに対する compute.addresses.use
    • レガシー ネットワークの使用時に VM に外部 IP アドレスを割り当てる: プロジェクトに対する compute.networks.useExternalIp
    • VM のサブネットを指定する: プロジェクトまたは選択したサブネットに対する compute.subnetworks.use
    • VPC ネットワークの使用時に VM に外部 IP アドレスを割り当てる: プロジェクトまたは選択したサブネットに対する compute.subnetworks.useExternalIp
    • VM の VM インスタンス メタデータを設定する: プロジェクトに対する compute.instances.setMetadata
    • VM にタグを設定する: VM に対する compute.instances.setTags
    • VM にラベルを設定する: VM に対する compute.instances.setLabels
    • VM が使用するサービス アカウントを設定する: VM に対する compute.instances.setServiceAccount
    • VM に新しいディスクを作成する: プロジェクトに対する compute.disks.create
    • 既存のディスクを読み取り専用モードまたは読み取り / 書き込みモードでアタッチする: ディスクに対する compute.disks.use
    • 既存のディスクを読み取り専用モードでアタッチする: ディスクに対する compute.disks.useReadOnly
  • インスタンス テンプレートを作成する: プロジェクトに対する compute.instanceTemplates.create

カスタムロールや他の事前定義ロールを使用して、これらの権限を取得することもできます。

予約を消費する

以下の各セクションの例では、単一のコンピューティング インスタンスを作成して予約を消費する方法を示しています。また、別のデプロイ オプションを消費して予約のプロパティに一致するインスタンスを作成するか、既存のインスタンスのプロパティを更新して自動的に使用される予約に一致させることで、予約を消費することもできます。

予約を消費するには、次のいずれかの方法を使用します。

自動的に消費される予約を消費する

自動的に消費される予約を作成すると、予約のプロパティに一致するコンピューティング インスタンスが自動的に予約を消費します。この消費に関する動作は、新規および既存の実行中のインスタンスの両方に適用されます。予約を作成した場合、または Compute Engine が将来の予約内容を遂行するために予約を自動的に作成した場合は、この予約タイプがデフォルト設定になります。

単一プロジェクトの自動予約と共有の自動予約のプロパティが一致する場合、プロジェクト内のインスタンスは、単一プロジェクトの予約を先に消費してから、共有予約を消費します。詳細については、予約の消費順序をご覧ください。

自動予約の例を作成して消費するには、次のいずれかのオプションを選択します。

コンソール

次の例は、32 個の vCPU と最小 CPU プラットフォームとして Intel Cascade Lake を備えた 3 つの N2 インスタンスの自動予約をゾーン us-central1-a に作成する方法を示しています。また、予約を消費する単一のインスタンスを作成する方法も示しています。

サンプル自動予約を作成して消費するには、次の操作を行います。

  1. 予約の例を作成する手順は次のとおりです。

    1. Google Cloud コンソールで、[予約] ページに移動します。

      [予約] に移動

      残りの手順は、Google Cloud コンソールに自動的に表示されます。

    2. [オンデマンド予約] タブ(デフォルト)で、 [予約を作成] をクリックします。[予約を作成] ページが表示されます。

    3. [名前] フィールドに、予約の名前を入力します。たとえば、「reservation-01」と入力します。

    4. リソースを予約するリージョンゾーンを選択します。たとえば、[us-central1] と [us-central1-a] をそれぞれ選択します。

    5. [共有タイプ] セクションで、次のいずれかを行います。

      • 単一プロジェクトの予約を作成するには、[ローカル] を選択します。

      • 共有予約を作成するには、[共有] を選択し、予約を共有するプロジェクトを指定します。

    6. [VM インスタンスでの使用] セクションで、[予約を自動的に使用する] を選択します(まだ選択されていない場合)。

    7. [VM インスタンスの数] フィールドに「3」と入力します。

    8. [汎用] タブで [N2] を選択します。

    9. [マシンタイプ] セクションの [プリセット] タブ(デフォルト)で、[n2-standard-32] を選択します。

    10. [CPU プラットフォームと GPU] を開き、[CPU プラットフォーム] フィールドで [Intel Cascade Lake 以降] を選択します。

    11. [作成] をクリックします。

  2. サンプルの予約を消費するインスタンスを作成するには、次の手順を行います。

    1. Google Cloud コンソールで [インスタンスの作成] ページに移動します。

      [インスタンスの作成] に移動

      [インスタンスの作成] ページが表示され、[マシンの構成] ペインが表示されます。

    2. [マシンの構成] ペインで、次の操作を行います。

      1. [名前] フィールドに、インスタンスの名前を入力します。この例では、「instance-01」と入力します。

      2. リソースを予約するリージョンゾーンを指定します。この例では、それぞれ [us-central1] と [us-central1-a] を選択しています。

      3. [汎用] タブで [N2] を選択します。

      4. [マシンタイプ] セクションの [プリセット] タブ(デフォルト)で、[n2-standard-32] を選択します。

      5. [詳細オプション] セクションを開き、[CPU プラットフォーム] フィールドで [Intel Cascade Lake 以降] を選択します。

    3. 省略可: 一致する予約を自動的に使用する状態がデフォルトの設定です。ただし、この設定を指定する場合は、次の操作を行います。

      1. ナビゲーション メニューで、[詳細設定] をクリックします。[詳細設定] ペインが表示されます。

      2. [予約] セクションで、[自動選択を使用する] を選択します。

    4. [作成] をクリックします。

gcloud

次の例は、32 個の vCPU と最小 CPU プラットフォームとして Intel Cascade Lake を備えた 3 つの N2 インスタンスの自動予約をゾーン us-central1-a に作成する方法を示しています。また、予約を消費する単一のインスタンスを作成する方法も示しています。

サンプル自動予約を作成して消費するには、次の操作を行います。

  1. サンプルの予約を作成するには、gcloud compute reservations create コマンドを使用します。

    gcloud compute reservations create reservation-01 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --vm-count=3 \
        --zone=us-central1-a
    
  2. サンプル予約を使用するインスタンスを作成するには、--reservation-affinity フラグを any に設定して gcloud compute instances create コマンドを使用します。any はデフォルトの構成であるため、このフラグを省略することもできます。

    gcloud compute instances create instance-01 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --reservation-affinity=any \
        --zone=us-central1-a
    

Go

インスタンス テンプレートを使用してサンプルの自動予約を作成し、同じテンプレートを使用して予約を消費するインスタンスを作成するには、次のコードサンプルを使用します。

import (
	"context"
	"fmt"
	"io"

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

// consumeAnyReservation creates instance, consuming any available reservation
func consumeAnyReservation(w io.Writer, projectID, zone, instanceName, sourceTemplate string) error {
	// projectID := "your_project_id"
	// zone := "us-west3-a"
	// instanceName := "your_instance_name"
	// sourceTemplate: existing template path. Following formats are allowed:
	//  	- projects/{project_id}/global/instanceTemplates/{template_name}
	//  	- projects/{project_id}/regions/{region}/instanceTemplates/{template_name}
	//  	- https://www.googleapis.com/compute/v1/projects/{project_id}/global/instanceTemplates/instanceTemplate
	//  	- https://www.googleapis.com/compute/v1/projects/{project_id}/regions/{region}/instanceTemplates/instanceTemplate

	ctx := context.Background()

	instancesClient, err := compute.NewInstancesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstancesRESTClient: %w", err)
	}
	defer instancesClient.Close()

	req := &computepb.InsertInstanceRequest{
		Project:                projectID,
		Zone:                   zone,
		SourceInstanceTemplate: proto.String(sourceTemplate),
		InstanceResource: &computepb.Instance{
			Name: proto.String(instanceName),
			// specifies that any matching reservation should be consumed
			ReservationAffinity: &computepb.ReservationAffinity{
				ConsumeReservationType: proto.String("ANY_RESERVATION"),
			},
		},
	}

	op, err := instancesClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create instance: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}
	fmt.Fprintf(w, "Instance created from reservation\n")

	return nil
}

Java

次の例は、4 つの vCPU と最小 CPU プラットフォームとして Intel Skylake を備えた N1 インスタンスをゾーン us-central1-a に作成する方法を示しています。インスタンスは、一致する予約を自動的に使用します。

サンプル インスタンスを作成するには、次のコードサンプルを使用します。

import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.ANY_RESERVATION;

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.InsertInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.ReservationAffinity;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ConsumeAnyMatchingReservation {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";
    // Zone where the VM instance will be created.
    String zone = "us-central1-a";
    // Name of the VM instance you want to query.
    String instanceName = "YOUR_INSTANCE_NAME";
    // machineType: machine type of the VM being created.
    // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
    String machineTypeName = "n1-standard-4";
    // sourceImage: path to the operating system image to mount.
    // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
    String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
    // diskSizeGb: storage size of the boot disk to attach to the instance.
    long diskSizeGb = 10L;
    // networkName: network interface to associate with the instance.
    String networkName = "default";
    // Minimum CPU platform of the instances.
    String minCpuPlatform = "Intel Skylake";

    createInstanceAsync(projectId, zone, instanceName, machineTypeName, sourceImage,
        diskSizeGb, networkName, minCpuPlatform);
  }

  // Create a virtual machine targeted with the reserveAffinity field.
  // In this consumption model, existing and new VMs automatically consume a reservation
  // if their properties match the VM properties specified in the reservation.
  public static Instance createInstanceAsync(String projectId, String zone,
      String instanceName, String machineTypeName, String sourceImage,
      long diskSizeGb, String networkName, String minCpuPlatform)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    String machineType = String.format("zones/%s/machineTypes/%s", zone, machineTypeName);
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (InstancesClient instancesClient = InstancesClient.create()) {
      AttachedDisk disk =
          AttachedDisk.newBuilder()
              .setBoot(true)
              .setAutoDelete(true)
              .setType(AttachedDisk.Type.PERSISTENT.toString())
              .setDeviceName("disk-1")
              .setInitializeParams(
                  AttachedDiskInitializeParams.newBuilder()
                      .setSourceImage(sourceImage)
                      .setDiskSizeGb(diskSizeGb)
                      .build())
              .build();

      NetworkInterface networkInterface = NetworkInterface.newBuilder()
          .setName(networkName)
          .build();

      ReservationAffinity reservationAffinity =
          ReservationAffinity.newBuilder()
              .setConsumeReservationType(ANY_RESERVATION.toString())
              .build();

      Instance instanceResource =
          Instance.newBuilder()
              .setName(instanceName)
              .setMachineType(machineType)
              .addDisks(disk)
              .addNetworkInterfaces(networkInterface)
              .setMinCpuPlatform(minCpuPlatform)
              .setReservationAffinity(reservationAffinity)
              .build();

      InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setInstanceResource(instanceResource)
          .build();

      OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
          insertInstanceRequest);

      Operation response = operation.get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        return null;
      }
      return instancesClient.get(projectId, zone, instanceName);
    }
  }
}

Node.js

次の例は、4 つの vCPU と最小 CPU プラットフォームとして Intel Skylake を備えた N1 インスタンスをゾーン us-central1-a に作成する方法を示しています。インスタンスは、一致する予約を自動的に使用します。

サンプル インスタンスを作成するには、次のコードサンプルを使用します。

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

// Instantiate a reservationsClient
const instancesClient = new computeLib.InstancesClient();
// Instantiate a zoneOperationsClient
const zoneOperationsClient = new computeLib.ZoneOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The ID of the project where you want to create instance.
const projectId = await instancesClient.getProjectId();
// The zone in which to create instance.
const zone = 'us-central1-a';
// The name of the instance to create.
// const instanceName = 'instance-01';
// Machine type to use for VM.
const machineType = 'n1-standard-4';

// Create instance to consume reservation if their properties match the VM properties
async function callCreateInstanceToConsumeAnyReservation() {
  // Describe the size and source image of the boot disk to attach to the instance.
  const disk = new compute.Disk({
    boot: true,
    autoDelete: true,
    type: 'PERSISTENT',
    initializeParams: {
      diskSizeGb: '10',
      sourceImage: 'projects/debian-cloud/global/images/family/debian-12',
    },
  });

  //  Define networkInterface
  const networkInterface = new compute.NetworkInterface({
    name: 'global/networks/default',
  });

  // Define reservationAffinity
  const reservationAffinity = new compute.ReservationAffinity({
    consumeReservationType: 'ANY_RESERVATION',
  });

  // Create an instance
  const instance = new compute.Instance({
    name: instanceName,
    machineType: `zones/${zone}/machineTypes/${machineType}`,
    minCpuPlatform: 'Intel Skylake',
    disks: [disk],
    networkInterfaces: [networkInterface],
    reservationAffinity,
  });

  const [response] = await instancesClient.insert({
    project: projectId,
    instanceResource: instance,
    zone,
  });

  let operation = response.latestResponse;

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

  console.log(`Instance ${instanceName} created.`);
}

await callCreateInstanceToConsumeAnyReservation();

Python

次の例は、1 つの vCPU と最小 CPU プラットフォームとして Intel Ivy を備えた 3 つの N1 インスタンスに対して、ゾーン us-central1-a に自動予約を作成する方法を示しています。また、予約を消費する単一のインスタンスを作成する方法も示しています。

サンプル自動予約を作成して消費するには、次の操作を行います。

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def consume_any_project_reservation(
    project_id: str,
    zone: str,
    reservation_name: str,
    instance_name: str,
    machine_type: str = "n1-standard-1",
    min_cpu_platform: str = "Intel Ivy Bridge",
) -> compute_v1.Instance:
    """
    Creates a specific reservation in a single project and launches a VM
    that consumes the newly created reservation.
    Args:
        project_id (str): The ID of the Google Cloud project.
        zone (str): The zone to create the reservation.
        reservation_name (str): The name of the reservation to create.
        instance_name (str): The name of the instance to create.
        machine_type (str): The machine type for the instance.
        min_cpu_platform (str): The minimum CPU platform for the instance.
    """
    instance_properties = (
        compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
            machine_type=machine_type,
            min_cpu_platform=min_cpu_platform,
        )
    )

    reservation = compute_v1.Reservation(
        name=reservation_name,
        specific_reservation=compute_v1.AllocationSpecificSKUReservation(
            count=3,
            instance_properties=instance_properties,
        ),
    )

    # Create a reservation client
    client = compute_v1.ReservationsClient()
    operation = client.insert(
        project=project_id,
        zone=zone,
        reservation_resource=reservation,
    )
    wait_for_extended_operation(operation, "Reservation creation")

    instance = compute_v1.Instance()
    instance.name = instance_name
    instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
    instance.min_cpu_platform = min_cpu_platform
    instance.zone = zone

    # Set the reservation affinity to target any matching reservation
    instance.reservation_affinity = compute_v1.ReservationAffinity(
        consume_reservation_type="ANY_RESERVATION",  # Type of reservation to consume
    )
    # Define the disks for the instance
    instance.disks = [
        compute_v1.AttachedDisk(
            boot=True,  # Indicates that this is a boot disk
            auto_delete=True,  # The disk will be deleted when the instance is deleted
            initialize_params=compute_v1.AttachedDiskInitializeParams(
                source_image="projects/debian-cloud/global/images/family/debian-11",
                disk_size_gb=10,
            ),
        )
    ]
    instance.network_interfaces = [
        compute_v1.NetworkInterface(
            network="global/networks/default",  # The network to use
            access_configs=[
                compute_v1.AccessConfig(
                    name="External NAT",  # Name of the access configuration
                    type="ONE_TO_ONE_NAT",  # Type of access configuration
                )
            ],
        )
    ]
    # Create a request to insert the instance
    request = compute_v1.InsertInstanceRequest()
    request.zone = zone
    request.project = project_id
    request.instance_resource = instance

    vm_client = compute_v1.InstancesClient()
    operation = vm_client.insert(request)
    wait_for_extended_operation(operation, "instance creation")
    print(f"Instance {instance_name} that targets any open reservation created.")

    return vm_client.get(project=project_id, zone=zone, instance=instance_name)

REST

次の例は、32 個の vCPU と最小 CPU プラットフォームとして Intel Cascade Lake を備えた 3 つの N2 インスタンスの自動予約をゾーン us-central1-a に作成する方法を示しています。また、予約を消費する単一のインスタンスを作成する方法も示しています。

サンプル自動予約を作成して消費するには、次の操作を行います。

  1. サンプルの予約を作成するには、reservations.insert メソッドPOST リクエストを送信します。

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations
    
    {
      "name": "reservation-01",
      "specificReservation": {
        "count": "3",
        "instanceProperties": {
          "machineType": "n2-standard-32",
          "minCpuPlatform": "Intel Cascade Lake",
        }
      }
    }
    
  2. サンプル予約を消費するインスタンスを作成するには、instances.insert メソッドPOST リクエストを送信します。リクエストの本文に、ANY_RESERVATION に設定された consumeReservationType フィールドを含めます。ただし、ANY_RESERVATION はデフォルトの構成であるため、このフィールドを省略することもできます。

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/instances
    
    {
      "name": "instance-01",
      "machineType": "zones/us-central1-a/machineTypes/n2-standard-32",
      "minCpuPlatform": "Intel Cascade Lake",
      "disks": [
        {
          "boot": true,
          "initializeParams": {
            "sourceImage": "projects/debian-cloud/global/images/family/debian-12"
          }
        }
      ],
      "networkInterfaces": [
        {
          "network": "global/networks/default"
        }
      ],
      "reservationAffinity": {
        "consumeReservationType": "ANY_RESERVATION"
      }
    }
    

明示的に対象となる予約を消費する

明示的に対象となっている予約では、インスタンスが予約を対象としている場合にのみ、新しいコンピューティング インスタンスが一致する予約を消費できます。インスタンスが正常に作成されるのは、インスタンスのプロパティが予約プロパティと一致する場合のみです。そうしない場合、エラーが発生します。

使用する作成方法に基づいて、次のように特定の予約と、それらの予約を対象とするインスタンスを作成します。

作成方法 予約を作成する場合 インスタンスを作成する場合
Google Cloud コンソール [VM インスタンスでの使用] セクションで、[特定の予約を選択する] を選択します。 [詳細設定] ペインの [予約] セクションで、[予約を選択] を選択します。
Google Cloud CLI --require-specific-reservation フラグを追加します。 次のフラグを設定します。
  • --reservation-affinity フラグが specific に設定されています。
  • 予約の URL に設定されている --reservation フラグ。
Go true に設定されている SpecificReservationRequired フィールドを配置します。 ReservationAffinity フィールドに次のフィールドを配置します。
  • SPECIFIC_RESERVATION に設定されている ConsumeReservationType フィールド。
  • compute.googleapis.com/reservation-name に設定されている Key フィールド。
  • 予約の URL に設定されている Values フィールド。
Java true に設定されている setSpecificReservationRequired フィールドを配置します。 ReservationAffinity フィールドに次のフィールドを配置します。
  • SPECIFIC_RESERVATION に設定されている setConsumeReservationType フィールド。
  • compute.googleapis.com/reservation-name に設定されている setKey フィールド。
  • 予約の URL に設定されている addValues フィールド。
Node.js と REST API true に設定されている specificReservationRequired フィールドを配置します。 reservationAffinity フィールドに次のフィールドを配置します。
  • SPECIFIC_RESERVATION に設定されている consumeReservationType フィールド。
  • compute.googleapis.com/reservation-name に設定されている key フィールド。
  • 予約の URL に設定されている values フィールド。
Python と Terraform true に設定されている specific_reservation_required フィールドを配置します。 reservation_affinity フィールドに次のフィールドを配置します。
  • SPECIFIC_RESERVATION に設定されている consume_reservation_type フィールド。
  • compute.googleapis.com/reservation-name に設定されている key フィールド。
  • 予約の URL に設定されている values フィールド。

特定のサンプル予約と、その予約を消費するインスタンスを作成するには、次のいずれかのオプションを選択します。

コンソール

次の例は、32 個の vCPU と最小 CPU プラットフォームとして Intel Cascade Lake を備えた 3 つの N2 インスタンスに対して、ゾーン us-central1-a に特定の予約を作成する方法を示しています。また、予約を消費する単一のインスタンスを作成する方法も示しています。

特定のサンプル予約を作成して消費するには、次の操作を行います。

  1. 予約の例を作成する手順は次のとおりです。

    1. Google Cloud コンソールで、[予約] ページに移動します。

      [予約] に移動

      残りの手順は、Google Cloud コンソールに自動的に表示されます。

    2. [オンデマンド予約] タブ(デフォルト)で、 [予約を作成] をクリックします。[予約を作成] ページが表示されます。

    3. [名前] フィールドに、予約の名前を入力します。たとえば、「reservation-02」と入力します。

    4. リソースを予約するリージョンゾーンを指定します。この例では、それぞれ [us-central1] と [us-central1-a] を選択しています。

    5. [共有タイプ] セクションで、次のいずれかを行います。

      • 単一プロジェクトの予約を作成するには、[ローカル] を選択します。

      • 共有予約を作成するには、[共有] を選択し、予約を共有するプロジェクトを指定します。

    6. [VM インスタンスでの使用] セクションで、[特定の予約を選択する] を選択します。

    7. [VM インスタンスの数] フィールドに「3」と入力します。

    8. [汎用] タブで [N2] を選択します。

    9. [マシンタイプ] セクションの [プリセット] タブ(デフォルト)で、[n2-standard-32] を選択します。

    10. [CPU プラットフォームと GPU] を開き、[CPU プラットフォーム] フィールドで [Intel Cascade Lake 以降] を選択します。

    11. [作成] をクリックします。

  2. サンプルの予約を消費するインスタンスを作成するには、次の手順を行います。

    1. Google Cloud コンソールで [インスタンスの作成] ページに移動します。

      [インスタンスの作成] に移動

      [インスタンスの作成] ページが表示され、[マシンの構成] ペインが表示されます。

    2. [マシンの構成] ペインで、次の操作を行います。

      1. [名前] フィールドに、インスタンスの名前を入力します。この例では、「instance-02」と入力します。

      2. リソースを予約するリージョンゾーンを指定します。この例では、それぞれ [us-central1] と [us-central1-a] を選択しています。

      3. [汎用] タブで [N2] を選択します。

      4. [マシンタイプ] セクションの [プリセット] タブ(デフォルト)で、[n2-standard-32] を選択します。

      5. [詳細オプション] セクションを開き、[CPU プラットフォーム] フィールドで [Intel Cascade Lake 以降] を選択します。

    3. ナビゲーション メニューで、[詳細設定] をクリックします。[詳細設定] ペインが表示されます。

    4. [予約] セクションで [予約を選択] を選択し、[予約を選択] をクリックします。

    5. 表示された [予約を選択] ペインで、次の操作を行います。

      1. 前の手順で作成した特定の予約を選択します。別のプロジェクトに存在する共有予約を消費する場合は、[プロジェクト] リストで、予約が存在するプロジェクトを選択します。

      2. [選択] をクリックします。

    6. [作成] をクリックします。

gcloud

次の例は、32 個の vCPU と最小 CPU プラットフォームとして Intel Cascade Lake を備えた 3 つの N2 インスタンスに対して、ゾーン us-central1-a に特定の予約を作成する方法を示しています。また、予約を消費する単一のインスタンスを作成する方法も示しています。

特定のサンプル予約を作成して消費するには、次の操作を行います。

  1. サンプル予約を作成するには、--require-specific-reservation フラグを指定して gcloud compute reservations create コマンドを使用します。

    gcloud compute reservations create reservation-02 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --require-specific-reservation \
        --vm-count=3 \
        --zone=us-central1-a
    
  2. サンプル予約を消費するインスタンスを作成するには、--reservation フラグと --reservation-affinity=specific フラグを指定して gcloud compute instances create コマンドを使用します。

    gcloud compute instances create instance-02 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --reservation-affinity=specific \
        --reservation=RESERVATION_URL \
        --zone=us-central1-a
    

    RESERVATION_URL は、予約の URL に置き換えます。次のいずれかの値を指定します。

    • 同じプロジェクトで予約を作成した場合: reservation-02

    • 予約が別のプロジェクトに存在する場合: projects/PROJECT_ID/reservations/reservation-02

Go

次の例は、32 個の vCPU と最小 CPU プラットフォームとして Intel Cascade Lake を備えた N2 インスタンスをゾーン us-central1-a に作成し、特定の一致する予約を消費する方法を示しています。

  • 単一プロジェクトの特定の予約を消費するサンプル インスタンスを作成するには、次のコードサンプルを使用します。

    import (
    	"context"
    	"fmt"
    	"io"
    
    	compute "cloud.google.com/go/compute/apiv1"
    	computepb "cloud.google.com/go/compute/apiv1/computepb"
    	"google.golang.org/protobuf/proto"
    )
    
    // consumeSpecificReservation creates instance, consuming specific reservation
    // Note: respective reservation should have SpecificReservationRequired: true
    func consumeSpecificReservation(w io.Writer, projectID, zone, instanceName, reservationName string) error {
    	// projectID := "your_project_id"
    	// zone := "us-west3-a"
    	// reservationName := "your_reservation_name"
    	// instanceName := "your_instance_name"
    
    	ctx := context.Background()
    	machineType := fmt.Sprintf("zones/%s/machineTypes/%s", zone, "n2-standard-32")
    	sourceImage := "projects/debian-cloud/global/images/family/debian-12"
    
    	instancesClient, err := compute.NewInstancesRESTClient(ctx)
    	if err != nil {
    		return fmt.Errorf("NewInstancesRESTClient: %w", err)
    	}
    	defer instancesClient.Close()
    
    	req := &computepb.InsertInstanceRequest{
    		Project: projectID,
    		Zone:    zone,
    		InstanceResource: &computepb.Instance{
    			Disks: []*computepb.AttachedDisk{
    				{
    					InitializeParams: &computepb.AttachedDiskInitializeParams{
    						DiskSizeGb:  proto.Int64(10),
    						SourceImage: proto.String(sourceImage),
    					},
    					AutoDelete: proto.Bool(true),
    					Boot:       proto.Bool(true),
    					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
    				},
    			},
    			MachineType:    proto.String(machineType),
    			MinCpuPlatform: proto.String("Intel Cascade Lake"),
    			Name:           proto.String(instanceName),
    			NetworkInterfaces: []*computepb.NetworkInterface{
    				{
    					Name: proto.String("global/networks/default"),
    				},
    			},
    			// specifies particular reservation, which should be consumed
    			ReservationAffinity: &computepb.ReservationAffinity{
    				ConsumeReservationType: proto.String("SPECIFIC_RESERVATION"),
    				Key:                    proto.String("compute.googleapis.com/reservation-name"),
    				Values:                 []string{reservationName},
    			},
    		},
    	}
    
    	op, err := instancesClient.Insert(ctx, req)
    	if err != nil {
    		return fmt.Errorf("unable to create instance: %w", err)
    	}
    
    	if err = op.Wait(ctx); err != nil {
    		return fmt.Errorf("unable to wait for the operation: %w", err)
    	}
    	fmt.Fprintf(w, "Instance created from reservation\n")
    
    	return nil
    }
    
  • 共有の特定の予約を消費するサンプル インスタンスを作成するには、次のコードサンプルを使用します。

    import (
    	"context"
    	"fmt"
    	"io"
    
    	computepb "cloud.google.com/go/compute/apiv1/computepb"
    	"google.golang.org/protobuf/proto"
    )
    
    // consumeSpecificSharedReservation consumes specific shared reservation in particular zone
    func consumeSpecificSharedReservation(w io.Writer, client InstanceClientInterface, projectID, baseProjectId, zone, instanceName, reservationName string) error {
    	// client, err := compute.NewInstancesRESTClient(ctx)
    	// projectID := "your_project_id". Project where reservation is created.
    	// baseProjectId := "shared_project_id". Project where instance will be consumed and created.
    	// zone := "us-west3-a"
    	// reservationName := "your_reservation_name"
    	// instanceName := "your_instance_name"
    
    	ctx := context.Background()
    	machineType := fmt.Sprintf("zones/%s/machineTypes/%s", zone, "n2-standard-32")
    	sourceImage := "projects/debian-cloud/global/images/family/debian-12"
    	sharedReservation := fmt.Sprintf("projects/%s/reservations/%s", baseProjectId, reservationName)
    
    	req := &computepb.InsertInstanceRequest{
    		Project: projectID,
    		Zone:    zone,
    		InstanceResource: &computepb.Instance{
    			Disks: []*computepb.AttachedDisk{
    				{
    					InitializeParams: &computepb.AttachedDiskInitializeParams{
    						DiskSizeGb:  proto.Int64(10),
    						SourceImage: proto.String(sourceImage),
    					},
    					AutoDelete: proto.Bool(true),
    					Boot:       proto.Bool(true),
    					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
    				},
    			},
    			MachineType:    proto.String(machineType),
    			MinCpuPlatform: proto.String("Intel Cascade Lake"),
    			Name:           proto.String(instanceName),
    			NetworkInterfaces: []*computepb.NetworkInterface{
    				{
    					Name: proto.String("global/networks/default"),
    				},
    			},
    			// specifies particular reservation, which should be consumed
    			ReservationAffinity: &computepb.ReservationAffinity{
    				ConsumeReservationType: proto.String("SPECIFIC_RESERVATION"),
    				Key:                    proto.String("compute.googleapis.com/reservation-name"),
    				Values:                 []string{sharedReservation},
    			},
    		},
    	}
    
    	op, err := client.Insert(ctx, req)
    	if err != nil {
    		return fmt.Errorf("unable to create instance: %w", err)
    	}
    
    	if op != nil {
    		if err = op.Wait(ctx); err != nil {
    			return fmt.Errorf("unable to wait for the operation: %w", err)
    		}
    	}
    	fmt.Fprintf(w, "Instance created from shared reservation\n")
    
    	return nil
    }
    

Java

次の例は、4 つの vCPU と最小 CPU プラットフォームとして Intel Skylake を備えた N1 インスタンスをゾーン us-central1-a に作成し、一致する特定の予約を消費する方法を示しています。

  • 単一プロジェクトの予約としてサンプル予約を作成し、その予約を消費するインスタンスを作成するには、次のコードサンプルを使用します。

    import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.SPECIFIC_RESERVATION;
    
    import com.google.api.gax.longrunning.OperationFuture;
    import com.google.cloud.compute.v1.AttachedDisk;
    import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
    import com.google.cloud.compute.v1.InsertInstanceRequest;
    import com.google.cloud.compute.v1.Instance;
    import com.google.cloud.compute.v1.InstancesClient;
    import com.google.cloud.compute.v1.NetworkInterface;
    import com.google.cloud.compute.v1.Operation;
    import com.google.cloud.compute.v1.ReservationAffinity;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class ConsumeSingleProjectReservation {
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(developer): Replace these variables before running the sample.
        // Project ID or project number of the Cloud project you want to use.
        String projectId = "YOUR_PROJECT_ID";
        // Name of the zone where the reservation is located.
        String zone = "us-central1-a";
        // Name of the reservation you want to query.
        String reservationName = "YOUR_RESERVATION_NAME";
        // Name of the VM instance you want to query.
        String instanceName = "YOUR_INSTANCE_NAME";
        // machineType: machine type of the VM being created.
        // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
        String machineTypeName = "n1-standard-4";
        // sourceImage: path to the operating system image to mount.
        // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
        String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
        // diskSizeGb: storage size of the boot disk to attach to the instance.
        long diskSizeGb = 10L;
        // networkName: network interface to associate with the instance.
        String networkName = "default";
        // Minimum CPU platform of the instances.
        String minCpuPlatform = "Intel Skylake";
    
        createInstanceAsync(projectId, zone, instanceName, reservationName, machineTypeName,
            sourceImage, diskSizeGb, networkName, minCpuPlatform);
      }
    
      // Create a virtual machine targeted with the reserveAffinity field.
      // Ensure that the VM's properties match the reservation's VM properties.
      public static Instance createInstanceAsync(String projectId, String zone, String instanceName,
          String reservationName, String machineTypeName, String sourceImage, long diskSizeGb,
          String networkName, String minCpuPlatform)
          throws IOException, InterruptedException, ExecutionException, TimeoutException {
        String machineType = String.format("zones/%s/machineTypes/%s", zone, machineTypeName);
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (InstancesClient instancesClient = InstancesClient.create()) {
          AttachedDisk disk =
              AttachedDisk.newBuilder()
                  .setBoot(true)
                  .setAutoDelete(true)
                  .setType(AttachedDisk.Type.PERSISTENT.toString())
                  .setDeviceName("disk-1")
                  .setInitializeParams(
                      AttachedDiskInitializeParams.newBuilder()
                          .setSourceImage(sourceImage)
                          .setDiskSizeGb(diskSizeGb)
                          .build())
                  .build();
    
          NetworkInterface networkInterface = NetworkInterface.newBuilder()
              .setName(networkName)
              .build();
    
          ReservationAffinity reservationAffinity =
              ReservationAffinity.newBuilder()
                  .setConsumeReservationType(SPECIFIC_RESERVATION.toString())
                  .setKey("compute.googleapis.com/reservation-name")
                  // Set specific reservation
                  .addValues(reservationName)
                  .build();
    
          Instance instanceResource =
              Instance.newBuilder()
                  .setName(instanceName)
                  .setMachineType(machineType)
                  .addDisks(disk)
                  .addNetworkInterfaces(networkInterface)
                  .setMinCpuPlatform(minCpuPlatform)
                  .setReservationAffinity(reservationAffinity)
                  .build();
    
          InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
              .setProject(projectId)
              .setZone(zone)
              .setInstanceResource(instanceResource)
              .build();
    
          OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
              insertInstanceRequest);
          Operation response = operation.get(3, TimeUnit.MINUTES);
    
          if (response.hasError()) {
            return null;
          }
          return instancesClient.get(projectId, zone, instanceName);
        }
      }
    }
  • 共有予約としてサンプル予約を作成し、その予約を消費するインスタンスを作成するには、次のコードサンプルを使用します。

    import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.SPECIFIC_RESERVATION;
    
    import com.google.api.gax.longrunning.OperationFuture;
    import com.google.cloud.compute.v1.AttachedDisk;
    import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
    import com.google.cloud.compute.v1.InsertInstanceRequest;
    import com.google.cloud.compute.v1.Instance;
    import com.google.cloud.compute.v1.InstancesClient;
    import com.google.cloud.compute.v1.NetworkInterface;
    import com.google.cloud.compute.v1.Operation;
    import com.google.cloud.compute.v1.ReservationAffinity;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class ConsumeSpecificSharedReservation {
      public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
        // TODO(developer): Replace these variables before running the sample.
        // Project ID or project number of the Cloud project you want to use.
        String projectId = "YOUR_PROJECT_ID";
        // Name of the zone the reservation is located.
        String zone = "us-central1-a";
        // Name of the reservation you want to query.
        String reservationName = "YOUR_RESERVATION_NAME";
        // Name of the VM instance you want to query.
        String instanceName = "YOUR_INSTANCE_NAME";
        // machineType: machine type of the VM being created.
        // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
        String machineTypeName = "n1-standard-4";
        // sourceImage: path to the operating system image to mount.
        // *   For details about images you can mount, see https://cloud.google.com/compute/docs/images
        String sourceImage = "projects/debian-cloud/global/images/family/debian-11";
        // diskSizeGb: storage size of the boot disk to attach to the instance.
        long diskSizeGb = 10L;
        // networkName: network interface to associate with the instance.
        String networkName = "default";
        // Minimum CPU platform of the instances.
        String minCpuPlatform = "Intel Skylake";
    
        createInstanceAsync(projectId, zone, instanceName, reservationName, machineTypeName,
            sourceImage, diskSizeGb, networkName, minCpuPlatform);
      }
    
      // Create a virtual machine targeted with the reserveAffinity field.
      // Ensure that the VM's properties match the reservation's VM properties.
      public static Instance createInstanceAsync(String projectId, String zone, String instanceName,
          String reservationName, String machineTypeName, String sourceImage, long diskSizeGb,
          String networkName, String minCpuPlatform)
          throws IOException, InterruptedException, ExecutionException, TimeoutException {
        String machineType = String.format("zones/%s/machineTypes/%s", zone, machineTypeName);
        // To consume this reservation from any consumer projects that this reservation is shared with,
        // you must also specify the owner project of the reservation - the path to the reservation.
        String reservationPath =
            String.format("projects/%s/reservations/%s", projectId, reservationName);
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (InstancesClient instancesClient = InstancesClient.create()) {
          AttachedDisk disk =
              AttachedDisk.newBuilder()
                  .setBoot(true)
                  .setAutoDelete(true)
                  .setType(AttachedDisk.Type.PERSISTENT.toString())
                  .setDeviceName("disk-1")
                  .setInitializeParams(
                      AttachedDiskInitializeParams.newBuilder()
                          .setSourceImage(sourceImage)
                          .setDiskSizeGb(diskSizeGb)
                          .build())
                  .build();
    
          NetworkInterface networkInterface = NetworkInterface.newBuilder()
              .setName(networkName)
              .build();
    
          ReservationAffinity reservationAffinity =
              ReservationAffinity.newBuilder()
                  .setConsumeReservationType(SPECIFIC_RESERVATION.toString())
                  .setKey("compute.googleapis.com/reservation-name")
                  // Set specific reservation
                  .addValues(reservationPath)
                  .build();
    
          Instance instanceResource =
              Instance.newBuilder()
                  .setName(instanceName)
                  .setMachineType(machineType)
                  .addDisks(disk)
                  .addNetworkInterfaces(networkInterface)
                  .setMinCpuPlatform(minCpuPlatform)
                  .setReservationAffinity(reservationAffinity)
                  .build();
    
          InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
              .setProject(projectId)
              .setZone(zone)
              .setInstanceResource(instanceResource)
              .build();
    
          OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
              insertInstanceRequest);
          Operation response = operation.get(3, TimeUnit.MINUTES);
    
          if (response.hasError()) {
            return null;
          }
          return instancesClient.get(projectId, zone, instanceName);
        }
      }
    }

Node.js

次の例は、4 つの vCPU と最小 CPU プラットフォームとして Intel Skylake を備えた N1 インスタンスをゾーン us-central1-a に作成し、一致する特定の予約を消費する方法を示しています。

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

// Instantiate a reservationsClient
const instancesClient = new computeLib.InstancesClient();
// Instantiate a zoneOperationsClient
const zoneOperationsClient = new computeLib.ZoneOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The ID of the project where you want to create instance.
const projectId = await instancesClient.getProjectId();
// The zone in which to create instance.
const zone = 'us-central1-a';
// The name of the instance to create.
// const instanceName = 'instance-01';
// The name of the reservation to consume.
// Ensure that the specificReservationRequired field in reservation properties is set to true.
// const reservationName = 'reservation-01';
// Machine type to use for VM.
const machineType = 'n1-standard-4';

// Create instance to consume a specific single-project reservation
async function callCreateInstanceToConsumeSingleProjectReservation() {
  // Describe the size and source image of the boot disk to attach to the instance.
  // Ensure that the VM's properties match the reservation's VM properties,
  // including the zone, machine type (machine family, vCPUs, and memory),
  // minimum CPU platform, GPU amount and type, and local SSD interface and size
  const disk = new compute.Disk({
    boot: true,
    autoDelete: true,
    type: 'PERSISTENT',
    initializeParams: {
      diskSizeGb: '10',
      sourceImage: 'projects/debian-cloud/global/images/family/debian-12',
    },
  });

  //  Define networkInterface
  const networkInterface = new compute.NetworkInterface({
    name: 'global/networks/default',
  });

  // Define reservationAffinity
  const reservationAffinity = new compute.ReservationAffinity({
    consumeReservationType: 'SPECIFIC_RESERVATION',
    key: 'compute.googleapis.com/reservation-name',
    values: [reservationName],
  });

  // Create an instance
  const instance = new compute.Instance({
    name: instanceName,
    machineType: `zones/${zone}/machineTypes/${machineType}`,
    minCpuPlatform: 'Intel Skylake',
    disks: [disk],
    networkInterfaces: [networkInterface],
    reservationAffinity,
  });

  const [response] = await instancesClient.insert({
    project: projectId,
    instanceResource: instance,
    zone,
  });

  let operation = response.latestResponse;

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

  console.log(`Instance ${instanceName} created.`);
}

await callCreateInstanceToConsumeSingleProjectReservation();

Python

次の例は、32 個の vCPU と最小 CPU プラットフォームとして Intel Cascade Lake を備えた N2 インスタンスをゾーン us-central1-a に作成し、特定の一致する予約を消費する方法を示しています。

特定のサンプル予約を作成して消費するには、次の操作を行います。

  • 単一プロジェクトの予約としてサンプル予約を作成して消費するには、次のコードサンプルを使用します。

    from __future__ import annotations
    
    import sys
    from typing import Any
    
    from google.api_core.extended_operation import ExtendedOperation
    from google.cloud import compute_v1
    
    
    def wait_for_extended_operation(
        operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
    ) -> Any:
        """
        Waits for the extended (long-running) operation to complete.
    
        If the operation is successful, it will return its result.
        If the operation ends with an error, an exception will be raised.
        If there were any warnings during the execution of the operation
        they will be printed to sys.stderr.
    
        Args:
            operation: a long-running operation you want to wait on.
            verbose_name: (optional) a more verbose name of the operation,
                used only during error and warning reporting.
            timeout: how long (in seconds) to wait for operation to finish.
                If None, wait indefinitely.
    
        Returns:
            Whatever the operation.result() returns.
    
        Raises:
            This method will raise the exception received from `operation.exception()`
            or RuntimeError if there is no exception set, but there is an `error_code`
            set for the `operation`.
    
            In case of an operation taking longer than `timeout` seconds to complete,
            a `concurrent.futures.TimeoutError` will be raised.
        """
        result = operation.result(timeout=timeout)
    
        if operation.error_code:
            print(
                f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
                file=sys.stderr,
                flush=True,
            )
            print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
            raise operation.exception() or RuntimeError(operation.error_message)
    
        if operation.warnings:
            print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
            for warning in operation.warnings:
                print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)
    
        return result
    
    
    def consume_specific_single_project_reservation(
        project_id: str,
        zone: str,
        reservation_name: str,
        instance_name: str,
        machine_type: str = "n1-standard-1",
        min_cpu_platform: str = "Intel Ivy Bridge",
    ) -> compute_v1.Instance:
        """
        Creates a specific reservation in a single project and launches a VM
        that consumes the newly created reservation.
        Args:
            project_id (str): The ID of the Google Cloud project.
            zone (str): The zone to create the reservation.
            reservation_name (str): The name of the reservation to create.
            instance_name (str): The name of the instance to create.
            machine_type (str): The machine type for the instance.
            min_cpu_platform (str): The minimum CPU platform for the instance.
        """
        instance_properties = (
            compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
                machine_type=machine_type,
                min_cpu_platform=min_cpu_platform,
            )
        )
    
        reservation = compute_v1.Reservation(
            name=reservation_name,
            specific_reservation=compute_v1.AllocationSpecificSKUReservation(
                count=3,
                instance_properties=instance_properties,
            ),
            # Only VMs that target the reservation by name can consume from this reservation
            specific_reservation_required=True,
        )
    
        # Create a reservation client
        client = compute_v1.ReservationsClient()
        operation = client.insert(
            project=project_id,
            zone=zone,
            reservation_resource=reservation,
        )
        wait_for_extended_operation(operation, "Reservation creation")
    
        instance = compute_v1.Instance()
        instance.name = instance_name
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
        instance.min_cpu_platform = min_cpu_platform
        instance.zone = zone
    
        # Set the reservation affinity to target the specific reservation
        instance.reservation_affinity = compute_v1.ReservationAffinity(
            consume_reservation_type="SPECIFIC_RESERVATION",  # Type of reservation to consume
            key="compute.googleapis.com/reservation-name",  # Key for the reservation
            values=[reservation_name],  # Reservation name to consume
        )
        # Define the disks for the instance
        instance.disks = [
            compute_v1.AttachedDisk(
                boot=True,  # Indicates that this is a boot disk
                auto_delete=True,  # The disk will be deleted when the instance is deleted
                initialize_params=compute_v1.AttachedDiskInitializeParams(
                    source_image="projects/debian-cloud/global/images/family/debian-11",
                    disk_size_gb=10,
                ),
            )
        ]
        instance.network_interfaces = [
            compute_v1.NetworkInterface(
                network="global/networks/default",  # The network to use
                access_configs=[
                    compute_v1.AccessConfig(
                        name="External NAT",  # Name of the access configuration
                        type="ONE_TO_ONE_NAT",  # Type of access configuration
                    )
                ],
            )
        ]
        # Create a request to insert the instance
        request = compute_v1.InsertInstanceRequest()
        request.zone = zone
        request.project = project_id
        request.instance_resource = instance
    
        vm_client = compute_v1.InstancesClient()
        operation = vm_client.insert(request)
        wait_for_extended_operation(operation, "instance creation")
        print(f"Instance {instance_name} with specific reservation created successfully.")
    
        return vm_client.get(project=project_id, zone=zone, instance=instance_name)
    
    
  • サンプルの予約を作成して共有予約として消費するには、次のコードサンプルを使用します。

    from __future__ import annotations
    
    import sys
    from typing import Any
    
    from google.api_core.extended_operation import ExtendedOperation
    from google.cloud import compute_v1
    
    
    def wait_for_extended_operation(
        operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
    ) -> Any:
        """
        Waits for the extended (long-running) operation to complete.
    
        If the operation is successful, it will return its result.
        If the operation ends with an error, an exception will be raised.
        If there were any warnings during the execution of the operation
        they will be printed to sys.stderr.
    
        Args:
            operation: a long-running operation you want to wait on.
            verbose_name: (optional) a more verbose name of the operation,
                used only during error and warning reporting.
            timeout: how long (in seconds) to wait for operation to finish.
                If None, wait indefinitely.
    
        Returns:
            Whatever the operation.result() returns.
    
        Raises:
            This method will raise the exception received from `operation.exception()`
            or RuntimeError if there is no exception set, but there is an `error_code`
            set for the `operation`.
    
            In case of an operation taking longer than `timeout` seconds to complete,
            a `concurrent.futures.TimeoutError` will be raised.
        """
        result = operation.result(timeout=timeout)
    
        if operation.error_code:
            print(
                f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
                file=sys.stderr,
                flush=True,
            )
            print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
            raise operation.exception() or RuntimeError(operation.error_message)
    
        if operation.warnings:
            print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
            for warning in operation.warnings:
                print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)
    
        return result
    
    
    def consume_specific_shared_project_reservation(
        owner_project_id: str,
        shared_project_id: str,
        zone: str,
        reservation_name: str,
        instance_name: str,
        machine_type: str = "n1-standard-1",
        min_cpu_platform: str = "Intel Ivy Bridge",
    ) -> compute_v1.Instance:
        """
        Creates a specific reservation in a single project and launches a VM
        that consumes the newly created reservation.
        Args:
            owner_project_id (str): The ID of the Google Cloud project.
            shared_project_id: The ID of the owner project of the reservation in the same zone.
            zone (str): The zone to create the reservation.
            reservation_name (str): The name of the reservation to create.
            instance_name (str): The name of the instance to create.
            machine_type (str): The machine type for the instance.
            min_cpu_platform (str): The minimum CPU platform for the instance.
        """
        instance_properties = (
            compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(
                machine_type=machine_type,
                min_cpu_platform=min_cpu_platform,
            )
        )
    
        reservation = compute_v1.Reservation(
            name=reservation_name,
            specific_reservation=compute_v1.AllocationSpecificSKUReservation(
                count=3,
                instance_properties=instance_properties,
            ),
            # Only VMs that target the reservation by name can consume from this reservation
            specific_reservation_required=True,
            share_settings=compute_v1.ShareSettings(
                share_type="SPECIFIC_PROJECTS",
                project_map={
                    shared_project_id: compute_v1.ShareSettingsProjectConfig(
                        project_id=shared_project_id
                    )
                },
            ),
        )
    
        # Create a reservation client
        client = compute_v1.ReservationsClient()
        operation = client.insert(
            project=owner_project_id,
            zone=zone,
            reservation_resource=reservation,
        )
        wait_for_extended_operation(operation, "Reservation creation")
    
        instance = compute_v1.Instance()
        instance.name = instance_name
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
        instance.min_cpu_platform = min_cpu_platform
        instance.zone = zone
    
        # Set the reservation affinity to target the specific reservation
        instance.reservation_affinity = compute_v1.ReservationAffinity(
            consume_reservation_type="SPECIFIC_RESERVATION",  # Type of reservation to consume
            key="compute.googleapis.com/reservation-name",
            # To consume this reservation from any consumer projects, specify the owner project of the reservation
            values=[f"projects/{owner_project_id}/reservations/{reservation_name}"],
        )
        # Define the disks for the instance
        instance.disks = [
            compute_v1.AttachedDisk(
                boot=True,  # Indicates that this is a boot disk
                auto_delete=True,  # The disk will be deleted when the instance is deleted
                initialize_params=compute_v1.AttachedDiskInitializeParams(
                    source_image="projects/debian-cloud/global/images/family/debian-11",
                    disk_size_gb=10,
                ),
            )
        ]
        instance.network_interfaces = [
            compute_v1.NetworkInterface(
                network="global/networks/default",  # The network to use
                access_configs=[
                    compute_v1.AccessConfig(
                        name="External NAT",  # Name of the access configuration
                        type="ONE_TO_ONE_NAT",  # Type of access configuration
                    )
                ],
            )
        ]
        # Create a request to insert the instance
        request = compute_v1.InsertInstanceRequest()
        request.zone = zone
        # The instance will be created in the shared project
        request.project = shared_project_id
        request.instance_resource = instance
    
        vm_client = compute_v1.InstancesClient()
        operation = vm_client.insert(request)
        wait_for_extended_operation(operation, "instance creation")
        print(f"Instance {instance_name} from project {owner_project_id} created.")
        # The instance is created in the shared project, so we return it from there.
        return vm_client.get(project=shared_project_id, zone=zone, instance=instance_name)
    
    

REST

次の例は、32 個の vCPU と最小 CPU プラットフォームとして Intel Cascade Lake を備えた 3 つの N2 インスタンスに対して、ゾーン us-central1-a に特定の予約を作成する方法を示しています。また、予約を消費する単一のインスタンスを作成する方法も示しています。

特定のサンプル予約を作成して消費するには、次の操作を行います。

  1. サンプルの予約を作成するには、instances.insert メソッドPOST リクエストを送信します。リクエストの本文に、true に設定された specificReservationRequired フィールドを含めます。

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations
    
    {
      "name": "reservation-02",
      "specificReservation": {
        "count": "3",
        "instanceProperties": {
          "machineType": "n2-standard-32",
          "minCpuPlatform": "Intel Cascade Lake",
        }
      },
      "specificReservationRequired": true
    }
    
  2. サンプル予約を消費するインスタンスを作成するには、instances.insert メソッドPOST リクエストを送信します。リクエスト本文の reservationAffinity フィールドに、次の対象を指定します。

    • SPECIFIC_RESERVATION に設定されている consumeReservationType フィールド。

    • compute.googleapis.com/reservation-name に設定されている key フィールド。

    • 予約の URL に設定されている values フィールド。

    出力は次のようになります。

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/instances
    
    {
      "name": "instance-02",
      "machineType": "zones/us-central1-a/machineTypes/n2-standard-32",
      "minCpuPlatform": "Intel Cascade Lake",
      "disks": [
        {
          "boot": true,
          "initializeParams": {
            "sourceImage": "projects/debian-cloud/global/images/family/debian-12"
          }
        }
      ],
      "networkInterfaces": [
        {
          "network": "global/networks/default"
        }
      ],
      "reservationAffinity": {
        "consumeReservationType": "SPECIFIC_RESERVATION",
        "key": "compute.googleapis.com/reservation-name",
        "values": [
          "RESERVATION_URL"
        ]
      }
    }
    

    RESERVATION_URL は、予約の URL に置き換えます。次のいずれかの値を指定します。

    • 同じプロジェクトで予約を作成した場合: reservation-02

    • 予約が別のプロジェクトに存在する場合: projects/PROJECT_ID/reservations/reservation-02

インスタンスのプロパティが自動的に消費される予約と一致することをテストする

コンピューティング インスタンスのプロパティが自動的に消費される予約と一致するかどうかをテストするには、次の操作を行います。

  1. 単一インスタンスの明示的に対象となる予約として、予約のコピーを作成します。

  2. 予約を消費するテスト インスタンスを作成します。

テスト インスタンスを作成できる場合、そのプロパティはテスト予約のプロパティと一致します。それ以外の場合、インスタンスの作成は失敗します。

テスト インスタンスとテスト予約のプロパティが一致していることを確認したら、予約テスト インスタンスを削除します。

予約の消費を確認する

予約の消費を確認するには、次のうち 1 つ以上の操作を実施します。

  • 予約を消費しているコンピューティング インスタンスの現在の数と、新たに予約を消費できるインスタンスの数を確認するには、予約を表示します。

  • 30 分ごとに更新される予約の消費量データをモニタリングし、予約が消費された場合または消費されなかった場合にアラートを受信するには、予約の消費をモニタリングします。

  • 24 時間ごとに更新される予約の消費量データを表示するには、次のいずれかを行います。

次のステップ