Consume reservations


This document explains how to use Compute Engine to do the following:

  • Consume reserved virtual machine (VM) instances.

  • Verify reservations consumption.

  • View reservation usage reports.

For more information about consuming reservations in other Google Cloud products that use VMs, see the reservations documentation for the following products:

Before you begin

  • Review the requirements and restrictions for reservations.
  • If you haven't already, then set up authentication. Authentication is the process by which your identity is verified for access to Google Cloud services and APIs. To run code or samples from a local development environment, you can authenticate to Compute Engine by selecting one of the following options:

    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.

    Go

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

    1. Install the Google Cloud CLI.
    2. 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.

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

    Java

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

    1. Install the Google Cloud CLI.
    2. 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.

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

    Node.js

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

    1. Install the Google Cloud CLI.
    2. 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.

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

    Python

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

    1. Install the Google Cloud CLI.
    2. 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.

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

    REST

    To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.

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

      gcloud init

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

Required roles

To get the permissions that you need to consume reservations, ask your administrator to grant you the Compute Instance Admin (v1) (roles/compute.instanceAdmin.v1) IAM role on the project. For more information about granting roles, see Manage access to projects, folders, and organizations.

This predefined role contains the permissions required to consume reservations. To see the exact permissions that are required, expand the Required permissions section:

Required permissions

The following permissions are required to consume reservations:

  • To create reservations: compute.reservations.create on the project
  • To create VMs:
    • compute.instances.create on the project
    • To use a custom image to create the VM: compute.images.useReadOnly on the image
    • To use a snapshot to create the VM: compute.snapshots.useReadOnly on the snapshot
    • To use an instance template to create the VM: compute.instanceTemplates.useReadOnly on the instance template
    • To assign a legacy network to the VM: compute.networks.use on the project
    • To specify a static IP address for the VM: compute.addresses.use on the project
    • To assign an external IP address to the VM when using a legacy network: compute.networks.useExternalIp on the project
    • To specify a subnet for the VM: compute.subnetworks.use on the project or on the chosen subnet
    • To assign an external IP address to the VM when using a VPC network: compute.subnetworks.useExternalIp on the project or on the chosen subnet
    • To set VM instance metadata for the VM: compute.instances.setMetadata on the project
    • To set tags for the VM: compute.instances.setTags on the VM
    • To set labels for the VM: compute.instances.setLabels on the VM
    • To set a service account for the VM to use: compute.instances.setServiceAccount on the VM
    • To create a new disk for the VM: compute.disks.create on the project
    • To attach an existing disk in read-only or read-write mode: compute.disks.use on the disk
    • To attach an existing disk in read-only mode: compute.disks.useReadOnly on the disk
  • To create instance templates: compute.instanceTemplates.create on the project

You might also be able to get these permissions with custom roles or other predefined roles.

Consume reserved VMs

When you create a virtual machine (VM) instance, the VM starts consuming a reservation only if the properties for both the VM and the reservation are matching. Additionally, you must set the reservation affinity property of the VM to one of the following options:

  • Consume any matching reservation—the VM can automatically consume any reservation with matching properties (default).

    This option is useful if you create and delete lots of VMs, and you want to use your reservations whenever possible. In this scenario, a VM can be created whether its properties match a reservation or not. If they match, the VM starts consuming the reservation depending on the reservation's consumption order.

  • Consume a specific reservation—the VM can consume only a specific reservation. The reservation can't be automatically consumed.

    This option is useful when, for example, you want to hold a certain amount of capacity as backup for special events. In this scenario, a VM can be created only if its properties and the specific reservation's properties are matching.

  • Can't consume any reservation at all—the VM can't consume any reservation.

    This option is useful when, for example, you create a temporary VM that you don't want to consume reserved resources.

Consume VMs from any matching reservation

In this consumption model, existing and new VMs automatically consume a reservation if their properties match the VM properties specified in the reservation.

When using this consumption model, the VMs in the current project consume all single-project reservations first before consuming any shared reservations. For more information about how reservations are automatically consumed, see consumption order.

