Consume reservations

This document explains how to consume reservations in Compute Engine. To learnhow to consume reservations in other Google Cloud products, see the followingdocumentation:

After you create a reservation, or Compute Engine automatically createsa reservation for you to fulfill a future reservation, Compute Engineholds your reserved resources for you. You can then use those reserved resourcesto create Compute Engine instances that match the reservation'sproperties. This action is known asconsuming a reservation. You can use yourreserved capacity for creating instances until the reservation isfully consumed.

Limitations

You can't consume a reservation to create the following Compute Engineresources:

  • Flex-start VMs

  • Spot VMs or preemptible instances

  • Sole-tenant nodes

Before you begin

Required roles

To get the permissions that you need to consume reservations, ask your administrator to grant you the following IAM roles:

For more information about granting roles, seeManage access to projects, folders, and organizations.

These predefined roles contain the permissions required to consume reservations. To see the exact permissions that are required, expand theRequired permissions section:

Required permissions

The following permissions are required to consume reservations:

  • To create reservations:compute.reservations.create on the project
  • To create instances:
    • 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 alegacy 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 withcustom roles or otherpredefined roles.

Consume a reservation

The examples in the following sections show how to consume a reservation bycreating a single compute instance. You can also consume reservations bycreating instances that match the reservations' properties using a differentdeployment option, or byupdating the properties of existing instances to match automatically consumedreservations.

To consume a reservation, use one of the following methods:

Consume an automatically consumed reservation

Automatically consumed reservations allow any compute instances that match thereservation's properties to automatically consume it. This consumption behaviorapplies to both new and existing, running instances. When you createreservations, or Compute Engine automatically creates a reservation tofulfill a future reservation, this reservation type is the default setting.

If the properties of a single-project, automatic reservation and a shared,automatic reservation match, then the instances in your project consume thesingle-project reservation first, and then they consume the shared reservation.For more information, see theconsumption order for reservations.

To create and consume an example automatic reservation, select one of thefollowing options:

Console

The following example shows how to create an automatic reservation in zoneus-central1-a for three N2 instances with 32 vCPUs, and Intel Cascade Lakeas the minimum CPU platform. It also shows how to create a single instanceto consume the reservation.

To create the example automatic reservation and consume it, do thefollowing:

  1. To create an example reservation, complete the following steps:

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

      Go to Reservations

      The remaining steps automatically appear in theGoogle Cloud console.

    2. On theOn-demand reservation tab (default), clickCreate reservation.TheCreate a reservation page appears.

    3. In theName field, enter a name for the reservation. Forexample, enterreservation-01.

    4. Select theRegion andZone where to reserve resources. Forexample, selectus-central1 andus-central1-a respectively.

    5. In theShare type section, do one of the following:

      • To create a single-project reservation, selectLocal.

      • To create a shared reservation, selectShared, and thenspecify the projects that you want to share the reservationwith.

    6. In theUse with VM instance section, selectUse reservation automatically, if it isn't already selected.

    7. In theNumber of VM instances field, enter3.

    8. On theGeneral purpose tab, selectN2.

    9. In theMachine type section, on thePreset tab (default),selectn2-standard-32.

    10. ExpandCPU platform and GPU, and then, in theCPU platformfield, selectIntel Cascade Lake or later.

    11. ClickCreate.

  2. To create an instance that consumes the example reservation, completethe following steps:

    1. In the Google Cloud console, go to theCreate an instancepage.

      Go to Create an instance

      TheCreate an instance page appears and displays theMachine configuration pane.

    2. In the Machine configuration pane, do the following:

      1. In theName field, enter a name for the instance. For thisexample, enterinstance-01.

      2. Specify theRegion andZone where to reserve resources.For this example, selectus-central1 andus-central1-arespectively.

      3. On theGeneral purpose tab, selectN2.

      4. In theMachine type section, on thePreset tab (default),selectn2-standard-32.

      5. Expand theAdvanced options section, and then,in theCPU platform field, selectIntel Cascade Lake or later.

    3. Optional: Automatically consuming a matching reservation is thedefault setting. However, if you want to specify this setting, dothe following:

      1. In the navigation menu, clickAdvanced. TheAdvancedpane appears.

      2. In theReservations section, selectUse automatic selection.

    4. ClickCreate.

gcloud

The following example shows how to create an automatic reservation in zoneus-central1-a for three N2 instances with 32 vCPUs, and Intel Cascade Lakeas the minimum CPU platform. It also shows how to create a single instanceto consume the reservation.

To create the example automatic reservation and consume it, do thefollowing:

  1. To create the example reservation, use thegcloud compute reservations create command:

    gcloud compute reservations create reservation-01 \    --machine-type=n2-standard-32 \    --min-cpu-platform="Intel Cascade Lake" \    --vm-count=3 \    --zone=us-central1-a
  2. To create an instance that consumes the example reservation, use thegcloud compute instances create commandwith the--reservation-affinity flag set toany. Becauseany isthe default configuration, you can also omit this flag.

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

Go

