Create a reservation for a single project

This document explains how to create a single-project reservation, whichcan be consumed only by virtual machine (VM) instances in the same project. Tolearn more about reservations, seeReservations of Compute Engine zonal resources.

For other methods of creating reservations, see instead the following pages:

  • To create a reservation that can be used by multiple projects, seeCreate a shared reservation.

  • To create a reservation when purchasing a resource-based commitment, seePurchase commitments with attached reservations.Commitments provide discounts, known as committed use discounts (CUDs), onyour on-demand resource costs in exchange for purchasing a minimum level ofresources or for spending a minimum amount.

Note: After you create a reservation, you are charged for the reservedresources, even if they are not used, until you delete the reservation. If youdelete a reservation but don't delete the VMs that were using the reservedresources, the resources still incur charges. For more information, seeBilling.

Before you begin

Required roles

To get the permissions that you need to create single-project reservations, ask your administrator to grant you theCompute Admin (roles/compute.admin) 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 create single-project reservations. To see the exact permissions that are required, expand theRequired permissions section:

Required permissions

The following permissions are required to create single-project reservations:

  • compute.reservations.create on the project
  • To specify an instance template: compute.instanceTemplates.useReadOnly on the instance template

You might also be able to get these permissions withcustom roles or otherpredefined roles.

Create a single-project reservation

To consume a reservation, a VM must haveproperties thatexactly matchthat reservation. To specify the properties of the VMs that you want to reserve,select one of the following sections in this document:

  • Recommended:Specify an instance template

    This section explains how to use aninstance template to define theproperties of a reservation. By using an instance template, you can definethe properties of a reservation and the VMs that can consume the reservationin the same place.

  • Specify an existing VM

    This section explains how to use an existing VM to define the properties ofa reservation. By using the properties of an existing VM, you can consumethe reservation by creating VMs with properties that match the reference VM.

  • Specify properties directly

    This section explains how to directly define the properties of areservation. This method requires you to manually ensure that the propertiesof your VMs and reservationsexactly match—any mismatched propertiesprevent consumption.

By default, a reservation can be automatically consumed by any VMs withproperties that match it. If you want to control reservation consumption, do oneor more of the following:

Additionally, you can specify acompact placement policywhen creating a single-projectspecific reservation.A compact placement policy specifies that VMs are to be located as close to eachother as possible to reduce network latency.

Specify an instance template

To avoid errors when creating a reservation by specifying an instance template,make sure of the following:

  • Create your reservation in the same region and zone as the resourceswithin the instance template. Anyregionalorzonal resourcesspecified in an instance template—such as a machine type or aPersistent Disk volume—restrict the use of the template to the locationswhere those resources exist. For example, if your instance templatespecifies an existing Persistent Disk volume in zoneus-central1-a, thenyou can only create your reservation in the same zone. To check if anexisting template specifies any resources that bind the template to aspecific region or zone,view the details of the instance templateand look for references to regional or zonal resources inside of it.

  • If the instance template specifies acompact placement policy,then make sure that the template specifies asupported machine typefor compact placement policies. Otherwise, creating the reservation fails.

To create a single-project reservation by specifying an instance template,select one of the following options:

Console

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

    Go to Reservations

  2. On theOn-demand reservations tab (default), clickCreate reservation.

    TheCreate a reservation page opens.

  3. ForName, enter a name for your reservation.

  4. ForRegion andZone, select where you want to reserve resources.

  5. In theShare type section, selectLocal if it isn't alreadyselected.

  6. Optional: To allow a reservation of GPU VMs to be consumed bycustom training jobs orprediction jobs inVertex AI, in theGoogle Cloud services section,selectShare reservation.

  7. In theUse with VM instance section, select one of the followingoptions:

  8. ForNumber of VM instances, enter the number of VMs that you want toreserve.

  9. In theMachine configuration section, do the following:

    1. To specify the properties of your VMs from an existinginstance template, selectUse instance template.

    2. In theInstance template field, select the instance template ofyour choice. If you select a regional instance template, then youcan only reserve resources within the region of the instancetemplate.

  10. In theAuto-delete section, you can enable the auto-delete optionto let Compute Engine automatically delete the reservation ata specific date and time. Automatically deleting reservations can beuseful to avoid unnecessary charges when you stop consuming thereservation.

  11. To create the reservation, clickCreate.

    TheReservations page opens. Creating the single-project reservationmight take up to a minute to complete.

gcloud

To create a single-project reservation, use thegcloud compute reservations create command.

To create a single-project reservation by specifying an instance templateand without including any optional flags, run the following command:

gcloud compute reservations createRESERVATION_NAME \    --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE

Replace the following:

  • RESERVATION_NAME: the name of the reservation tocreate.

  • PROJECT_ID: the ID of the project where you want toreserve resources and where the instance template exists.

  • LOCATION: the location of the instance template.Specify one of the following values:

    • For a global instance template:global.

    • For a regional instance template:regions/REGION.ReplaceREGION with the region where the instancetemplate is located. If you specify a regional instance template,then you can only reserve VMs within the same region as thetemplate's region.

  • INSTANCE_TEMPLATE_NAME: the name of an existinginstance template. If the instance template specifies an A3 Mega,A3 High, or A3 Edge machine type or a compact placement policy, then youmust include the--require-specific-reservation flag.This indicates that only VMs that specifically target the reservationcan consume it. For more information, seeConsume VMs from a specific reservation.

  • NUMBER_OF_VMS: the number of VMs to reserve.

  • ZONE: the zone in which to reserve resources.