When you create a reservation, this is the default consumption model, as long as you don't use the flag or option that indicates specific reservations are required.

Console

  1. To create a reservation with resources that can be used by VMs with a reservation affinity property configured to consume any reservations (default), follow these steps:

    1. Select the type of reservation that you want to create:

      • To create standalone reservation, do the following:

        1. In the Google Cloud console, go to the Reservations page.

          Go to Reservations

        2. On the On-demand reservation tab (default), click Create reservation.

          The Create a reservation page opens.

      • To create a reservation that is attached to a commitment, do the following:

        1. In the Google Cloud console, go to the Committed use discounts page.

          Go to Committed use discounts

          The Commitment list page opens.

        2. Click Purchase commitment.

          The Purchase a committed use discount page opens.

        3. Specify the commitment properties. Then, in the Reservations section, click Add an item.

          The Add a new reservation section appears.

          For more information about how to purchase a commitment with an attached reservation, see Purchase commitments with attached reservations.

    2. In the Name field, enter a name for your reservation. For this example, enter reservation-01.

    3. Choose the Region and Zone where you want to reserve resources. For this example, select us-central1 as the region and us-central1-a as the zone.

    4. Choose your preferred Share type:

      • To create a reservation for a single project, select Local.
      • To create a shared reservation among multiple projects, select Shared. To share this reservation with other projects, click Add projects and select the desired projects from the current project's organization.
    5. In the Use with VM instance section, select Use reservation automatically, so that any matching VMs can automatically use this reservation.

    6. In the Number of VM instances field, enter the number of VMs that you want to reserve. For this example, enter 2.

    7. Specify the resources that you want to reserve for each VM:

      • If you want to reserve VMs that match an existing instance template, select Use instance template and select an instance template from the list.
      • Otherwise, select Specify machine type and specify the following:
        1. In the Machine family, Series, and Machine type fields, select a machine family, series, and machine type.
        2. Optional: Specify a minimum CPU platform and/or GPUs:
          1. To expand the CPU Platform and GPU section, click the expander arrow.
          2. Optional: To specify a minimum CPU platform, in the CPU Platform list, select an option.
          3. Optional: To add GPUs, click Add GPU. Then, in the GPU type and Number of GPUs fields, select the type and number of GPUs for each VM.
        3. Optional: Add local SSDs:
          1. In the Number of disks field, select the number of local SSDs for each VM.
          2. In the Interface type field, select the interface for the local SSDs.

      For this example, select Specify machine type. Then select the n2-standard-32 machine type for the General-purpose machine family and N2 series and select the minimum CPU platform Intel Cascade Lake.

    8. Finish creating the reservation:

      • If you are creating standalone reservation, click Create.

      • If you are creating a reservation that is attached to a commitment:

        1. To finish specifying the properties for this reservation, click Done.
        2. To finish creating the commitment and attached reservations, click Purchase.
  2. In the same project or a project that the reservation is shared with, create a VM that targets any open reservation.

    Ensure that the VM's properties match the VM properties in reservation-01, including the zone, machine type (machine family, vCPUs, and memory), minimum CPU platform, GPU amount and type, and local SSD interface and size.

    For more information about how to create a VM, see Create and start a VM

    1. In the Google Cloud console, go to the Create an instance page.

      Go to Create an instance

      The Create an instance page opens.

    2. Specify a name for your VM.

    3. In the following sections, select a configuration that exactly matches all the properties of your reservation, including any optional properties. For this example, you must match the following VM properties with reservation-01:

      • Region: us-central1
      • Zone: us-central1-a
      • Machine type: n2-standard-32
      • Minimum CPU platform: Intel Cascade Lake
      • GPUs: none
      • Local SSDs: none
    4. Expand the Advanced options section and then expand the Management section. In the Reservations list, select Automatically use created reservation.

    5. To create the VM, click Create.

