Consume reservations Stay organized with collections Save and categorize content based on your preferences.
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
- If you haven't already, set upauthentication. Authentication verifies your identity 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
Install the Google Cloud CLI. After installation,initialize the Google Cloud CLI by running the following command:
gcloudinit
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.- 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.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
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.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
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.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
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.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
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.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.For more information, seeAuthenticate 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 following IAM roles:
- To consume a reservation:Compute Instance Admin (v1) (
roles/compute.instanceAdmin.v1) on the project - To consume a shared reservation from a consumer project:Compute Instance Admin (v1) (
roles/compute.instanceAdmin.v1) on the owner project and the consumer project
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.createon the project - To create instances:
compute.instances.createon the project- To use a custom image to create the VM:
compute.images.useReadOnlyon the image - To use a snapshot to create the VM:
compute.snapshots.useReadOnlyon the snapshot - To use an instance template to create the VM:
compute.instanceTemplates.useReadOnlyon the instance template - To assign alegacy network to the VM:
compute.networks.useon the project - To specify a static IP address for the VM:
compute.addresses.useon the project - To assign an external IP address to the VM when using a legacy network:
compute.networks.useExternalIpon the project - To specify a subnet for the VM:
compute.subnetworks.useon the project or on the chosen subnet - To assign an external IP address to the VM when using a VPC network:
compute.subnetworks.useExternalIpon the project or on the chosen subnet - To set VM instance metadata for the VM:
compute.instances.setMetadataon the project - To set tags for the VM:
compute.instances.setTagson the VM - To set labels for the VM:
compute.instances.setLabelson the VM - To set a service account for the VM to use:
compute.instances.setServiceAccounton the VM - To create a new disk for the VM:
compute.disks.createon the project - To attach an existing disk in read-only or read-write mode:
compute.disks.useon the disk - To attach an existing disk in read-only mode:
compute.disks.useReadOnlyon the disk
- To create instance templates:
compute.instanceTemplates.createon 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:
To create an instance that consumes an automatic reservation, regardless ofhow that reservation was created, seeConsume an automatically consumed reservation.
To create an instance that consumes a specific reservation that you created,seeConsume a specifically targeted reservation.
To create an instance to consume a specific reservation that wasautomatically created by Compute Engine (in this case, to fulfill afuture reservation in calendar mode), seeConsume an auto-created reservation for a request in calendar mode.
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:
To create an example reservation, complete the following steps:
In the Google Cloud console, go to theReservations page.
The remaining steps automatically appear in theGoogle Cloud console.
On theOn-demand reservation tab (default), clickCreate reservation.TheCreate a reservation page appears.
In theName field, enter a name for the reservation. Forexample, enter
reservation-01.Select theRegion andZone where to reserve resources. Forexample, selectus-central1 andus-central1-a respectively.
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.
In theUse with VM instance section, selectUse reservation automatically, if it isn't already selected.
In theNumber of VM instances field, enter
3.On theGeneral purpose tab, selectN2.
In theMachine type section, on thePreset tab (default),selectn2-standard-32.
ExpandCPU platform and GPU, and then, in theCPU platformfield, selectIntel Cascade Lake or later.
ClickCreate.
To create an instance that consumes the example reservation, completethe following steps:
In the Google Cloud console, go to theCreate an instancepage.
TheCreate an instance page appears and displays theMachine configuration pane.
In the Machine configuration pane, do the following:
In theName field, enter a name for the instance. For thisexample, enter
instance-01.Specify theRegion andZone where to reserve resources.For this example, selectus-central1 andus-central1-arespectively.
On theGeneral purpose tab, selectN2.
In theMachine type section, on thePreset tab (default),selectn2-standard-32.
Expand theAdvanced options section, and then,in theCPU platform field, selectIntel Cascade Lake or later.
Optional: Automatically consuming a matching reservation is thedefault setting. However, if you want to specify this setting, dothe following:
In the navigation menu, clickAdvanced. TheAdvancedpane appears.
In theReservations section, selectUse automatic selection.
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:
To create the example reservation, use the
gcloud compute reservations createcommand:gcloud compute reservations create reservation-01 \ --machine-type=n2-standard-32 \ --min-cpu-platform="Intel Cascade Lake" \ --vm-count=3 \ --zone=us-central1-aTo create an instance that consumes the example reservation, use the
gcloud compute instances createcommandwith the--reservation-affinityflag set toany. Becauseanyisthe 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:
To create the example reservation, make a
POSTrequest toreservations.insertmethod: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", } }}To create an instance that consumes the example reservation, make a
POSTrequest to theinstances.insertmethod.In the request body, include theconsumeReservationTypefield set toANY_RESERVATION. However, becauseANY_RESERVATIONis 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 method | When you create a reservation | When you create instances to consume the reservation |
|---|---|---|
| Google Cloud console | In 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 CLI | Include the--require-specific-reservation flag. | Include the following flags:
|
| Go | Include theSpecificReservationRequired field set totrue. | In theReservationAffinity field, include the following fields:
|
| Java | Include thesetSpecificReservationRequired field set totrue. | In theReservationAffinity field, include the following fields:
|
| Node.js and REST API | Include thespecificReservationRequired field set totrue. | In thereservationAffinity field, include the following fields:
|
| Python | Include thespecific_reservation_required field set totrue. | In thereservation_affinity field, include the following fields:
|
| Terraform | Include thespecific_reservation_required field set totrue. | In thereservation_affinity field, include the following fields:
|
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:
To create an example reservation, complete the following steps:
In the Google Cloud console, go to theReservations page.
The remaining steps automatically appear in theGoogle Cloud console.
On theOn-demand reservation tab (default), clickCreate reservation.TheCreate a reservation page appears.
In theName field, enter a name for the reservation. Forexample, enter
reservation-02.Specify theRegion andZone where to reserve resources. Forthis example, selectus-central1 andus-central1-arespectively.
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.
In theUse with VM instance section, selectSelect specific reservation.
In theNumber of VM instances field, enter
3.On theGeneral purpose tab, selectN2.
In theMachine type section, on thePreset tab (default),selectn2-standard-32.
ExpandCPU platform and GPU, and then, in theCPU platformfield, selectIntel Cascade Lake or later.
ClickCreate.
To create an instance that consumes the example reservation, completethe following steps:
In the Google Cloud console, go to theCreate an instancepage.
TheCreate an instance page appears and displays theMachine configuration pane.
In the Machine configuration pane, do the following:
In theName field, enter a name for the instance. For thisexample, enter
instance-02.Specify theRegion andZone where to reserve resources. Forthis example, selectus-central1 andus-central1-arespectively.
On theGeneral purpose tab, selectN2.
In theMachine type section, on thePreset tab (default),selectn2-standard-32.
Expand theAdvanced options section, and then,in theCPU platform field, selectIntel Cascade Lake or later.
In the navigation menu, clickAdvanced. TheAdvanced paneappears.
In theReservations section, selectChoose a reservation,and then clickChoose reservation.
On theChoose a reservation pane that appears, do the following:
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.
ClickChoose.
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:
To create the example reservation, use the
gcloud compute reservations createcommandwith the--require-specific-reservationflag: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-aTo create an instance that consumes the example reservation, use the
gcloud compute instances createcommandwith the--reservationand--reservation-affinity=specificflags: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-aReplace
RESERVATION_URLwith the URL of thereservation. Specify one of the following values:If you created the reservation in the same project:
reservation-02If 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:
To create the example reservation, make a
POSTrequest to theinstances.insertmethod.In the request body, include thespecificReservationRequiredfield 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}To create an instance that consumes the example reservation, make a
POSTrequest to theinstances.insertmethod.In the request body, in thereservationAffinityfield, include thefollowing:The
consumeReservationTypefield set toSPECIFIC_RESERVATION.The
keyfield set tocompute.googleapis.com/reservation-name.The
valuesfield 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" ] }}Replace
RESERVATION_URLwith the URL of thereservation. Specify one of the following values:If you created the reservation in the same project:
reservation-02If 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 instance mustspecifically target the reservation.
The instance must bestopped or deleted at the reservation end time.
The instance must use thereservation-bound provisioning model.When you create an instance, you can specify this model as follows:
In the Google Cloud console, if you specify a supported machine typefor future reservations in calendar mode, then the reservation-boundmodel is automatically selected.
In the gcloud CLI, include the
--provisioning-modelflagset toreservation-bound.In the REST API, include the
provisioningModelfield set toRESERVATION_BOUND.
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
Create an example request for five A3 Ultra instances and submit it forreview:
In the Google Cloud console, go to theReservations page.
Click theFuture reservations tab.
ClickCreate future reservation. TheCreate a future reservationpage appears.
Click theGPUs tab, and then, in theGPU type list, selectNVIDIA H200 141GB. This action specifies an A3 Ultra instance.
In theTotal capacity needed field, enter
5.In theReservation period section, specify the start time andduration for your reservation period.
ClickSearch for capacity, and then, in theAvailable capacity section, select one of the availablemachines.
ClickCreate.
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.In the Google Cloud console, go to theCreate an instancepage.
In theName field, enter a name for the instance. For thisexample, enter
example-instance.Specify theRegion andZone where the auto-createdreservation exists. For this example, selectus-central1 andus-central1-b respectively.
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.
In the navigation menu, clickAdvanced.
In theReservations section, selectChoose a reservation,and then clickChoose a reservation.
On theChoose a reservation pane, do the following:
Select the example auto-created reservation.
ClickChoose.
In theProvisioning model section, expand theVM provisioning model advanced settings section.
In theOn VM termination list, selectStop (default) orDelete.
ClickCreate.
gcloud
To create an example request for five A3 Ultra VMs and submit it forreview, use the
gcloud compute future-reservations createcommand: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-bAssume 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.
At the request start time, to create an A3 Ultra instance to consume theexample auto-created reservation, use the
gcloud compute instances createcommandwith the following flags:The
--instance-termination-actionflag.The
--provisioning-modelflag set toRESERVATION_BOUND.The
--reservationflag.The
--reservation-affinityflag 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
To create an example request for five A3 Ultra instances and submit itfor review, make a
POSTrequest to thefutureReservations.insertmethod: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.
At the request start time, to create an A3 Ultra instance to consume theexample auto-created reservation, make a
POSTrequest toinstances.insertmethod.In the request body, include the following fields:The
reservationAffinity.consumeReservationTypefield set toSPECIFIC_RESERVATION.The
reservationAffinity.keyfield set tocompute.googleapis.com/reservation-name.The
reservationAffinity.valuesfield set to the URL of thereservation.The
scheduling.instanceTerminationActionfield.The
scheduling.provisioningModelfield 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:
Create a copy of the reservation as a specifically targeted reservation fora single instance.
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:
To check which reservation a compute instance is consuming,view the reservation that an instance is consuming.
To check which instances are consuming a specific reservation,view a list of instances that are consuming a reservation.
To check the current reservation usage and see the number of instances thatare consuming a reservation, and how many more instances can consume it,view reservations.
To monitor reservations consumption data, which updates every 30 minutes,and receive alerts when reservations are consumed,monitor reservations consumption.
To analyze reservation consumption by using Cloud Billing data exportedto BigQuery, see the following examples:
To view reservations consumption data, which updates every 24 hours, doone of the following:
- To receive consumption reports in a Cloud Storage bucket to analyzeconsumption trends and identify unconsumed reservations,view reservations usage report.
- To analyze consumption trends and plan for future capacity needs byviewing past and forecasted reservation consumption,use Capacity Planner.
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.