For example, to create a reservation for ten VMs in zoneus-central1-a byspecifying a global instance template, run the following command:

gcloud compute reservations create my-reservation \    --source-instance-template=projects/example-project/global/example-instance-template \    --vm-count=10 \    --zone=us-central1-a

Optionally, you can do one or more of the following:

  • To specify that only VMs that specifically target this reservation canconsume it, include the--require-specific-reservationflag.

    gcloud compute reservations createRESERVATION_NAME \    --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \--require-specific-reservation \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE
  • To allow a reservation of GPU VMs to be consumed bycustom training jobs orprediction jobs inVertex AI, include the--reservation-sharing-policyflag set toALLOW_ALL.

    gcloud compute reservations createRESERVATION_NAME \    --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \--reservation-sharing-policy=ALLOW_ALL \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE
  • To enable Compute Engine toautomatically delete the reservation,select one of the following methods:

    Preview — The--delete-at-time and--delete-after-duration flags

    This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.

    • To delete the reservation at a specific date and time, use thegcloud beta compute reservations create commandwith the--delete-at-time flag.

      gcloud beta compute reservations createRESERVATION_NAME \--delete-at-time=DELETE_AT_TIME \    --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE

      ReplaceDELETE_AT_TIME with a date and timeformatted as anRFC 3339 timestamp, whichmust be as follows:noneYYYY-MM-DDTHH:MM:SSOFFSET

      Replace the following:

      • YYYY-MM-DD: a date formatted as a 4-digityear, 2-digit month, and a 2-digit day of the month, separatedby hyphens (-).

      • HH:MM:SS: a time formatted as a 2-digit hourusing a 24-hour time, 2-digit minutes, and 2-digit seconds,separated by colons (:).

      • OFFSET: the time zone formatted as an offsetofCoordinated Universal Time (UTC).For example, to use the Pacific Standard Time (PST), specify-08:00. Alternatively, to use no offset, specifyZ.

    • To delete the reservation after a specific duration, use thegcloud beta compute reservations create commandwith the--delete-after-duration flag.

      gcloud beta compute reservations createRESERVATION_NAME \--delete-after-duration=DELETE_AFTER_DURATION \    --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE

      ReplaceDELETE_AFTER_DURATION with a duration indays, hours, minutes, or seconds. For example, specify30m for 30minutes, or1d2h3m4s for 1 day, 2 hours, 3 minutes, and 4 seconds.

Go

import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/protobuf/proto")// Creates the reservation from given template in particular zonefunccreateReservation(wio.Writer,projectID,zone,reservationName,sourceTemplatestring)error{// projectID := "your_project_id"// zone := "us-west3-a"// reservationName := "your_reservation_name"// template: 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()reservationsClient,err:=compute.NewReservationsRESTClient(ctx)iferr!=nil{returnerr}deferreservationsClient.Close()req:=&computepb.InsertReservationRequest{Project:projectID,ReservationResource:&computepb.Reservation{Name:proto.String(reservationName),Zone:proto.String(zone),SpecificReservation:&computepb.AllocationSpecificSKUReservation{Count:proto.Int64(2),SourceInstanceTemplate:proto.String(sourceTemplate),},},Zone:zone,}op,err:=reservationsClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create reservation: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Reservation created\n")returnnil}

Java

