예약 사용

이 문서에서는 Compute Engine에서 예약을 사용하는 방법을 설명합니다. 다른 Trusted Cloud by S3NS 제품에서 예약을 사용하는 방법을 알아보려면 다음 문서를 참조하세요.

사용자가 예약을 만들거나 Compute Engine이 미래용 예약을 처리하기 위해 예약을 자동으로 만든 후 Compute Engine은 예약된 리소스를 자동으로 보관합니다. 그런 다음 예약된 리소스를 사용하여 예약의 속성과 일치하는 Compute Engine 인스턴스를 만들 수 있습니다. 이러한 작업을 예약을 사용한다고 합니다. 예약이 완전히 사용될 때까지 예약된 용량을 사용하여 인스턴스를 만들 수 있습니다.

제한사항

예약을 사용하여 다음 Compute Engine 리소스를 만들 수는 없습니다.

  • 스팟 VM 또는 선점형 인스턴스

  • 단독 테넌트 노드

시작하기 전에

  • 아직 인증을 설정하지 않았다면 설정합니다. 인증은 Trusted Cloud by S3NS 서비스 및 API에 액세스하기 위해 ID를 확인하는 프로세스입니다. 로컬 개발 환경에서 코드 또는 샘플을 실행하려면 다음 옵션 중 하나를 선택하여 Compute Engine에 인증하면 됩니다.

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

    Console

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

    gcloud

    1. After installing the Google Cloud CLI, sign in to the gcloud CLI with your federated identity and then initialize it by running the following command:

      gcloud init
    2. Set a default region and zone.
    3. Go

      로컬 개발 환경에서 이 페이지의 Go 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

      1. Install the Google Cloud CLI.

      2. Configure the gcloud CLI to use your federated identity.

        For more information, see Sign in to the gcloud CLI with your federated identity.

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

        gcloud init
      4. Create local authentication credentials for your user account:

        gcloud auth application-default login

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

      5. 자세한 내용은 다음을 참조하세요: Set up authentication for a local development environment.

      Java

      로컬 개발 환경에서 이 페이지의 Java 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

      1. Install the Google Cloud CLI.

      2. Configure the gcloud CLI to use your federated identity.

        For more information, see Sign in to the gcloud CLI with your federated identity.

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

        gcloud init
      4. Create local authentication credentials for your user account:

        gcloud auth application-default login

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

      5. 자세한 내용은 다음을 참조하세요: Set up authentication for a local development environment.

      Node.js

      로컬 개발 환경에서 이 페이지의 Node.js 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

      1. Install the Google Cloud CLI.

      2. Configure the gcloud CLI to use your federated identity.

        For more information, see Sign in to the gcloud CLI with your federated identity.

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

        gcloud init
      4. Create local authentication credentials for your user account:

        gcloud auth application-default login

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

      5. 자세한 내용은 다음을 참조하세요: Set up authentication for a local development environment.

      Python

      로컬 개발 환경에서 이 페이지의 Python 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

      1. Install the Google Cloud CLI.

      2. Configure the gcloud CLI to use your federated identity.

        For more information, see Sign in to the gcloud CLI with your federated identity.

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

        gcloud init
      4. Create local authentication credentials for your user account:

        gcloud auth application-default login

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

      5. 자세한 내용은 다음을 참조하세요: Set up authentication for a local development environment.

      REST

      로컬 개발 환경에서 이 페이지의 REST API 샘플을 사용하려면 gcloud CLI에 제공한 사용자 인증 정보를 사용합니다.

        After installing the Google Cloud CLI, sign in to the gcloud CLI with your federated identity and then initialize it by running the following command:

        gcloud init

      자세한 내용은 Trusted 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에서 미래용 예약을 처리하기 위해 예약을 자동으로 만드는 경우 이 예약 유형이 기본 설정입니다.

단일 프로젝트 자동 예약과 공유 자동 예약의 속성이 일치하면 프로젝트의 인스턴스가 단일 프로젝트 예약을 먼저 사용한 다음 공유 예약을 사용합니다. 자세한 내용은 예약 사용 순서를 참조하세요.

예시 자동 예약을 만들고 사용하려면 다음 옵션 중 하나를 선택하세요.

콘솔

다음 예에서는 vCPU가 32개이고 Intel Cascade Lake가 최소 CPU 플랫폼인 N2 인스턴스 3개에 대해 us-central1-a 영역에서 자동 예약을 만드는 방법을 보여줍니다. 또한 예약을 사용하는 단일 인스턴스를 만드는 방법도 보여줍니다.

