Prevent compute instances from consuming reservations

This document explains how to prevent Compute Engine instances from consumingreservations. To learn more about reservations, seeReservations of Compute Engine zonal resources.

Automatically consumed reservationsallow instances with properties that match the reservations to automaticallyconsume them. To prevent instances from consuming a reservation, do one of thefollowing:

  • Configure instances to not consume reservations, as described in thisdocument.

  • Create or update instances with properties that don't match the reservation.

You can avoid consuming reservations when you want to use your instances fortasks like testing, debugging, or isolated deployments.

Limitations

You can only update an existing instance to not consume reservations if theinstance is configured to automatically consume matching reservations.

Before you begin

Required roles

To get the permissions that you need to prevent a compute instance from consuming reservations, ask your administrator to grant you theCompute Instance Admin (v1) (roles/compute.instanceAdmin.v1) IAM role on the project. For more information about granting roles, seeManage access to projects, folders, and organizations.

This predefined role contains the permissions required to prevent a compute instance from consuming reservations. To see the exact permissions that are required, expand theRequired permissions section:

Required permissions

The following permissions are required to prevent a compute instance from consuming 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.

Prevent reservation consumption

To prevent a compute instance from consuming reservations, set its reservationaffinity (reservationAffinity) property to not consume reservations. Thisproperty controls if an instance can consume matching reservations, a specificreservation, or no reservations.

To prevent one or more instances from consuming reservations, use one of thefollowing methods:

Prevent consumption in an existing instance

You can update a running instance so that it no longer automatically consumesreservations. You must restart the instance to make the changes effective, asdescribed in this section.

To prevent an existing instance from consuming reservations, select one of thefollowing options:

gcloud

  1. Create an empty YAML file.

  2. To export the properties of an instance into the YAML file that you'vejust created, use thegcloud compute instances export command:

    gcloud compute instances exportINSTANCE_NAME \    --destination=YAML_FILE \    --zone=ZONE

    Replace the following:

    • INSTANCE_NAME: the name of the instance.

    • YAML_FILE: the path to the empty YAML file thatyou created in the previous step.

    • ZONE: the zone where the instance exists.

  3. In the YAML configuration file, set theconsumeReservationType toNO_RESERVATION:

    reservationAffinity:  consumeReservationType: NO_RESERVATION
    Tip: To avoid getting an error such as"ERROR: (gcloud.compute.instances.update-from-file) Cannot parse YAML: [Expected type for field value, found True (type)]", add quotes (' ') around any label values ofyes orno in the exported instance configuration file. This indicates the values are strings, not Boolean values.
  4. To update the instance and restart it, use thegcloud compute instances update-from-file commandwith the--most-disruptive-allowed-action flag set toRESTART:

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

    Replace the following:

    • INSTANCE_NAME: the name of the instance.

    • YAML_FILE: the path to the YAML file with theconfiguration data that you modified in the previous step.

    • ZONE: the zone where the instance exists.

REST

  1. To view the properties of an existing instance, make aGET request totheinstances.get method:

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

    Replace the following:

    • PROJECT_ID: the ID of the project where youcreated the instance.

    • ZONE: the zone where the instance exists.

    • INSTANCE_NAME: the name of the instance.

  2. Store the output from theGET request in a file or text editor. Modifythe copied output to change theconsumeReservationType field toNO_RESERVATION:

    {  ...  "reservationAffinity": {    "consumeReservationType": "NO_RESERVATION"  },  ...}
  3. To update the instance and restart it, make aPUT request to theinstances.update method.In the request, do the following:

    • In the request URL, include themostDisruptiveAllowedAction queryparameter set toRESTART.

    • For the request body, use the output from theGET request that youedited in a previous step.

    The request is similar to the following example:

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

For more information about updating an instance, seeUpdate instance properties.

Prevent consumption while creating an instance

To create a compute instance that can't consume reservations, select one of thefollowing options:

Console

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

    Go to Create an instance

  2. In theName field, enter a name for the instance.

  3. In theRegion andZone lists, select the region and zone inwhich to create the instance.

  4. Specify the machine type to use for the instance.

  5. In the navigation menu, clickAdvanced.

  6. In theReservations section, selectDon't use a reservation.

  7. ClickCreate.

gcloud

To create an instance that can't consume reservations, use thegcloud compute instances create commandwith the--reservation-affinity flag set tonone:

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

Replace the following:

  • INSTANCE_NAME: the name of the instance.

  • MACHINE_TYPE: the machine type to use for theinstance.

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

Go

