Create instance templates Stay organized with collections Save and categorize content based on your preferences.
This page describes how to create and manageinstance templates.Instance templates let you specify the machine type, boot disk image, network,and other VM properties that you want to use when creating virtual machine(VM) instances.
You can use instance templates to do the following:
- Createindividual VMs.
- Create VMs in amanaged instance group (MIG).
- Create reservations for VMs.
Before you begin
- Read when and why to createdeterministic instance templates.
- Read aboutregional and global instance templates.
- If you include Dynamic Network Interfaces (NICs) in the instance template, review the properties and limitations of Dynamic NICs as described inDynamic NICs. For more information about creating instances with multiple network interfaces, seeCreate VMs with multiple network interfaces.
- 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.
Limitations
- Shared VPC on interfaces other than
nic0for instance templates issupported in gcloud CLI and REST, but not inGoogle Cloud console. - You can't update an existing instance template or change an instancetemplate after it has been created. If an instance template goes out of date, oryou need to make changes to the configuration, create a new instance template.
- If you want to specify an image family in an instance template, you can't usethe Google Cloud console. You can use the Google Cloud CLI orREST instead.
- If you want to specify regional disks instead of zonal disks in an instancetemplate, you can't use the Google Cloud console. You can use theGoogle Cloud CLI or REST instead.
- You can use an instance template to create VMs with a Hyperdisk Balanced boot disk thatis in astorage pool,if the storage pool exists in the same zone that the VM iscreated in. You can't use global instance templates to create VMs with non-bootdisks that are in a storage pool.
Create an instance template
Most of the VM properties that you can specify in a request to create anindividual VM instance can also be specified for an instance template,including any VM metadata, startup scripts, persistent disks, and serviceaccounts. You must specify the machine type, boot disk, and network.
Create a regional or global instance template through theGoogle Cloud console,Google Cloud CLI, or theAPI. To create a globalinstance template, you can also use the Terraform ortheCloud Client Libraries.
Permissions required for this task
To perform this task, you must have the followingpermissions:
- All permissions required to call the
instanceTemplates.insertmethod.
Console
In the Google Cloud console, go to theInstance templates page.
The remaining steps appear in the Google Cloud console.
- Click
Create instance template . - Select theLocation as follows:
- If you want to use the instance template across regions, chooseGlobal.
- If you want to reduce cross-region dependency, chooseRegional.
- If you chose regional, then select theRegion where you want to create your instance template.
For the following fields, either accept the default values or modify them as required. The default values change based on the machine family that you select.
- Select a
Machine type . - To update the boot disk type or image, in the
Boot disk section, clickChange. - To update the network interface or IP address settings, click
Advanced options , then clickNetworking, and then click the network interface you want to edit.
- Select a
Optional: If you chose an image that supports Shielded VM, change the VM'sShielded VM settings:
- ClickAdvanced options, and then click theSecurity tab.
- If you want to disable Secure Boot, clear theTurn on Secure Boot checkbox. Secure Boot helps protect your VM instances against boot-level and kernel-level malware and rootkits. For more information, seeSecure boot.
If you want to disable the virtual trusted platform module (vTPM), clear theTurn on vTPM checkbox. The vTPM enables Measured boot, which validates the VM pre-boot and boot integrity. For more information, seeVirtual Trusted Platform Module (vTPM).
Important: Disabling the vTPM also disables integrity monitoring because integrity monitoring relies on data gathered by Measured boot.If you want to disable integrity monitoring, uncheck theTurn on Integrity Monitoring checkbox. Integrity monitoring lets youn monitor the boot integrity of your Shielded VM instances by using Cloud Monitoring. For more information, seeIntegrity monitoring.
Optional: UnderAdvanced options, click the tabs to further customize your template. For example, you can add up to 15 secondary non-boot disks.
Optional: ClickEquivalent REST to view the REST request body, which includes theJSON representation of your instance template.
ClickCreate to create the template.
gcloud
To create a regional or global instance template, use theinstance-templates create command.For a regional instance template, you must use the--instance-template-region flag to set the region of the template.
Create a regional instance template using the following command.
gcloud compute instance-templates createINSTANCE_TEMPLATE_NAME \ --instance-template-region=REGION
ReplaceREGION with the region where youwant to create the regional instance template.
Create a global instance template using the following command:
gcloud compute instance-templates createINSTANCE_TEMPLATE_NAME
If you don't provide explicit template settings,gcloud compute usesthe following default values:
- Machine type: the machine type—for example,
n1-standard-1 - Image: the latest Debian image
- Boot disk: a new standard boot disk named after the VM
- Network: the default VPC network
- IP address: an ephemeral external IPv4 address
- Stack type:
IPV4_ONLY
You can also explicitly provide these configuration settings. For example:
gcloud compute instance-templates create my-instance-template \ --machine-type=e2-standard-4 \ --image-family=debian-11 \ --image-project=debian-cloud \ --boot-disk-size=250GB
You can add up to 15 secondary non-boot disks. Specify the--create-diskflag for each secondary disk you create. To create secondary disks from apublic or custom image, specify theimage andimage-project propertiesfor each disk in the--create-disk flag. To create a blank disk, don'tinclude these properties. Optionally, include properties for the disksizeandtype. Tospecify regional disks, use thereplica-zones property.
gcloud compute instance-templates createINSTANCE_TEMPLATE_NAME \ --machine-type=MACHINE_TYPE \ --create-disk=image-family=DISK_IMAGE_FAMILY,image-project=DISK_IMAGE_PROJECT,size=SIZE_GB_DISK1 \ --create-disk=device-name=DISK_NAME,type=DISK_TYPE,size=SIZE_GB_DISK2,replica-zones=^:^ZONE:REMOTE_ZONE,boot=false
Tip: When specifyingthe diskreplica-zones parameter, the characters^:^ specify thatthe separation character between values is a colon (:) instead of theexpected comma (,).
Replace the following:
INSTANCE_TEMPLATE_NAME: the name for the templateMACHINE_TYPE: the machine type of the VMsDISK_IMAGE_FAMILY: an image family to use as anon-boot diskFor more information about image families, seebest practices when using image familieson Compute Engine.
You can use instead the flag
--image=IMAGEto specify a specificversion of an image.For blank disks, don't specify the
image-familyorimageproperty.DISK_IMAGE_PROJECT: theimage project that contains the imageFor blank disks, don't specify the
image-projectproperty. For moreinformation on public images, seePublic images.SIZE_GB_DISK1andSIZE_GB_DISK2: the size of each secondary diskDISK_NAME: Optional: the disk name displayed tothe guest OS after the VM is created.DISK_TYPE: Optional: the type of disk to create.If not specified, the default disk type that is used depends on thevalue of the--machine-typeflag.ZONEandREMOTE_ZONE:the zone to create theregional diskin and the zone to replicate it to.For zonal disks, don't include the
replica-zonesproperty.
If you chose an image that supportsShielded VM, you canoptionally change the instance's Shielded VM settings using oneof the following flags:
--no-shielded-secure-boot: turns off Secure BootSecure Boot helps protect your VM instances against boot-level andkernel-level malware and rootkits. For more information, seeSecure Boot.
--no-shielded-vtpm: turns off the virtual trusted platform module(vTPM)The vTPM enables Measured Boot, which validates the VM pre-bootand boot integrity. For more information, seeVirtual Trusted Platform Module (vTPM).
Important: Disabling the vTPM alsodisables integrity monitoring because integrity monitoring relies ondata gathered by Measured Boot.--no-shielded-integrity-monitoring: turns off integrity monitoringIntegrity monitoring lets you monitor the boot integrity of yourShielded VM instances using Cloud Monitoring.For more information, seeIntegrity monitoring.
For a list of all available subcommands and flags, see theinstance-templates reference.
Terraform
To create an instance template, use one of the following resources:
- For a regional instance template, use the
google_compute_region_instance_templateresource. - For a global instance template, use the
google_compute_instance_templateresource.
The following example creates a global instance template:
resource "google_compute_instance_template" "foobar" { name = "my-instance-template" machine_type = "e2-standard-4" disk { source_image = "debian-cloud/debian-11" disk_size_gb = 250 } network_interface { network = "default" # default access config, defining external IP configuration access_config { network_tier = "PREMIUM" } } # To avoid embedding secret keys or user credentials in the instances, Google recommends that you use custom service accounts with the following access scopes. service_account { scopes = [ "https://www.googleapis.com/auth/cloud-platform" ] }}To learn how to apply or remove a Terraform configuration, seeBasic Terraform commands.
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")// createTemplate creates a new instance template with the provided name and a specific instance configuration.funccreateTemplate(wio.Writer,projectID,templateNamestring)error{// projectID := "your_project_id"// templateName := "your_template_name"ctx:=context.Background()instanceTemplatesClient,err:=compute.NewInstanceTemplatesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewInstanceTemplatesRESTClient: %w",err)}deferinstanceTemplatesClient.Close()req:=&computepb.InsertInstanceTemplateRequest{Project:projectID,InstanceTemplateResource:&computepb.InstanceTemplate{Name:proto.String(templateName),Properties:&computepb.InstanceProperties{// The template describes the size and source image of the boot disk// to attach to the instance.Disks:[]*computepb.AttachedDisk{{InitializeParams:&computepb.AttachedDiskInitializeParams{DiskSizeGb:proto.Int64(250),SourceImage:proto.String("projects/debian-cloud/global/images/family/debian-11"),},AutoDelete:proto.Bool(true),Boot:proto.Bool(true),},},MachineType:proto.String("e2-standard-4"),// The template connects the instance to the `default` network,// without specifying a subnetwork.NetworkInterfaces:[]*computepb.NetworkInterface{{Name:proto.String("global/networks/default"),// The template lets the instance use an external IP address.AccessConfigs:[]*computepb.AccessConfig{{Name:proto.String("External NAT"),Type:proto.String(computepb.AccessConfig_ONE_TO_ONE_NAT.String()),NetworkTier:proto.String(computepb.AccessConfig_PREMIUM.String()),},},},},},},}op,err:=instanceTemplatesClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create instance template: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance template created\n")returnnil}Java
importcom.google.cloud.compute.v1.AccessConfig;importcom.google.cloud.compute.v1.AccessConfig.NetworkTier;importcom.google.cloud.compute.v1.AttachedDisk;importcom.google.cloud.compute.v1.AttachedDiskInitializeParams;importcom.google.cloud.compute.v1.GlobalOperationsClient;importcom.google.cloud.compute.v1.InsertInstanceTemplateRequest;importcom.google.cloud.compute.v1.InstanceProperties;importcom.google.cloud.compute.v1.InstanceTemplate;importcom.google.cloud.compute.v1.InstanceTemplatesClient;importcom.google.cloud.compute.v1.NetworkInterface;importcom.google.cloud.compute.v1.Operation;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateInstanceTemplate{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// projectId: project ID or project number of the Cloud project you use.// templateName: name of the new template to create.StringprojectId="your-project-id";StringtemplateName="template-name";createInstanceTemplate(projectId,templateName);}/* Create a new instance template with the provided name and a specific instance configuration. */publicstaticvoidcreateInstanceTemplate(StringprojectId,StringtemplateName)throwsIOException,ExecutionException,InterruptedException,TimeoutException{try(InstanceTemplatesClientinstanceTemplatesClient=InstanceTemplatesClient.create()){StringmachineType="e2-standard-4";StringsourceImage="projects/debian-cloud/global/images/family/debian-11";// The template describes the size and source image of the boot disk// to attach to the instance.AttachedDiskattachedDisk=AttachedDisk.newBuilder().setInitializeParams(AttachedDiskInitializeParams.newBuilder().setSourceImage(sourceImage).setDiskType("pd-balanced").setDiskSizeGb(250).build()).setAutoDelete(true).setBoot(true).build();// The template connects the instance to the `default` network,// without specifying a subnetwork.NetworkInterfacenetworkInterface=NetworkInterface.newBuilder().setName("global/networks/default")// The template lets the instance use an external IP address..addAccessConfigs(AccessConfig.newBuilder().setName("External NAT").setType(AccessConfig.Type.ONE_TO_ONE_NAT.toString()).setNetworkTier(NetworkTier.PREMIUM.toString()).build()).build();InstancePropertiesinstanceProperties=InstanceProperties.newBuilder().addDisks(attachedDisk).setMachineType(machineType).addNetworkInterfaces(networkInterface).build();InsertInstanceTemplateRequestinsertInstanceTemplateRequest=InsertInstanceTemplateRequest.newBuilder().setProject(projectId).setInstanceTemplateResource(InstanceTemplate.newBuilder().setName(templateName).setProperties(instanceProperties).build()).build();// Create the Instance Template.Operationresponse=instanceTemplatesClient.insertAsync(insertInstanceTemplateRequest).get(3,TimeUnit.MINUTES);if(response.hasError()){System.out.println("Instance Template creation failed ! ! "+response);return;}System.out.printf("Instance Template Operation Status %s: %s",templateName,response.getStatus());}}publicstaticvoidcreateInstanceTemplateWithDiskType(StringprojectId,StringtemplateName)throwsIOException,ExecutionException,InterruptedException,TimeoutException{try(InstanceTemplatesClientinstanceTemplatesClient=InstanceTemplatesClient.create();GlobalOperationsClientglobalOperationsClient=GlobalOperationsClient.create()){AttachedDiskdisk=AttachedDisk.newBuilder().setInitializeParams(AttachedDiskInitializeParams.newBuilder().setDiskSizeGb(10).setDiskType("pd-balanced").setSourceImage("projects/debian-cloud/global/images/family/debian-11").build()).setAutoDelete(true).setBoot(true).setType(AttachedDisk.Type.PERSISTENT.toString()).build();InstanceTemplateinstanceTemplate=InstanceTemplate.newBuilder().setName(templateName).setProperties(InstanceProperties.newBuilder().setMachineType("n1-standard-1").addDisks(disk).addNetworkInterfaces(NetworkInterface.newBuilder().setName("global/networks/default").build()).build()).build();InsertInstanceTemplateRequestinsertInstanceTemplateRequest=InsertInstanceTemplateRequest.newBuilder().setProject(projectId).setInstanceTemplateResource(instanceTemplate).build();Operationresponse=instanceTemplatesClient.insertAsync(insertInstanceTemplateRequest).get(3,TimeUnit.MINUTES);if(response.hasError()){System.out.println("Instance Template creation failed ! ! "+response);return;}System.out.printf("Instance Template Operation Status %s: %s",templateName,response.getStatus());}}}Node.js
/** * TODO(developer): Uncomment and replace these variables before running the sample. */// const projectId = 'YOUR_PROJECT_ID';// const templateName = 'your_template_name';constcompute=require('@google-cloud/compute');// Create a new instance template with the provided name and a specific instance configuration.asyncfunctioncreateTemplate(){constinstanceTemplatesClient=newcompute.InstanceTemplatesClient();const[response]=awaitinstanceTemplatesClient.insert({project:projectId,instanceTemplateResource:{name:templateName,properties:{disks:[{// The template describes the size and source image of the boot disk// to attach to the instance.initializeParams:{diskSizeGb:'250',sourceImage:'projects/debian-cloud/global/images/family/debian-11',},autoDelete:true,boot:true,},],machineType:'e2-standard-4',// The template connects the instance to the `default` network,// without specifying a subnetwork.networkInterfaces:[{// Use the network interface provided in the networkName argument.name:'global/networks/default',// The template lets the instance use an external IP address.accessConfigs:[{name:'External NAT',type:'ONE_TO_ONE_NAT',networkTier:'PREMIUM',},],},],},},});letoperation=response.latestResponse;constoperationsClient=newcompute.GlobalOperationsClient();// Wait for the create operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,});}console.log('Instance template created.');}createTemplate();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_template(project_id:str,template_name:str)->compute_v1.InstanceTemplate:""" Create a new instance template with the provided name and a specific instance configuration. Args: project_id: project ID or project number of the Cloud project you use. template_name: name of the new template to create. Returns: InstanceTemplate object that represents the new instance template. """# The template describes the size and source image of the boot disk# to attach to the instance.disk=compute_v1.AttachedDisk()initialize_params=compute_v1.AttachedDiskInitializeParams()initialize_params.source_image=("projects/debian-cloud/global/images/family/debian-11")initialize_params.disk_size_gb=250disk.initialize_params=initialize_paramsdisk.auto_delete=Truedisk.boot=True# The template connects the instance to the `default` network,# without specifying a subnetwork.network_interface=compute_v1.NetworkInterface()network_interface.name="global/networks/default"# The template lets the instance use an external IP address.access_config=compute_v1.AccessConfig()access_config.name="External NAT"access_config.type_="ONE_TO_ONE_NAT"access_config.network_tier="PREMIUM"network_interface.access_configs=[access_config]template=compute_v1.InstanceTemplate()template.name=template_nametemplate.properties.disks=[disk]template.properties.machine_type="e2-standard-4"template.properties.network_interfaces=[network_interface]template_client=compute_v1.InstanceTemplatesClient()operation=template_client.insert(project=project_id,instance_template_resource=template)wait_for_extended_operation(operation,"instance template creation")returntemplate_client.get(project=project_id,instance_template=template_name)REST
To create a regional instance template, make aPOST request to theregionInstanceTemplates.insert methodas follows:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/instanceTemplates
To create a global instance template, make aPOST request to theinstanceTemplates.insert method:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/instanceTemplates
You can add up to 15 secondary non-boot disks by using thedisks property, with a field for each additional disk. For eachadditional disk, you can do the following:
- Create additional disks with a public or custom image.
- To add a blank disk, define the
initializeParamsentry with nosourceImagevalue. - To create regional disks, define the
initializeParamsentrywith the propertyreplicaZones.
In the body of the request, provide the template properties:
{ "name": "INSTANCE_TEMPLATE_NAME", "properties": { "machineType": "MACHINE_TYPE", "networkInterfaces": [ { "network": "global/networks/default", "accessConfigs": [ { "name": "external-IP", "type": "ONE_TO_ONE_NAT" } ] } ], "disks": [ { "type": "PERSISTENT", "boot": true, "mode": "READ_WRITE", "initializeParams": { "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE" } }, { "type": "PERSISTENT", "boot": false, "deviceName": "DISK_NAME", "initializeParams": { "replicaZones": [ "projects/PROJECT_NAME/zones/ZONE", "projects/PROJECT_NAME/zones/REMOTE_ZONE" ] } } ] }}Replace the following:
PROJECT_ID: yourproject idREGION: the region where you want to create yourregional instance templateINSTANCE_TEMPLATE_NAME: the name of the instancetemplateZONE: the zone where VMs are locatedMACHINE_TYPE: the machine type of the VMsIMAGE_PROJECT: the image project that contains the imageFor more information on public images, seePublic images.
IMAGEorIMAGE_FAMILY:specify one of the following:IMAGE: a specific version of the imageFor example,
"sourceImage": "projects/debian-cloud/global/images/debian-10-buster-v20200309"IMAGE_FAMILY: animage familyThis creates the VM from the most recent, non-deprecated OS image. For example, if you specify
"sourceImage": "projects/debian-cloud/global/images/family/debian-10", Compute Engine creates a VM from the latest version of the OS image in the Debian 10 image family.For more information on image families, see best practices when using image families on Compute Engine.
DISK_NAME: Optional: the disk name displayed tothe guest OS after the VM is created.PROJECT_NAME: the project associated with the VMREMOTE_ZONE: the zone where the regional diskshould be replicated to
You can specify one of the following options for thedisks property:
Specify
initializeParamsto create boot disks for eachinstance. You can create disks by using public or custom images(orimage families) using thesourceImageproperty, as shown in the preceding example. To add blankdisks, don't specify asourceImage. You can also add up to 15 secondarynon-boot disks by using theinitializeParamsproperty for eachadditional disk.Specify
sourceto attach an existing boot disk. If you attachan existing boot disk, you can only create one instance from yourtemplate.
Optionally, you can specify thediskSizeGb,diskType, andlabels properties forinitializeParams and thediskSizeGb property forsource.
If you chose an image that supportsShielded VM, you canoptionally change the VM's Shielded VM settings by usingthe following Boolean request body items:
enableSecureBoot: turns on or off Secure BootSecure Boot helps protect your VM instances against boot-level andkernel-level malware and rootkits. For more information, seeSecure Boot.
enableVtpm: turns on or off the virtual trusted platform module(vTPM)The vTPM enables Measured Boot, which validates the VMpre-boot and boot integrity. For more information, seeVirtual Trusted Platform Module (vTPM).Important: Disabling the vTPM alsodisables integrity monitoring because integrity monitoring relies ondata gathered by Measured Boot.
enableIntegrityMonitoring: turns on or off integritymonitoringIntegrity monitoring lets you monitor and verify theruntime boot integrity of your Shielded VM instances by usingCloud Monitoring reports. For more information, seeIntegrity monitoring.
To learn more about request parameters, see theinstanceTemplates.insert method.
Create an instance template based on an existing instance
You can use REST or gcloud CLI to save theconfiguration of an existing VM instance as an instance template. You canoptionally override how the source disks are defined in the template.
If you need to override other properties, first create an instancetemplate based on an existing instance, thencreate a similar template with additionaloverrides.
Warning: If the existing instance contains a static external IP address, thataddress is copied into the instance template and might limit the use of thetemplate.Permissions required for this task
To perform this task, you must have the followingpermissions:
- All permissions required to call the
instanceTemplates.insertmethod.
gcloud
Use thegcloud compute instance-templates create commandwith the--source-instance and--source-instance-zone flags. If you wantto create a regional instance template, then you must also use the--instance-template-region flag to specify the region of the instancetemplate.
To create a regional instance template, use the following command:
gcloud compute instance-templates createINSTANCE_TEMPLATE_NAME \ --source-instance=SOURCE_INSTANCE \ --source-instance-zone=SOURCE_INSTANCE_ZONE \ --instance-template-region=REGION
To create a global instance template, use the following command:
gcloud compute instance-templates createINSTANCE_TEMPLATE_NAME \ --source-instance=SOURCE_INSTANCE \ --source-instance-zone=SOURCE_INSTANCE_ZONE
To override how the source instance's disks are defined, add one or more--configure-disk flags.
The following example creates a global instancetemplate from an existing instance and overrides the source instance'sdisk with the specifications that you provide.
gcloud compute instance-templates createINSTANCE_TEMPLATE_NAME \ --source-instance=SOURCE_INSTANCE \ --source-instance-zone=SOURCE_INSTANCE_ZONE \ --configure-disk= \ device-name=SOURCE_DISK, \ instantiate-from=INSTANTIATE_OPTIONS, \ auto-delete=AUTO_DELETE
Replace the following:
INSTANCE_TEMPLATE_NAMEis the name of the templateto create.SOURCE_INSTANCEis the name of the instance to useas a model for the new template.SOURCE_INSTANCE_ZONEis the zone that contains thesource instance.SOURCE_DISKis the name of a source-instance diskthat you want to override within the template.INSTANTIATE_OPTIONSspecifies whether to includethe disk and which image to use. Valid values depend on the type of disk:source-imageorsource-image-family(valid only for boot and otherpersistent read-write disks). Specify this option if you want to use thesame source image or source image family that was used to create thedisk in the source VM instance.custom-image(valid only for boot and other persistent read-writedisks). If you want to retain applications and settings from the sourceVMs in your instance template, you cancreate a custom imageand then specify it when you create the template.If specified, then provide the path or URL for the custom image,as shown in the following example. Alternatively, youcan specify an image family using the following format:--configure-disk=device-name=DATA_DISK_NAME,instantiate-from=custom-image, \custom-image=projects/PROJECT_ID/global/images/family/IMAGE_FAMILY_NAMEattach-read-only(valid only for read-only disks).blank(valid only for non-boot persistent disks and local SSDs). Ifspecified, then, when the template is used to create a new instance, thedisk is created unformatted. You mustformat and mountthe disk in a startup script before you can use it in a scalable setup.do-not-include(valid only for non-boot persistent disks andread-only disks).
AUTO_DELETEspecifies whether the disk isauto-deleted when the instance is deleted. Valid values are:false,no,true, andyes.
For example, the following command creates an instance template based onmy-source-instance, with the option to use the original image fromdata-disk-a, but set auto-delete totrue and replacedata-disk-bwith a custom image.
gcloud compute instance-templates create my-instance-template \ --source-instance=my-source-instance \ --configure-disk=device-name=data-disk-a,instantiate-from=source-image,auto-delete=true \ --configure-disk=device-name=data-disk-b,instantiate-from=custom-image,custom-image=projects/cps-cloud/global/images/cos-89-16108-403-15
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")// createTemplateFromInstance creates a new instance template based on an existing instance.// This new template specifies a different boot disk.funccreateTemplateFromInstance(wio.Writer,projectID,instance,templateNamestring)error{// projectID := "your_project_id"// instance := "projects/project/zones/zone/instances/instance"// templateName := "your_template_name"ctx:=context.Background()instanceTemplatesClient,err:=compute.NewInstanceTemplatesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewInstanceTemplatesRESTClient: %w",err)}deferinstanceTemplatesClient.Close()req:=&computepb.InsertInstanceTemplateRequest{Project:projectID,InstanceTemplateResource:&computepb.InstanceTemplate{Name:proto.String(templateName),SourceInstance:proto.String(instance),SourceInstanceParams:&computepb.SourceInstanceParams{DiskConfigs:[]*computepb.DiskInstantiationConfig{{// Device name must match the name of a disk attached to the instance// your template is based on.DeviceName:proto.String("disk-1"),// Replace the original boot disk image used in your instance with a Rocky Linux image.InstantiateFrom:proto.String(computepb.DiskInstantiationConfig_CUSTOM_IMAGE.String()),CustomImage:proto.String("projects/rocky-linux-cloud/global/images/family/rocky-linux-8"),// Override the auto_delete setting.AutoDelete:proto.Bool(true),},},},},}op,err:=instanceTemplatesClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create instance template: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance template created\n")returnnil}Java
importcom.google.cloud.compute.v1.DiskInstantiationConfig;importcom.google.cloud.compute.v1.DiskInstantiationConfig.InstantiateFrom;importcom.google.cloud.compute.v1.GlobalOperationsClient;importcom.google.cloud.compute.v1.InsertInstanceTemplateRequest;importcom.google.cloud.compute.v1.InstanceTemplate;importcom.google.cloud.compute.v1.InstanceTemplatesClient;importcom.google.cloud.compute.v1.Operation;importcom.google.cloud.compute.v1.SourceInstanceParams;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateTemplateFromInstance{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{// TODO(developer): Replace these variables before running the sample.// projectId: project ID or project number of the Cloud project you use.// instance: the instance to base the new template on. This value uses the following format:// **NOTE**: "projects/{project}/zones/{zone}/instances/{instance_name}"// templateName: name of the new template to create.StringprojectId="your-project-id";StringtemplateName="template-name";Stringinstance=String.format("projects/%s/zones/%s/instances/%s",projectId,"zone","instanceName");createTemplateFromInstance(projectId,templateName,instance);}// Create a new instance template based on an existing instance.// This new template specifies a different boot disk.publicstaticvoidcreateTemplateFromInstance(StringprojectId,StringtemplateName,Stringinstance)throwsIOException,ExecutionException,InterruptedException,TimeoutException{try(InstanceTemplatesClientinstanceTemplatesClient=InstanceTemplatesClient.create();GlobalOperationsClientglobalOperationsClient=GlobalOperationsClient.create()){SourceInstanceParamssourceInstanceParams=SourceInstanceParams.newBuilder().addDiskConfigs(DiskInstantiationConfig.newBuilder()// Device name must match the name of a disk attached to the instance you are// basing your template on..setDeviceName("disk-1")// Replace the original boot disk image used in your instance// with a Rocky Linux image..setInstantiateFrom(InstantiateFrom.CUSTOM_IMAGE.toString()).setCustomImage(String.format("projects/%s/global/images/family/%s","rocky-linux-cloud","rocky-linux-8"))// Override the AutoDelete setting..setAutoDelete(true).build()).build();InstanceTemplateinstanceTemplate=InstanceTemplate.newBuilder().setName(templateName).setSourceInstance(instance).setSourceInstanceParams(sourceInstanceParams).build();InsertInstanceTemplateRequestinsertInstanceTemplateRequest=InsertInstanceTemplateRequest.newBuilder().setProject(projectId).setInstanceTemplateResource(instanceTemplate).build();Operationoperation=instanceTemplatesClient.insertCallable().futureCall(insertInstanceTemplateRequest).get(3,TimeUnit.MINUTES);Operationresponse=globalOperationsClient.wait(projectId,operation.getName());if(response.hasError()){System.out.println("Instance Template creation failed ! ! "+response);return;}System.out.printf("Instance Template creation operation status %s: %s",templateName,response.getStatus());}}}Node.js
/** * TODO(developer): Uncomment and replace these variables before running the sample. */// const projectId = 'YOUR_PROJECT_ID';// const instance = 'projects/project/zones/zone/instances/instance';// const templateName = 'your_template_name';constcompute=require('@google-cloud/compute');// Create a new instance template based on an existing instance.// This new template specifies a different boot disk.asyncfunctioncreateTemplateFromInstance(){constinstanceTemplatesClient=newcompute.InstanceTemplatesClient();const[response]=awaitinstanceTemplatesClient.insert({project:projectId,instanceTemplateResource:{name:templateName,sourceInstance:instance,sourceInstanceParams:{diskConfigs:[{// Device name must match the name of a disk attached to the instance// your template is based on.deviceName:'disk-1',// Replace the original boot disk image used in your instance with a Rocky Linux image.instantiateFrom:'CUSTOM_IMAGE',customImage:'projects/rocky-linux-cloud/global/images/family/rocky-linux-8',// Override the auto_delete setting.autoDelete:true,},],},},});letoperation=response.latestResponse;constoperationsClient=newcompute.GlobalOperationsClient();// Wait for the create operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,});}console.log('Instance template created.');}createTemplateFromInstance();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_template_from_instance(project_id:str,instance:str,template_name:str)->compute_v1.InstanceTemplate:""" Create a new instance template based on an existing instance. This new template specifies a different boot disk. Args: project_id: project ID or project number of the Cloud project you use. instance: the instance to base the new template on. This value uses the following format: "projects/{project}/zones/{zone}/instances/{instance_name}" template_name: name of the new template to create. Returns: InstanceTemplate object that represents the new instance template. """disk=compute_v1.DiskInstantiationConfig()# Device name must match the name of a disk attached to the instance you are# basing your template on.disk.device_name="disk-1"# Replace the original boot disk image used in your instance with a Rocky Linux image.disk.instantiate_from="CUSTOM_IMAGE"disk.custom_image="projects/rocky-linux-cloud/global/images/family/rocky-linux-8"# Override the auto_delete setting.disk.auto_delete=Truetemplate=compute_v1.InstanceTemplate()template.name=template_nametemplate.source_instance=instancetemplate.source_instance_params=compute_v1.SourceInstanceParams()template.source_instance_params.disk_configs=[disk]template_client=compute_v1.InstanceTemplatesClient()operation=template_client.insert(project=project_id,instance_template_resource=template)wait_for_extended_operation(operation,"instance template creation")returntemplate_client.get(project=project_id,instance_template=template_name)REST
To create a regional instance template, use theregionInstanceTemplates.insert method,or, to create a global instance template, use theinstanceTemplates.insert method.
In your request, you must specify thesourceInstance field. To override how the sourceinstance's disks are defined, add one or morediskConfigs fields.
For example, make the following call to create a global instance templatefrom an existing instance.
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/instanceTemplates{ "name": "INSTANCE_TEMPLATE_NAME", "sourceInstance": "zones/SOURCE_INSTANCE_ZONE/instances/SOURCE_INSTANCE", "sourceInstanceParams": { "diskConfigs": [ { "deviceName": "SOURCE_DISK", "instantiateFrom": "INSTANTIATE_OPTIONS", "autoDelete": false } ] }}Replace the following:
PROJECT_ID: yourproject idINSTANCE_TEMPLATE_NAME: the name for the new templateSOURCE_INSTANCE_ZONE: the zone of the source instanceSOURCE_INSTANCE: the name of the source instance to use as a modelfor this instance templateSOURCE_DISK: the name of a source-instance disk that you want tooverride within the templateINSTANTIATE_OPTIONS: specifies whether to include the disk and which imageto useValid values depend on the type of disk:
source-imageorsource-image-family(valid only for boot andother persistent read-write disks).custom-image(valid only for boot and other persistent read-writedisks). If you want to retain applications and settings from the sourceVMs in your instance template, you cancreate a custom imageand then specify it when you create the template.If specified, then provide the path or URL for the custom image,as shown in the following example. Alternatively, youcan specify an image family using the following format:"diskConfigs": [ { "deviceName":DATA_DISK_NAME, "instantiateFrom": custom-image, "customImage": "projects/PROJECT_ID/global/images/family/IMAGE_FAMILY_NAME" } ]attach-read-only(valid only for read-only disks).blank(valid only for non-boot persistent disks and local SSDs). Ifspecified, then, when the template is used to create a new instance, thedisk is created unformatted. You mustformat and mountthe disk in a startup script before you can use it in a scalable setup.do-not-include(valid only for non-boot persistent disks andread-only disks).
The following example creates a new instance template based onmy-source-instance. In the instance template, the image fordata-disk-ais replaced withprojects/cos-cloud/global/images/cos-89-16108-403-15.
POST https://compute.googleapis.com/compute/v1/projects/my_project/global/instanceTemplates{ "name": "my-instance-template", "sourceInstance": "zones/us-central1-a/instances/my-source-instance", "sourceInstanceParams": { "diskConfigs": [ { "deviceName": "data-disk-a", "instantiateFrom": "custom-image", "customImage": "projects/cos-cloud/global/images/cos-89-16108-403-15" } ] }}The following table shows how the options for overriding disks are definedin the template.
| Disk type | Options |
|---|---|
| Boot disk |
|
| Other read/write persistent disks |
|
| Read-only disk(s) |
|
| Local SSD(s) |
|
For each disk, you can also override theauto-delete attribute to specifywhether the disk should be deleted when its associated instance isdeleted.
By default, if no override options are specified, the disk configuration inthe template matches the source instance.
Create an instance template based on an existing template
You can't update an existing instance template. But, if an instance templategoes out of date or if you need to make changes, you can create another one withsimilar properties by using the console.
Go to theInstance templates page.
Click the instance template that you want to copy and update.
ClickCreate similar.
Update the configuration in the new template.
ClickCreate.
Create an instance template for GPU VMs
When creating an instance template, you can configure it for creating VMsthat have attached GPUs by specifying the following:
A machine type thatsupports the GPU type you want.If you want to create a regional instance template, the GPU type that youspecify in the template must beavailable in at least one zone in the region.
A maintenance policy that stops VMs duringhost maintenance events.
Note: If you want to run data science or machine learning workloads,consider using a Deep Learning VM image when you create aninstance template. Deep Learning VM Images is a set ofprepackaged VM images that comes with machine learning frameworks and essentialtools. For more information about these images, seeChoose an imagein the Deep Learning VM Images documentation. To perform this task, you must have the followingpermissions:Permissions required for this task
instanceTemplates.insert method.
Console
To create an instance template for GPU VMs, do the following:
In the Google Cloud console, go to theInstance templates page.
ClickCreate instance template.
In theName field, enter a name for the instance template.
In theLocation section, select one of the following options:
To create a global instance template, selectGlobal (default).
To create a regional instance template, selectRegional, andthen select the region where you want to create the instancetemplate.
In theMachine configuration section, do the following:
Click theGPUs tab.
In theGPU type menu, select the GPU type.
In theNumber of GPUs menu, select the number of GPUs.
Optional: If your GPU model supportsNVIDIA RTX Virtual Workstations (vWS) for graphics workloads,and you plan to run graphics-intensive workloads, selectEnable Virtual Workstation (NVIDIA GRID).
In theMachine type section, select a machine type.
Optional: To change the default value boot disk type or image, in theBoot disk section, clickChange. Then, follow the prompts tochange the boot disk.
ClickCreate.
gcloud
To create an instance template for GPU VMs, use theinstance-templates create commandwith the--maintenance-policy flag set toTERMINATE.
For example, to create a global instance template for GPU VMs, use thefollowing command:
gcloud compute instance-templates createINSTANCE_TEMPLATE_NAME \ --image-project=IMAGE_PROJECT \ --image-family=IMAGE_FAMILY \ --machine-type=MACHINE_TYPE \ --maintenance-policy=TERMINATEReplace the following:
INSTANCE_TEMPLATE_NAME: the name of the instancetemplate.IMAGE_PROJECT: the image project that contains theimage; for example,debian-cloud. For more information about thesupported image projects, seePublic images.IMAGE_FAMILYorIMAGE: specify oneof the following:IMAGE_FAMILY: animage family. This specifies themost recent, non-deprecated OS image. For example, if you specifydebian-10, the latest version in the Debian 10 image family isused. For more information about using image families, seeImage families best practices.IMAGE: a specific version of the OS image; forexample,debian-10-buster-v20200309. If you choose to specify aspecific version of the OS image, then you must replace the--image-familyflag with the--imageflag.
MACHINE_TYPE: the machine type of the VMs. If youspecify an N1 machine type, then include the--acceleratorflagto specify the number and type of GPUs to attach to your VMs.
For example, assume that you want to create a global instance template forGPU VMs that specifies the following properties:
An N1 predefined machine type with 2 vCPUs.
One NVIDIA T4 GPU to attach to the VMs.
Debian as the image project.
Debian 10 as the image family.
To create the example instance template, use the following command:
gcloud compute instance-templates create instance-template-gpu \ --accelerator=count=1,type=nvidia-tesla-t4 \ --machine-type=n1-standard-2 \ --image-family=debian-10 \ --image-project=debian-cloud \ --maintenance-policy=TERMINATETerraform
To create an instance template, use one of the following resources:
- For a regional instance template, use the
google_compute_region_instance_templateresource. - For a global instance template, use the
google_compute_instance_templateresource.
The following example creates a global instance template that specifies anN1 predefined machine type with 2 vCPUs and one NVIDIA T4 GPU attached:
resource "google_compute_instance_template" "default" { name = "gpu-template" machine_type = "n1-standard-2" disk { source_image = "debian-cloud/debian-11" } network_interface { network = "default" } guest_accelerator { type = "nvidia-tesla-t4" count = 1 } scheduling { on_host_maintenance = "TERMINATE" }}To learn how to apply or remove a Terraform configuration, seeBasic Terraform commands.
REST
To create an instance template for GPU VMs, make aPOST request to theinstanceTemplates.insert method.In the request body, include theonHostMaintenance field and set it toTERMINATE.
For example, to create a global instance template for GPU VMs, make aPOSTrequest as follows:
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/instanceTemplates{ "name": "INSTANCE_TEMPLATE_NAME", "properties": { "disks": [ { "type": "PERSISTENT", "boot": true, "mode": "READ_WRITE", "initializeParams": { "sourceImage": "projects/IMAGE_PROJECT/global/images/IMAGE" } } ], "machineType": "MACHINE_TYPE", "networkInterfaces": [ { "accessConfigs": [ { "name": "external-IP", "type": "ONE_TO_ONE_NAT" } ], "network": "global/networks/default" } ], "scheduling": { "onHostMaintenance": "TERMINATE" } }}Replace the following:
PROJECT_ID: the ID of the project in which you wantto create the instance template.INSTANCE_TEMPLATE_NAME: the name of the instancetemplate.IMAGE_PROJECT: the image project that contains theimage; for example,debian-cloud. For more information about thesupported image projects, seePublic images.IMAGEorIMAGE_FAMILY: specify oneof the following:IMAGE: a specific version of the OS image; forexample,debian-10-buster-v20200309.IMAGE_FAMILY: animage family. This specifies themost recent, non-deprecated OS image. For example, if you specifyfamily/debian-10, the latest version in the Debian 10 image familyis used. For more information about using image families, seeImage families best practices.
MACHINE_TYPE: the machine type of the VMs. If youspecify an N1 machine type, then include theguestAcceleratorsfieldto specify the number and type of GPUs to attach to your VMs.
For example, assume that you want to create a global instance template forGPU VMs that specifies the following properties:
An N1 predefined machine type with 2 vCPUs.
One NVIDIA T4 GPU to attach to the VMs.
Debian as the image project.
Debian 10 as the image family.
To create the example instance template, make aPOST request as follows:
POST https://compute.googleapis.com/compute/v1/projects/example-project/global/instanceTemplates{ "name": "instance-template-gpu", "properties": { "disks": [ { "type": "PERSISTENT", "boot": true, "mode": "READ_WRITE", "initializeParams": { "sourceImage": "projects/debian-cloud/global/images/family/debian-10" } } ], "guestAccelerators": [ { "acceleratorType": "nvidia-tesla-t4", "acceleratorCount": 1 } ], "machineType": "n1-standard-2", "networkInterfaces": [ { "accessConfigs": [ { "name": "external-IP", "type": "ONE_TO_ONE_NAT" } ], "network": "global/networks/default" } ], "scheduling": { "onHostMaintenance": "TERMINATE" } }}For more configuration options when creating an instance template, seeCreate an instance template in this document.
Create an instance template with a container image
Note: The Compute Engine feature that deploys containers on VMs during VM creation is deprecated. Use thedocker run commands in a startup script or use thecloud-init tool to configure and to run containers on your VMs and MIGs. For more information, seeMigrate containers that were deployed on VMs during VM creation.You can specify a container image in an instance template. By default,Compute Engine also includes in the template aContainer-Optimized OS image with Dockerinstalled. When you use the template to create a new instance, the container islaunched automatically as the instance starts up.
Console
Note: TheDeploy container option in the Google Cloud console is deprecated. Use the equivalentdocker run command to configure and to run the container.Go to theInstance templates page.
ClickCreate instance template.
In theContainer section, clickDeploy Container.
In theConfigure container dialog, specify theContainer image to use.
- You can specify an image fromContainer RegistryorArtifact Registry.For example:
gcr.io/cloud-marketplace/google/nginx1:TAG,whereTAG is the tag defined for a specificversion of NGINX container image available on Google Cloud Marketplace.us-docker.pkg.dev/google-samples/containers/gke/hello-app:1.0selects a samplehello-appimage stored in Artifact Registry.
- If you use a container image from Docker Hub, always specify thefull Docker image name. For example, specify the following image nameto deploy an Apache container image:
docker.io/httpd:2.4.
- You can specify an image fromContainer RegistryorArtifact Registry.For example:
Optionally, clickAdvanced container options. For more information,seeConfiguring options to run your Container.
ClickCreate.
gcloud
Note: Thecreate-with-container gcloud CLI command is deprecated. Use the equivalentdocker run command to configure and to run the container.Use thegcloud compute instance-templates create-with-container command:
gcloud compute instance-templates create-with-containerINSTANCE_TEMPLATE_NAME \ --container-image=CONTAINER_IMAGE
Replace the following:
INSTANCE_TEMPLATE_NAME: The name of the templateto create.CONTAINER_IMAGE: The full name of the containerimage to use.
For example, the following command creates a new instance template namednginx-vm. A VM instance created from this template launches andruns the container image,gcr.io/cloud-marketplace/google/nginx1:TAG,when the VM starts.
gcloud compute instance-templates create-with-container nginx-vm \ --container-image=gcr.io/cloud-marketplace/google/nginx1:TAG
ReplaceTAG with the tag defined for a specificversion of NGINX container image available on Google Cloud Marketplace.
You can also configureoptions to run your container.
Caution: Container Registry is deprecated. Effective March 18, 2025, Container Registry is shut down, and writing images to Container Registry is unavailable. For details on the deprecation and how to migrate to Artifact Registry, seeContainer Registry deprecation.
Create an instance template that specifies a subnet
gcloud
To create a regional or global instance template, use theinstance-templates create command.Use the--subnet flag to place instances that are created from the templateinto the subnet of your choice. The--subnet flag requires the--regionflag.
If you want to create a regional instance template, you must use the--instance-template-region flag to set the region of the template. Make surethat you use a subnet from the same region as where you want to create theregional instance template.
gcloud compute instance-templates createINSTANCE_TEMPLATE_NAME \ --region=REGION \ --subnet=SUBNET_NAME_OR_URL \ --stack-type=STACK_TYPE \ --instance-template-region=INSTANCE_TEMPLATE_REGION
Replace the following:
INSTANCE_TEMPLATE_NAME: the name for theinstance templateREGION: the region of the subnet
Note: If you use the subnet name, Google finds that subnet in the targetregion (provided that it exists there). However, if you use the subnet URL,the instance template can only be used to create instances in the specificregion that is associated with the subnet URL.SUBNET_NAME_OR_URL: either the name of the subnet orits URLSTACK_TYPE: Optional: whether IPv6 is enabled on thedefault network interface. The following values can be used:IPV4_ONLY,IPV4_IPV6, orIPV6_ONLY. If youdon't include this flag, the default value isIPV4_ONLY.INSTANCE_TEMPLATE_REGION: the region where you wantto create the instance template. This region must be same asREGION.
The following example creates a template calledtemplate-qa that only createsinstances in thesubnet-us-qa subnet.
gcloud compute instance-templates create template-qa \ --region=us-central1 \ --subnet=subnet-us-qa
The output is similar to the following:
Created [https://compute.googleapis.com/compute/latest/projects/PROJECT_ID/global/instanceTemplates/template-qa].NAME MACHINE_TYPE PREEMPTIBLE CREATION_TIMESTAMPtemplate-qa e2-standard-2 2019-12-23T20:34:00.791-07:00
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")// createTemplateWithSubnet creates an instance template that uses a provided subnet.funccreateTemplateWithSubnet(wio.Writer,projectID,network,subnetwork,templateNamestring)error{// projectID := "your_project_id"// network := "projects/project/global/networks/network"// subnetwork := "projects/project/regions/region/subnetworks/subnetwork"// templateName := "your_template_name"ctx:=context.Background()instanceTemplatesClient,err:=compute.NewInstanceTemplatesRESTClient(ctx)iferr!=nil{returnfmt.Errorf("NewInstanceTemplatesRESTClient: %w",err)}deferinstanceTemplatesClient.Close()req:=&computepb.InsertInstanceTemplateRequest{Project:projectID,InstanceTemplateResource:&computepb.InstanceTemplate{Name:proto.String(templateName),Properties:&computepb.InstanceProperties{// The template describes the size and source image of the boot disk// to attach to the instance.Disks:[]*computepb.AttachedDisk{{InitializeParams:&computepb.AttachedDiskInitializeParams{DiskSizeGb:proto.Int64(250),SourceImage:proto.String("projects/debian-cloud/global/images/family/debian-11"),},AutoDelete:proto.Bool(true),Boot:proto.Bool(true),},},MachineType:proto.String("e2-standard-4"),// The template connects the instance to the specified network and subnetwork.NetworkInterfaces:[]*computepb.NetworkInterface{{Network:proto.String(network),Subnetwork:proto.String(subnetwork),},},},},}op,err:=instanceTemplatesClient.Insert(ctx,req)iferr!=nil{returnfmt.Errorf("unable to create instance template: %w",err)}iferr=op.Wait(ctx);err!=nil{returnfmt.Errorf("unable to wait for the operation: %w",err)}fmt.Fprintf(w,"Instance template created\n")returnnil}Java
importcom.google.cloud.compute.v1.AttachedDisk;importcom.google.cloud.compute.v1.AttachedDiskInitializeParams;importcom.google.cloud.compute.v1.GlobalOperationsClient;importcom.google.cloud.compute.v1.InsertInstanceTemplateRequest;importcom.google.cloud.compute.v1.InstanceProperties;importcom.google.cloud.compute.v1.InstanceTemplate;importcom.google.cloud.compute.v1.InstanceTemplatesClient;importcom.google.cloud.compute.v1.NetworkInterface;importcom.google.cloud.compute.v1.Operation;importjava.io.IOException;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.TimeUnit;importjava.util.concurrent.TimeoutException;publicclassCreateTemplateWithSubnet{publicstaticvoidmain(String[]args)throwsIOException,ExecutionException,InterruptedException,TimeoutException{/* TODO(developer): Replace these variables before running the sample. projectId: project ID or project number of the Cloud project you use. network: the network to be used in the new template. This value uses the following format: "projects/{project}/global/networks/{network}" subnetwork: the subnetwork to be used in the new template. This value uses the following format: "projects/{project}/regions/{region}/subnetworks/{subnetwork}" templateName: name of the new template to create. */StringprojectId="your-project-id";Stringnetwork=String.format("projects/%s/global/networks/%s",projectId,"network");Stringsubnetwork=String.format("projects/%s/regions/%s/subnetworks/%s",projectId,"region","subnetwork");StringtemplateName="template-name";createTemplateWithSubnet(projectId,network,subnetwork,templateName);}// Create an instance template that uses a provided subnet.publicstaticvoidcreateTemplateWithSubnet(StringprojectId,Stringnetwork,Stringsubnetwork,StringtemplateName)throwsIOException,ExecutionException,InterruptedException,TimeoutException{try(InstanceTemplatesClientinstanceTemplatesClient=InstanceTemplatesClient.create();GlobalOperationsClientglobalOperationsClient=GlobalOperationsClient.create()){AttachedDiskdisk=AttachedDisk.newBuilder().setInitializeParams(AttachedDiskInitializeParams.newBuilder().setSourceImage(String.format("projects/%s/global/images/family/%s","debian-cloud","debian-11")).setDiskSizeGb(250).build()).setAutoDelete(true).setBoot(true).build();InstancePropertiesinstanceProperties=InstanceProperties.newBuilder().addDisks(disk).setMachineType("e2-standard-4").addNetworkInterfaces(NetworkInterface.newBuilder().setNetwork(network).setSubnetwork(subnetwork).build()).build();InstanceTemplateinstanceTemplate=InstanceTemplate.newBuilder().setName(templateName).setProperties(instanceProperties).build();InsertInstanceTemplateRequestinsertInstanceTemplateRequest=InsertInstanceTemplateRequest.newBuilder().setProject(projectId).setInstanceTemplateResource(instanceTemplate).build();Operationoperation=instanceTemplatesClient.insertCallable().futureCall(insertInstanceTemplateRequest).get(3,TimeUnit.MINUTES);Operationresponse=globalOperationsClient.wait(projectId,operation.getName());if(response.hasError()){System.out.println("Template creation from subnet failed ! ! "+response);return;}System.out.printf("Template creation from subnet operation status %s: %s",templateName,response.getStatus());}}}Node.js
/** * TODO(developer): Uncomment and replace these variables before running the sample. */// const projectId = 'YOUR_PROJECT_ID';// const network = 'projects/project/global/networks/network';// const subnetwork = 'projects/project/regions/region/subnetworks/subnetwork';// const templateName = 'your_template_name';constcompute=require('@google-cloud/compute');// Create an instance template that uses a provided subnet.asyncfunctioncreateTemplateWithSubnet(){constinstanceTemplatesClient=newcompute.InstanceTemplatesClient();const[response]=awaitinstanceTemplatesClient.insert({project:projectId,instanceTemplateResource:{name:templateName,properties:{// The template describes the size and source image of the boot disk// to attach to the instance.disks:[{// The template describes the size and source image of the boot disk// to attach to the instance.initializeParams:{diskSizeGb:'250',sourceImage:'projects/debian-cloud/global/images/family/debian-11',},autoDelete:true,boot:true,},],machineType:'e2-standard-4',// The template connects the instance to the specified network and subnetwork.networkInterfaces:[{network,subnetwork,},],},},});letoperation=response.latestResponse;constoperationsClient=newcompute.GlobalOperationsClient();// Wait for the create operation to complete.while(operation.status!=='DONE'){[operation]=awaitoperationsClient.wait({operation:operation.name,project:projectId,});}console.log('Instance template created.');}createTemplateWithSubnet();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_template_with_subnet(project_id:str,network:str,subnetwork:str,template_name:str)->compute_v1.InstanceTemplate:""" Create an instance template that uses a provided subnet. Args: project_id: project ID or project number of the Cloud project you use. network: the network to be used in the new template. This value uses the following format: "projects/{project}/global/networks/{network}" subnetwork: the subnetwork to be used in the new template. This value uses the following format: "projects/{project}/regions/{region}/subnetworks/{subnetwork}" template_name: name of the new template to create. Returns: InstanceTemplate object that represents the new instance template. """# The template describes the size and source image of the book disk to# attach to the instance.disk=compute_v1.AttachedDisk()initialize_params=compute_v1.AttachedDiskInitializeParams()initialize_params.source_image=("projects/debian-cloud/global/images/family/debian-11")initialize_params.disk_size_gb=250disk.initialize_params=initialize_paramsdisk.auto_delete=Truedisk.boot=Truetemplate=compute_v1.InstanceTemplate()template.name=template_nametemplate.properties=compute_v1.InstanceProperties()template.properties.disks=[disk]template.properties.machine_type="e2-standard-4"# The template connects the instance to the specified network and subnetwork.network_interface=compute_v1.NetworkInterface()network_interface.network=networknetwork_interface.subnetwork=subnetworktemplate.properties.network_interfaces=[network_interface]template_client=compute_v1.InstanceTemplatesClient()operation=template_client.insert(project=project_id,instance_template_resource=template)wait_for_extended_operation(operation,"instance template creation")returntemplate_client.get(project=project_id,instance_template=template_name)Using this template to create instances for aMIG (with or withoutautoscaling) automatically creates the instancein the specified region and subnet. This lets you control the subnet of newinstances created for load balancing.
Use custom or public images in your instance templates
You can either use a custom image or a public image for your instance templates:
Custom images. As MIGs are designed to add and remove instancesfrequently, it is useful tocreate a custom imageand specify it in the instance template. You can prepare your image with theapplications and settings that your VMs need, so you don't have tomanually configure those items on individual VMs in the MIG.
Public images. You can create an instance template that uses apublic image and astartup script to prepare the instance afterit starts running.
Custom images are moredeterministicand start more quickly than VMs with startup scripts. However, startupscripts are more flexible, which helps you update the apps and settingsin your instances.
If you're managing images usingimage families,you can specify the name of your custom or public image family in the instancetemplate. For more information on image families, seebestpractices when using image familieson Compute Engine.
Note: If the image you want to use belongs to a different project, you canstill use that image in your instance template, provided that the owner of thatproject grants the MIG access to the images. For more information, seeGranting a MIG access to images.What's next
- View an instance templateto see its ID and instance properties.
- Create aVM from an instance template.
- Create amanaged instance group (MIG).
- Update theVMs in an existing MIGto use the properties from a different instance template.
- Create areservation for VMs.
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.