예시 자동 예약을 만들고 사용하려면 다음 단계를 따르세요.

  1. 예시 예약을 만들려면 다음 단계를 완료하세요.

    1. Trusted Cloud 콘솔에서 예약 페이지로 이동합니다.

      예약으로 이동

      나머지 단계는Trusted Cloud 콘솔에 자동으로 표시됩니다.

    2. 온디맨드 예약 탭(기본값)에서 예약 만들기를 클릭합니다. 예약 만들기 페이지가 표시됩니다.

    3. 이름 필드에 예약 이름을 입력합니다. 예를 들어 reservation-01을 입력합니다.

    4. 리소스를 예약할 리전영역을 선택합니다. 예를 들어 각각 us-central1us-central1-a를 선택합니다.

    5. 공유 유형 섹션에서 다음 중 하나를 수행합니다.

      • 단일 프로젝트 예약을 만들려면 로컬을 선택합니다.

      • 공유 예약을 만들려면 공유를 선택한 후 예약을 공유할 프로젝트를 지정합니다.

    6. VM 인스턴스와 함께 사용 섹션에서 예약 자동 사용을 선택합니다(아직 선택하지 않은 경우).

    7. VM 인스턴스 수 필드에 3을 입력합니다.

    8. 범용 탭에서 N2를 선택합니다.

    9. 머신 유형 섹션의 사전 설정 탭(기본값)에서 n2-standard-32를 선택합니다.

    10. CPU 플랫폼 및 GPU를 펼친 다음 CPU 플랫폼 필드에서 Intel Cascade Lake 이상을 선택합니다.

    11. 만들기를 클릭합니다.

  2. 예시 예약을 사용하는 인스턴스를 만들려면 다음 단계를 완료하세요.

    1. Trusted Cloud 콘솔에서 인스턴스 만들기 페이지로 이동합니다.

      인스턴스 만들기로 이동

      인스턴스 만들기 페이지가 표시되고 머신 구성 창이 표시됩니다.

    2. 머신 구성 창에서 다음을 수행합니다.

      1. 이름 필드에 인스턴스의 이름을 입력합니다. 이 예시에서는 instance-01를 입력합니다.

      2. 리소스를 예약할 리전영역을 지정합니다. 이 예시에서는 각각 us-central1us-central1-a를 선택합니다.

      3. 범용 탭에서 N2를 선택합니다.

      4. 머신 유형 섹션의 사전 설정 탭(기본값)에서 n2-standard-32를 선택합니다.

      5. 고급 옵션 섹션을 펼친 후 CPU 플랫폼 필드에서 Intel Cascade Lake 이상을 선택합니다.

    3. 선택사항: 일치하는 예약을 자동으로 사용하는 것이 기본 설정입니다. 하지만 이 설정을 지정하려면 다음 단계를 따르세요.

      1. 탐색 메뉴에서 고급을 클릭합니다. 고급 창이 표시됩니다.

      2. 예약 섹션에서 자동 선택 사용을 선택합니다.

    4. 만들기를 클릭합니다.

gcloud

다음 예에서는 vCPU가 32개이고 Intel Cascade Lake가 최소 CPU 플랫폼인 N2 인스턴스 3개에 대해 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
}

자바

다음 예시에서는 us-central1-a 영역에서 vCPU가 4개이고 Intel Skylake가 최소 CPU 플랫폼인 N1 인스턴스를 만드는 방법을 보여줍니다. 인스턴스가 일치하는 예약을 자동으로 사용합니다.

예시 인스턴스를 만들려면 다음 코드 샘플을 사용하세요.

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

다음 예시에서는 us-central1-a 영역에서 vCPU가 4개이고 Intel Skylake가 최소 CPU 플랫폼인 N1 인스턴스를 만드는 방법을 보여줍니다. 인스턴스가 일치하는 예약을 자동으로 사용합니다.

예시 인스턴스를 만들려면 다음 코드 샘플을 사용하세요.

// 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

다음 예시에서는 vCPU가 하나이고 Intel Ivy가 최소 CPU 플랫폼인 N1 인스턴스 3개에 대해 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

다음 예에서는 vCPU가 32개이고 Intel Cascade Lake가 최소 CPU 플랫폼인 N2 인스턴스 3개에 대해 us-central1-a 영역에서 자동 예약을 만드는 방법을 보여줍니다. 또한 예약을 사용하는 단일 인스턴스를 만드는 방법도 보여줍니다.

예시 자동 예약을 만들고 사용하려면 다음 단계를 따르세요.

  1. 예시 예약을 만들려면 POST 요청을 reservations.insert 메서드에 보냅니다.

    POST https://compute.s3nsapis.fr/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. 예시 예약을 사용하는 인스턴스를 만들려면 POST 요청을 instances.insert 메서드에 보냅니다. 요청 본문에 ANY_RESERVATION으로 설정된 consumeReservationType 필드를 포함합니다. 하지만 ANY_RESERVATION이 기본 구성이므로 이 필드를 생략해도 됩니다.

    POST https://compute.s3nsapis.fr/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"
      }
    }
    

