Create a shared reservation Stay organized with collections Save and categorize content based on your preferences.
This document explains how to create shared reservations, which are reservationsshared across multiple projects, and manage which projects in your organizationcan consume the shared reservations.
A shared reservation can be used by the project that hosts the reservation(owner project) and by the projects the reservation is shared with (consumerprojects). Use shared reservations if your organization has multiple projectsthat need virtual machine (VM) instances with the same properties reserved.By using shared reservations, you can improve the utilization of yourreservations and reduce the number of reservations that you need to create andmanage. To learn 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 only be used by a single project, seeCreate a reservation for a single project.
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.
Before you begin
- Review therequirements andrestrictions for reservations.
- Review thequota requirements andrestrictions for shared reservations.
- Make sure the project you use to create shared reservations has been addedto the allowlist for theShared Reservations Owner Projects(
compute.sharedReservationsOwnerProjects) organization policyconstraint by an organization policy administrator. This allowlist is empty bydefault, so you can't create shared reservations until your organizationgrants this permission to one or more projects. For more details on viewingand editing the organization policy constraint, seeAllowing and restricting projects fromcreating and modifying shared reservations in this document. - If you haven't already, set upauthentication. Authentication verifies your identity for access to Google Cloud services and APIs. To run code or samples from a local development environment, you can authenticate to Compute Engine by selecting one of the following options:
Select the tab for how you plan to use the samples on this page:
Console
When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.
gcloud
Install the Google Cloud CLI. After installation,initialize the Google Cloud CLI by running the following command:
gcloudinit
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.- Set a default region and zone.
Terraform
To use the Terraform samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Go
To use the Go samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Java
To use the Java samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Node.js
To use the Node.js samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
Python
To use the Python samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.If you're using a local shell, then create local authentication credentials for your user account:
gcloudauthapplication-defaultlogin
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
For more information, see Set up authentication for a local development environment.
REST
To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Note: If you installed the gcloud CLI previously, make sure you have the latest version by runninggcloud components update.For more information, seeAuthenticate for using REST in the Google Cloud authentication documentation.
Required roles
To get the permissions that you need to create shared reservations, ask your administrator to grant you the following IAM roles:
- Compute Admin (
roles/compute.admin) on the project - To view and edit organization policies:Organization Policy Administrator (
roles/orgpolicy.policyAdmin) on the organization
For more information about granting roles, seeManage access to projects, folders, and organizations.
These predefined roles contain the permissions required to create shared reservations. To see the exact permissions that are required, expand theRequired permissions section:
Required permissions
The following permissions are required to create shared reservations:
compute.reservations.createon the project- To view organization policies:
orgpolicy.policy.geton the organization - To edit organization policies:
orgpolicy.policy.seton the organization - To specify an instance template:
compute.instanceTemplates.useReadOnlyon the instance template
You might also be able to get these permissions withcustom roles or otherpredefined roles.
Best practices
When creating shared reservations, the following best practices are recommended.By following them, you can help optimize the manageability and utilization ofshared reservations in your organization.
- Have the owner project create the shared reservation but not consume it.
- To spread spendings across projects, it's recommended to only have consumer projects consume a shared reservation. The owner project should only be used to create the shared reservation.
- When creating a shared reservation, the owner project must have sufficient quota for the total resources to reserve. Then, after the reservation is created, the owner project must have quota for any reserved resources that it wants to consume. For more information, see Additional quota requirements for shared reservations.
- Minimize the number of projects in your organization that you allow to create shared reservations. You can control this through the Shared Reservations Owner Projects (
compute.sharedReservationsOwnerProjects) organization policy constraint.- You can only list the reservations created by each project. This means that shared reservations are only listed in the owner project—you cannot list the reservations shared with each project or list all shared reservations in each organization—so having only a few owner projects makes it easier to monitor and manage your shared reservations.
- Limit the sharing of a shared reservation to a few projects only to manage the quota of your reserved resources more easily.
- For more information, seeAllow and restrict projects from creating and modifying shared reservations.
- Minimize the number of separate shared reservations with identical VM properties.
- An organization can have up to 100 shared reservations for each unique combination ofVM properties. As a result, minimizing the number of shared reservations with identical VM properties that you create helps mitigate this limit.
- Having fewer shared reservations improves manageability.
- Only share reservations between projects with the same Cloud Billing account.
- Limit each shared reservation to only be shared with consumer projects that have the same Cloud Billing account as the owner project. This makes it easier for you to see if a reservation was consumed and how it was billed.Caution: If you have a shared reservation and also have CUD sharing enabled for your commitment's Cloud Billing account, then Google recommends that you share your reservation only with projects that are linked to the commitment's Cloud Billing account. Otherwise, when projects outside the Cloud Billing account consume that shared reservation, their usage won't be eligible for this Cloud Billing account's shared resource-based CUDs and will be charged at on-demand rates.
- For future reservation requests, carefully review the total count of VMs that you request.
- If you are creating afuture reservation request, ensure that you request atotal count of VMs that accounts for all of the following:
- All matching reserved VMs that will already exist at the future date.
- All matching unreserved VMs that will already exist at the future date.
- Any matching unused on-demand reservations that will already exist at the future date.
- The increase in usage that you want to reserve at the future date.
For example, suppose you need 10 additional VMs at the future date and you'll already have the following resources at the future date:
- 40 matching reserved VMs
- 50 matching unreserved VMs
or
- 40 matching reserved VMs
- 50 matching unused on-demand reservations
Because your existing usage at the future date already adds up to 90 matching VMs and reservations, and you need an additional ten VMs, you must specify a total count of
Note: If you create additional on-demand reservations after submitting the future reservation request and before the future date, then those are counted toward your total count.100in your future reservation request.
If after the future date, you add more on-demand reservations, then those reservations are added on top of the previous total count. For example, if after the future date, you reserve another ten VMs, then you have 110 reservations.For more information, see Count and provision reserved resources.
- If you are creating afuture reservation request, ensure that you request atotal count of VMs that accounts for all of the following:
Allow and restrict projects from creating and modifying shared reservations
By default, no projects are allowed to create or modify shared reservationsin an organization. Add projects to theShared Reservations Owner Projects (compute.sharedReservationsOwnerProjects) organization policy constraintto allow them to create and modify shared reservations. For more informationabout organization policy constraints, seeIntroduction to the Organization Policy Service.
Use the following steps to view and edit theShared Reservations Owner Projects (compute.sharedReservationsOwnerProjects)organization policy constraint.
View the shared reservations organization policy constraint
To see which projects are allowed to create and modify shared reservations,use the Google Cloud console or gcloud CLI.
Console
Follow the steps forViewing organization policiesusing theShared Reservations Owner Projects constraint.
gcloud
To see which projects thecompute.sharedReservationsOwnerProjectsconstraint allows to create and modify shared reservations:
Download the policy for your organization as a file named
policy.yaml,using thegcloud resource-manager org-policies describecommand:gcloud resource-manager org-policies describe compute.sharedReservationsOwnerProjects --organization=ORGANIZATION_ID > policy.yaml
ReplaceORGANIZATION_ID with theorganization IDof your organization.
Use a text editor to open the
policy.yamlfile and view thecompute.sharedReservationsOwnerProjectsconstraint. The projectsthat are allowed to create and modify shared reservations are listedunder itsallowedValues:...constraint: constraints/compute.sharedReservationsOwnerProjectslistPolicy: allowedValues: - projects/PROJECT_NUMBER_1 - projects/PROJECT_NUMBER_2 - projects/PROJECT_NUMBER_3...wherePROJECT_NUMBER_1,PROJECT_NUMBER_2, andPROJECT_NUMBER_3 are theproject numbersof the only projects in your organization that are allowed tocreate shared reservations.
Optional: Delete the
policy.yamlfile.If you are using a Linux or macOS terminal, use the following command:
rm policy.yaml
If you are using a Windows terminal, use the following command:
del policy.yaml
Edit the shared reservations organization policy constraint
To edit which projects are allowed to create and modify shared reservations,use the Google Cloud console or gcloud CLI.
Console
Follow the steps forCustomizing policies for list constraintsusing theShared Reservations Owner Projects constraint.
Note: You must specify theproject number(not project ID) for each project that you want to allow to createshared reservations.gcloud
To edit which projects thecompute.sharedReservationsOwnerProjectsconstraint allows to create and modify shared reservations,use one of the following methods:
Togrant permission to a single project to create and modifyshared reservations, use the
gcloud resource-manager org-policies allowcommand.You can repeat this command for each project that you want to grantthis permission to.gcloud resource-manager org-policies allow compute.sharedReservationsOwnerProjects projects/PROJECT_NUMBER \ --organization=ORGANIZATION_IDReplace the following:
- PROJECT_NUMBER: theproject number(not project ID) of a project in your organization that you want toallow to create and modify shared reservations.
- ORGANIZATION_ID: theorganization IDof your organization.
Togrant or revoke the permissions for multiple projects tocreate and modify shared reservations, replace the organizationpolicy constraint:
To download the policy for your organization as a file named
policy.yaml,use thegcloud resource-manager org-policies describecommand:gcloud resource-manager org-policies describe compute.sharedReservationsOwnerProjects --organization=ORGANIZATION_ID > policy.yaml
ReplaceORGANIZATION_ID with theorganization IDof your organization.
Use a text editor to modify the
policy.yamlfile so that thecompute.sharedReservationsOwnerProjectsconstraint lists all of theprojects that you want to be allowed to create and modify sharedreservations under itsallowedValues.- For each project that you want to grant the permission to createand modify shared reservations, add the project in a new line under
allowedValues. - For each project that you want to revoke the permission to createand modify shared reservations, delete the line for that project.
When you are finished, make sure the
policy.yamlfile lookssimilar to the following:...constraint: constraints/compute.sharedReservationsOwnerProjectslistPolicy: allowedValues: - projects/PROJECT_NUMBER_1 - projects/PROJECT_NUMBER_2 - projects/PROJECT_NUMBER_3...wherePROJECT_NUMBER_1,PROJECT_NUMBER_2, andPROJECT_NUMBER_3 are theproject numbers(not project IDs) of all of the projects in your organization thatyou want to be allowed to create and modify shared reservations.
- For each project that you want to grant the permission to createand modify shared reservations, add the project in a new line under
Save the
policy.yamlfile and close the text editor.To update the policy for your organization with your changes, use the
gcloud resource-manager org-policies set-policycommand:gcloud resource-manager org-policies set-policy --organization=ORGANIZATION_ID policy.yamlReplaceORGANIZATION_ID with theorganization IDof your organization.
Optional: Delete the
policy.yamlfile.If you are using a Linux or macOS terminal, use the following command:
rm policy.yamlIf you are using a Windows terminal, use the following command:
del policy.yaml
You might need to wait a few minutes for the edit to take effect.
Create a shared reservation
This section explains how to create shared reservations. After you create ashared reservation, it can be modified only by the owner project, but theresources for a shared reservation can be consumed by the owner project or anyconsumer projects.
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 shared reservation. By using an instance template, you candefine the properties of a reservation and the VMs that can consume thereservation in the same place. However, because templates areproject-specific, you can't use the same template to create VMs that canconsume the reservation outside of the project that created the reservation.For the projects the reservation is shared with, you must create similartemplates in those projects or create VMs by specifying properties directly.
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.
This section explains how to directly define the properties of a sharedreservation. This method requires you to manually ensure that the propertiesof your VMs and reservations matchexactly—anymismatched properties prevent consumption.
By default, a reservation can be automatically consumed by any VMs withproperties that match it. If you want to control reservationconsumption, do one or more of the following:
Create a reservation that can only be consumed by VMs that specificallytarget it, as explained in the following sections in this document.Then,configure VMs to consume that specific reservation.
Specify an instance template
Before creating a reservation by specifying an instance template, make sure ofthe following:
An instance template contains project-specific settings, so you can onlyaccess and use an instance template within the same project. If you create ashared reservation by specifying an instance template, then you can't usethe same template to create VMs that can consume the reservation outside ofthe project that created the reservation.
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 zone
us-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.
To create a shared reservation by specifying an instance template, select oneof the following options:
Console
In the Google Cloud console, go to theReservations page.
TheReservations page appears.
ClickCreate reservation.
TheCreate a reservation page appears.
ForName, enter a name for your reservation.
ForRegion andZone, select where you want to reserve resources.
In theShare type section, do the following:
To specify a shared reservation, selectShared.
ClickAdd projects, andthen select the projects from the current project's organizationthat you want to share the reservation with. You can select up to100 consumer projects.
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.
In theUse with VM instance section, select one of the followingoptions:
To allow matching VM instances to automatically use thisreservation, selectUse reservation automatically if it's notalready selected.
To consume this reservation's resources only when creating matchingVMs that specifically target this reservation by name, selectSelect specific reservation.
Note: If your instance template specifies an A3 Mega, A3 High, orA3 Edge machine type, then you must selectSelect specific reservation. Otherwise, you encounter errors.
ForNumber of VM instances, enter the number of VMs that you want toreserve.
In theMachine configuration section, selectUse instance template, and then select the instance template ofyour choice. If you select a regional instance template, then you canonly reserve resources within the same region as the template's region.
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.
To create the reservation, clickCreate.
TheReservations page opens. Creating the shared reservation mighttake up to a minute to complete.
gcloud
To create a shared reservation, use thegcloud compute reservations create commandwith the--share-setting=projects and--share-with flags.
To create a shared reservation by specifying an instance template andwithout including any optional flags, run the following command:
gcloud compute reservations createRESERVATION_NAME \ --share-setting=projects \ --share-with=CONSUMER_PROJECT_IDS \ --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \ --vm-count=NUMBER_OF_VMS \ --zone=ZONEReplace 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.CONSUMER_PROJECT_IDS: a comma-separated list ofIDs of projectsthat can consume this reservation—for example,project-1,project-2. You can include up to 100 consumer projects.These projects must be in the same organization as the owner project.Don't include the owner project. By default, it's already allowed toconsume the reservation.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.ReplaceREGIONwith 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, then you must include the--require-specific-reservationflag.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 by specifying a global instancetemplate in zoneus-central1-a, share the reservation with projectsproject-1 andproject-2, and reserve ten VMs that each use an N2predefined machine type with 4 vCPUs, run the following command:
gcloud compute reservations create my-reservation \ --share-setting=projects \ --share-with=project-1,project-2 \ --source-instance-template=projects/example-project/global/example-instance-template \ --vm-count=10 \ --zone=us-central1-aOptionally, 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 \--require-specific-reservation \ --share-setting=projects \ --share-with=CONSUMER_PROJECT_IDS \ --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \ --vm-count=NUMBER_OF_VMS \ --zone=ZONETo 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 \--reservation-sharing-policy=ALLOW_ALL \ --share-setting=projects \ --share-with=CONSUMER_PROJECT_IDS \ --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \ --vm-count=NUMBER_OF_VMS \ --zone=ZONETo enable Compute Engine toautomatically delete the reservation,select one of the following methods:
Preview — The
--delete-at-timeand--delete-after-durationflagsThis 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 the
gcloud beta compute reservations createcommandwith the--delete-at-timeflag.gcloud beta compute reservations createRESERVATION_NAME \--delete-at-time=DELETE_AT_TIME \ --share-setting=projects \ --share-with=CONSUMER_PROJECT_IDS \ --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \ --vm-count=NUMBER_OF_VMS \ --zone=ZONEReplace
DELETE_AT_TIMEwith a date and timeformatted as anRFC 3339 timestamp, whichmust be as follows:YYYY-MM-DDTHH:MM:SSOFFSETReplace 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 the
gcloud beta compute reservations createcommandwith the--delete-after-durationflag.gcloud beta compute reservations createRESERVATION_NAME \--delete-after-duration=DELETE_AFTER_DURATION \ --share-setting=projects \ --share-with=CONSUMER_PROJECT_IDS \ --source-instance-template=projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME \ --vm-count=NUMBER_OF_VMS \ --zone=ZONEReplace
DELETE_AFTER_DURATIONwith a duration indays, hours, minutes, or seconds. For example, specify30mfor 30minutes, or1d2h3m4sfor 1 day, 2 hours, 3 minutes, and 4 seconds.
Go
import("context""fmt""io"computepb"cloud.google.com/go/compute/apiv1/computepb""google.golang.org/protobuf/proto")// Creates shared reservation from given template in particular zonefunccreateSharedReservation(wio.Writer,clientClientInterface,projectID,baseProjectId,zone,reservationName,sourceTemplatestring)error{// client, err := compute.NewReservationsRESTClient(ctx)// projectID := "your_project_id". Destination of sharing.// baseProjectId := "your_project_id2". Project where the reservation will be created.// zone := "us-west3-a"// reservationName := "your_reservation_name"// sourceTemplate: existing template path. Following formats are allowed:// - projects/{project_id}/global/instanceTemplates/{template_name}// - projects/{project_id}/regions/{region}/instanceTemplates/{template_name}// - https://www.googleapis.com/compute/v1/projects/{project_id}/global/instanceTemplates/instanceTemplate// - https://www.googleapis.com/compute/v1/projects/{project_id}/regions/{region}/instanceTemplates/instanceTemplatectx:=context.Background()shareSettings:=map[string]*computepb.ShareSettingsProjectConfig{projectID:{ProjectId:proto.String(projectID)},}req:=&computepb.InsertReservationRequest{Project:baseProjectId,ReservationResource:&computepb.Reservation{Name:proto.String(reservationName),Zone:proto.String(zone),SpecificReservation:&computepb.AllocationSpecificSKUReservation{Count:proto.Int64(2),SourceInstanceTemplate:proto.String(sourceTemplate),},ShareSettings:&computepb.ShareSettings{ProjectMap:shareSettings,ShareType:proto.String("SPECIFIC_PROJECTS"),},},Zone:zone,}op,err:=client.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create reservation: %w",err)}ifop!=nil{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.InsertReservationRequest;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.Operation.Status;importcom.google.cloud.compute.v1.Reservation;importcom.google.cloud.compute.v1.ReservationsClient;importcom.google.cloud.compute.v1.ShareSettings;importcom.google.cloud.compute.v1.ShareSettingsProjectConfig;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateSharedReservation{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// The ID of the project where you want to reserve resources// and where the instance template exists.// By default, no projects are allowed to create or modify shared reservations// in an organization. Add projects to the Shared Reservations Owner Projects// (compute.sharedReservationsOwnerProjects) organization policy constraint// to allow them to create and modify shared reservations.// For more information visit this page:// https://cloud.google.com/compute/docs/instances/reservations-shared#shared_reservation_constraintStringprojectId="YOUR_PROJECT_ID";// Zone in which to reserve resources.Stringzone="us-central1-a";// Name of the reservation to be created.StringreservationName="YOUR_RESERVATION_NAME";// The URI of the global instance template to be used for creating the reservation.StringinstanceTemplateUri=String.format("projects/%s/global/instanceTemplates/%s",projectId,"YOUR_INSTANCE_TEMPLATE_NAME");// Number of instances for which capacity needs to be reserved.intvmCount=3;createSharedReservation(projectId,zone,reservationName,instanceTemplateUri,vmCount);}// Creates a shared reservation with the given name in the given zone.publicstaticStatuscreateSharedReservation(StringprojectId,Stringzone,StringreservationName,StringinstanceTemplateUri,intvmCount)throwsExecutionException,InterruptedException,TimeoutException,IOException{// 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()){ShareSettingsshareSettings=ShareSettings.newBuilder().setShareType(String.valueOf(ShareSettings.ShareType.SPECIFIC_PROJECTS))// The IDs of projects that can consume this reservation. You can include up to// 100 consumer projects. These projects must be in the same organization as// the owner project. Don't include the owner project.// By default, it is already allowed to consume the reservation..putProjectMap("CONSUMER_PROJECT_1",ShareSettingsProjectConfig.newBuilder().build()).putProjectMap("CONSUMER_PROJECT_2",ShareSettingsProjectConfig.newBuilder().build()).build();ReservationreservationResource=Reservation.newBuilder().setName(reservationName).setZone(zone).setSpecificReservationRequired(true).setShareSettings(shareSettings).setSpecificReservation(AllocationSpecificSKUReservation.newBuilder().setCount(vmCount).setSourceInstanceTemplate(instanceTemplateUri).build()).build();InsertReservationRequestrequest=InsertReservationRequest.newBuilder().setProject(projectId).setZone(zone).setReservationResource(reservationResource).build();Operationresponse=reservationsClient.insertAsync(request).get(3,TimeUnit.MINUTES);if(response.hasError()){thrownewError("Reservation creation failed!!"+response);}returnresponse.getStatus();}}}Node.js
// Import the Compute libraryconstcomputeLib=require('@google-cloud/compute');constcompute=computeLib.protos.google.cloud.compute.v1;/** * TODO(developer): Uncomment reservationsClient and zoneOperationsClient before running the sample. */// Instantiate a reservationsClient// reservationsClient = new computeLib.ReservationsClient();// Instantiate a zoneOperationsClient// zoneOperationsClient = new computeLib.ZoneOperationsClient();/** * TODO(developer): Update 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.constreservationName='reservation-01';// The number of VMs to reserve.constvmsNumber=3;// The name of an existing instance template.constinstanceTemplateName='global-instance-template-name';// The location of the instance template.constlocation='global';asyncfunctioncallCreateComputeSharedReservation(){// 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 share settings. Share reservation with one customer project.constshareSettings=newcompute.ShareSettings({shareType:'SPECIFIC_PROJECTS',projectMap:{// The IDs of projects that can consume this reservation. You can include up to 100 consumer projects.// These projects must be in the same organization as the owner project.// Don't include the owner project. By default, it is already allowed to consume the reservation.consumer_project_id:{projectId:'consumer_project_id',},},});// Create a reservation.constreservation=newcompute.Reservation({name:reservationName,specificReservation,specificReservationRequired:true,shareSettings,});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.`);returnresponse;}returnawaitcallCreateComputeSharedReservation();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_shared_reservation(project_id:str,zone:str="us-central1-a",reservation_name="your-reservation-name",shared_project_id:str="shared-project-id",)->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. shared_project_id (str): The ID of the project that the reservation is shared with. Returns: Reservation object that represents the new reservation. """instance_properties=compute_v1.AllocationSpecificSKUAllocationReservedInstanceProperties(machine_type="n1-standard-1",# Optional. Specifies amount of local ssd to reserve with each instance.local_ssds=[compute_v1.AllocationSpecificSKUAllocationAllocatedInstancePropertiesReservedDisk(disk_size_gb=375,interface="NVME"),],)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,),share_settings=compute_v1.ShareSettings(share_type="SPECIFIC_PROJECTS",project_map={shared_project_id:compute_v1.ShareSettingsProjectConfig(project_id=shared_project_id)},),)# 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)shared_project=next(iter(reservation.share_settings.project_map.values()))print("Name: ",reservation.name)print("STATUS: ",reservation.status)print("SHARED PROJECT: ",shared_project)# Example response:# Name: your-reservation-name# STATUS: READY# SHARED PROJECT: project_id: "123456789012"returnreservationREST
To create a shared reservation, make aPOST request to thereservations.insert method.In the request body, include the following:
The
projectMapfield.The
shareTypefield set toSPECIFIC_PROJECTS.
For example, to create a shared reservation by specifying an instancetemplate without including any optional fields, and share the reservationwith two consumer projects, make the followingPOST request:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{ "name": "RESERVATION_NAME", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "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.CONSUMER_PROJECT_ID_1andCONSUMER_PROJECT_ID_2: theIDs of projectsthat can consume this reservation. You can include up to 100 consumerprojects. These projects must be in the same organization as the ownerproject. Don't include the owner project. By default, it is alreadyallowed to consume the reservation.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.ReplaceREGIONwith 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, you must include thespecificReservationRequiredfieldin 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, and share the reservation withprojectsproject-1 andproject-2, make the followingPOST request:
POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations{ "name": "my-reservation", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "project-1": { "projectId": "project-1" }, "project-2": { "projectId": "project-2" } } }, "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 the
specificReservationRequiredfield in therequest body, and set the field totrue.For example, to create a specific reservation by specifying an instancetemplate, and share the reservation with two consumer projects, make arequest as follows:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{ "name": "RESERVATION_NAME", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "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 the
serviceShareTypefield and setit toALLOW_ALL.POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{ "name": "RESERVATION_NAME","reservationSharingPolicy": { "serviceShareType": "ALLOW_ALL" }, "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "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 — The
deleteAtTimeanddeleteAfterDurationfieldsThis 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 a
POSTrequest to thebeta.reservations.insertmethod.In the request body, include thedeleteAtTimefield.For example, to create a reservation by specifying an instancetemplate, auto delete the reservation at a specific date and time,and share the reservation with two consumer projects, make a requestas follows:
POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations{"deleteAtTime": "DELETE_AT_TIME", "name": "RESERVATION_NAME", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "specificReservation": { "count": "NUMBER_OF_VMS", "sourceInstanceTemplate": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME" }}Replace
DELETE_AT_TIMEwith a date and timeformatted as anRFC 3339 timestamp, whichmust be as follows:YYYY-MM-DDTHH:MM:SSOFFSETReplace 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 a
POSTrequest to thebeta.reservations.insertmethod.In the request body, include thedeleteAfterDurationfield.For example, to create a reservation by specifying an instancetemplate, auto delete the reservation after a specific duration, andshare the reservation with two consumer projects, make a request asfollows:
POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations{"deleteAfterDuration": { "seconds": "DELETE_AFTER_DURATION" }, "name": "RESERVATION_NAME", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "specificReservation": { "count": "NUMBER_OF_VMS", "sourceInstanceTemplate": "projects/PROJECT_ID/LOCATION/instanceTemplates/INSTANCE_TEMPLATE_NAME" }}Replace
DELETE_AFTER_DURATIONwith a duration inseconds. For example, specify86400for 86,400 seconds (1 day).
Specify an existing VM
You can only create a shared reservation based on an existing VM in the sameproject and zone as the 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:
Create and use an instance template as follows:
Create an instance template based on the reference VMwithout overriding the reference VM's properties.
Note: You can't create an instance template based on the reference VMoutside of the VM's project. For the projects that the reservation isshared with, you must create similar instance templates in thoseprojects.Create VMs using the newly-created template by doing one or both of thefollowing:
Create a VM with properties thatexactly match the reference VM asfollows:
In the owner project,create a VM based on the reference VMwithout changing the properties of the VM that you're creating.
In the consumer projects, create a VM while manually ensuring that itsproperties and the reference VM's properties match.
To create a shared reservation that uses the properties of an existing VM, dothe following:
In the Google Cloud console, go to theReservations page.
On theOn-demand reservations tab (default), clickCreate reservation.
TheCreate a reservation page opens.
ForName, enter a name for your reservation.
ForRegion andZone, select where you want to reserve resources.
In theShare type section, do the following:
To specify a shared reservation, selectShared.
ClickAdd projects, and thenselect the projects from the current project's organization that youwant to share the reservation with. You can select up to 100 consumerprojects.
In theUse with VM instance section, select one of the followingoptions:
To allow matching VMs to automatically consume this reservation, selectUse reservation automatically if it's not already selected.
To consume this reservation's resources only when creating matchingVMs that specifically target this reservation by name, selectSelect specific reservation.
Note: If the reference VM specifies an A3 Mega, A3 High, or A3 Edgemachine type, then you must selectSelect specific reservation.Otherwise, you can't create the reservation.
ForNumber of VM instances, enter the number of VMs that you want toreserve.
In theMachine configuration section, do the following:
SelectUse existing VM.
ForExisting VM, select the VM which properties you want to useto create the reservation.
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.
To create the reservation, clickCreate.
TheReservations page opens. Creating the reservation might take up to aminute to complete.
Specify properties directly
To create a shared reservation by specifying properties directly, select one ofthe following options:
Console
In the Google Cloud console, go to theReservations page.
On theOn-demand reservations tab (default), clickCreate reservation.
ClickCreate reservation.
TheCreate a reservation page appears.
ForName, enter a name for your reservation.
ForRegion andZone, select where you want to reserve resources.
In theShare type section, do the following:
To specify a shared reservation, selectShared.
ClickAdd projects, andthen select the projects from the current project's organizationthat you want to share the reservation with. You can select up to100 consumer projects.
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.
In theUse with VM instance section, select one of the followingoptions:
To allow matching VMs to automatically consume this reservation,selectUse reservation automatically (default).
To consume this reservation's resources only when creating matchingVMs that specifically target this reservation by name, selectSelect specific reservation.
Note: If you want to specify an A3 Mega, A3 High, or A3 Edgemachine type in the reservation, then you must selectSelect specific reservation. Otherwise, you encounter errors.
ForNumber of VM instances, enter the number of VMs that you want toreserve.
In theMachine configuration section, selectSpecify machine type, and then specify the following:
ForMachine family,Series, andMachine type, select a machine family, series, and machine type.
Optional: To specify a minimum CPU platform or attach GPUs to N1 VMs, do the following:
To expand theCPU Platform and GPU section, click the expander arrow.
Optional: To specify a minimum CPU platform, forCPU Plaform, select an option.
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.
Optional: To attach Local SSD disks to amachine type that doesn't include Local SSD disks by default, do the following:
ForNumber of disks, select the number of Local SSD disks to attach.
ForInterface type, select the disk interface for the Local SSD disks.
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.
To create the reservation, clickCreate.
TheReservations page opens. Creating the shared reservation mighttake up to a minute time to complete.
gcloud
To create a shared reservation, use thegcloud compute reservations create commandwith the--share-setting=projects and--share-with flags.
To create a shared reservation by specifying properties directly and withoutincluding any optional flags, run the following command:
gcloud compute reservations createRESERVATION_NAME \ --machine-type=MACHINE_TYPE \ --share-setting=projects \ --share-with=CONSUMER_PROJECT_IDS \ --vm-count=NUMBER_OF_VMS \ --zone=ZONEReplace 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-reservationflag.This indicates that only VMs that specifically target the reservationcan consume it. For more information, seeConsume VMs from a specific reservation.CONSUMER_PROJECT_IDS: a comma-separated list ofIDs of projectsthat can consume this reservation—for example,project-1,project-2. You can include up to 100 consumer projects.These projects must be in the same organization as the owner project.Don't include the owner project. By default, it is already allowed toconsume the 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, and share thereservation with projectsproject-1 andproject-2, run the followingcommand:
gcloud compute reservations create my-reservation \ --machine-type=n2-standard-4 \ --share-setting=projects \ --share-with=project-1,project-2 \ --vm-count=10 \ --zone=us-central1-aOptionally, 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 \ --share-setting=projects \ --share-with=CONSUMER_PROJECT_IDS \ --vm-count=NUMBER_OF_VMS \ --zone=ZONEReplace the following:
NUMBER_OF_ACCELERATORS: the number of GPUs to addper reserved VM.ACCELERATOR_TYPE: asupported GPU model for N1 VMs. Ensurethat your chosen GPU modelis available in the zonewhere you want to reserve resources. Otherwise, creating thereservation fails.
To attach Local SSD disks to amachine type that doesn't include Local SSD disks by default,include the
--local-ssdflag. 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=ZONEReplace 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:
nvmeFor 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-platformflag.gcloud compute reservations createRESERVATION_NAME \ --machine-type=MACHINE_TYPE \--min-cpu-platform="MIN_CPU_PLATFORM" \ --share-setting=projects \ --share-with=CONSUMER_PROJECT_IDS \ --vm-count=NUMBER_OF_VMS \ --zone=ZONEReplace
MIN_CPU_PLATFORMwith 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 \ --share-setting=projects \ --share-with=CONSUMER_PROJECT_IDS \ --vm-count=NUMBER_OF_VMS \ --zone=ZONETo 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 \ --share-setting=projects \ --share-with=CONSUMER_PROJECT_IDS \ --vm-count=NUMBER_OF_VMS \ --zone=ZONETo enable Compute Engine toautomatically delete the reservation,select one of the following methods:
Preview — The
--delete-at-timeand--delete-after-durationflagsThis 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 the
gcloud beta compute reservations createcommandwith the--delete-at-timeflag.gcloud beta compute reservations createRESERVATION_NAME \--delete-at-time=DELETE_AT_TIME \ --machine-type=MACHINE_TYPE \ --share-setting=projects \ --share-with=CONSUMER_PROJECT_IDS \ --vm-count=NUMBER_OF_VMS \ --zone=ZONEReplace
DELETE_AT_TIMEwith a date and timeformatted as anRFC 3339 timestamp, whichmust be as follows:YYYY-MM-DDTHH:MM:SSOFFSETReplace 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 the
gcloud beta compute reservations createcommandwith the--delete-after-durationflag.gcloud beta compute reservations createRESERVATION_NAME \--delete-after-duration=DELETE_AFTER_DURATION \ --machine-type=MACHINE_TYPE \ --share-setting=projects \ --share-with=CONSUMER_PROJECT_IDS \ --vm-count=NUMBER_OF_VMS \ --zone=ZONEReplace
DELETE_AFTER_DURATIONwith a duration indays, hours, minutes, or seconds. For example, specify30mfor 30minutes, or1d2h3m4sfor 1 day, 2 hours, 3 minutes, and 4 seconds.
Terraform
To create a reservation, use thegoogle_compute_reservation Terraform resource.To specify a shared reservation, define theshare_settings block:
- Set the
share_typefield toSPECIFIC_PROJECTS. - In the
project_mapblock, specify theproject IDsof the projects that you want to share this reservation with.
For more information about how to use Terraform, seeUsing Terraform with Google Cloud.
REST
To create a shared reservation, make aPOST request to thereservations.insert method.In the request body, include the following:
The
projectMapfield.The
shareTypefield set toSPECIFIC_PROJECTS.
For example, to create a shared reservation without including any optionalfields and share the reservation with two consumer projects, make thefollowingPOST request:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{ "name": "RESERVATION_NAME", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "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.CONSUMER_PROJECT_ID_1andCONSUMER_PROJECT_ID_2: theIDs of projectsthat can consume this reservation. You can include up to 100 consumerprojects. These projects must be in the same organization as the ownerproject. Don't include the owner project. By default, it is alreadyallowed to consume the reservation.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 thespecificReservationRequiredfield inthe request body, and set the field totrue. This indicates that onlyVMs that specifically target the reservation can consume it.
For example, to create a reservation by specifying a global instancetemplate in zoneus-central1-a, share the reservation with projectsproject-1 andproject-2, and reserve ten VMs that each use an N2predefined machine type with 4 vCPUs, make the followingPOSTrequest:
POST https://compute.googleapis.com/compute/v1/projects/example-project/zones/us-central1-a/reservations{ "name": "my-reservation", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "project-1": { "projectId": "project-1" }, "project-2": { "projectId": "project-2" } } }, "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 the
guestAcceleratorsfield in the request body.For example, to create a reservation shared with two consumer projects,and attach GPUs to any reserved N1 VMs, make a request as follows:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{ "name": "RESERVATION_NAME", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "specificReservation": { "count": "NUMBER_OF_VMS", "instanceProperties": {"guestAccelerators": [ { "acceleratorCount":NUMBER_OF_ACCELERATORS, "acceleratorType": "ACCELERATOR_TYPE" } ], "machineType": "MACHINE_TYPE" } }}Replace the following:
NUMBER_OF_ACCELERATORS: the number of GPUs to addper reserved VM.ACCELERATOR_TYPE: asupported GPU model for N1 VMs. Ensurethat your chosen GPU modelis available in the zonewhere you want to reserve resources. Otherwise, creating thereservation fails.
To attach Local SSD disks to amachine type that doesn't include Local SSD disks by default,include the
localSsdsfield 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 while specifying two consumer projects, make a requestas follows:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{ "name": "RESERVATION_NAME", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "specificReservation": { "count": "NUMBER_OF_VMS", "instanceProperties": {"localSsds": [ { "diskSizeGb": "375", "interface": "INTERFACE_TYPE" }, { "diskSizeGb": "375", "interface": "INTERFACE_TYPE" } ], "machineType": "MACHINE_TYPE" } }}Replace
INTERFACE_TYPEwith 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:
NVMEFor the SCSI disk interface:
SCSI
To have the reserved VMs use a specificminimum CPU platforminstead of the zone's default CPU platform, include the
minCpuPlatformfield in the request body.For example, to create a shared reservation while specifying a minimumCPU platform and two consumer projects, make a request as follows:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{ "name": "RESERVATION_NAME", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "specificReservation": { "count": "NUMBER_OF_VMS", "instanceProperties": { "machineType": "MACHINE_TYPE","minCpuPlatform": "MIN_CPU_PLATFORM" } }}Replace
MIN_CPU_PLATFORMwith 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 thatspecifically target this reservationcan consume it, include the
specificReservationRequiredfield in therequest body, and set the field totrue.For example, to create a specific reservation and share it with twoconsumer projects, make a request as follows:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{ "name": "RESERVATION_NAME", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "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 the
serviceShareTypefield and setit toALLOW_ALL.POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/reservations{ "name": "RESERVATION_NAME","reservationSharingPolicy": { "serviceShareType": "ALLOW_ALL" }, "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "specificReservation": { "count": "NUMBER_OF_VMS", "instanceProperties": { "machineType": "MACHINE_TYPE" } }}To enable Compute Engine toautomatically delete the reservation,select one of the following methods:
Preview — The
deleteAtTimeanddeleteAfterDurationfieldsThis 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 a
POSTrequest to thebeta.reservations.insertmethod.In the request body, include thedeleteAtTimefield.For example, to create a reservation while specifying a date andtime to delete a reservation, and share the reservation with twoconsumer projects, make a request as follows:
POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations{"deleteAtTime": "DELETE_AT_TIME", "name": "RESERVATION_NAME", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "specificReservation": { "count": "NUMBER_OF_VMS", "instanceProperties": { "machineType": "MACHINE_TYPE" } }}Replace
DELETE_AT_TIMEwith a date and timeformatted as anRFC 3339 timestamp, whichmust be as follows:YYYY-MM-DDTHH:MM:SSOFFSETReplace 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 a
POSTrequest to thebeta.reservations.insertmethod.In the request body, include thedeleteAfterDurationfield.For example, to create a reservation that Compute Enginedeletes after a specific duration, and share the reservation withtwo consumer projects, make a request as follows:
POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/reservations{"deleteAfterDuration": { "seconds": "DELETE_AFTER_DURATION" }, "name": "RESERVATION_NAME", "shareSettings": { "shareType": "SPECIFIC_PROJECTS", "projectMap": { "CONSUMER_PROJECT_ID_1": { "projectId": "CONSUMER_PROJECT_ID_1" }, "CONSUMER_PROJECT_ID_2": { "projectId": "CONSUMER_PROJECT_ID_2" } } }, "specificReservation": { "count": "NUMBER_OF_VMS", "instanceProperties": { "machineType": "MACHINE_TYPE" } }}Replace
DELETE_AFTER_DURATIONwith a duration inseconds. For example, specify86400for 86,400 seconds (1 day).
Troubleshooting
Learn how totroubleshoot reservation creation.
What's next
Learn how toview your reservations.
Learn how toattach reservations to commitments.
Learn how toconsume reservations.
Learn how tomonitor reservations consumption.
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.