To create an instance that can't consume reservations, use the followingcode 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")// createInstanceNotConsumeReservation creates VM, without consuming reservationfunccreateInstanceNotConsumeReservation(wio.Writer,projectID,zone,instanceNamestring)error{ctx:=context.Background()machineType:=fmt.Sprintf("zones/%s/machineTypes/%s",zone,"n2-standard-32")sourceImage:="projects/debian-cloud/global/images/family/debian-12"instancesClient,err:=compute.NewInstancesRESTClient(ctx)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"),},},ReservationAffinity:&computepb.ReservationAffinity{ConsumeReservationType:proto.String("NO_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\n")returnnil}

Java

To create an instance that can't consume reservations, use the followingcode sample:

import staticcom.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.NO_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;publicclassCreateInstanceWithoutConsumingReservation{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 you want to use.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.// *   This value uses the format zones/{zone}/machineTypes/{type_name}.// *   For a list of machine types, see https://cloud.google.com/compute/docs/machine-typesStringmachineTypeName="n1-standard-1";// sourceImage: path to the operating system image to mount.// *   For details about images you can mount, see https://cloud.google.com/compute/docs/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";createInstanceWithoutConsumingReservationAsync(projectId,zone,instanceName,machineTypeName,sourceImage,diskSizeGb,networkName);}// Create a virtual machine that explicitly doesn't consume reservationspublicstaticInstancecreateInstanceWithoutConsumingReservationAsync(Stringproject,Stringzone,StringinstanceName,StringmachineTypeName,StringsourceImage,longdiskSizeGb,StringnetworkName)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(NO_RESERVATION.toString()).build();InstanceinstanceResource=Instance.newBuilder().setName(instanceName).setMachineType(machineType).addDisks(disk).addNetworkInterfaces(networkInterface).setReservationAffinity(reservationAffinity).build();InsertInstanceRequestinsertInstanceRequest=InsertInstanceRequest.newBuilder().setProject(project).setZone(zone).setInstanceResource(instanceResource).build();OperationFuture<Operation,Operation>operation=instancesClient.insertAsync(insertInstanceRequest);// Wait for the operation to complete.Operationresponse=operation.get(3,TimeUnit.MINUTES);if(response.hasError()){returnnull;}returninstancesClient.get(project,zone,instanceName);}}}

Node.js

To create an instance that can't consume reservations, use the followingcode 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 a VM that explicitly doesn't consume reservationsasyncfunctioncallCreateInstanceToNotConsumeReservation(){// 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:'NO_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.`);}awaitcallCreateInstanceToNotConsumeReservation();

Python

To create an instance that can't consume reservations, use the followingcode 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)returnresultdefcreate_vm_not_consume_reservation(project_id:str,zone:str,instance_name:str,machine_type:str="n2-standard-2")->compute_v1.Instance:"""Creates a VM that explicitly doesn't consume reservations    Args:        project_id (str): The ID of the Google Cloud project.        zone (str): The zone where the VM will be created.        instance_name (str): The name of the instance to create.        machine_type (str, optional): The machine type for the instance.    Returns:        compute_v1.Instance: The created instance.    """instance=compute_v1.Instance()instance.name=instance_nameinstance.machine_type=f"zones/{zone}/machineTypes/{machine_type}"instance.zone=zoneinstance.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)],)]# Set the reservation affinity to not consume any reservationinstance.reservation_affinity=compute_v1.ReservationAffinity(consume_reservation_type="NO_RESERVATION",# Prevents the instance from consuming reservations)# 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"Creating the{instance_name} instance in{zone}...")returnvm_client.get(project=project_id,zone=zone,instance=instance_name)

REST

To create an instance that can't consume reservations, make aPOST requestto theinstances.insert method.In the request body, include theconsumeReservationType field set toNO_RESERVATION:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances{  "name": "INSTANCE_NAME",  "machineType": "zones/ZONE/machineTypes/MACHINE_TYPE",  "disks": [    {      "boot": true,      "initializeParams": {        "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"      }    }  ],  "networkInterfaces": [    {      "network": "global/networks/default"    }  ],  "reservationAffinity": {    "consumeReservationType": "NO_RESERVATION"  }}

Replace the following:

  • PROJECT_ID: the ID of the project where you want tocreate the instance.

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

  • INSTANCE_NAME: the name of the instance.

  • MACHINE_TYPE: the machine type to use for theinstance.

  • IMAGE_PROJECT: the image project that contains the OSimage; for example,debian-cloud. For more information about thesupported image projects, seePublic images.

  • IMAGE: specify one of the following:

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

    • Animage family, which must beformatted asfamily/IMAGE_FAMILY. This specifiesthe most recent, non-deprecated OS image. For example, if youspecifyfamily/debian-12, the latest version in the Debian 12image family is used. For more information about using imagefamilies, seeImage families best practices.

For more information about creating an instance, seeCreate and start a Compute Engine instance.

Prevent consumption while creating instances in bulk

To create compute instances in bulk that can't consume reservations, select oneof the following options:

gcloud

To create instances in bulk that can't consume reservations, use thegcloud compute instances bulk create commandwith the--reservation-affinity flag set tonone.

For example, to create instances in bulk in a single zone and specify a namepattern, run the following command:

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

Replace the following:

  • COUNT: the number of instances to create.

  • MACHINE_TYPE: the machine type to use for theinstances.

  • NAME_PATTERN: the name pattern for the instances. Toreplace a sequence of numbers in a instance name, use a sequence of hash(#) characters. For example, usinginstance-# for the name patterngenerates instances with names starting withinstance-1,instance-2,and continuing up to the number of instances specified byCOUNT.

  • ZONE: the zone in which to create instances in bulk.

REST

To create instances in bulk that can't consume reservations, make aPOSTrequest to theinstances.bulkInsert method.In the request body, include theconsumeReservationType field set toNO_RESERVATION.

For example, to create instances in bulk in a single zone and specify a namepattern, make a request as follows:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/bulkInsert{  "count":COUNT,  "namePattern": "NAME_PATTERN",  "instanceProperties": {    "machineType": "MACHINE_TYPE",    "disks": [      {        "boot": true,        "initializeParams": {          "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"        }      }    ],    "networkInterfaces": [      {        "network": "global/networks/default"      }    ],    "reservationAffinity": {      "consumeReservationType": "NO_RESERVATION"    }  }}

Replace the following:

  • PROJECT_ID: the ID of the project in which to createinstances in bulk.

  • ZONE: the zone in which to create instances in bulk.

  • COUNT: the number of instances to create.

  • NAME_PATTERN: the name pattern for the instances. Toreplace a sequence of numbers in a instance name, use a sequence of hash(#) characters. For example, usinginstance-# for the name patterngenerates instances with names starting withinstance-1,instance-2,and continuing up to the number of instances specified byCOUNT.

  • MACHINE_TYPE: the machine type to use for theinstances.

  • IMAGE_PROJECT: the image project that contains the OSimage; for example,debian-cloud. For more information about thesupported image projects, seePublic images.

  • IMAGE: specify one of the following:

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

    • Animage family, which must beformatted asfamily/IMAGE_FAMILY. This specifiesthe most recent, non-deprecated OS image. For example, if youspecifyfamily/debian-12, the latest version in the Debian 12image family is used. For more information about using imagefamilies, seeImage families best practices.

For more information about creating instances in bulk, seeCreate VMs in bulk.

Prevent consumption while creating an instance template

After you create an instance template that configures instances to not consumereservations, you can use the template to do the following:

To create an instance template that configures instances to not consumereservations, select one of the following options:

Console

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

    Go to Create an instance template

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

  3. In theLocation section, specify whether you want to create aregional (default) or global instance template.

  4. In theMachine configuration section, specify the machine type touse for the instances created using the template.

  5. Expand theAdvanced options section, and then do thefollowing:

    1. Expand theManagement section.

    2. In theReservations section, selectDon't use a reservation.

  6. ClickCreate.

gcloud

To create an instance template that configures instances to to not consumereservations, use thegcloud compute instances-templates create commandwith the--reservation-affinity flag set tonone.

To create a regional instance template that configures instances to notconsume reservations, run the following command. If you want to create aglobal instance template, then use the same command without the--instance-template-region flag.

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

Replace the following:

  • INSTANCE_TEMPLATE_NAME: the name of the instancetemplate.

  • REGION: the region in which to create the instancetemplate.

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

Go

To create an instance template that configures instances to not consumereservations, 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")// createInstanceNotConsumeReservation creates a new instance template, which won't consume reservationsfunccreateTemplateNotConsumeReservation(wio.Writer,projectID,templateNamestring)error{// projectID := "your_project_id"// templateName := "your_template_name"ctx:=context.Background()instanceTemplatesClient,err:=compute.NewInstanceTemplatesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewInstanceTemplatesRESTClient: %w",err)}deferinstanceTemplatesClient.Close()req:=&computepb.InsertInstanceTemplateRequest{Project:projectID,InstanceTemplateResource:&computepb.InstanceTemplate{Name:proto.String(templateName),Properties:&computepb.InstanceProperties{// The template describes the size and source image of the boot disk// to attach to the instance.Disks:[]*computepb.AttachedDisk{{InitializeParams:&computepb.AttachedDiskInitializeParams{DiskSizeGb:proto.Int64(250),SourceImage:proto.String("projects/debian-cloud/global/images/family/debian-11"),},AutoDelete:proto.Bool(true),Boot:proto.Bool(true),},},MachineType:proto.String("e2-standard-4"),// The template connects the instance to the `default` network,// without specifying a subnetwork.NetworkInterfaces:[]*computepb.NetworkInterface{{Name:proto.String("global/networks/default"),// The template lets the instance use an external IP address.AccessConfigs:[]*computepb.AccessConfig{{Name:proto.String("External NAT"),Type:proto.String(computepb.AccessConfig_ONE_TO_ONE_NAT.String()),NetworkTier:proto.String(computepb.AccessConfig_PREMIUM.String()),},},},},ReservationAffinity:&computepb.ReservationAffinity{ConsumeReservationType:proto.String("NO_RESERVATION"),},},},}op,err:=instanceTemplatesClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create instance template: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance template created\n")returnnil}

Java

To create an instance template that configures instances to not consumereservations, use the following code sample:

import staticcom.google.cloud.compute.v1.ReservationAffinity.ConsumeReservationType.NO_RESERVATION;importcom.google.cloud.compute.v1.AccessConfig;importcom.google.cloud.compute.v1.AttachedDisk;importcom.google.cloud.compute.v1.AttachedDiskInitializeParams;importcom.google.cloud.compute.v1.InsertInstanceTemplateRequest;importcom.google.cloud.compute.v1.InstanceProperties;importcom.google.cloud.compute.v1.InstanceTemplate;importcom.google.cloud.compute.v1.InstanceTemplatesClient;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;publicclassCreateTemplateWithoutConsumingReservation{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 template you want to query.StringtemplateName="YOUR_INSTANCE_TEMPLATE_NAME";StringmachineType="e2-standard-4";StringsourceImage="projects/debian-cloud/global/images/family/debian-11";createTemplateWithoutConsumingReservationAsync(projectId,templateName,machineType,sourceImage);}// Create a template that explicitly doesn't consume any reservations.publicstaticInstanceTemplatecreateTemplateWithoutConsumingReservationAsync(StringprojectId,StringtemplateName,StringmachineType,StringsourceImage)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Initialize client that will be used to send requests. This client only needs to be created// once, and can be reused for multiple requests.try(InstanceTemplatesClientinstanceTemplatesClient=InstanceTemplatesClient.create()){AttachedDiskattachedDisk=AttachedDisk.newBuilder().setInitializeParams(AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskType("pd-balanced").setDiskSizeGb(250).build()).setAutoDelete(true).setBoot(true).build();NetworkInterfacenetworkInterface=NetworkInterface.newBuilder().setName("global/networks/default").addAccessConfigs(AccessConfig.newBuilder().setName("External NAT").setType(AccessConfig.Type.ONE_TO_ONE_NAT.toString()).setNetworkTier(AccessConfig.NetworkTier.PREMIUM.toString()).build()).build();ReservationAffinityreservationAffinity=ReservationAffinity.newBuilder().setConsumeReservationType(NO_RESERVATION.toString()).build();InstancePropertiesinstanceProperties=InstanceProperties.newBuilder().addDisks(attachedDisk).setMachineType(machineType).setReservationAffinity(reservationAffinity).addNetworkInterfaces(networkInterface).build();InsertInstanceTemplateRequestinsertInstanceTemplateRequest=InsertInstanceTemplateRequest.newBuilder().setProject(projectId).setInstanceTemplateResource(InstanceTemplate.newBuilder().setName(templateName).setProperties(instanceProperties).build()).build();Operationresponse=instanceTemplatesClient.insertAsync(insertInstanceTemplateRequest).get(3,TimeUnit.MINUTES);if(response.hasError()){returnnull;}returninstanceTemplatesClient.get(projectId,templateName);}}}

Node.js

To create an instance template that configures instances to not consumereservations, use the following code sample:

// Import the Compute libraryconstcomputeLib=require('@google-cloud/compute');constcompute=computeLib.protos.google.cloud.compute.v1;// Instantiate an instanceTemplatesClientconstinstanceTemplatesClient=newcomputeLib.InstanceTemplatesClient();// Instantiate a globalOperationsClientconstglobalOperationsClient=newcomputeLib.GlobalOperationsClient();/** * TODO(developer): Update/uncomment these variables before running the sample. */// The ID of the project where you want to create template.constprojectId=awaitinstanceTemplatesClient.getProjectId();// The name of the template to create.// const templateName = 'instance-01';// Create an instance template that creates VMs that don't explicitly consume reservationsasyncfunctioncallCreateTemplateToNotConsumeReservation(){// Define the boot disk for the instance templateconstdisk=newcompute.AttachedDisk({initializeParams:newcompute.AttachedDiskInitializeParams({sourceImage:'projects/debian-cloud/global/images/debian-12-bookworm-v20240815',diskSizeGb:'100',diskType:'pd-balanced',}),autoDelete:true,boot:true,type:'PERSISTENT',});// Define the network interface for the instance templateconstnetwork=newcompute.NetworkInterface({network:`projects/${projectId}/global/networks/default`,});// Define reservationAffinityconstreservationAffinity=newcompute.ReservationAffinity({consumeReservationType:'NO_RESERVATION',});// Define instance templateconstinstanceTemplate=newcompute.InstanceTemplate({name:templateName,properties:{disks:[disk],machineType:'e2-medium',// The template connects the instance to the `default` network,// without specifying a subnetwork.networkInterfaces:[network],reservationAffinity,},});const[response]=awaitinstanceTemplatesClient.insert({project:projectId,instanceTemplateResource:instanceTemplate,});letoperation=response.latestResponse;// Wait for the create instance operation to complete.while(operation.status!=='DONE'){[operation]=awaitglobalOperationsClient.wait({operation:operation.name,project:projectId,});}console.log(`Template${templateName} created.`);}awaitcallCreateTemplateToNotConsumeReservation();

Python

To create an instance template that configures instances to not consumereservations, 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)returnresultdefcreate_instance_template_not_consume_reservation(project_id:str,template_name:str,machine_type:str="n1-standard-1",)->compute_v1.InstanceTemplate:"""    Creates an instance template that creates VMs that don't explicitly consume reservations    Args:        project_id: project ID or project number of the Cloud project you use.        template_name: name of the new template to create.        machine_type: machine type for the instance.    Returns:        InstanceTemplate object that represents the new instance template.    """template=compute_v1.InstanceTemplate()template.name=template_nametemplate.properties.machine_type=machine_type# The template describes the size and source image of the boot disk# to attach to the instance.template.properties.disks=[compute_v1.AttachedDisk(boot=True,auto_delete=True,# The disk will be deleted when the instance is deletedinitialize_params=compute_v1.AttachedDiskInitializeParams(source_image="projects/debian-cloud/global/images/family/debian-11",disk_size_gb=10,),)]# The template connects the instance to the `default` network,template.properties.network_interfaces=[compute_v1.NetworkInterface(network="global/networks/default",access_configs=[compute_v1.AccessConfig(name="External NAT",type="ONE_TO_ONE_NAT",)],)]# The template doesn't explicitly consume reservationstemplate.properties.reservation_affinity=compute_v1.ReservationAffinity(consume_reservation_type="NO_RESERVATION")template_client=compute_v1.InstanceTemplatesClient()operation=template_client.insert(project=project_id,instance_template_resource=template)wait_for_extended_operation(operation,"instance template creation")returntemplate_client.get(project=project_id,instance_template=template_name)

REST

To create an instance template that configures instances to not consumereservations, make aPOST request to one of the following methods:

In the request body, include theconsumeReservationType field and set ittoNO_RESERVATION.

For example, to create a regional instance template and specify to notconsume reservations, make a request as follows:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/InstanceTemplates{  "name": "INSTANCE_TEMPLATE_NAME",  "properties": {    "machineType": "MACHINE_TYPE",    "disks": [      {        "boot": true,        "initializeParams": {          "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE"        }      }    ],    "networkInterfaces": [      {        "network": "global/networks/default"      }    ],    "reservationAffinity": {      "consumeReservationType": "NO_RESERVATION"    }  }}

Replace the following:

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

  • INSTANCE_TEMPLATE_NAME: the name of the instancetemplate.

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

  • IMAGE_PROJECT: the image project that contains the OSimage; for example,debian-cloud. For more information about thesupported image projects, seePublic images.

  • IMAGE: specify one of the following:

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

    • Animage family, which must beformatted asfamily/IMAGE_FAMILY. This specifiesthe most recent, non-deprecated OS image. For example, if youspecifyfamily/debian-12, the latest version in the Debian 12image family is used. For more information about using imagefamilies, seeImage families best practices.

For more information about creating instance templates, seeCreate instance templates.

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.