구체적으로 타겟팅된 예약 사용

구체적으로 타겟팅된 예약에서는 인스턴스가 예약을 타겟팅하는 경우에만 새 컴퓨팅 인스턴스가 일치하는 예약을 사용할 수 있습니다. 인스턴스는 속성이 예약 속성과 일치하는 경우에만 생성됩니다. 그렇지 않으면 오류가 발생합니다.

사용하려는 생성 방법에 따라 다음과 같이 특정 예약과 예약을 타겟팅하는 인스턴스를 만듭니다.

생성 방법 예약 만들기 인스턴스 만들기
Trusted Cloud 콘솔 VM 인스턴스와 함께 사용 섹션에서 특정 예약 선택을 선택합니다. 고급 창의 예약 섹션에서 예약 선택을 선택합니다.
Google Cloud CLI --require-specific-reservation 플래그를 포함합니다. 다음 플래그를 포함합니다.
  • specific으로 설정된 --reservation-affinity 플래그
  • 예약 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 필드

특정 예약 예시와 이를 사용하는 인스턴스를 만들려면 다음 옵션 중 하나를 선택합니다.

콘솔

다음 예에서는 vCPU가 32개이고 Intel Cascade Lake가 최소 CPU 플랫폼인 N2 인스턴스 3개에 대해 us-central1-a 영역에서 특정 예약을 만드는 방법을 보여줍니다. 또한 예약을 사용하는 단일 인스턴스를 만드는 방법도 보여줍니다.

예시 특정 예약을 만들고 사용하려면 다음 단계를 따르세요.

  1. 예시 예약을 만들려면 다음 단계를 완료하세요.

    1. Trusted Cloud 콘솔에서 예약 페이지로 이동합니다.

      예약으로 이동

      나머지 단계는Trusted Cloud 콘솔에 자동으로 표시됩니다.

    2. 온디맨드 예약 탭(기본값)에서 예약 만들기를 클릭합니다. 예약 만들기 페이지가 표시됩니다.

    3. 이름 필드에 예약 이름을 입력합니다. 예를 들어 reservation-02를 입력합니다.

    4. 리소스를 예약할 리전영역을 지정합니다. 이 예시에서는 각각 us-central1us-central1-a를 선택합니다.

    5. 공유 유형 섹션에서 다음 중 하나를 수행합니다.

      • 단일 프로젝트 예약을 만들려면 로컬을 선택합니다.

      • 공유 예약을 만들려면 공유를 선택한 후 예약을 공유할 프로젝트를 지정합니다.

    6. VM 인스턴스와 함께 사용 섹션에서 특정 예약 선택을 선택합니다.

    7. VM 인스턴스 수 필드에 3을 입력합니다.

    8. 범용 탭에서 N2를 선택합니다.

    9. 머신 유형 섹션의 사전 설정 탭(기본값)에서 n2-standard-32를 선택합니다.

    10. CPU 플랫폼 및 GPU를 펼친 다음 CPU 플랫폼 필드에서 Intel Cascade Lake 이상을 선택합니다.

    11. 만들기를 클릭합니다.

  2. 예시 예약을 사용하는 인스턴스를 만들려면 다음 단계를 완료하세요.

    1. Trusted Cloud 콘솔에서 인스턴스 만들기 페이지로 이동합니다.

      인스턴스 만들기로 이동

      인스턴스 만들기 페이지가 표시되고 머신 구성 창이 표시됩니다.

    2. 머신 구성 창에서 다음을 수행합니다.

      1. 이름 필드에 인스턴스의 이름을 입력합니다. 이 예시에서는 instance-02를 입력합니다.

      2. 리소스를 예약할 리전영역을 지정합니다. 이 예시에서는 각각 us-central1us-central1-a를 선택합니다.

      3. 범용 탭에서 N2를 선택합니다.

      4. 머신 유형 섹션의 사전 설정 탭(기본값)에서 n2-standard-32를 선택합니다.

      5. 고급 옵션 섹션을 펼친 후 CPU 플랫폼 필드에서 Intel Cascade Lake 이상을 선택합니다.

    3. 탐색 메뉴에서 고급을 클릭합니다. 고급 창이 표시됩니다.

    4. 예약 섹션에서 예약 선택을 선택한 다음 예약 선택을 클릭합니다.

    5. 예약 선택 창이 표시되면 다음을 수행합니다.

      1. 이전 단계에서 만든 특정 예약을 선택합니다. 다른 프로젝트에 있는 공유 예약을 사용하려면 프로젝트 목록에서 예약이 있는 프로젝트를 선택합니다.

      2. 선택을 클릭합니다.

    6. 만들기를 클릭합니다.

gcloud

다음 예에서는 vCPU가 32개이고 Intel Cascade Lake가 최소 CPU 플랫폼인 N2 인스턴스 3개에 대해 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