gcloud

  1. Create an open reservation called reservation-01.

    gcloud compute reservations create reservation-01 \
        --vm-count=2 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --zone=us-central1-a
    
  2. Create a VM that targets any open reservation and that matches the VM properties in reservation-01, including the zone, machine type (machine family. vCPUs, and memory), minimum CPU platform, GPU amount and type, and local SSD amount and interface.

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

Go

import (
	"context"
	"fmt"
	"io"

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

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

	ctx := context.Background()

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

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

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

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

	return nil
}

Java

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

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

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

  1. Create an open reservation named reservation-01.

    POST https://compute.googleapis.com/compute/v1/projects/my-project/zones/us-central1-a/reservations
    
    {
      "name": "reservation-01",
      "specificReservation": {
        "count": "2",
        "instanceProperties": {
          "machineType": "n2-standard-32",
          "minCpuPlatform": "Intel Cascade Lake",
        }
      }
    }
    
  2. Create a VM that targets any open reservation and that matches the VM properties in reservation-01, including the zone, machine type (machine family. vCPUs, and memory), minimum CPU platform, GPU amount and type, and local SSD amount and interface.

    POST https://compute.googleapis.com/compute/v1/projects/my-project/zones/us-central1-a/instances
    
    {
      "name": "instance-1",
      "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"
      }
    }
    

Consume VMs from a specific reservation

In this consumption model, only new VMs that target a specific reservation by name can consume that reservation, and the reservation is not consumed automatically.

When creating the reservation, specify that VMs are required to target the specific reservation by using one of the following methods:

  • In the Google Cloud console, select the Select specific reservation checkbox.
  • In the gcloud CLI, include the --require-specific-reservation flag.
  • In the Compute Engine API, set the specificReservationRequired field to true.
  • In Terraform, set the specific_reservation_required field to true.

Then create VMs that specifically target that reservation. You can only create a VM that targets a specific reservation if the VM properties and the reservation's properties are matching. Otherwise, creating the VM fails.

If you are using an instance template to create VMs in a regional managed instance group, create identical reservations with the same name in each applicable zone. Then, target the reservations by name in the group's instance template.

For example, create a specific reservation named reservation-02, and then create a matching VM that targets that reservation and that matches the reservation's VM properties.

Depending on the type of VM you want to consume, follow the steps for Consume a specific single-project reservation or Consume a specific shared reservation.

Consume a specific single-project reservation

To consume a specific single-project reservation, select one of the following options:

