컴퓨팅 인스턴스가 예약을 사용하지 못하도록 방지


이 문서에서는 Compute Engine 인스턴스가 예약을 사용하지 못하도록 하는 방법을 설명합니다. 예약에 대한 자세한 내용은 Compute Engine 영역별 리소스 예약을 참조하세요.

자동으로 소비되는 예약을 사용하면 예약과 일치하는 속성이 있는 인스턴스가 예약을 자동으로 사용할 수 있습니다. 인스턴스가 예약을 사용하지 못하도록 하려면 다음 중 하나를 실행합니다.

  • 이 문서에 설명된 대로 예약을 사용하지 않도록 인스턴스를 구성합니다.

  • 예약과 일치하지 않는 속성을 사용하여 인스턴스를 만들거나 업데이트합니다.

테스트, 디버깅, 격리된 배포와 같은 작업에 인스턴스를 사용하려는 경우 예약을 사용하지 않을 수 있습니다.

제한사항

인스턴스가 일치하는 예약을 자동으로 사용하도록 구성된 경우에만 기존 인스턴스를 업데이트하여 예약을 사용하지 않도록 할 수 있습니다.

시작하기 전에

  • 아직 인증을 설정하지 않았다면 설정합니다. 인증은 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. Install the Google Cloud CLI, 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. To initialize the gcloud CLI, run the following command:

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

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

      Java

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

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

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

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

      Node.js

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

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

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

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

      Python

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

      1. Install the Google Cloud CLI.
      2. To initialize the gcloud CLI, run the following command:

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

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

      REST

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

        Install the Google Cloud CLI, then initialize it by running the following command:

        gcloud init

      자세한 내용은 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 권한

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

예약 사용 방지

컴퓨팅 인스턴스가 예약을 사용하지 못하도록 하려면 예약 어피니티 (reservationAffinity) 속성을 예약을 사용하지 않도록 설정합니다. 이 속성은 인스턴스가 일치하는 예약, 특정 예약 또는 예약을 전혀 사용할 수 있는지 여부를 제어합니다.

하나 이상의 인스턴스에서 예약을 사용하지 못하도록 하려면 다음 방법 중 하나를 사용하세요.

기존 인스턴스에서 사용 방지

더 이상 예약을 자동으로 사용하지 않도록 실행 중인 인스턴스를 업데이트할 수 있습니다. 변경사항을 적용하려면 이 섹션에 설명된 대로 인스턴스를 다시 시작해야 합니다.

기존 인스턴스가 예약을 사용하지 못하도록 하려면 다음 옵션 중 하나를 선택합니다.

gcloud

  1. 빈 YAML 파일을 만듭니다.

  2. 인스턴스의 속성을 방금 만든 YAML 파일로 내보내려면 gcloud compute instances export 명령어를 사용합니다.

    gcloud compute instances export INSTANCE_NAME \
        --destination=YAML_FILE \
        --zone=ZONE
    

    다음을 바꿉니다.

    • INSTANCE_NAME: 인스턴스 이름입니다.

    • YAML_FILE: 이전 단계에서 만든 빈 YAML 파일의 경로입니다.

    • ZONE: 인스턴스가 있는 영역입니다.

  3. YAML 구성 파일에서 consumeReservationTypeNO_RESERVATION로 설정합니다.

    reservationAffinity:
      consumeReservationType: NO_RESERVATION
    
  4. 인스턴스를 업데이트하고 다시 시작하려면 --most-disruptive-allowed-action 플래그를 RESTART로 설정하고 gcloud compute instances update-from-file 명령어를 사용합니다.

    gcloud compute instances update-from-file INSTANCE_NAME \
        --most-disruptive-allowed-action=RESTART \
        --source=YAML_FILE \
        --zone=ZONE
    

    다음을 바꿉니다.

    • INSTANCE_NAME: 인스턴스 이름입니다.

    • YAML_FILE: 이전 단계에서 수정한 구성 데이터가 포함된 YAML 파일의 경로입니다.

    • ZONE: 인스턴스가 있는 영역입니다.