To create the example automatic reservation using an instance template, andcreate an instance to consume the reservation using the same template, usethe following code sample:

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 reservationfuncconsumeAnyReservation(wio.Writer,projectID,zone,instanceName,sourceTemplatestring)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/instanceTemplatectx:=context.Background()instancesClient,err:=compute.NewInstancesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewInstancesRESTClient: %w",err)}deferinstancesClient.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 consumedReservationAffinity:&computepb.ReservationAffinity{ConsumeReservationType:proto.String("ANY_RESERVATION"),},},}op,err:=instancesClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create instance: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance created from reservation\n")returnnil}

Java

The following example shows how to create an N1 instance with four vCPUs,and Intel Skylake as the minimum CPU platform in zoneus-central1-a. Theinstance automatically consumes a matching reservation.

To create the example instance, use the following code sample:

import staticcom.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.ANY_RESERVATION;importcom.google.api.gax.longrunning.OperationFuture;importcom.google.cloud.compute.v1.AttachedDisk;importcom.google.cloud.compute.v1.AttachedDiskInitializeParams;importcom.google.cloud.compute.v1.InsertInstanceRequest;importcom.google.cloud.compute.v1.Instance;importcom.google.cloud.compute.v1.InstancesClient;importcom.google.cloud.compute.v1.NetworkInterface;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.ReservationAffinity;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassConsumeAnyMatchingReservation{publicstaticvoidmain(String[]args)throwsIOException,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.StringprojectId="YOUR_PROJECT_ID";// Zone where the VM instance will be created.Stringzone="us-central1-a";// Name of the VM instance you want to query.StringinstanceName="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-typesStringmachineTypeName="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/imagesStringsourceImage="projects/debian-cloud/global/images/family/debian-11";// diskSizeGb: storage size of the boot disk to attach to the instance.longdiskSizeGb=10L;// networkName: network interface to associate with the instance.StringnetworkName="default";// Minimum CPU platform of the instances.StringminCpuPlatform="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.publicstaticInstancecreateInstanceAsync(StringprojectId,Stringzone,StringinstanceName,StringmachineTypeName,StringsourceImage,longdiskSizeGb,StringnetworkName,StringminCpuPlatform)throwsIOException,InterruptedException,ExecutionException,TimeoutException{StringmachineType=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(InstancesClientinstancesClient=InstancesClient.create()){AttachedDiskdisk=AttachedDisk.newBuilder().setBoot(true).setAutoDelete(true).setType(AttachedDisk.Type.PERSISTENT.toString()).setDeviceName("disk-1").setInitializeParams(AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskSizeGb(diskSizeGb).build()).build();NetworkInterfacenetworkInterface=NetworkInterface.newBuilder().setName(networkName).build();ReservationAffinityreservationAffinity=ReservationAffinity.newBuilder().setConsumeReservationType(ANY_RESERVATION.toString()).build();InstanceinstanceResource=Instance.newBuilder().setName(instanceName).setMachineType(machineType).addDisks(disk).addNetworkInterfaces(networkInterface).setMinCpuPlatform(minCpuPlatform).setReservationAffinity(reservationAffinity).build();InsertInstanceRequestinsertInstanceRequest=InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instanceResource).build();OperationFuture<Operation,Operation>operation=instancesClient.insertAsync(insertInstanceRequest);Operationresponse=operation.get(3,TimeUnit.MINUTES);if(response.hasError()){returnnull;}returninstancesClient.get(projectId,zone,instanceName);}}}

Node.js

The following example shows how to create an N1 instance with four vCPUs,and Intel Skylake as the minimum CPU platform in zoneus-central1-a. Theinstance automatically consumes a matching reservation.

To create the example instance, use the following code sample:

// Import the Compute libraryconstcomputeLib=require('@google-cloud/compute');constcompute=computeLib.protos.google.cloud.compute.v1;// Instantiate a reservationsClientconstinstancesClient=newcomputeLib.InstancesClient();// Instantiate a zoneOperationsClientconstzoneOperationsClient=newcomputeLib.ZoneOperationsClient();/** * TODO(developer): Update/uncomment these variables before running the sample. */// The ID of the project where you want to create instance.constprojectId=awaitinstancesClient.getProjectId();// The zone in which to create instance.constzone='us-central1-a';// The name of the instance to create.// const instanceName = 'instance-01';// Machine type to use for VM.constmachineType='n1-standard-4';// Create instance to consume reservation if their properties match the VM propertiesasyncfunctioncallCreateInstanceToConsumeAnyReservation(){// Describe the size and source image of the boot disk to attach to the instance.constdisk=newcompute.Disk({boot:true,autoDelete:true,type:'PERSISTENT',initializeParams:{diskSizeGb:'10',sourceImage:'projects/debian-cloud/global/images/family/debian-12',},});//  Define networkInterfaceconstnetworkInterface=newcompute.NetworkInterface({name:'global/networks/default',});// Define reservationAffinityconstreservationAffinity=newcompute.ReservationAffinity({consumeReservationType:'ANY_RESERVATION',});// Create an instanceconstinstance=newcompute.Instance({name:instanceName,machineType:`zones/${zone}/machineTypes/${machineType}`,minCpuPlatform:'Intel Skylake',disks:[disk],networkInterfaces:[networkInterface],reservationAffinity,});const[response]=awaitinstancesClient.insert({project:projectId,instanceResource:instance,zone,});letoperation=response.latestResponse;// Wait for the create instance operation to complete.while(operation.status!=='DONE'){[operation]=awaitzoneOperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log(`Instance${instanceName} created.`);}awaitcallCreateInstanceToConsumeAnyReservation();

Python

The following example shows how to create an automatic reservation in zoneus-central1-a for three N1 instances with one vCPU, and Intel Ivy as theminimum CPU platform. It also shows how to create a single instance toconsume the reservation.

To create the example automatic reservation and consume it, do thefollowing:

from__future__importannotationsimportsysfromtypingimportAnyfromgoogle.api_core.extended_operationimportExtendedOperationfromgoogle.cloudimportcompute_v1defwait_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)ifoperation.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)raiseoperation.exception()orRuntimeError(operation.error_message)ifoperation.warnings:print(f"Warnings during{verbose_name}:\n",file=sys.stderr,flush=True)forwarninginoperation.warnings:print(f" -{warning.code}:{warning.message}",file=sys.stderr,flush=True)returnresultdefconsume_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 clientclient=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_nameinstance.machine_type=f"zones/{zone}/machineTypes/{machine_type}"instance.min_cpu_platform=min_cpu_platforminstance.zone=zone# Set the reservation affinity to target any matching reservationinstance.reservation_affinity=compute_v1.ReservationAffinity(consume_reservation_type="ANY_RESERVATION",# Type of reservation to consume)# Define the disks for the instanceinstance.disks=[compute_v1.AttachedDisk(boot=True,# Indicates that this is a boot diskauto_delete=True,# The disk will be deleted when the instance is deletedinitialize_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 useaccess_configs=[compute_v1.AccessConfig(name="External NAT",# Name of the access configurationtype="ONE_TO_ONE_NAT",# Type of access configuration)],)]# Create a request to insert the instancerequest=compute_v1.InsertInstanceRequest()request.zone=zonerequest.project=project_idrequest.instance_resource=instancevm_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.")returnvm_client.get(project=project_id,zone=zone,instance=instance_name)