Console

  1. To create a reservation with resources that can only be used by VMs that specifically target the reservation by name, follow these steps:

    1. Select one of the following options:

      • To create standalone reservation, do the following:

        1. In the Google Cloud console, go to the Reservations page.

          Go to Reservations

        2. On the On-demand reservations tab (default), click Create reservation.

          The Create a reservation page opens.

      • To create a reservation that is attached to a commitment, do the following:

        1. In the Google Cloud console, go to the Committed use discounts page.

          Go to Committed use discounts

        2. Click Purchase commitment.

          The Purchase a committed use discount page opens.

        3. Specify the commitment properties. Then, in the Reservations section, click Add an item.

          The Add a new reservation section appears.

          For more information about how to purchase a commitment with an attached reservation, see Purchase commitments with attached reservations.

    2. In the Name field, enter a name for your reservation. For this example, enter reservation-02.

    3. Choose the Region and Zone where you want to reserve resources. For this example, select us-central1 as the region and us-central1-a as the zone.

    4. To specify that your reservation will be a single-project reservation, select Local as the Share type.

    5. In the Use with VM instance section, select Select specific reservation, so that only matching VMs that specifically target this reservation by name can use this reservation.

    6. In the Number of VM instances field, enter the number of VMs that you want to reserve. For this example, enter 10.

    7. Specify the resources that you want to reserve for each VM:

      • If you want to reserve VMs that match an existing instance template, select Use instance template and select an instance template from the list.
      • Otherwise, select Specify machine type and specify the following:
        1. In the Machine family, Series, and Machine type fields, select a machine family, series, and machine type.
        2. Optional: Specify a minimum CPU platform and/or GPUs:
          1. To expand the CPU Platform and GPU section, click the expander arrow.
          2. Optional: To specify a minimum CPU platform, in the CPU Platform list, select an option.
          3. Optional: To add GPUs, click Add GPU. Then, in the GPU type and Number of GPUs fields, select the type and number of GPUs for each VM.
        3. Optional: Add local SSDs:
          1. In the Number of disks field, select the number of local SSDs for each VM.
          2. In the Interface type field, select the interface for the local SSDs.

      For this example, select Specify machine type. Then select the n2-standard-32 machine type for the General-purpose machine family and N2 series and select the minimum CPU platform Intel Cascade Lake.

    8. Finish creating the reservation:

      • If you are creating standalone reservation, click Create.

      • If you are creating a reservation that is attached to a commitment:

        1. To finish specifying the properties for this reservation, click Done.
        2. To finish creating the commitment and attached reservations, click Purchase.
  2. In the same project, create a VM that targets that specific reservation by name.

    Ensure that the VM's properties match the VM properties of that specific reservation, including the zone, machine type (machine family, vCPUs, and memory), minimum CPU platform, GPU amount and type, and local SSD interface and size.

    For more information about how to create a VM, see Create and start a VM.

    1. In the Google Cloud console, go to the Create an instance page.

      Go to Create an instance

    2. In the Name field, enter a name for the VM.

    3. In the following sections, select a configuration that exactly matches all the properties of your reservation, including any optional properties. For this example, you must match the following VM properties with reservation-02:

      • Region: us-central1
      • Zone: us-central1-a
      • Machine type: n2-standard-32
      • Minimum CPU platform: Intel Cascade Lake
      • GPUs: none
      • Local SSDs: none
    4. Expand the Advanced options section, and then do the following:

      1. Expand the Management section.

      2. In the Reservations section, in the Application policy list, select Select specific reservation.

      3. Select the reservation with matching VM properties that you want your VM to consume. For this example, select reservation-02.

    5. To create the VM, click Create.

gcloud

  1. Create a reservation named reservation-02 with the --require-specific-reservation flag. These reserved resources can be used only by VMs that specifically target this reservation by name.

    gcloud compute reservations create reservation-02 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --vm-count=10 \
        --zone=us-central1-a \
        --require-specific-reservation
    
  2. Create a VM that targets reservation-02 by name by using the --reservation-affinity and --reservation flags.

    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.

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

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

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

Java

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);
    }
  }
}

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

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)

REST

  1. Create a reservation named reservation-02 with the specificReservationRequired field set to true.

    POST https://compute.googleapis.com/compute/v1/projects/my-project/zones/us-central1-a/reservations
    
    {
      "name":"reservation-02",
      "specificReservation":{
        "count":"10",
        "instanceProperties":{
          "machineType":"n2-standard-32",
          "minCpuPlatform": "Intel Cascade Lake",
        }
      },
      "specificReservationRequired": true
    }
    
  2. Create a VM that targets reservation-02 by name by using the reservationAffinity field.

    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.

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

Consume a specific shared reservation

To consume a specific shared reservation, select one of the following options:

Console

  1. To create a shared reservation with resources that can only be used by VMs that specifically target this reservation by name, follow these steps:

    1. Select one of the following options:

      • To create standalone reservation, do the following:

        1. In the Google Cloud console, go to the Reservations page.

          Go to Reservations

        2. On the On-demand reservations tab (default), click Create reservation.

          The Create a reservation page opens.

      • To create a reservation that is attached to a commitment, do the following:

        1. In the Google Cloud console, go to the Committed use discounts page.

          Go to Committed use discounts

        2. Click Purchase commitment.

          The Purchase a committed use discount page opens.

        3. Specify the commitment properties. Then, in the Reservations section, click Add an item.

          The Add a new reservation section appears.

          For more information about how to purchase a commitment with an attached reservation, see Purchase commitments with attached reservations.

    2. In the Name field, enter a name for your reservation. For this example, enter reservation-02.

    3. Choose the Region and Zone where you want to reserve resources. For this example, select us-central1 as the region and us-central1-a as the zone.

    4. To specify that your reservation is a shared reservation, select Shared as the Share type.

    5. Click Add projects and select the projects from the current project's organization that you want to share the reservation with.

    6. In the Use with VM instance section, select Select specific reservation, so that only matching VMs that specifically target this reservation by name can use this reservation.

    7. In the Number of VM instances field, enter the number of VMs that you want to reserve. For this example, enter 10.

    8. Specify the resources that you want to reserve for each VM:

      • If you want to reserve VMs that match an existing instance template, select Use instance template and select an instance template from the list.
      • Otherwise, select Specify machine type and specify the following:
        1. In the Machine family, Series, and Machine type fields, select a machine family, series, and machine type.
        2. Optional: Specify a minimum CPU platform and/or GPUs:
          1. To expand the CPU Platform and GPU section, click the expander arrow.
          2. Optional: To specify a minimum CPU platform, in the CPU Platform list, select an option.
          3. Optional: To add GPUs, click Add GPU. Then, in the GPU type and Number of GPUs fields, select the type and number of GPUs for each VM.
        3. Optional: Add local SSDs:
          1. In the Number of disks field, select the number of local SSDs for each VM.
          2. In the Interface type field, select the interface for the local SSDs.

      For this example, select Specify machine type. Then select the n2-standard-32 machine type for the General-purpose machine family and N2 series and select the minimum CPU platform Intel Cascade Lake. 1. Finish creating the reservation:

      • If you are creating standalone reservation, click Create.

      • If you are creating a reservation that is attached to a commitment:

        1. To finish specifying the properties for this reservation, click Done.
        2. To finish creating the commitment and attached reservations, click Purchase.
  2. In the same project or a project that the reservation is shared with, create a VM that targets that specific reservation by name.

    Ensure that the VM's properties match the VM properties of that specific reservation, including the zone, machine type (machine family, vCPUs, and memory), minimum CPU platform, GPU amount and type, and local SSD interface and size.

    1. In the Google Cloud console, go to the Create an instance page.

      Go to Create an instance

      The Create an instance page opens.

    2. Specify a Name for your VM.

    3. In the following sections, select a configuration that exactly matches all the properties of your reservation, including any optional properties. For this example, you must match the following VM properties with reservation-02:

      • Region: us-central1
      • Zone: us-central1-a
      • Machine type: n2-standard-32
      • Minimum CPU platform: Intel Cascade Lake
      • GPUs: none
      • Local SSDs: none
    4. Expand the Advanced options section and then expand the Management section. In the Reservations list, select Select specific reservation, and then do the following:

      1. Select a Reservation project that has reservations shared with your current project. For this example, select the project that you used to create reservation-02.
      2. Select the Reservation name of the shared reservation that you want this VM to consume. For this example, select reservation-02.
    5. To create the VM, click Create.

gcloud

  1. Create a reservation named reservation-02 with the --require-specific-reservation flag. These reserved resources can be used only by VMs that specifically target this reservation by name.

    gcloud compute reservations create reservation-02 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --vm-count=10 \
        --zone=us-central1-a \
        --project=my-owner-project \
        --share-setting=projects \
        --share-with=project-1,project-2 \
        --require-specific-reservation
    
  2. Create a VM that targets reservation-02 by name by using the --reservation-affinity and --reservation flags. To consume this reservation from any consumer projects that this reservation is shared with, you must also specify the project that created the reservation, my-owner-project.

    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.

    gcloud compute instances create instance-2 \
        --machine-type=n2-standard-32 \
        --min-cpu-platform="Intel Cascade Lake" \
        --zone=us-central1-a \
        --reservation-affinity=specific \
        --reservation=projects/my-owner-project/reservations/reservation-02
    

Go