REST

  1. 기존 인스턴스의 속성을 보려면 instances.get 메서드GET 요청을 실행합니다.

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME
    

    다음을 바꿉니다.

    • PROJECT_ID: 인스턴스를 만든 프로젝트의 ID입니다.

    • ZONE: 인스턴스가 있는 영역입니다.

    • INSTANCE_NAME: 인스턴스 이름입니다.

  2. GET 요청의 출력을 파일이나 텍스트 편집기에 저장합니다. 복사한 출력을 수정하여 consumeReservationType 필드를 NO_RESERVATION로 변경합니다.

    {
      ...
      "reservationAffinity": {
        "consumeReservationType": "NO_RESERVATION"
      },
      ...
    }
    
  3. 인스턴스를 업데이트하고 다시 시작하려면 PUT 요청을 instances.update 메서드에 보냅니다. 요청에서 다음을 수행합니다.

    • 요청 URL에 RESTART로 설정된 mostDisruptiveAllowedAction 쿼리 매개변수를 포함합니다.

    • 요청 본문에는 이전 단계에서 수정한 GET 요청의 출력을 사용합니다.

    요청은 다음 예와 유사합니다.

    PUT https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central-1/instances/instance-01?mostDisruptiveAllowedAction=RESTART
    
    {
      ...
      "reservationAffinity": {
        "consumeReservationType": "NO_RESERVATION"
      },
      ...
    }
    

인스턴스 업데이트에 대한 자세한 내용은 인스턴스 속성 업데이트를 참고하세요.

인스턴스를 만드는 동안 사용 방지

예약을 사용할 수 없는 컴퓨팅 인스턴스를 만들려면 다음 옵션 중 하나를 선택합니다.

콘솔

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

    인스턴스 만들기로 이동

  2. 이름 필드에 인스턴스의 이름을 입력합니다.

  3. 리전영역 목록에서 인스턴스를 만들 리전과 영역을 선택합니다.

  4. 인스턴스에 사용할 머신 유형을 지정합니다.

  5. 탐색 메뉴에서 고급을 클릭합니다.

  6. 예약 섹션에서 예약 사용 안함을 선택합니다.

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

gcloud

예약을 사용할 수 없는 인스턴스를 만들려면 --reservation-affinity 플래그를 none로 설정하고 gcloud compute instances create 명령어를 사용합니다.

gcloud compute instances create INSTANCE_NAME \
    --machine-type=MACHINE_TYPE \
    --reservation-affinity=none \
    --zone=ZONE

다음을 바꿉니다.

  • INSTANCE_NAME: 인스턴스 이름입니다.

  • MACHINE_TYPE: 인스턴스에 사용할 머신 유형입니다.

  • ZONE: 인스턴스를 만들 영역입니다.

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"
)

// createInstanceNotConsumeReservation creates VM, without consuming reservation
func createInstanceNotConsumeReservation(w io.Writer, projectID, zone, instanceName string) error {
	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"),
				},
			},
			ReservationAffinity: &computepb.ReservationAffinity{
				ConsumeReservationType: proto.String("NO_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\n")

	return nil
}

자바

예약을 사용할 수 없는 인스턴스를 만들려면 다음 코드 샘플을 사용하세요.