importcom.google.cloud.compute.v1.AllocationSpecificSKUReservation;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.Reservation;importcom.google.cloud.compute.v1.ReservationsClient;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateReservationForInstanceTemplate{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 in which you want to create the reservation.Stringzone="us-central1-a";// Name of the reservation you want to create.StringreservationName="YOUR_RESERVATION_NAME";// The number of virtual machines you want to create.intnumberOfVms=3;// The URI of the instance template with GLOBAL location// to be used for creating the reservation.StringinstanceTemplateUri="projects/YOUR_PROJECT_ID/global/instanceTemplates/YOUR_INSTANCE_TEMPLATE_NAME";// The URI of the instance template with REGIONAL location// to be used for creating the reservation. For us-central1 region in this case.// String instanceTemplateUri =// "projects/YOUR_PROJECT_ID/regions/us-central1/instanceTemplates/YOUR_INSTANCE_TEMPLATE_NAME"createReservationForInstanceTemplate(projectId,reservationName,instanceTemplateUri,numberOfVms,zone);}// Creates a reservation in a project for the instance template.publicstaticReservationcreateReservationForInstanceTemplate(StringprojectId,StringreservationName,StringinstanceTemplateUri,intnumberOfVms,Stringzone)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(ReservationsClientreservationsClient=ReservationsClient.create()){Reservationreservation=Reservation.newBuilder().setName(reservationName).setZone(zone).setSpecificReservation(AllocationSpecificSKUReservation.newBuilder()// Set the number of instances.setCount(numberOfVms)// Set the instance template to be used for creating the reservation..setSourceInstanceTemplate(instanceTemplateUri).build()).build();Operationresponse=reservationsClient.insertAsync(projectId,zone,reservation).get(3,TimeUnit.MINUTES);if(response.hasError()){returnnull;}returnreservationsClient.get(projectId,zone,reservationName);}}}

Node.js

// Import the Compute libraryconstcomputeLib=require('@google-cloud/compute');constcompute=computeLib.protos.google.cloud.compute.v1;// Instantiate a reservationsClientconstreservationsClient=newcomputeLib.ReservationsClient();// Instantiate a zoneOperationsClientconstzoneOperationsClient=newcomputeLib.ZoneOperationsClient();/** * TODO(developer): Update/uncomment these variables before running the sample. */// The ID of the project where you want to reserve resources and where the instance template exists.constprojectId=awaitreservationsClient.getProjectId();// The zone in which to reserve resources.constzone='us-central1-a';// The name of the reservation to create.// reservationName = 'reservation-01';// The number of VMs to reserve.constvmsNumber=3;/** * The name of an existing instance template. * TODO(developer): Uncomment and update instanceTemplateName before running the sample. */// const instanceTemplateName = 'pernament-region-template-name';/** * // The location of the instance template. * TODO(developer): Uncomment the `location` variable depending on which template you want to use. */// The location for a regional instance template: regions/{region}. Replace region with the region where the instance template is located.// If you specify a regional instance template, then you can only reserve VMs within the same region as the template's region.// const location = `regions/${zone.slice(0, -2)}`;// The location for a global instance template.// const location = 'global';asyncfunctioncallCreateComputeReservationInstanceTemplate(){// Create reservation for 3 VMs in zone us-central1-a by specifying a instance template.constspecificReservation=newcompute.AllocationSpecificSKUReservation({count:vmsNumber,sourceInstanceTemplate:`projects/${projectId}/${location}/instanceTemplates/${instanceTemplateName}`,});// Create a reservation.constreservation=newcompute.Reservation({name:reservationName,specificReservation,// To specify that only VMs that specifically target this reservation can consume it,// set specificReservationRequired field to true.specificReservationRequired:true,});const[response]=awaitreservationsClient.insert({project:projectId,reservationResource:reservation,zone,});letoperation=response.latestResponse;// Wait for the create reservation operation to complete.while(operation.status!=='DONE'){[operation]=awaitzoneOperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log(`Reservation:${reservationName} created.`);}awaitcallCreateComputeReservationInstanceTemplate();

Python

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_reservation_from_template(project_id:str,reservation_name:str,template:str)->compute_v1.Reservation:"""    Create a new reservation based on an existing template.    Args:        project_id: project ID or project number of the Cloud project you use.        reservation_name: the name of new reservation.        template: existing template path. Following formats are allowed:            - projects/{project_id}/global/instanceTemplates/{template_name}            - projects/{project_id}/regions/{region}/instanceTemplates/{template_name}            - https://www.googleapis.com/compute/v1/projects/{project_id}/global/instanceTemplates/instanceTemplate            - https://www.googleapis.com/compute/v1/projects/{project_id}/regions/{region}/instanceTemplates/instanceTemplate    Returns:        Reservation object that represents the new reservation.    """reservations_client=compute_v1.ReservationsClient()request=compute_v1.InsertReservationRequest()request.project=project_idrequest.zone="us-central1-a"specific_reservation=compute_v1.AllocationSpecificSKUReservation()specific_reservation.count=1specific_reservation.source_instance_template=templatereservation=compute_v1.Reservation()reservation.name=reservation_namereservation.specific_reservation=specific_reservationrequest.reservation_resource=reservationoperation=reservations_client.insert(request)wait_for_extended_operation(operation,"Reservation creation")returnreservations_client.get(project=project_id,zone="us-central1-a",reservation=reservation_name)

REST

To create a single-project reservation, make aPOST request to thereservations.insert method.

To create a single-project reservation by specifying an instance templateand without including any optional flags, make the followingPOST request:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{  "name": "RESERVATION_NAME",  "specificReservation": {    "count": "NUMBER_OF_VMS",    "sourceInstanceTemplate": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"  }}

Replace the following:

  • PROJECT_ID: the ID of the project where you want toreserve resources and where the instance template exists.

  • ZONE: the zone in which to reserve resources.

  • RESERVATION_NAME: the name of the reservation tocreate.

  • NUMBER_OF_VMS: the number of VMs to reserve.

  • LOCATION: the location of the instance template.Specify one of the following values:

    • For a global instance template:global.

    • For a regional instance template:regions/REGION.ReplaceREGION with the region where the instancetemplate is located. If you specify a regional instance template,then you can only reserve VMs within the same region as thetemplate's region.

  • INSTANCE_TEMPLATE_NAME: the name of an existinginstance template. If the instance template specifies an A3 Mega,A3 High, or A3 Edge machine type or a compact placement policy, then youmust include thespecificReservationRequired fieldin the request body, and set the field totrue. This indicates thatonly VMs that specifically target this reservation can consume it. Formore information, seeConsume VMs from a specific reservation.

For example, to create a reservation for ten VMs in zoneus-central1-a byspecifying a global instance template, make the followingPOST request:

POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations{  "name": "my-reservation",  "specificReservation": {    "count": "10",    "sourceInstanceTemplate": "projects/example-project/global/instanceTemplates/example-instance-template"  }}

Optionally, you can do one or more of the following:

  • To specify that only VMs that specifically target this reservation canconsume it, include thespecificReservationRequired field in therequest body, and set the field totrue.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{  "name": "RESERVATION_NAME",  "specificReservation": {    "count": "NUMBER_OF_VMS",    "sourceInstanceTemplate": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"  },"specificReservationRequired": true}
  • To allow a reservation of GPU VMs to be consumed bycustom training jobs orprediction jobs inVertex AI, include theserviceShareType field and setit toALLOW_ALL.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{  "name": "RESERVATION_NAME","reservationSharingPolicy": {    "serviceShareType": "ALLOW_ALL"  },  "specificReservation": {    "count": "NUMBER_OF_VMS",    "sourceInstanceTemplate": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"  }}
  • To enable Compute Engine toautomatically delete the reservation,select one of the following methods:

    Preview — ThedeleteAtTime anddeleteAfterDuration fields

    This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.

    • To delete the reservation at a specific date and time, make aPOSTrequest to thebeta.reservations.insert method.In the request body, include thedeleteAtTime field.

      POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations{"deleteAtTime": "DELETE_AT_TIME",  "name": "RESERVATION_NAME",  "specificReservation": {    "count": "NUMBER_OF_VMS",    "sourceInstanceTemplate": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"  }}

      ReplaceDELETE_AT_TIME with a date and timeformatted as anRFC 3339 timestamp, whichmust be as follows:

      YYYY-MM-DDTHH:MM:SSOFFSET

      Replace the following:

      • YYYY-MM-DD: a date formatted as a 4-digityear, 2-digit month, and a 2-digit day of the month, separatedby hyphens (-).

      • HH:MM:SS: a time formatted as a 2-digit hourusing a 24-hour time, 2-digit minutes, and 2-digit seconds,separated by colons (:).

      • OFFSET: the time zone formatted as an offsetofCoordinated Universal Time (UTC).For example, to use the Pacific Standard Time (PST), specify-08:00. Alternatively, to use no offset, specifyZ.

    • To delete the reservation after a specific duration, make aPOSTrequest to thebeta.reservations.insert method.In the request body, include thedeleteAfterDuration field.

      POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations{"deleteAfterDuration": {    "seconds": "DELETE_AFTER_DURATION"  },  "name": "RESERVATION_NAME",  "specificReservation": {    "count": "NUMBER_OF_VMS",    "sourceInstanceTemplate": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME"  }}

      ReplaceDELETE_AFTER_DURATION with a duration inseconds. For example, specify86400 for 86,400 seconds (1 day).

Specify an existing VM

You can only create a reservation based on an existing VM in the same zone asthe VM.

After creating the reservation, you can consume it by creating VMs withproperties that match the reference VM. You can do this by doing one of thefollowing:

To create a single-project reservation that uses the properties of an existingVM, do the following:

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

    Go to Reservations

  2. ClickCreate reservation.

    TheCreate a reservation page opens.

  3. ForName, enter a name for your reservation.

  4. ForRegion andZone, select where you want to reserve resources.

  5. In theShare type section, clickLocal if it isn't already selected.

  6. In theUse with VM instance section, select one of the followingoptions:

  7. ForNumber of VM instances, enter the number of VMs that you want toreserve.

  8. In theMachine configuration section, do the following:

    1. SelectUse existing VM.

    2. ForExisting VM, select the VM which properties you want to useto create the reservation.

  9. Optional: To specify a compact placement policy for a reservation that meetstherequirements,in theGroup placement policy section, click theSelect or create a group placement policy list, and then do one of thefollowing:

  10. In theAuto-delete section, you can enable the auto-delete option to letCompute Engine automatically delete the reservation at a specificdate and time. Automatically deleting reservations can be useful to avoidunnecessary charges when you stop consuming the reservation.

  11. To create the reservation, clickCreate.

    TheReservations page opens. Creating the reservation might take up to aminute to complete.

Specify properties directly

To create a single-project reservation by specifying properties directly, selectone of the following options:

Console

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

    Go to Reservations

  2. On theOn-demand reservations tab (default), clickCreate reservation.

    TheCreate a reservation page opens.

  3. ForName, enter a name for your reservation.

  4. ForRegion andZone, select where you want to reserve resources.

  5. In theShare type section, clickLocal if it isn't alreadyselected.

  6. Optional: To allow a reservation of GPU VMs to be consumed bycustom training jobs orprediction jobs inVertex AI, in theGoogle Cloud services section,selectShare reservation.

  7. In theUse with VM instance section, select one of the followingoptions:

  8. ForNumber of VM instances, enter the number of VMs that you want toreserve.

  9. In theMachine configuration section, selectSpecify machine type, and then specify the following:

    1. ForMachine family,Series, andMachine type, select a machine family, series, and machine type.

    2. Optional: To specify a minimum CPU platform or attach GPUs to N1 VMs, do the following:

      1. To expand theCPU Platform and GPU section, click the expander arrow.

      2. Optional: To specify a minimum CPU platform, forCPU Platform, select an option.

      3. Optional: To attach GPUs to N1 VMs, clickAdd GPU. Then, forGPU type andNumber of GPUs, select the type and number of GPUs to attach to each N1 VM.

  10. Optional: To attach Local SSD disks to amachine type that doesn't include Local SSD disks by default,do the following:

    1. ForNumber of disks, select the number of Local SSD disks toattach.

    2. ForInterface type, select the disk interface for the Local SSDdisks.

  11. Optional: To specify a compact placement policy for a reservation thatmeets therequirements,in theGroup placement policy section, click theSelect or create a group placement policy list, and then do one ofthe following:

  12. In theAuto-delete section, you can enable the auto-delete option tolet Compute Engine automatically delete the reservation at aspecific date and time. Automatically deleting reservations can beuseful to avoid unnecessary charges when you stop consuming thereservation.

  13. To create the reservation, clickCreate.

    TheReservations page opens. Creating the single-project reservationmight take up to a minute to complete.

gcloud

To create a single-project reservation, use thegcloud compute reservations create command.

To create a single-project reservation by specifying properties directly andwithout including any optional flags, run the following command:

gcloud compute reservations createRESERVATION_NAME \    --machine-type=MACHINE_TYPE \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE

Replace the following:

  • RESERVATION_NAME: the name of the reservation tocreate.

  • MACHINE_TYPE: a machine type to use for each VM. Ifyou specify an A3 Mega, A3 High, or A3 Edge machine type, then you mustinclude the--require-specific-reservation flag.This indicates that only VMs that specifically target the reservationcan consume it. For more information, seeConsume VMs from a specific reservation.

  • NUMBER_OF_VMS: the number of VMs to reserve.

  • ZONE: the zone in which to reserve resources.

For example, to create a reservation in zoneus-central1-a for ten VMsthat each use an N2 predefined machine type with 4 vCPUs, run thefollowing command:

gcloud compute reservations create my-reservation \    --machine-type=n2-standard-4 \    --vm-count=10 \    --zone=us-central1-a

Optionally, you can do one or more of the following:

  • To attach GPUs to your reserved N1 VMs, include the--acceleratorflag.

    gcloud compute reservations createRESERVATION_NAME \--accelerator=count=NUMBER_OF_ACCELERATORS,type=ACCELERATOR_TYPE \    --machine-type=MACHINE_TYPE \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE

    Replace the following:

  • To attach Local SSD disks to amachine type that doesn't include Local SSD disks by default,include the--local-ssd flag. You can only attach Local SSD disks of375 GB.

    gcloud compute reservations createRESERVATION_NAME \--local-ssd=count=NUMBER_OF_LOCAL_SSD_DISKS,size=375,interface=INTERFACE_TYPE \    --machine-type=MACHINE_TYPE \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE

    Replace the following:

    • NUMBER_OF_LOCAL_SSD_DISKS: the number of LocalSSD disks to attach.

    • INTERFACE_TYPE: the type of disk interface thatyou want each Local SSD disk to use and thatyour specified machine type supports.Specify one of the following values:

      • For the NVME disk interface:nvme

      • For the SCSI disk interface:scsi

  • To have the reserved VMs use a specificminimum CPU platforminstead of the zone's default CPU platform, include the--min-cpu-platform flag.

    gcloud compute reservations createRESERVATION_NAME \    --machine-type=MACHINE_TYPE \--min-cpu-platform="MIN_CPU_PLATFORM" \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE

    ReplaceMIN_CPU_PLATFORM with a minimum CPU platform.To make sure that a CPU platform is available in the zone where you'rereserving resources,view the available CPU platforms by zone.

  • To specify that only VMs that specifically target this reservation canconsume it, include the--require-specific-reservationflag.

    gcloud compute reservations createRESERVATION_NAME \    --machine-type=MACHINE_TYPE \--require-specific-reservation \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE
  • To specify acompact placement policyfor lower network latency among VMs, include the--resource-policies=policy flag.

    gcloud compute reservations createRESERVATION_NAME \    --machine-type=MACHINE_TYPE \--resource-policies=policy=COMPACT_PLACEMENT_POLICY_NAME \    --require-specific-reservation \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE

    ReplaceCOMPACT_PLACEMENT_POLICY_NAME with the name ofan existing compact placement policy. Additionally, to avoid errors whencreating a single-project reservation that specifies a compact placementpolicy, make sure to specify the following:

    • Asupported machine type and maximum number of VMsfor compact placement policies.

    • A zone within the region where the compact placement policy islocated.

    • The--require-specific-reservation flag. This indicates that onlyVMs that specifically target the reservation can consume it.

  • To allow a reservation of GPU VMs to be consumed bycustom training jobs orprediction jobs inVertex AI, include the--reservation-sharing-policyflag set toALLOW_ALL.

    gcloud compute reservations createRESERVATION_NAME \    --machine-type=MACHINE_TYPE \--reservation-sharing-policy=ALLOW_ALL \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE
  • To enable Compute Engine toautomatically delete the reservation,select one of the following methods:

    Preview — The--delete-at-time and--delete-after-duration flags

    This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.

    • To delete the reservation at a specific date and time, use thegcloud beta compute reservations create commandwith the--delete-at-time flag.

      gcloud beta compute reservations createRESERVATION_NAME \--delete-at-time=DELETE_AT_TIME \    --machine-type=MACHINE_TYPE \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE

      ReplaceDELETE_AT_TIME with a date and timeformatted as anRFC 3339 timestamp, whichmust be as follows:

      YYYY-MM-DDTHH:MM:SSOFFSET

      Replace the following:

      • YYYY-MM-DD: a date formatted as a 4-digityear, 2-digit month, and a 2-digit day of the month, separatedby hyphens (-).

      • HH:MM:SS: a time formatted as a 2-digit hourusing a 24-hour time, 2-digit minutes, and 2-digit seconds,separated by colons (:).

      • OFFSET: the time zone formatted as an offsetofCoordinated Universal Time (UTC).For example, to use the Pacific Standard Time (PST), specify-08:00. Alternatively, to use no offset, specifyZ.

    • To delete the reservation after a specific duration, use thegcloud beta compute reservations create commandwith the--delete-after-duration flag.

      gcloud beta compute reservations createRESERVATION_NAME \--delete-after-duration=DELETE_AFTER_DURATION \    --machine-type=MACHINE_TYPE \    --vm-count=NUMBER_OF_VMS \    --zone=ZONE

      ReplaceDELETE_AFTER_DURATION with a duration indays, hours, minutes, or seconds. For example, specify30m for 30minutes, or1d2h3m4s for 1 day, 2 hours, 3 minutes, and 4 seconds.

Go

import("context""fmt""io"compute"cloud.google.com/go/compute/apiv1"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/protobuf/proto")// Creates the reservation with accelerated imagefunccreateBaseReservation(wio.Writer,projectID,zone,reservationNamestring)error{// projectID := "your_project_id"// zone := "us-west3-a"// reservationName := "your_reservation_name"ctx:=context.Background()reservationsClient,err:=compute.NewReservationsRESTClient(ctx)iferr!=nil{returnerr}deferreservationsClient.Close()// Creating reservation based on direct propertiesreq:=&computepb.InsertReservationRequest{Project:projectID,ReservationResource:&computepb.Reservation{Name:proto.String(reservationName),Zone:proto.String(zone),SpecificReservation:&computepb.AllocationSpecificSKUReservation{Count:proto.Int64(2),// Properties, which allows customising instancesInstanceProperties:&computepb.AllocationSpecificSKUAllocationReservedInstanceProperties{// Attaching GPUs to the reserved VMs// Read more: https://cloud.google.com/compute/docs/gpus#n1-gpusGuestAccelerators:[]*computepb.AcceleratorConfig{{AcceleratorCount:proto.Int32(1),AcceleratorType:proto.String("nvidia-tesla-t4"),},},// Including local SSD disksLocalSsds:[]*computepb.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk{{DiskSizeGb:proto.Int64(375),Interface:proto.String("NVME"),},},MachineType:proto.String("n1-standard-2"),// Specifying minimum CPU platform// Read more: https://cloud.google.com/compute/docs/instances/specify-min-cpu-platformMinCpuPlatform:proto.String("Intel Skylake"),},},},Zone:zone,}op,err:=reservationsClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create reservation: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Reservation created\n")returnnil}

Java

importcom.google.cloud.compute.v1.AcceleratorConfig;importcom.google.cloud.compute.v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk;importcom.google.cloud.compute.v1.AllocationSpecificSKUAllocationReservedInstanceProperties;importcom.google.cloud.compute.v1.AllocationSpecificSKUReservation;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.Reservation;importcom.google.cloud.compute.v1.ReservationsClient;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateReservation{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 in which you want to create the disk.Stringzone="us-central1-a";// Name of the reservation you want to create.StringreservationName="YOUR_RESERVATION_NAME";// Number of instances in the reservation.intnumberOfVms=3;createReservation(projectId,reservationName,numberOfVms,zone);}// Creates reservation with optional flagspublicstaticReservationcreateReservation(StringprojectId,StringreservationName,intnumberOfVms,Stringzone)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// Create the reservation with optional properties:// Machine type of the instances in the reservation.StringmachineType="n1-standard-2";// Number of accelerators to be attached to the instances in the reservation.intnumberOfAccelerators=1;// Accelerator type to be attached to the instances in the reservation.StringacceleratorType="nvidia-tesla-t4";// Minimum CPU platform to be attached to the instances in the reservation.StringminCpuPlatform="Intel Skylake";// Local SSD size in GB to be attached to the instances in the reservation.intlocalSsdSize=375;// Local SSD interfaces to be attached to the instances in the reservation.StringlocalSsdInterface1="NVME";StringlocalSsdInterface2="SCSI";booleanspecificReservationRequired=true;// 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(ReservationsClientreservationsClient=ReservationsClient.create()){Reservationreservation=Reservation.newBuilder().setName(reservationName).setZone(zone).setSpecificReservationRequired(specificReservationRequired).setSpecificReservation(AllocationSpecificSKUReservation.newBuilder()// Set the number of instances.setCount(numberOfVms)// Set instance properties.setInstanceProperties(AllocationSpecificSKUAllocationReservedInstanceProperties.newBuilder().setMachineType(machineType).setMinCpuPlatform(minCpuPlatform).addGuestAccelerators(AcceleratorConfig.newBuilder().setAcceleratorCount(numberOfAccelerators).setAcceleratorType(acceleratorType).build()).addLocalSsds(AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk.newBuilder().setDiskSizeGb(localSsdSize).setInterface(localSsdInterface1).build()).addLocalSsds(AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk.newBuilder().setDiskSizeGb(localSsdSize).setInterface(localSsdInterface2).build()).build()).build()).build();Operationresponse=reservationsClient.insertAsync(projectId,zone,reservation).get(7,TimeUnit.MINUTES);if(response.hasError()){returnnull;}returnreservationsClient.get(projectId,zone,reservationName);}}}

Node.js

// Import the Compute libraryconstcomputeLib=require('@google-cloud/compute');constcompute=computeLib.protos.google.cloud.compute.v1;// Instantiate a reservationsClientconstreservationsClient=newcomputeLib.ReservationsClient();// Instantiate a zoneOperationsClientconstzoneOperationsClient=newcomputeLib.ZoneOperationsClient();/** * TODO(developer): Update/uncomment these variables before running the sample. */// The ID of the project where you want to reserve resources.constprojectId=awaitreservationsClient.getProjectId();// The zone in which to reserve resources.constzone='us-central1-a';// The name of the reservation to create.// reservationName = 'reservation-01';// The number of VMs to reserve.constvmsNumber=3;// Machine type to use for each VM.constmachineType='n1-standard-4';asyncfunctioncallCreateComputeReservationFromProperties(){// Create specific reservation for 3 VMs that each use an N1 predefined machine type with 4 vCPUs.constspecificReservation=newcompute.AllocationSpecificSKUReservation({count:vmsNumber,instanceProperties:{machineType,// To have the reserved VMs use a specific minimum CPU platform instead of the zone's default CPU platform.minCpuPlatform:'Intel Skylake',// If you want to attach GPUs to your reserved N1 VMs, update and uncomment guestAccelerators if needed.// guestAccelerators: [//   {//     // The number of GPUs to add per reserved VM.//     acceleratorCount: 1,//     // Supported GPU model for N1 VMs. Ensure that your chosen GPU model is available in the zone,//     // where you want to reserve resources.//     acceleratorType: 'nvidia-tesla-t4',//   },// ],// If you want to add local SSD disks to each reserved VM, update and uncomment localSsds if needed.// You can specify up to 24 Local SSD disks. Each Local SSD disk is 375 GB.// localSsds: [//   {//     diskSizeGb: 375,//     // The type of interface you want each Local SSD disk to use. Specify one of the following values: NVME or SCSI.//     // Make sure that the machine type you specify for the reserved VMs supports the chosen disk interfaces.//     interface: 'NVME',//   },// ],},});// Create a reservation.constreservation=newcompute.Reservation({name:reservationName,zone,specificReservation,// To specify that only VMs that specifically target this reservation can consume it,// set specificReservationRequired field to true.specificReservationRequired:true,});const[response]=awaitreservationsClient.insert({project:projectId,reservationResource:reservation,zone,});letoperation=response.latestResponse;// Wait for the create reservation operation to complete.while(operation.status!=='DONE'){[operation]=awaitzoneOperationsClient.wait({operation:operation.name,project:projectId,zone:operation.zone.split('/').pop(),});}console.log(`Reservation:${reservationName} created.`);}awaitcallCreateComputeReservationFromProperties();

Python

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_compute_reservation(project_id:str,zone:str="us-central1-a",reservation_name="your-reservation-name",)->compute_v1.Reservation:"""Creates a compute reservation in GCP.    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.    Returns:        Reservation object that represents the new reservation.    """instance_properties=compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(machine_type="n1-standard-1",# Optional. Specifies the minimum CPU platform for the VM instance.min_cpu_platform="Intel Ivy Bridge",# Optional. Specifies amount of local ssd to reserve with each instance.local_ssds=[compute_v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk(disk_size_gb=375,interface="NVME"),compute_v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk(disk_size_gb=375,interface="SCSI"),],# Optional. Specifies the GPUs allocated to each instance.# guest_accelerators=[#     compute_v1.AcceleratorConfig(#         accelerator_count=1, accelerator_type="nvidia-tesla-t4"#     )# ],)reservation=compute_v1.Reservation(name=reservation_name,specific_reservation=compute_v1.AllocationSpecificSKUReservation(count=3,# Number of resources that are allocated.# If you use source_instance_template, you must exclude the instance_properties field.# It can be a full or partial URL.# source_instance_template="projects/[PROJECT_ID]/global/instanceTemplates/my-instance-template",instance_properties=instance_properties,),)# Create a clientclient=compute_v1.ReservationsClient()operation=client.insert(project=project_id,zone=zone,reservation_resource=reservation,)wait_for_extended_operation(operation,"Reservation creation")reservation=client.get(project=project_id,zone=zone,reservation=reservation_name)print("Name: ",reservation.name)print("STATUS: ",reservation.status)print(reservation.specific_reservation)# Example response:# Name:  your-reservation-name# STATUS:  READY# count: 3# instance_properties {#   machine_type: "n1-standard-1"#   local_ssds {#     disk_size_gb: 375#     interface: "NVME"#   }# ...returnreservation

Terraform

To create a single-project reservation, use thegoogle_compute_reservation Terraform resource.

For example, to create a single-project reservation for one N2 predefinedmachine type with 2 vCPUs, use the following resource:

resource "google_compute_reservation" "default" {  name = "gce-reservation-local"  zone = "us-central1-a"  /**   * To specify a single-project reservation, omit the share_settings block   * (default) or set the share_type field to LOCAL.   */  share_settings {    share_type = "LOCAL"  }  specific_reservation {    count = 1    instance_properties {      machine_type = "n2-standard-2"    }  }  /**   * To let VMs with affinity for any reservation consume this reservation, omit   * the specific_reservation_required field (default) or set it to false.   */  specific_reservation_required = false}

For more information about how to use Terraform, seeUsing Terraform with Google Cloud.

REST

To create a single-project reservation, make aPOST request to thereservations.insert method.

To create a single-project reservation by specifying properties directly andwithout any including any optional fields, make the followingPOSTrequest:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{  "name": "RESERVATION_NAME",  "specificReservation": {    "count": "NUMBER_OF_VMS",    "instanceProperties": {      "machineType": "MACHINE_TYPE"    }  }}

Replace the following:

  • PROJECT_ID: the ID of the project where you want toreserve resources.

  • ZONE: the zone in which to reserve resources.

  • RESERVATION_NAME: the name of the reservation tocreate.

  • NUMBER_OF_VMS: the number of VMs to reserve.

  • MACHINE_TYPE: a machine type to use for each VM. Ifyou specify an A3 Mega, A3 High, or A3 Edge machine type, then you mustinclude thespecificReservationRequired field inthe request body, and set the field totrue. This indicates that onlyVMs that specifically target the reservation can consume it. For moreinformation, seeConsume VMs from a specific reservation.

For example, to create a reservation in zoneus-central1-a for ten VMsthat each use an N2 predefined machine type with 4 vCPUs, make thefollowingPOST request:

POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations{  "name": "my-reservation",  "specificReservation": {    "count": "10",    "instanceProperties": {      "machineType": "n2-standard-4",    }  }}

Optionally, you can do one or more of the following:

  • To attach GPUs to your reserved N1 VMs, include theguestAcceleratorsfield in the request body.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{  "name": "RESERVATION_NAME",  "specificReservation": {    "count": "NUMBER_OF_VMS",    "instanceProperties": {"guestAccelerators": [        {          "acceleratorCount":NUMBER_OF_ACCELERATORS,          "acceleratorType": "ACCELERATOR_TYPE"        }      ],      "machineType": "MACHINE_TYPE"    }  }}

    Replace the following:

  • To attach Local SSD disks to amachine type that doesn't include Local SSD disks by default,include thelocalSsds field in the request body. You can only attachLocal SSD disks of 375 GB.

    For example, to attach two Local SSD disks to the machine type that youwant to reserve, make a request as follows:

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{  "name": "RESERVATION_NAME",  "specificReservation": {    "count": "NUMBER_OF_VMS",    "instanceProperties": {"localSsds": [        {          "diskSizeGb": "375",          "interface": "INTERFACE_TYPE"        },        {          "diskSizeGb": "375",          "interface": "INTERFACE_TYPE"        }      ],      "machineType": "MACHINE_TYPE"    }  }}

    ReplaceINTERFACE_TYPE with the type of diskinterface that you want each Local SSD disk to use and thatyour specified machine type supports.Specify one of the following values:

    • For the NVME disk interface:NVME

    • For the SCSI disk interface:SCSI

  • To have the reserved VMs use a specificminimum CPU platforminstead of the zone's default CPU platform, include theminCpuPlatformfield in the request body.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{  "name": "RESERVATION_NAME",  "specificReservation": {    "count": "NUMBER_OF_VMS",    "instanceProperties": {      "machineType": "MACHINE_TYPE","minCpuPlatform": "MIN_CPU_PLATFORM"    }  }}

    ReplaceMIN_CPU_PLATFORM with a minimum CPU platform.To make sure that a CPU platform is available in the zone where you'rereserving resources,view the available CPU platforms by zone.

  • To specify acompact placement policyto reduce network latency among your reserved VMs, include theresourcePolicies field in the request body.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{  "name": "RESERVATION_NAME","resourcePolicies": {    "policy" : "projects/example-project/regions/REGION/resourcePolicies/COMPACT_PLACEMENT_POLICY_NAME"  },  "specificReservation": {    "count": "NUMBER_OF_VMS",    "instanceProperties": {      "machineType": "MACHINE_TYPE"    }  },  "specificReservationRequired": true}

    Replace the following:

    • REGION: the region where the compact placementpolicy is located. You can only create the reservation within theregion of the placement policy.

    • COMPACT_PLACEMENT_POLICY_NAME: the name of anexisting compact placement policy.

    Additionally, to avoid errors when creating a single-project reservationthat specifies a compact placement policy, make sure to specify thefollowing:

    • Asupported machine typefor compact placement policies.

    • ThespecificReservationRequired field set totrue. Thisindicates that only VMs that specifically target this reservationcan consume it.

  • To specify that only VMs that specifically target this reservation canconsume it, include thespecificReservationRequired field in therequest body and set the field totrue.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{  "name": "RESERVATION_NAME",  "specificReservation": {    "count": "NUMBER_OF_VMS",    "instanceProperties": {      "machineType": "MACHINE_TYPE"    }  },"specificReservationRequired": true}
  • To allow a reservation of GPU VMs to be consumed bycustom training jobs orprediction jobs inVertex AI, include theserviceShareType field and setit toALLOW_ALL.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{  "name": "RESERVATION_NAME","reservationSharingPolicy": {    "serviceShareType": "ALLOW_ALL"  },  "specificReservation": {    "count": "NUMBER_OF_VMS",    "instanceProperties": {      "machineType": "MACHINE_TYPE"    }  }}
  • To enable Compute Engine toautomatically delete the reservation,select one of the following methods:

    Preview — ThedeleteAtTime anddeleteAfterDuration fields

    This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.

    • To delete the reservation at a specific date and time, make aPOSTrequest to thebeta.reservations.insert method.In the request body, include thedeleteAtTime field.

      POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations{"deleteAtTime": "DELETE_AT_TIME",  "name": "RESERVATION_NAME",  "specificReservation": {    "count": "NUMBER_OF_VMS",    "instanceProperties": {      "machineType": "MACHINE_TYPE"    }  }}

      ReplaceDELETE_AT_TIME with a date and timeformatted as anRFC 3339 timestamp, whichmust be as follows:

      YYYY-MM-DDTHH:MM:SSOFFSET

      Replace the following:

      • YYYY-MM-DD: a date formatted as a 4-digityear, 2-digit month, and a 2-digit day of the month, separatedby hyphens (-).

      • HH:MM:SS: a time formatted as a 2-digit hourusing a 24-hour time, 2-digit minutes, and 2-digit seconds,separated by colons (:).

      • OFFSET: the time zone formatted as an offsetofCoordinated Universal Time (UTC).For example, to use the Pacific Standard Time (PST), specify-08:00. Alternatively, to use no offset, specifyZ.

    • To delete the reservation after a specific duration, make aPOSTrequest to thebeta.reservations.insert method.In the request body, include thedeleteAfterDuration field.

      POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations{"deleteAfterDuration": {    "seconds": "DELETE_AFTER_DURATION"  },  "name": "RESERVATION_NAME",  "specificReservation": {    "count": "NUMBER_OF_VMS",    "instanceProperties": {      "machineType": "MACHINE_TYPE"    }  }}

      ReplaceDELETE_AFTER_DURATION with a duration inseconds. For example, specify86400 for 86,400 seconds (1 day).

Troubleshooting

Learn how totroubleshoot reservation creation.

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 2025-12-15 UTC.