import (
	"context"
	"fmt"
	"io"

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

// consumeSpecificSharedReservation consumes specific shared reservation in particular zone
func consumeSpecificSharedReservation(w io.Writer, client InstanceClientInterface, projectID, baseProjectId, zone, instanceName, reservationName string) error {
	// client, err := compute.NewInstancesRESTClient(ctx)
	// projectID := "your_project_id". Project where reservation is created.
	// baseProjectId := "shared_project_id". Project where instance will be consumed and created.
	// zone := "us-west3-a"
	// reservationName := "your_reservation_name"
	// instanceName := "your_instance_name"

	ctx := context.Background()
	machineType := fmt.Sprintf("zones/%s/machineTypes/%s", zone, "n2-standard-32")
	sourceImage := "projects/debian-cloud/global/images/family/debian-12"
	sharedReservation := fmt.Sprintf("projects/%s/reservations/%s", baseProjectId, reservationName)

	req := &computepb.InsertInstanceRequest{
		Project: projectID,
		Zone:    zone,
		InstanceResource: &computepb.Instance{
			Disks: []*computepb.AttachedDisk{
				{
					InitializeParams: &computepb.AttachedDiskInitializeParams{
						DiskSizeGb:  proto.Int64(10),
						SourceImage: proto.String(sourceImage),
					},
					AutoDelete: proto.Bool(true),
					Boot:       proto.Bool(true),
					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
				},
			},
			MachineType:    proto.String(machineType),
			MinCpuPlatform: proto.String("Intel Cascade Lake"),
			Name:           proto.String(instanceName),
			NetworkInterfaces: []*computepb.NetworkInterface{
				{
					Name: proto.String("global/networks/default"),
				},
			},
			// specifies particular reservation, which should be consumed
			ReservationAffinity: &computepb.ReservationAffinity{
				ConsumeReservationType: proto.String("SPECIFIC_RESERVATION"),
				Key:                    proto.String("compute.googleapis.com/reservation-name"),
				Values:                 []string{sharedReservation},
			},
		},
	}

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

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

	return nil
}

Java

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);
    }
  }
}

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

  1. Create a reservation named reservation-02 with the specificReservationRequired field set to true.

    POST https://compute.googleapis.com/compute/v1/projects/my-owner-project/zones/us-central1-a/reservations
    
    {
      "name":"reservation-02",
      "specificReservation":{
        "count":"10",
        "instanceProperties":{
          "machineType":"n2-standard-32",
          "minCpuPlatform": "Intel Cascade Lake"
        }
      },
      "shareSettings": {
        "shareType": "SPECIFIC_PROJECTS",
        "projectMap": {
          "project-1": {
            "projectId": "project-1"
          },
          "project-2": {
            "projectId": "project-2"
          }
        }
      },
      "specificReservationRequired": true
    }
    
  2. Create a VM that targets reservation-02 by name by using the reservationAffinity field. To consume this reservation from any consumer projects that this reservation is shared with, you must also specify the owner project of the reservation, my-owner-project.

    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.

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

Create VMs without consuming reservations

If you create an automatically consumed reservation, then any running VMs with matching properties in your project can consume the reservation. To prevent one or more of your VMs from consuming the reservation, do the following:

  • Set the reservation affinity property of the VMs to explicitly not consume any reservations as described in this section.

  • Make sure that your VMs don't match the VM properties of the reservation.

To create VMs that explicitly don't consume reservations, select one of the following methods:

Create a VM to not consume reservations

To create a VM that explicitly doesn't consume reservations, select one of the following options:

Console

  1. In the Google Cloud console, go to the Create an instance page.

    Go to Create an instance

  2. In the Name field, enter a name for the VM.

  3. In the Region and Zone lists, select the region and zone in which to create the VM.

  4. In the Machine configuration section, specify the machine type to use for the VM.

  5. Expand the Advanced options section, and then do the following:

    1. Expand the Management section.

    2. In the Reservations section, in the Application policy list, select Don't use.

  6. Click Create.

gcloud