import static com.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.NO_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 CreateInstanceWithoutConsumingReservation {
  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 you want to use.
    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.
    // *   This value uses the format zones/{zone}/machineTypes/{type_name}.
    // *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-types
    String machineTypeName = "n1-standard-1";
    // 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";

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

  // Create a virtual machine that explicitly doesn't consume reservations
  public static Instance createInstanceWithoutConsumingReservationAsync(
      String project, String zone, String instanceName,
      String machineTypeName, String sourceImage, long diskSizeGb, String networkName)
      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(NO_RESERVATION.toString())
              .build();

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

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

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

      // Wait for the operation to complete.
      Operation response = operation.get(3, TimeUnit.MINUTES);

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

Node.js

예약을 사용할 수 없는 인스턴스를 만들려면 다음 코드 샘플을 사용하세요.

// 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 a VM that explicitly doesn't consume reservations
async function callCreateInstanceToNotConsumeReservation() {
  // 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: 'NO_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 callCreateInstanceToNotConsumeReservation();

Python

예약을 사용할 수 없는 인스턴스를 만들려면 다음 코드 샘플을 사용하세요.

from __future__ import annotations

import sys
from typing import Any

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


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

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

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

    Returns:
        Whatever the operation.result() returns.

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

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

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

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

    return result


def create_vm_not_consume_reservation(
    project_id: str, zone: str, instance_name: str, machine_type: str = "n2-standard-2"
) -> compute_v1.Instance:
    """Creates a VM that explicitly doesn't consume reservations
    Args:
        project_id (str): The ID of the Google Cloud project.
        zone (str): The zone where the VM will be created.
        instance_name (str): The name of the instance to create.
        machine_type (str, optional): The machine type for the instance.
    Returns:
        compute_v1.Instance: The created instance.
    """
    instance = compute_v1.Instance()
    instance.name = instance_name
    instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"
    instance.zone = zone

    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
                )
            ],
        )
    ]

    # Set the reservation affinity to not consume any reservation
    instance.reservation_affinity = compute_v1.ReservationAffinity(
        consume_reservation_type="NO_RESERVATION",  # Prevents the instance from consuming reservations
    )

    # 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"Creating the {instance_name} instance in {zone}...")

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

REST

예약을 사용할 수 없는 인스턴스를 만들려면 instances.insert 메서드POST 요청을 실행합니다. 요청 본문에 NO_RESERVATION로 설정된 consumeReservationType 필드를 포함합니다.

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances

{
  "name": "INSTANCE_NAME",
  "machineType": "zones/ZONE/machineTypes/MACHINE_TYPE",
  "disks": [
    {
      "boot": true,
      "initializeParams": {
        "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"
      }
    }
  ],
  "networkInterfaces": [
    {
      "network": "global/networks/default"
    }
  ],
  "reservationAffinity": {
    "consumeReservationType": "NO_RESERVATION"
  }
}

다음을 바꿉니다.

  • PROJECT_ID: 인스턴스를 만들려는 프로젝트의 ID입니다.

  • ZONE: 인스턴스를 만들 영역입니다.

  • INSTANCE_NAME: 인스턴스 이름입니다.

  • MACHINE_TYPE: 인스턴스에 사용할 머신 유형입니다.

  • IMAGE_PROJECT: OS 이미지가 포함된 이미지 프로젝트입니다(예: debian-cloud). 지원되는 이미지 프로젝트에 대한 자세한 내용은 공개 이미지를 참조하세요.

  • IMAGE: 다음 중 하나를 지정합니다.

    • OS 이미지의 특정 버전입니다(예: debian-12-bookworm-v20240617).

    • 이미지 계열이며 형식은 family/IMAGE_FAMILY여야 합니다. 중단되지 않은 최신 OS 이미지를 지정합니다. 예를 들어 family/debian-12를 지정하면 Debian 12 이미지 계열의 최신 버전이 사용됩니다. 이미지 계열 사용에 대한 자세한 내용은 이미지 계열 권장사항을 참조하세요.

인스턴스 만들기에 관한 자세한 내용은 Compute Engine 인스턴스 만들기 및 시작을 참고하세요.

인스턴스를 일괄 생성하는 동안 소비 방지

예약을 사용할 수 없는 컴퓨팅 인스턴스를 일괄적으로 만들려면 다음 옵션 중 하나를 선택합니다.

gcloud

예약을 사용할 수 없는 인스턴스를 일괄적으로 만들려면 --reservation-affinity 플래그를 none로 설정하고 gcloud compute instances bulk create 명령어를 사용합니다.

예를 들어 단일 영역에서 인스턴스를 일괄로 만들고 이름 패턴을 지정하려면 다음 명령어를 실행합니다.