REST

The following example shows how to create an automatic reservation in zoneus-central1-a for three N2 instances with 32 vCPUs, and Intel Cascade Lakeas the minimum CPU platform. It also shows how to create a single instanceto consume the reservation.

To create the example automatic reservation and consume it, do thefollowing:

  1. To create the example reservation, make aPOST request toreservations.insert method:

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations{  "name": "reservation-01",  "specificReservation": {    "count": "3",    "instanceProperties": {      "machineType": "n2-standard-32",      "minCpuPlatform": "Intel Cascade Lake",    }  }}
  2. To create an instance that consumes the example reservation, make aPOST request to theinstances.insert method.In the request body, include theconsumeReservationType field set toANY_RESERVATION. However, becauseANY_RESERVATION is the defaultconfiguration, you can also omit the field.

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

Consume a specifically targeted reservation

Specifically targeted reservations allow new compute instances that match thereservation's properties and target the reservation to consume it. Instances aresuccessfully created only if their properties match the reservation properties.Otherwise, you encounter errors.

Based on the creation method that you want to use, create specific reservationsand instances that target them as follows:

Creation methodWhen you create a reservationWhen you create instances to consume the reservation
Google Cloud consoleIn theUse with VM instance section, selectSelect specific reservation.In theAdvanced pane, in theReservations section, selectChoose a reservation. Then, follow the prompts to select a reservation.
Google Cloud CLIInclude the--require-specific-reservation flag.Include the following flags:
  • The--reservation-affinity flag set tospecific.
  • The--reservation flag set to the resource path to the reservation, formatted asprojects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
GoInclude theSpecificReservationRequired field set totrue.In theReservationAffinity field, include the following fields:
  • TheConsumeReservationType field set toSPECIFIC_RESERVATION.
  • TheKey field set tocompute.googleapis.com/reservation-name.
  • TheValues field set to the resource path to the reservation, formatted asprojects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
JavaInclude thesetSpecificReservationRequired field set totrue.In theReservationAffinity field, include the following fields:
  • ThesetConsumeReservationType field set toSPECIFIC_RESERVATION.
  • ThesetKey field set tocompute.googleapis.com/reservation-name.
  • TheaddValues field set to the resource path to the reservation, formatted asprojects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
Node.js and REST APIInclude thespecificReservationRequired field set totrue.In thereservationAffinity field, include the following fields:
  • TheconsumeReservationType field set toSPECIFIC_RESERVATION.
  • Thekey field set tocompute.googleapis.com/reservation-name.
  • Thevalues field set to a list that contains a single item with the resource path to the reservation, formatted asprojects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
PythonInclude thespecific_reservation_required field set totrue.In thereservation_affinity field, include the following fields:
  • Theconsume_reservation_type field set toSPECIFIC_RESERVATION.
  • Thekey field set tocompute.googleapis.com/reservation-name.
  • Thevalues field set to the resource path to the reservation, formatted asprojects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
TerraformInclude thespecific_reservation_required field set totrue.In thereservation_affinity field, include the following fields:
  • Thetype field set toSPECIFIC_RESERVATION.
  • Thespecific_reservation field, which includes the following fields:
    • Thekey field set tocompute.googleapis.com/reservation-name.
    • Thevalues field set to a list that contains a single item with the resource path to the reservation, formatted asprojects/OWNER_PROJECT_ID/reservations/RESERVATION_NAME.