To create a VM that explicitly doesn't consume reservations, use the gcloud compute instances create command with the --reservation-affinity=none flag.

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

Replace the following:

  • VM_NAME: the name of the VM.

  • MACHINE_TYPE: the machine type to use for the VM.

  • ZONE: the zone in which to create the VM.

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
}

Java

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

To create a VM that explicitly doesn't consume reservations, make a POST request to the instances.insert method. In the request body, include the consumeReservationType field set to NO_RESERVATION.

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

{
  "name": "VM_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"
  }
}

Replace the following:

  • PROJECT_ID: the ID of the project in which to create the VM.

  • ZONE: the zone in which to create the VM.

  • VM_NAME: the name of the VM.

  • MACHINE_TYPE: the machine type to use for the VM.

  • IMAGE_PROJECT: the image project that contains the OS image—for example, debian-cloud. For more information about the supported image projects, see Public images.

  • IMAGE: specify one of the following:

    • A specific version of the OS image—for example, debian-12-bookworm-v20240617.

    • An image family, which must be formatted as family/IMAGE_FAMILY. This specifies the most recent, non-deprecated OS image. For example, if you specify family/debian-12, the latest version in the Debian 12 image family is used. For more information about using image families, see Image families best practices.

For more information about creating a VM, see Create and start a Compute Engine instance.

Create an instance template to not consume reservations

To create an instance template that creates VMs that don't explicitly consume reservations, select one of the following options:

Console

  1. In the Google Cloud console, go to the Create an instance template page.

    Go to Create an instance template

  2. In the Name field, enter a name for the instance template.

  3. In the Location section, specify whether you want to create a regional (default) or global instance template.

  4. In the Machine configuration section, specify the machine type to use for the VMs created using the template.

  5. Expand the Advanced options section, and then do the following:

    1. Expand the Management section.

    2. In the Reservations section, in the Application policy list, select Don't use.

  6. Click Create.

gcloud

To create an instance template that creates VMs that don't explicitly consume reservations, use the gcloud compute instances-templates create command with the --reservation-affinity=none flag.

For example, to create a global instance template that creates VMs that don't explicitly consume reservations, run the following command:

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

Replace the following:

  • INSTANCE_TEMPLATE_NAME: the name of the instance template.

  • MACHINE_TYPE: the machine type to use for the VMs created using the instance template.

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
}

Java

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

To create an instance template that creates VMs that don't explicitly consume reservations, make a POST request to one of the following methods:

In the request body, include the consumeReservationType field and set it to NO_RESERVATION.

For example, to create a global instance template that creates VMs that don't explicitly consume reservations, make a request as follows:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/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"
    }
  }
}

Replace the following:

  • PROJECT_ID: the ID of the project in which to create the instance template.

  • INSTANCE_TEMPLATE_NAME: the name of the instance template.

  • MACHINE_TYPE: the machine type to use for the VMs created using the instance template.

  • IMAGE_PROJECT: the image project that contains the OS image—for example, debian-cloud. For more information about the supported image projects, see Public images.

  • IMAGE: specify one of the following:

    • A specific version of the OS image—for example, debian-12-bookworm-v20240617.

    • An image family, which must be formatted as family/IMAGE_FAMILY. This specifies the most recent, non-deprecated OS image. For example, if you specify family/debian-12, the latest version in the Debian 12 image family is used. For more information about using image families, see Image families best practices.

For more information about creating instance templates, see Create instance templates.

Test that VM properties match a reservation

To test whether VMs can automatically consume a reservation, you can create a copy of the reservation as a specific reservation, and then see if a VM you plan to create can consume that reservation. If you can successfully create the VM, then you've verified that the VM can correctly consume the matching reservation. Otherwise, creating the VM fails because the properties don't match or there are no available reserved resources. After testing, you can do one or more of the following:

Verify reservations consumption