gcloud compute instances bulk create \
    --count=COUNT \
    --machine-type=MACHINE_TYPE \
    --name-pattern="NAME_PATTERN" \
    --reservation-affinity=none \
    --zone=ZONE

다음을 바꿉니다.

  • COUNT: 만들 인스턴스 수입니다.

  • MACHINE_TYPE: 인스턴스에 사용할 머신 유형입니다.

  • NAME_PATTERN: 인스턴스의 이름 패턴입니다. 인스턴스 이름에서 일련의 숫자를 바꾸려면 해시(#) 문자 시퀀스를 사용하세요. 예를 들어 이름 패턴에 instance-#을 사용하면 이름이 instance-1, instance-2로 시작하고 COUNT에 지정된 최대 인스턴스 수까지 이어지는 인스턴스가 생성됩니다.

  • ZONE: 인스턴스를 일괄로 만들 영역입니다.

REST

예약을 사용할 수 없는 인스턴스를 일괄적으로 만들려면 instances.bulkInsert 메서드POST 요청을 실행합니다. 요청 본문에 NO_RESERVATION으로 설정된 consumeReservationType 필드를 포함합니다.

예를 들어 단일 영역에서 인스턴스를 일괄로 만들고 이름 패턴을 지정하려면 다음과 같이 요청합니다.

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/bulkInsert

{
  "count": COUNT,
  "namePattern": "NAME_PATTERN",
  "instanceProperties": {
    "machineType": "MACHINE_TYPE",
    "disks": [
      {
        "boot": true,
        "initializeParams": {
          "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"
        }
      }
    ],
    "networkInterfaces": [
      {
        "network": "global/networks/default"
      }
    ],
    "reservationAffinity": {
      "consumeReservationType": "NO_RESERVATION"
    }
  }
}

다음을 바꿉니다.

  • PROJECT_ID: 인스턴스를 일괄로 만들 프로젝트의 ID입니다.

  • ZONE: 인스턴스를 일괄로 만들 영역입니다.

  • COUNT: 만들 인스턴스 수입니다.

  • NAME_PATTERN: 인스턴스의 이름 패턴입니다. 인스턴스 이름에서 일련의 숫자를 바꾸려면 해시(#) 문자 시퀀스를 사용하세요. 예를 들어 이름 패턴에 instance-#을 사용하면 이름이 instance-1, instance-2로 시작하고 COUNT에 지정된 최대 인스턴스 수까지 이어지는 인스턴스가 생성됩니다.

  • MACHINE_TYPE: 인스턴스에 사용할 머신 유형입니다.

  • IMAGE_PROJECT: OS 이미지가 포함된 이미지 프로젝트입니다(예: debian-cloud). 지원되는 이미지 프로젝트에 대한 자세한 내용은 공개 이미지를 참조하세요.

  • IMAGE: 다음 중 하나를 지정합니다.

    • OS 이미지의 특정 버전입니다(예: debian-12-bookworm-v20240617).

    • 이미지 계열이며 형식은 family/IMAGE_FAMILY여야 합니다. 중단되지 않은 최신 OS 이미지를 지정합니다. 예를 들어 family/debian-12를 지정하면 Debian 12 이미지 계열의 최신 버전이 사용됩니다. 이미지 계열 사용에 대한 자세한 내용은 이미지 계열 권장사항을 참조하세요.

인스턴스를 일괄로 만드는 방법에 대한 자세한 내용은 VM 일괄 생성을 참고하세요.

인스턴스 템플릿을 만드는 동안 사용 차단

예약을 사용하지 않도록 인스턴스를 구성하는 인스턴스 템플릿을 만든 후에는 템플릿을 사용하여 다음을 수행할 수 있습니다.

예약을 사용하지 않도록 인스턴스를 구성하는 인스턴스 템플릿을 만들려면 다음 옵션 중 하나를 선택합니다.

콘솔

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

    인스턴스 템플릿 만들기로 이동

  2. 이름 필드에 인스턴스 템플릿의 이름을 입력합니다.

  3. 위치 섹션에서 리전(기본값) 또는 전역 인스턴스 템플릿을 만들지 여부를 지정합니다.

  4. 머신 구성 섹션에서 템플릿을 사용하여 만든 인스턴스에 사용할 머신 유형을 지정합니다.

  5. 고급 옵션 섹션을 펼친 후 다음을 수행합니다.

    1. 관리 섹션을 펼칩니다.

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

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

gcloud

인스턴스가 예약을 사용하지 않도록 구성하는 인스턴스 템플릿을 만들려면 --reservation-affinity 플래그가 none로 설정된 gcloud compute instances-templates create 명령어를 사용합니다.

예약을 사용하지 않도록 인스턴스를 구성하는 리전 인스턴스 템플릿을 만들려면 다음 명령어를 실행합니다. 전역 인스턴스 템플릿을 만들려면 --instance-template-region 플래그 없이 동일한 명령어를 사용합니다.

gcloud compute instance-templates create INSTANCE_TEMPLATE_NAME \
    --instance-template-region=REGION \
    --machine-type=MACHINE_TYPE \
    --reservation-affinity=none

다음을 바꿉니다.

  • INSTANCE_TEMPLATE_NAME: 인스턴스 템플릿의 이름입니다.

  • REGION: 인스턴스 템플릿을 만들 리전입니다.

  • MACHINE_TYPE: 인스턴스 템플릿을 사용하여 만든 인스턴스에 사용할 머신 유형입니다.

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"
)

// createInstanceNotConsumeReservation creates a new instance template, which won't consume reservations
func createTemplateNotConsumeReservation(w io.Writer, projectID, templateName string) error {
	// projectID := "your_project_id"
	// templateName := "your_template_name"

	ctx := context.Background()
	instanceTemplatesClient, err := compute.NewInstanceTemplatesRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewInstanceTemplatesRESTClient: %w", err)
	}
	defer instanceTemplatesClient.Close()

	req := &computepb.InsertInstanceTemplateRequest{
		Project: projectID,
		InstanceTemplateResource: &computepb.InstanceTemplate{
			Name: proto.String(templateName),
			Properties: &computepb.InstanceProperties{
				// The template describes the size and source image of the boot disk
				// to attach to the instance.
				Disks: []*computepb.AttachedDisk{
					{
						InitializeParams: &computepb.AttachedDiskInitializeParams{
							DiskSizeGb:  proto.Int64(250),
							SourceImage: proto.String("projects/debian-cloud/global/images/family/debian-11"),
						},
						AutoDelete: proto.Bool(true),
						Boot:       proto.Bool(true),
					},
				},
				MachineType: proto.String("e2-standard-4"),
				// The template connects the instance to the `default` network,
				// without specifying a subnetwork.
				NetworkInterfaces: []*computepb.NetworkInterface{
					{
						Name: proto.String("global/networks/default"),
						// The template lets the instance use an external IP address.
						AccessConfigs: []*computepb.AccessConfig{
							{
								Name:        proto.String("External NAT"),
								Type:        proto.String(computepb.AccessConfig_ONE_TO_ONE_NAT.String()),
								NetworkTier: proto.String(computepb.AccessConfig_PREMIUM.String()),
							},
						},
					},
				},
				ReservationAffinity: &computepb.ReservationAffinity{
					ConsumeReservationType: proto.String("NO_RESERVATION"),
				},
			},
		},
	}

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

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

	fmt.Fprintf(w, "Instance template created\n")

	return nil
}