다음 예에서는 일치하는 특정 예약을 사용하기 위해 영역 us-central1-a에서 vCPU가 32개이고 Intel Cascade Lake가 최소 CPU 플랫폼인 N2 인스턴스를 만드는 방법을 보여줍니다.

  • 단일 프로젝트의 특정 예약을 사용하는 예시 인스턴스를 만들려면 다음 코드 샘플을 사용하세요.

    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
    }
    

자바

다음 예시에서는 일치하는 특정 예약을 사용하기 위해 영역 us-central1-a에서 vCPU가 4개이고 Intel Skylake가 최소 CPU 플랫폼인 N1 인스턴스를 만드는 방법을 보여줍니다.

  • 예시 예약을 단일 프로젝트 예약으로 만들고 이를 사용하는 인스턴스를 만들려면 다음 코드 샘플을 사용하세요.

    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

다음 예시에서는 일치하는 특정 예약을 사용하기 위해 us-central1-a 영역에서 vCPU가 4개이고 Intel Skylake가 최소 CPU 플랫폼인 N1 인스턴스를 만드는 방법을 보여줍니다.

// 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

다음 예에서는 일치하는 특정 예약을 사용하기 위해 영역 us-central1-a에서 vCPU가 32개이고 Intel Cascade Lake가 최소 CPU 플랫폼인 N2 인스턴스를 만드는 방법을 보여줍니다.

예시 특정 예약을 만들고 사용하려면 다음 단계를 따르세요.

  • 예시 예약을 단일 프로젝트 예약으로 만들어 사용하려면 다음 코드 샘플을 사용하세요.

    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

다음 예에서는 vCPU가 32개이고 Intel Cascade Lake가 최소 CPU 플랫폼인 N2 인스턴스 3개에 대해 us-central1-a 영역에서 특정 예약을 만드는 방법을 보여줍니다. 또한 예약을 사용하는 단일 인스턴스를 만드는 방법도 보여줍니다.

예시 특정 예약을 만들고 사용하려면 다음 단계를 따르세요.

  1. 예약 예시를 만들려면 POST 요청을 instances.insert 메서드에 보냅니다. 요청 본문에 true로 설정된 specificReservationRequired 필드를 포함합니다.

    POST https://compute.s3nsapis.fr/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. 예시 예약을 사용하는 인스턴스를 만들려면 POST 요청을 instances.insert 메서드에 보냅니다. 요청 본문의 reservationAffinity 필드에 다음을 포함합니다.

    • SPECIFIC_RESERVATION로 설정된 consumeReservationType 필드

    • compute.googleapis.com/reservation-name로 설정된 key 필드

    • 예약의 URL로 설정된 values 필드

    요청은 다음과 비슷합니다.

    POST https://compute.s3nsapis.fr/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.s3nsapis.fr/reservation-name",
        "values": [
          "RESERVATION_URL"
        ]
      }
    }
    

    RESERVATION_URL을 예약 URL로 바꿉니다. 다음 값 중 하나를 지정합니다.

    • 동일한 프로젝트에 예약을 만든 경우: reservation-02

    • 예약이 다른 프로젝트에 있는 경우: projects/PROJECT_ID/reservations/reservation-02

인스턴스 속성이 자동으로 사용되는 예약과 일치하는지 테스트

컴퓨팅 인스턴스의 속성이 자동으로 사용되는 예약과 일치하는지 테스트하려면 다음 단계를 따르세요.

  1. 예약의 사본을 단일 인스턴스에 대해 구체적으로 타겟팅된 예약으로 만듭니다.

  2. 예약을 사용하는 테스트 인스턴스를 만듭니다.

테스트 인스턴스를 만들 수 있다면 해당 속성이 테스트 예약의 속성과 일치하는 것입니다. 그렇지 않으면 인스턴스 만들기가 실패합니다.

테스트 인스턴스와 테스트 예약의 속성이 일치하는지 확인한 후 예약테스트 인스턴스를 삭제합니다.

예약 사용 확인

예약 사용을 확인하기 위해 다음 중 하나 이상을 수행할 수 있습니다.

  • 예약을 사용 중인 현재 컴퓨팅 인스턴스 수와 예약을 사용할 수 있는 추가 인스턴스 수를 보려면 예약을 확인합니다.

  • 30분마다 업데이트되는 예약 사용 데이터를 모니터링하고 예약이 사용되거나 사용되지 않을 때 알림을 받으려면 예약 사용을 모니터링합니다.

  • 24시간마다 업데이트되는 예약 사용 데이터를 보려면 다음 중 하나를 수행하세요.

    • Cloud Storage 버킷에서 사용 보고서를 수신하여 사용 추세를 분석하고 사용되지 않은 예약을 식별하려면 예약 사용량 보고서를 확인합니다.

다음 단계