To ensure that your VMs are effectively consuming your reservations, you can verify their consumption using the following methods:

  • View the details of the reservation

    If the number of VMs consuming a reservation increases by 1 after you create or update a VM, then your action likely caused the VM to start consuming the reservation. This is the quickest way to check if a reservation is being consumed. However, it might not work well to verify which exact VM is consuming the reservation.

  • Create the VM to target a specific reservation

    If you can successfully create a VM that targets a specific reservation, then the VM is consuming the reservation. This is the most reliable method to verify that a specific VM is consuming a reservation and that the VM's properties match the reservation's properties.

  • Monitor your reservations consumption

    By using Cloud Monitoring, you can access and view the information associated with the consumption of the reservations that were created in your project. Monitoring updates you reservations consumption data at least once every 30 minutes. This method is useful to verify the consumption trend of one or more reservations in a project, as well as receive notifications for underused or unused reservations.

  • View the historical usage of your reservations

    By using Capacity Planner (Preview), you can access and view the historical usage of your reservations from their creation up to their deletion. Capacity Planner updates reservations consumption data every 24 hours. This method is useful for verifying the past consumption of your reservations within a project, folder, or organization, as well as helping you plan for future capacity needs.

If you see that a VM isn't consuming a reservation after you've verified that the VM's reservation affinity can consume the reservation, the reservation isn't fully consumed, and the VM and the reservation's properties are matching, then see Resource availability.

View reservation usage reports

Export detailed reports of your Compute Engine usage to a Cloud Storage bucket using the usage export feature. For instructions, see Viewing usage reports.

The usage report shows the following:

  • The reserved resources that are in use. These entries appear as normal vCPU, memory, GPU, and local SSD resources.
  • The reserved resources that are not in use. These entries have normal SKU names and reservation resource URIs.
  • Total reserved resources. These entries have reservation SKU names and reservation resource URIs. There are no costs associated with these entries. Use these entries to calculate how much of your reservations you are using.
Measurement MeasurementId format Resource URI format
Reserved resources that are in use com.google.cloud/services/compute-engine/SKU_NAME https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/RESOURCE_TYPE/RESOURCE_NAME.

For example, https://compute.googleapis.com/compute/v1/projects/my-project/zones/us-central1-a/instances/my-instance
Reserved resources that are not in use com.google.cloud/services/compute-engine/SKU_NAME https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations/RESERVATION_NAME.

For example, https://compute.googleapis.com/compute/v1/projects/my-project/zones/europe-west1-b/reservations/my-reservation
Total reserved resources com.google.cloud/services/compute-engine/ReservationSKU_NAME https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations/RESERVATION_NAME.

For example, https://compute.googleapis.com/compute/v1/projects/my-project/zones/europe-west1-b/reservations/my-reservation

For example, in the following snippet from a usage report for a reservation named my-reservation:

  • Row 1 shows reserved RAM that is currently in use. The row's ResourceId shows that this RAM is used by a VM named my-instance.
  • Row 2 shows reserved RAM that is not in use. The row's ResourceId shows that this reserved RAM is held by my-reservation; it is not yet used by any VM.
  • Row 3 shows the reservation's total reserved RAM.
Report Date,MeasurementId,Quantity,Unit,Resource URI,ResourceId,Location
2019-06-06,com.google.cloud/services/compute-engine/VmimageN2StandardRam,166970074857472,byte-seconds,https://compute.googleapis.com/compute/v1/projects/my-project/zones/us-central2-a/instances/my-instance,1775485842510981624,us-central2-a
2019-06-06,com.google.cloud/services/compute-engine/VmimageN2StandardRam,166970074857472,byte-seconds,https://compute.googleapis.com/compute/v1/projects/my-project/zones/us-central2-a/reservations/my-reservation,7.58809E+17,us-central2-a
2019-06-06,com.google.cloud/services/compute-engine/ReservationN2StandardRam,333940149714944,byte-seconds,https://compute.googleapis.com/compute/v1/projects/my-project/zones/us-central2-a/reservations/my-reservation,7.58809E+17,us-central2-a
...

Troubleshoot

Learn how to troubleshoot issues with reservation consumption.

What's next