자바

예약을 사용하지 않도록 인스턴스를 구성하는 인스턴스 템플릿을 만들려면 다음 코드 샘플을 사용하세요.

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

import com.google.cloud.compute.v1.AccessConfig;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.InsertInstanceTemplateRequest;
import com.google.cloud.compute.v1.InstanceProperties;
import com.google.cloud.compute.v1.InstanceTemplate;
import com.google.cloud.compute.v1.InstanceTemplatesClient;
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 CreateTemplateWithoutConsumingReservation {
  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 template you want to query.
    String templateName = "YOUR_INSTANCE_TEMPLATE_NAME";
    String machineType = "e2-standard-4";
    String sourceImage = "projects/debian-cloud/global/images/family/debian-11";

    createTemplateWithoutConsumingReservationAsync(
        projectId, templateName, machineType, sourceImage);
  }


  // Create a template that explicitly doesn't consume any reservations.
  public static InstanceTemplate createTemplateWithoutConsumingReservationAsync(
      String projectId, String templateName, String machineType, String sourceImage)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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 (InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create()) {
      AttachedDisk attachedDisk = AttachedDisk.newBuilder()
          .setInitializeParams(AttachedDiskInitializeParams.newBuilder()
              .setSourceImage(sourceImage)
              .setDiskType("pd-balanced")
              .setDiskSizeGb(250)
              .build())
          .setAutoDelete(true)
          .setBoot(true)
          .build();

      NetworkInterface networkInterface = NetworkInterface.newBuilder()
          .setName("global/networks/default")
          .addAccessConfigs(AccessConfig.newBuilder()
              .setName("External NAT")
              .setType(AccessConfig.Type.ONE_TO_ONE_NAT.toString())
              .setNetworkTier(AccessConfig.NetworkTier.PREMIUM.toString())
              .build())
          .build();

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

      InstanceProperties instanceProperties = InstanceProperties.newBuilder()
          .addDisks(attachedDisk)
          .setMachineType(machineType)
          .setReservationAffinity(reservationAffinity)
          .addNetworkInterfaces(networkInterface)
          .build();

      InsertInstanceTemplateRequest insertInstanceTemplateRequest = InsertInstanceTemplateRequest
          .newBuilder()
          .setProject(projectId)
          .setInstanceTemplateResource(InstanceTemplate.newBuilder()
              .setName(templateName)
              .setProperties(instanceProperties)
              .build())
          .build();

      Operation response = instanceTemplatesClient.insertAsync(insertInstanceTemplateRequest)
          .get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        return null;
      }
      return instanceTemplatesClient.get(projectId, templateName);
    }
  }
}