Note: To enable a regional managed instance group (MIG) to consume specificreservations in multiple zones, create reservations with matching names andproperties in each zone. Then, target the reservations in the group's instancetemplate.

To create an example specific reservation and an instance to consume it, selectone of the following options:

Console

The following example shows how to create a specific reservation in zoneus-central1-a for three N2 instances with 32 vCPUs, and Intel Cascade Lakeas the minimum CPU platform. It also shows how to create a single instanceto consume the reservation.

To create the example specific reservation and consume it, do the following:

  1. To create an example reservation, complete the following steps:

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

      Go to Reservations

      The remaining steps automatically appear in theGoogle Cloud console.

    2. On theOn-demand reservation tab (default), clickCreate reservation.TheCreate a reservation page appears.

    3. In theName field, enter a name for the reservation. Forexample, enterreservation-02.

    4. Specify theRegion andZone where to reserve resources. Forthis example, selectus-central1 andus-central1-arespectively.

    5. In theShare type section, do one of the following:

      • To create a single-project reservation, selectLocal.

      • To create a shared reservation, selectShared, and thenspecify the projects that you want to share the reservationwith.

    6. In theUse with VM instance section, selectSelect specific reservation.

    7. In theNumber of VM instances field, enter3.

    8. On theGeneral purpose tab, selectN2.

    9. In theMachine type section, on thePreset tab (default),selectn2-standard-32.

    10. ExpandCPU platform and GPU, and then, in theCPU platformfield, selectIntel Cascade Lake or later.

    11. ClickCreate.

  2. To create an instance that consumes the example reservation, completethe following steps:

    1. In the Google Cloud console, go to theCreate an instancepage.

      Go to Create an instance

      TheCreate an instance page appears and displays theMachine configuration pane.

    2. In the Machine configuration pane, do the following:

      1. In theName field, enter a name for the instance. For thisexample, enterinstance-02.

      2. Specify theRegion andZone where to reserve resources. Forthis example, selectus-central1 andus-central1-arespectively.

      3. On theGeneral purpose tab, selectN2.

      4. In theMachine type section, on thePreset tab (default),selectn2-standard-32.

      5. Expand theAdvanced options section, and then,in theCPU platform field, selectIntel Cascade Lake or later.

    3. In the navigation menu, clickAdvanced. TheAdvanced paneappears.

    4. In theReservations section, selectChoose a reservation,and then clickChoose reservation.

    5. On theChoose a reservation pane that appears, do the following:

      1. Select the specific reservation that you created in the previoussteps. If you want to consume a shared reservation that existsin a different project, then, in theProject list, selectthe project in which the reservation exists.

      2. ClickChoose.

    6. ClickCreate.

gcloud

The following example shows how to create a specific reservation in zoneus-central1-a for three N2 instances with 32 vCPUs, and Intel Cascade Lakeas the minimum CPU platform. It also shows how to create a single instanceto consume the reservation.

To create the example specific reservation and consume it, do the following:

  1. To create the example reservation, use thegcloud compute reservations create commandwith the--require-specific-reservation flag:

    gcloud compute reservations create reservation-02 \    --machine-type=n2-standard-32 \    --min-cpu-platform="Intel Cascade Lake" \--require-specific-reservation \    --vm-count=3 \    --zone=us-central1-a
  2. To create an instance that consumes the example reservation, use thegcloud compute instances create commandwith the--reservation and--reservation-affinity=specific flags:

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

    ReplaceRESERVATION_URL with the URL of thereservation. Specify one of the following values:

    • If you created the reservation in the same project:reservation-02

    • If the reservation is in a different project:projects/PROJECT_ID/reservations/reservation-02

Go

The following examples show how to create an N2 instance with 32 vCPUs, andIntel Cascade Lake as the minimum CPU platform, in zoneus-central1-a toconsume a specific, matching reservation:

  • To create the example instance to consume a single-project, specificreservation, use the following code sample:

    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: truefuncconsumeSpecificReservation(wio.Writer,projectID,zone,instanceName,reservationNamestring)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)iferr!=nil{returnfmt.Errorf("NewInstancesRESTClient: %w",err)}deferinstancesClient.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 consumedReservationAffinity:&computepb.ReservationAffinity{ConsumeReservationType:proto.String("SPECIFIC_RESERVATION"),Key:proto.String("compute.googleapis.com/reservation-name"),Values:[]string{reservationName},},},}op,err:=instancesClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create instance: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance created from reservation\n")returnnil}
  • To create the example instance to consume a shared, specificreservation, use the following code sample:

    import("context""fmt""io"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/protobuf/proto")// consumeSpecificSharedReservation consumes specific shared reservation in particular zonefuncconsumeSpecificSharedReservation(wio.Writer,clientInstanceClientInterface,projectID,baseProjectId,zone,instanceName,reservationNamestring)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 consumedReservationAffinity:&computepb.ReservationAffinity{ConsumeReservationType:proto.String("SPECIFIC_RESERVATION"),Key:proto.String("compute.googleapis.com/reservation-name"),Values:[]string{sharedReservation},},},}op,err:=client.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create instance: %w",err)}ifop!=nil{iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}}fmt.Fprintf(w,"Instance created from shared reservation\n")returnnil}