Node.js

예약을 사용하지 않도록 인스턴스를 구성하는 인스턴스 템플릿을 만들려면 다음 코드 샘플을 사용하세요.

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

// Instantiate an instanceTemplatesClient
const instanceTemplatesClient = new computeLib.InstanceTemplatesClient();
// Instantiate a globalOperationsClient
const globalOperationsClient = new computeLib.GlobalOperationsClient();

/**
 * TODO(developer): Update/uncomment these variables before running the sample.
 */
// The ID of the project where you want to create template.
const projectId = await instanceTemplatesClient.getProjectId();
// The name of the template to create.
// const templateName = 'instance-01';

// Create an instance template that creates VMs that don't explicitly consume reservations
async function callCreateTemplateToNotConsumeReservation() {
  // Define the boot disk for the instance template
  const disk = new compute.AttachedDisk({
    initializeParams: new compute.AttachedDiskInitializeParams({
      sourceImage:
        'projects/debian-cloud/global/images/debian-12-bookworm-v20240815',
      diskSizeGb: '100',
      diskType: 'pd-balanced',
    }),
    autoDelete: true,
    boot: true,
    type: 'PERSISTENT',
  });

  // Define the network interface for the instance template
  const network = new compute.NetworkInterface({
    network: `projects/${projectId}/global/networks/default`,
  });

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

  // Define instance template
  const instanceTemplate = new compute.InstanceTemplate({
    name: templateName,
    properties: {
      disks: [disk],
      machineType: 'e2-medium',
      // The template connects the instance to the `default` network,
      // without specifying a subnetwork.
      networkInterfaces: [network],
      reservationAffinity,
    },
  });

  const [response] = await instanceTemplatesClient.insert({
    project: projectId,
    instanceTemplateResource: instanceTemplate,
  });

  let operation = response.latestResponse;

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

  console.log(`Template ${templateName} created.`);
}

await callCreateTemplateToNotConsumeReservation();

Python

예약을 사용하지 않도록 인스턴스를 구성하는 인스턴스 템플릿을 만들려면 다음 코드 샘플을 사용하세요.

from __future__ import annotations

import sys
from typing import Any

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


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

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

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

    Returns:
        Whatever the operation.result() returns.

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

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

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

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

    return result


def create_instance_template_not_consume_reservation(
    project_id: str,
    template_name: str,
    machine_type: str = "n1-standard-1",
) -> compute_v1.InstanceTemplate:
    """
    Creates an instance template that creates VMs that don't explicitly consume reservations

    Args:
        project_id: project ID or project number of the Cloud project you use.
        template_name: name of the new template to create.
        machine_type: machine type for the instance.
    Returns:
        InstanceTemplate object that represents the new instance template.
    """

    template = compute_v1.InstanceTemplate()
    template.name = template_name
    template.properties.machine_type = machine_type
    # The template describes the size and source image of the boot disk
    # to attach to the instance.
    template.properties.disks = [
        compute_v1.AttachedDisk(
            boot=True,
            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,
            ),
        )
    ]
    # The template connects the instance to the `default` network,
    template.properties.network_interfaces = [
        compute_v1.NetworkInterface(
            network="global/networks/default",
            access_configs=[
                compute_v1.AccessConfig(
                    name="External NAT",
                    type="ONE_TO_ONE_NAT",
                )
            ],
        )
    ]
    # The template doesn't explicitly consume reservations
    template.properties.reservation_affinity = compute_v1.ReservationAffinity(
        consume_reservation_type="NO_RESERVATION"
    )

    template_client = compute_v1.InstanceTemplatesClient()
    operation = template_client.insert(
        project=project_id, instance_template_resource=template
    )

    wait_for_extended_operation(operation, "instance template creation")

    return template_client.get(project=project_id, instance_template=template_name)

REST

예약을 사용하지 않도록 인스턴스를 구성하는 인스턴스 템플릿을 만들려면 다음 메서드 중 하나로 POST 요청을 실행합니다.

요청 본문에 consumeReservationType 필드를 포함하고 NO_RESERVATION으로 설정합니다.

예를 들어 지역 인스턴스 템플릿을 만들고 예약을 사용하지 않도록 지정하려면 다음과 같이 요청합니다.

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/InstanceTemplates

{
  "name": "INSTANCE_TEMPLATE_NAME",
  "properties": {
    "machineType": "MACHINE_TYPE",
    "disks": [
      {
        "boot": true,
        "initializeParams": {
          "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"
        }
      }
    ],
    "networkInterfaces": [
      {
        "network": "global/networks/default"
      }
    ],
    "reservationAffinity": {
      "consumeReservationType": "NO_RESERVATION"
    }
  }
}

다음을 바꿉니다.

  • PROJECT_ID: 인스턴스 템플릿을 만들 프로젝트의 ID입니다.

  • INSTANCE_TEMPLATE_NAME: 인스턴스 템플릿의 이름입니다.

  • MACHINE_TYPE: 인스턴스 템플릿을 사용하여 만든 인스턴스에 사용할 머신 유형입니다.

  • IMAGE_PROJECT: OS 이미지가 포함된 이미지 프로젝트입니다(예: debian-cloud). 지원되는 이미지 프로젝트에 대한 자세한 내용은 공개 이미지를 참조하세요.

  • IMAGE: 다음 중 하나를 지정합니다.

    • OS 이미지의 특정 버전입니다(예: debian-12-bookworm-v20240617).

    • 이미지 계열이며 형식은 family/IMAGE_FAMILY여야 합니다. 중단되지 않은 최신 OS 이미지를 지정합니다. 예를 들어 family/debian-12를 지정하면 Debian 12 이미지 계열의 최신 버전이 사용됩니다. 이미지 계열 사용에 대한 자세한 내용은 이미지 계열 권장사항을 참조하세요.

인스턴스 템플릿 만들기에 대한 자세한 내용은 인스턴스 템플릿 만들기를 참조하세요.

다음 단계