Java

The following examples show how to create an N1 instance with four vCPUs,and Intel Skylake as the minimum CPU platform, in zoneus-central1-a toconsume a specific, matching reservation:

  • To create an example reservation as a single-project reservation, andcreate an instance to consume it, use the following code sample:

    import staticcom.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.SPECIFIC_RESERVATION;importcom.google.api.gax.longrunning.OperationFuture;importcom.google.cloud.compute.v1.AttachedDisk;importcom.google.cloud.compute.v1.AttachedDiskInitializeParams;importcom.google.cloud.compute.v1.InsertInstanceRequest;importcom.google.cloud.compute.v1.Instance;importcom.google.cloud.compute.v1.InstancesClient;importcom.google.cloud.compute.v1.NetworkInterface;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.ReservationAffinity;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassConsumeSingleProjectReservation{publicstaticvoidmain(String[]args)throwsIOException,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.StringprojectId="YOUR_PROJECT_ID";// Name of the zone where the reservation is located.Stringzone="us-central1-a";// Name of the reservation you want to query.StringreservationName="YOUR_RESERVATION_NAME";// Name of the VM instance you want to query.StringinstanceName="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-typesStringmachineTypeName="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/imagesStringsourceImage="projects/debian-cloud/global/images/family/debian-11";// diskSizeGb: storage size of the boot disk to attach to the instance.longdiskSizeGb=10L;// networkName: network interface to associate with the instance.StringnetworkName="default";// Minimum CPU platform of the instances.StringminCpuPlatform="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.publicstaticInstancecreateInstanceAsync(StringprojectId,Stringzone,StringinstanceName,StringreservationName,StringmachineTypeName,StringsourceImage,longdiskSizeGb,StringnetworkName,StringminCpuPlatform)throwsIOException,InterruptedException,ExecutionException,TimeoutException{StringmachineType=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(InstancesClientinstancesClient=InstancesClient.create()){AttachedDiskdisk=AttachedDisk.newBuilder().setBoot(true).setAutoDelete(true).setType(AttachedDisk.Type.PERSISTENT.toString()).setDeviceName("disk-1").setInitializeParams(AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskSizeGb(diskSizeGb).build()).build();NetworkInterfacenetworkInterface=NetworkInterface.newBuilder().setName(networkName).build();ReservationAffinityreservationAffinity=ReservationAffinity.newBuilder().setConsumeReservationType(SPECIFIC_RESERVATION.toString()).setKey("compute.googleapis.com/reservation-name")// Set specific reservation.addValues(reservationName).build();InstanceinstanceResource=Instance.newBuilder().setName(instanceName).setMachineType(machineType).addDisks(disk).addNetworkInterfaces(networkInterface).setMinCpuPlatform(minCpuPlatform).setReservationAffinity(reservationAffinity).build();InsertInstanceRequestinsertInstanceRequest=InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instanceResource).build();OperationFuture<Operation,Operation>operation=instancesClient.insertAsync(insertInstanceRequest);Operationresponse=operation.get(3,TimeUnit.MINUTES);if(response.hasError()){returnnull;}returninstancesClient.get(projectId,zone,instanceName);}}}
  • To create an example reservation as a shared reservation, and createan instance to consume it, use the following code sample:

    import staticcom.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.SPECIFIC_RESERVATION;importcom.google.api.gax.longrunning.OperationFuture;importcom.google.cloud.compute.v1.AttachedDisk;importcom.google.cloud.compute.v1.AttachedDiskInitializeParams;importcom.google.cloud.compute.v1.InsertInstanceRequest;importcom.google.cloud.compute.v1.Instance;importcom.google.cloud.compute.v1.InstancesClient;importcom.google.cloud.compute.v1.NetworkInterface;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.ReservationAffinity;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassConsumeSpecificSharedReservation{publicstaticvoidmain(String[]args)throwsIOException,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.StringprojectId="YOUR_PROJECT_ID";// Name of the zone the reservation is located.Stringzone="us-central1-a";// Name of the reservation you want to query.StringreservationName="YOUR_RESERVATION_NAME";// Name of the VM instance you want to query.StringinstanceName="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-typesStringmachineTypeName="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/imagesStringsourceImage="projects/debian-cloud/global/images/family/debian-11";// diskSizeGb: storage size of the boot disk to attach to the instance.longdiskSizeGb=10L;// networkName: network interface to associate with the instance.StringnetworkName="default";// Minimum CPU platform of the instances.StringminCpuPlatform="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.publicstaticInstancecreateInstanceAsync(StringprojectId,Stringzone,StringinstanceName,StringreservationName,StringmachineTypeName,StringsourceImage,longdiskSizeGb,StringnetworkName,StringminCpuPlatform)throwsIOException,InterruptedException,ExecutionException,TimeoutException{StringmachineType=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.StringreservationPath=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(InstancesClientinstancesClient=InstancesClient.create()){AttachedDiskdisk=AttachedDisk.newBuilder().setBoot(true).setAutoDelete(true).setType(AttachedDisk.Type.PERSISTENT.toString()).setDeviceName("disk-1").setInitializeParams(AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskSizeGb(diskSizeGb).build()).build();NetworkInterfacenetworkInterface=NetworkInterface.newBuilder().setName(networkName).build();ReservationAffinityreservationAffinity=ReservationAffinity.newBuilder().setConsumeReservationType(SPECIFIC_RESERVATION.toString()).setKey("compute.googleapis.com/reservation-name")// Set specific reservation.addValues(reservationPath).build();InstanceinstanceResource=Instance.newBuilder().setName(instanceName).setMachineType(machineType).addDisks(disk).addNetworkInterfaces(networkInterface).setMinCpuPlatform(minCpuPlatform).setReservationAffinity(reservationAffinity).build();InsertInstanceRequestinsertInstanceRequest=InsertInstanceRequest.newBuilder().setProject(projectId).setZone(zone).setInstanceResource(instanceResource).build();OperationFuture<Operation,Operation>operation=instancesClient.insertAsync(insertInstanceRequest);Operationresponse=operation.get(3,TimeUnit.MINUTES);if(response.hasError()){returnnull;}returninstancesClient.get(projectId,zone,instanceName);}}}

Node.js

The following examples show how to create an N1 instance with 4 vCPUs, andIntel Skylake as the minimum CPU platform, in zoneus-central1-a toconsume a specific, matching reservation:

// Import the Compute libraryconstcomputeLib=require('@google-cloud/compute');constcompute=computeLib.protos.google.cloud.compute.v1;// Instantiate a reservationsClientconstinstancesClient=newcomputeLib.InstancesClient();// Instantiate a zoneOperationsClientconstzoneOperationsClient=newcomputeLib.ZoneOperationsClient();/** * TODO(developer): Update/uncomment these variables before running the sample. */// The ID of the project where you want to create instance.constprojectId=awaitinstancesClient.getProjectId();// The zone in which to create instance.constzone='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.constmachineType='n1-standard-4';// Create instance to consume a specific single-project reservationasyncfunctioncallCreateInstanceToConsumeSingleProjectReservation(){// 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 sizeconstdisk=newcompute.Disk({boot:true,autoDelete:true,type:'PERSISTENT',initializeParams:{diskSizeGb:'10',sourceImage:'projects/debian-cloud/global/images/family/debian-12',},});//  Define networkInterfaceconstnetworkInterface=newcompute.NetworkInterface({name:'global/networks/default',});// Define reservationAffinityconstreservationAffinity=newcompute.ReservationAffinity({consumeReservationType:'SPECIFIC_RESERVATION',key:'compute.googleapis.com/reservation-name',values:[reservationName],});// Create an instanceconstinstance=newcompute.Instance({name:instanceName,machineType:`zones/${zone}/machineTypes/${machineType}`,minCpuPlatform:'Intel Skylake',disks:[disk],networkInterfaces:[networkInterface],reservationAffinity,});const[response]=awaitinstancesClient.insert({project:projectId,instanceResource:instance,zone,});letoperation=response.latestResponse;// Wait for the create instance operation to complete.while(operation.status!=='DONE'){[operation]=awaitzoneOperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log(`Instance${instanceName} created.`);}awaitcallCreateInstanceToConsumeSingleProjectReservation();

Python

The following examples show how to create an N2 instance with 32 vCPUs, andIntel Cascade Lake as the minimum CPU platform, in zoneus-central1-a toconsume a specific, matching reservation:

To create the example specific reservation and consume it, do the following:

  • To create and consume the example reservation as a single-projectreservation, use the following code sample:

    from__future__importannotationsimportsysfromtypingimportAnyfromgoogle.api_core.extended_operationimportExtendedOperationfromgoogle.cloudimportcompute_v1defwait_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)ifoperation.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)raiseoperation.exception()orRuntimeError(operation.error_message)ifoperation.warnings:print(f"Warnings during{verbose_name}:\n",file=sys.stderr,flush=True)forwarninginoperation.warnings:print(f" -{warning.code}:{warning.message}",file=sys.stderr,flush=True)returnresultdefconsume_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 reservationspecific_reservation_required=True,)# Create a reservation clientclient=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_nameinstance.machine_type=f"zones/{zone}/machineTypes/{machine_type}"instance.min_cpu_platform=min_cpu_platforminstance.zone=zone# Set the reservation affinity to target the specific reservationinstance.reservation_affinity=compute_v1.ReservationAffinity(consume_reservation_type="SPECIFIC_RESERVATION",# Type of reservation to consumekey="compute.googleapis.com/reservation-name",# Key for the reservationvalues=[reservation_name],# Reservation name to consume)# Define the disks for the instanceinstance.disks=[compute_v1.AttachedDisk(boot=True,# Indicates that this is a boot diskauto_delete=True,# The disk will be deleted when the instance is deletedinitialize_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 useaccess_configs=[compute_v1.AccessConfig(name="External NAT",# Name of the access configurationtype="ONE_TO_ONE_NAT",# Type of access configuration)],)]# Create a request to insert the instancerequest=compute_v1.InsertInstanceRequest()request.zone=zonerequest.project=project_idrequest.instance_resource=instancevm_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.")returnvm_client.get(project=project_id,zone=zone,instance=instance_name)
  • To create and consume the example reservation as a shared reservation,use the following code sample:

    from__future__importannotationsimportsysfromtypingimportAnyfromgoogle.api_core.extended_operationimportExtendedOperationfromgoogle.cloudimportcompute_v1defwait_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)ifoperation.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)raiseoperation.exception()orRuntimeError(operation.error_message)ifoperation.warnings:print(f"Warnings during{verbose_name}:\n",file=sys.stderr,flush=True)forwarninginoperation.warnings:print(f" -{warning.code}:{warning.message}",file=sys.stderr,flush=True)returnresultdefconsume_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 reservationspecific_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 clientclient=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_nameinstance.machine_type=f"zones/{zone}/machineTypes/{machine_type}"instance.min_cpu_platform=min_cpu_platforminstance.zone=zone# Set the reservation affinity to target the specific reservationinstance.reservation_affinity=compute_v1.ReservationAffinity(consume_reservation_type="SPECIFIC_RESERVATION",# Type of reservation to consumekey="compute.googleapis.com/reservation-name",# To consume this reservation from any consumer projects, specify the owner project of the reservationvalues=[f"projects/{owner_project_id}/reservations/{reservation_name}"],)# Define the disks for the instanceinstance.disks=[compute_v1.AttachedDisk(boot=True,# Indicates that this is a boot diskauto_delete=True,# The disk will be deleted when the instance is deletedinitialize_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 useaccess_configs=[compute_v1.AccessConfig(name="External NAT",# Name of the access configurationtype="ONE_TO_ONE_NAT",# Type of access configuration)],)]# Create a request to insert the instancerequest=compute_v1.InsertInstanceRequest()request.zone=zone# The instance will be created in the shared projectrequest.project=shared_project_idrequest.instance_resource=instancevm_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.returnvm_client.get(project=shared_project_id,zone=zone,instance=instance_name)

REST

The following example shows how to create a specific reservation in zoneus-central1-a for three N2 instances with 32 vCPUs, and Intel Cascade Lakeas the minimum CPU platform. It also shows how to create a single instanceto consume the reservation.

To create the example specific reservation and consume it, do the following:

  1. To create the example reservation, make aPOST request to theinstances.insert method.In the request body, include thespecificReservationRequired field settotrue:

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations{  "name": "reservation-02",  "specificReservation": {    "count": "3",    "instanceProperties": {      "machineType": "n2-standard-32",      "minCpuPlatform": "Intel Cascade Lake",    }  },"specificReservationRequired": true}
  2. To create an instance that consumes the example reservation, make aPOST request to theinstances.insert method.In the request body, in thereservationAffinity field, include thefollowing:

    • TheconsumeReservationType field set toSPECIFIC_RESERVATION.

    • Thekey field set tocompute.googleapis.com/reservation-name.

    • Thevalues field set to the URL of the reservation.

    The request is similar to the following:

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

    ReplaceRESERVATION_URL with the URL of thereservation. Specify one of the following values:

    • If you created the reservation in the same project:reservation-02

    • If the reservation is in a different project:projects/PROJECT_ID/reservations/reservation-02

Consume an auto-created reservation for a request in calendar mode

This reservation type allows new compute instances to consume a reservation thatCompute Engine automatically creates (auto-creates) to fulfill afuture reservation in calendar mode.

To consume this type of reservation, you must create an instance as follows:

The following example creates a future reservation request in calendar mode forA3 Ultra instances. The example also shows the fields to specify when you createa standalone A3 Ultra instance to consume the auto-created reservation for therequest.

To consume the example auto-created reservation, select one of the followingoptions:

Console

  1. Create an example request for five A3 Ultra instances and submit it forreview:

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

      Go to Reservations

    2. Click theFuture reservations tab.

    3. ClickCreate future reservation. TheCreate a future reservationpage appears.

    4. Click theGPUs tab, and then, in theGPU type list, selectNVIDIA H200 141GB. This action specifies an A3 Ultra instance.

    5. In theTotal capacity needed field, enter5.

    6. In theReservation period section, specify the start time andduration for your reservation period.

    7. ClickSearch for capacity, and then, in theAvailable capacity section, select one of the availablemachines.

    8. ClickCreate.

  2. At the request start time, to create an A3 Ultra instance to consume theexample auto-created reservation, do the following:

    Important: The following steps show how to create a single-NIC A3 Ultrainstance, which is useful for quick tests. To create a multi-NIC A3Ultra instance, seeCreate an A3 Ultra or A4 instance.
    1. In the Google Cloud console, go to theCreate an instancepage.

      Go to Create an instance

    2. In theName field, enter a name for the instance. For thisexample, enterexample-instance.

    3. Specify theRegion andZone where the auto-createdreservation exists. For this example, selectus-central1 andus-central1-b respectively.

    4. Click theGPUs tab, and then, in theGPU type list, selectNVIDIA H200 141GB. This action specifies an A3 Ultra instanceand sets the provisioning model toReservation-bound.

    5. In the navigation menu, clickAdvanced.

    6. In theReservations section, selectChoose a reservation,and then clickChoose a reservation.

    7. On theChoose a reservation pane, do the following:

      1. Select the example auto-created reservation.

      2. ClickChoose.

    8. In theProvisioning model section, expand theVM provisioning model advanced settings section.

    9. In theOn VM termination list, selectStop (default) orDelete.

    10. ClickCreate.

gcloud

  1. To create an example request for five A3 Ultra VMs and submit it forreview, use thegcloud compute future-reservations create command:

    gcloud compute future-reservations create example-fr \    --auto-delete-auto-created-reservations \    --deployment-type=DENSE \    --planning-status=SUBMITTED \    --require-specific-reservation \    --reservation-mode=CALENDAR \    --reservation-name=example-reservation \    --share-setting=local \    --start-time=2026-03-05T00:00:00Z \    --end-time=2026-03-19T00:00:00Z \    --machine-type=a3-ultragpu-8g \    --total-count=5 \    --zone=us-central1-b

    Assume that Google Cloud approves the request andCompute Engine automatically creates an empty reservation. Atthe request start time, on March 5, 2026, Compute Engineincreases the number of reserved GPU VMs in the reservation. You canthen consume the reservation.

  2. At the request start time, to create an A3 Ultra instance to consume theexample auto-created reservation, use thegcloud compute instances create commandwith the following flags:

    • The--instance-termination-action flag.

    • The--provisioning-model flag set toRESERVATION_BOUND.

    • The--reservation flag.

    • The--reservation-affinity flag set tospecific.

    The command is similar to the following. For the full requirements tocreate an A3 Ultra instance, seeCreate an A3 Ultra or A4 instance.

    gcloud compute instance create example-a3ultra-instance  \    --machine-type=a3-ultragpu-8g \--instance-termination-action=TERMINATION_ACTION \--provisioning-model=RESERVATION_BOUND \--reservation-affinity=specific \--reservation=RESERVATION_URL \    --zone=us-central1-b \    ...

    The command includes the following values:

    • TERMINATION_ACTION: whetherCompute Engine stops (STOP) or deletes (DELETE) the VMat the end of the reservation period.

    • RESERVATION_URL: the URL of the reservation,which is formatted as follows:

      • If the auto-created reservation exists in your project:example-reservation.

      • If the auto-created reservation exists in a different project:projects/PROJECT_ID/reservations/example-reservation.

REST

  1. To create an example request for five A3 Ultra instances and submit itfor review, make aPOST request to thefutureReservations.insert method:

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-b/futureReservations{  "name": "example-request-calendar-mode",  "autoDeleteAutoCreatedReservations": true,  "deploymentType": "DENSE",  "planningStatus": "SUBMITTED",  "reservationMode": "CALENDAR",  "reservationName": "example-reservation",  "shareSettings": {    "shareType": "LOCAL"  },  "specificReservationRequired": true,  "specificSkuProperties": {    "machineType": "a3-ultragpu-8g",    "totalCount": 5  },  "timeWindow": {    "startTime": "2026-03-05T00:00:00Z",    "endTime": "2026-03-19T00:00:00Z"  }}

    Assume that Google Cloud approves the request andCompute Engine automatically creates an empty reservation. Atthe request start time, on March 5, 2026, Compute Engineincreases the number of reserved GPU VMs in the reservation. You canthen consume the reservation.

  2. At the request start time, to create an A3 Ultra instance to consume theexample auto-created reservation, make aPOST request toinstances.insert method.In the request body, include the following fields:

    • ThereservationAffinity.consumeReservationType field set toSPECIFIC_RESERVATION.

    • ThereservationAffinity.key field set tocompute.googleapis.com/reservation-name.

    • ThereservationAffinity.values field set to the URL of thereservation.

    • Thescheduling.instanceTerminationAction field.

    • Thescheduling.provisioningModel field set toRESERVATION_BOUND.

    The request is similar to the following. For the full requirements tocreate an A3 Ultra instance, seeCreate an A3 Ultra or A4 instance.

    POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-b/{  {    "machineType": "projects/example-project/zones/us-central1-b/machineTypes/a3-ultragpu-8g",    "name": "example-a3ultra-instance",    "reservationAffinity": {"consumeReservationType": "SPECIFIC_RESERVATION","key": "compute.googleapis.com/reservation-name","values":[        "RESERVATION_URL"      ],    },    "scheduling": {"instanceTerminationAction": "TERMINATION_ACTION","provisioningModel": "RESERVATION_BOUND"    },    ...  }}

    The request body includes the following values:

    • RESERVATION_URL: the URL of the reservation,which is formatted as follows:

      • If the auto-created reservation exists in your project:example-reservation.

      • If the auto-created reservation exists in a different project:projects/PROJECT_ID/reservations/example-reservation.

    • TERMINATION_ACTION: whetherCompute Engine stops (STOP) or deletes (DELETE) the VMat the end of the reservation period.

Test that instance properties match an automatically consumed reservation

To test if a compute instance's properties match an automatically consumedreservation, do the following:

  1. Create a copy of the reservation as a specifically targeted reservation fora single instance.

  2. Create a test instance to consume the reservation.

If you can create the test instance, then its properties match the properties ofthe test reservation. Otherwise, you encounter errors.

After you confirm that the properties of your test instance and test reservationmatch,delete the reservation andthetest instance.

Verify reservations consumption

To verify reservations consumption, use one of the following methods:

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-18 UTC.