googleComputeInstanceTemplate
Manages a VM instance template resource within GCE. For more information see the official documentation and API.
Example Usage
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as google from "./.gen/providers/google";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: google.
For a more precise conversion please use the --provider flag in convert.*/
const googleComputeResourcePolicyDailyBackup =
new google.computeResourcePolicy.ComputeResourcePolicy(this, "daily_backup", {
name: "every-day-4am",
region: "us-central1",
snapshot_schedule_policy: [
{
schedule: [
{
daily_schedule: [
{
days_in_cycle: 1,
start_time: "04:00",
},
],
},
],
},
],
});
const googleServiceAccountDefault = new google.serviceAccount.ServiceAccount(
this,
"default",
{
account_id: "service-account-id",
display_name: "Service Account",
}
);
const dataGoogleComputeImageMyImage =
new google.dataGoogleComputeImage.DataGoogleComputeImage(this, "my_image", {
family: "debian-11",
project: "debian-cloud",
});
const googleComputeDiskFoobar = new google.computeDisk.ComputeDisk(
this,
"foobar",
{
image: dataGoogleComputeImageMyImage.selfLink,
name: "existing-disk",
size: 10,
type: "pd-ssd",
zone: "us-central1-a",
}
);
const googleComputeInstanceTemplateDefault =
new google.computeInstanceTemplate.ComputeInstanceTemplate(
this,
"default_4",
{
can_ip_forward: false,
description: "This template is used to create app server instances.",
disk: [
{
auto_delete: true,
boot: true,
resource_policies: [googleComputeResourcePolicyDailyBackup.id],
source_image: "debian-cloud/debian-11",
},
{
auto_delete: false,
boot: false,
source: googleComputeDiskFoobar.name,
},
],
instance_description: "description assigned to instances",
labels: [
{
environment: "dev",
},
],
machine_type: "e2-medium",
metadata: [
{
foo: "bar",
},
],
name: "appserver-template",
network_interface: [
{
network: "default",
},
],
scheduling: [
{
automatic_restart: true,
on_host_maintenance: "MIGRATE",
},
],
service_account: [
{
email: googleServiceAccountDefault.email,
scopes: ["cloud-platform"],
},
],
tags: ["foo", "bar"],
}
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
googleComputeInstanceTemplateDefault.overrideLogicalId("default");
Example Usage - Automatic Envoy deployment
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as google from "./.gen/providers/google";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: google.
For a more precise conversion please use the --provider flag in convert.*/
const dataGoogleComputeDefaultServiceAccountDefault =
new google.dataGoogleComputeDefaultServiceAccount.DataGoogleComputeDefaultServiceAccount(
this,
"default",
{}
);
const dataGoogleComputeImageMyImage =
new google.dataGoogleComputeImage.DataGoogleComputeImage(this, "my_image", {
family: "debian-11",
project: "debian-cloud",
});
new google.computeInstanceTemplate.ComputeInstanceTemplate(this, "foobar", {
can_ip_forward: false,
disk: [
{
auto_delete: true,
boot: true,
source_image: dataGoogleComputeImageMyImage.selfLink,
},
],
labels: [
{
"gce-service-proxy": "on",
},
],
machine_type: "e2-medium",
metadata: [
{
"enable-guest-attributes": "true",
"enable-osconfig": "true",
"gce-service-proxy":
'{\n "api-version": "0.2",\n "proxy-spec": {\n "proxy-port": 15001,\n "network": "my-network",\n "tracing": "ON",\n "access-log": "/var/log/envoy/access.log"\n }\n "service": {\n "serving-ports": [80, 81]\n },\n "labels": {\n "app_name": "bookserver_app",\n "app_version": "STABLE"\n }\n}\n',
"gce-software-declaration":
'{\n "softwareRecipes": [{\n "name": "install-gce-service-proxy-agent",\n "desired_state": "INSTALLED",\n "installSteps": [{\n "scriptRun": {\n "script": "#! /bin/bash\\nZONE=$(curl --silent http://metadata.google.internal/computeMetadata/v1/instance/zone -H Metadata-Flavor:Google | cut -d/ -f4 )\\nexport SERVICE_PROXY_AGENT_DIRECTORY=$(mktemp -d)\\nsudo gsutil cp gs://gce-service-proxy-"$ZONE"/service-proxy-agent/releases/service-proxy-agent-0.2.tgz "$SERVICE_PROXY_AGENT_DIRECTORY" || sudo gsutil cp gs://gce-service-proxy/service-proxy-agent/releases/service-proxy-agent-0.2.tgz "$SERVICE_PROXY_AGENT_DIRECTORY"\\nsudo tar -xzf "$SERVICE_PROXY_AGENT_DIRECTORY"/service-proxy-agent-0.2.tgz -C "$SERVICE_PROXY_AGENT_DIRECTORY"\\n"$SERVICE_PROXY_AGENT_DIRECTORY"/service-proxy-agent/service-proxy-agent-bootstrap.sh"\n }\n }]\n }]\n}\n',
},
],
name: "appserver-template",
network_interface: [
{
network: "default",
},
],
scheduling: [
{
automatic_restart: true,
preemptible: false,
},
],
service_account: [
{
email: dataGoogleComputeDefaultServiceAccountDefault.email,
scopes: ["cloud-platform"],
},
],
tags: ["foo", "bar"],
});
Using with Instance Group Manager
Instance Templates cannot be updated after creation with the Google Cloud Platform API. In order to update an Instance Template, Terraform will destroy the existing resource and create a replacement. In order to effectively use an Instance Template resource with an Instance Group Manager resource, it's recommended to specify createBeforeDestroy
in a lifecycle block. Either omit the Instance Template name
attribute, or specify a partial name with namePrefix
. Example:
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as google from "./.gen/providers/google";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: google.
For a more precise conversion please use the --provider flag in convert.*/
const googleComputeInstanceTemplateInstanceTemplate =
new google.computeInstanceTemplate.ComputeInstanceTemplate(
this,
"instance_template",
{
disk: [{}],
machine_type: "e2-medium",
name_prefix: "instance-template-",
network_interface: [{}],
region: "us-central1",
}
);
googleComputeInstanceTemplateInstanceTemplate.addOverride("lifecycle", [
{
create_before_destroy: true,
},
]);
new google.computeInstanceGroupManager.ComputeInstanceGroupManager(
this,
"instance_group_manager",
{
base_instance_name: "instance-group-manager",
instance_template: googleComputeInstanceTemplateInstanceTemplate.id,
name: "instance-group-manager",
target_size: "1",
zone: "us-central1-f",
}
);
With this setup Terraform generates a unique name for your Instance Template and can then update the Instance Group manager without conflict before destroying the previous Instance Template.
Deploying the Latest Image
A common way to use instance templates and managed instance groups is to deploy the latest image in a family, usually the latest build of your application. There are two ways to do this in Terraform, and they have their pros and cons. The difference ends up being in how "latest" is interpreted. You can either deploy the latest image available when Terraform runs, or you can have each instance check what the latest image is when it's being created, either as part of a scaling event or being rebuilt by the instance group manager.
If you're not sure, we recommend deploying the latest image available when Terraform runs, because this means all the instances in your group will be based on the same image, always, and means that no upgrades or changes to your instances happen outside of a terraformApply
. You can achieve this by using the googleComputeImage
data source, which will retrieve the latest image on every terraformApply
, and will update the template to use that specific image:
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as google from "./.gen/providers/google";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: google.
For a more precise conversion please use the --provider flag in convert.*/
const dataGoogleComputeImageMyImage =
new google.dataGoogleComputeImage.DataGoogleComputeImage(this, "my_image", {
family: "debian-11",
project: "debian-cloud",
});
new google.computeInstanceTemplate.ComputeInstanceTemplate(
this,
"instance_template",
{
disk: [
{
source_image: dataGoogleComputeImageMyImage.selfLink,
},
],
machine_type: "e2-medium",
name_prefix: "instance-template-",
region: "us-central1",
}
);
To have instances update to the latest on every scaling event or instance re-creation, use the family as the image for the disk, and it will use GCP's default behavior, setting the image for the template to the family:
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as google from "./.gen/providers/google";
/*The following providers are missing schema information and might need manual adjustments to synthesize correctly: google.
For a more precise conversion please use the --provider flag in convert.*/
new google.computeInstanceTemplate.ComputeInstanceTemplate(
this,
"instance_template",
{
disk: [
{
source_image: "debian-cloud/debian-11",
},
],
machine_type: "e2-medium",
name_prefix: "instance-template-",
region: "us-central1",
}
);
Argument Reference
Note that changing any field for this resource forces a new resource to be created.
The following arguments are supported:
-
disk
- (Required) Disks to attach to instances created from this template. This can be specified multiple times for multiple disks. Structure is documented below. -
machineType
- (Required) The machine type to create.To create a machine with a custom type (such as extended memory), format the value like
customVcpusMemInMb
likecustom620480
for 6 vCPU and 20GB of RAM.
-
name
- (Optional) The name of the instance template. If you leave this blank, Terraform will auto-generate a unique name. -
namePrefix
- (Optional) Creates a unique name beginning with the specified prefix. Conflicts withname
. -
canIpForward
- (Optional) Whether to allow sending and receiving of packets with non-matching source or destination IPs. This defaults to false. -
description
- (Optional) A brief description of this resource. -
instanceDescription
- (Optional) A brief description to use for instances created from this template. -
labels
- (Optional) A set of key/value label pairs to assign to instances created from this template. -
metadata
- (Optional) Metadata key/value pairs to make available from within instances created from this template. -
metadataStartupScript
- (Optional) An alternative to using the startup-script metadata key, mostly to match the compute_instance resource. This replaces the startup-script metadata key on the created instance and thus the two mechanisms are not allowed to be used simultaneously. -
networkInterface
- (Required) Networks to attach to instances created from this template. This can be specified multiple times for multiple networks. Structure is documented below. -
networkPerformanceConfig
(Optional, Beta Configures network performance settings for the instance created from the template. Structure is documented below. Note:machineType
must be a supported type, theimage
used must include thegvnic
inguestOsFeatures
, andnetworkInterface0NicType
must begvnic
in order for this setting to take effect. -
project
- (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used. -
region
- (Optional) An instance template is a global resource that is not bound to a zone or a region. However, you can still specify some regional resources in an instance template, which restricts the template to the region where that resource resides. For example, a customsubnetwork
resource is tied to a specific region. Defaults to the region of the Provider if no value is given. -
resourcePolicies
(Optional) -- A list of self_links of resource policies to attach to the instance. Modifying this list will cause the instance to recreate. Currently a max of 1 resource policy is supported. -
reservationAffinity
- (Optional) Specifies the reservations that this instance can consume from. Structure is documented below. -
scheduling
- (Optional) The scheduling strategy to use. More details about this configuration option are detailed below. -
serviceAccount
- (Optional) Service account to attach to the instance. Structure is documented below. -
tags
- (Optional) Tags to attach to the instance. -
guestAccelerator
- (Optional) List of the type and count of accelerator cards attached to the instance. Structure documented below. -
minCpuPlatform
- (Optional) Specifies a minimum CPU platform. Applicable values are the friendly names of CPU platforms, such asintelHaswell
orintelSkylake
. See the complete list here. -
shieldedInstanceConfig
- (Optional) Enable Shielded VM on this instance. Shielded VM provides verifiable integrity to prevent against malware and rootkits. Defaults to disabled. Structure is documented below. Note:shieldedInstanceConfig
can only be used with boot images with shielded vm support. See the complete list here. -
enableDisplay
- (Optional, Beta) Enable Virtual Displays on this instance. Note:allowStoppingForUpdate
must be set to true in order to update this field. -
confidentialInstanceConfig
(Optional) - Enable Confidential Mode on this VM. Structure is documented below -
advancedMachineFeatures
(Optional) - Configure Nested Virtualisation and Simultaneous Hyper Threading on this VM. Structure is documented below
-
autoDelete
- (Optional) Whether or not the disk should be auto-deleted. This defaults to true. -
boot
- (Optional) Indicates that this is a boot disk. -
deviceName
- (Optional) A unique device name that is reflected into the /dev/ tree of a Linux operating system running within the instance. If not specified, the server chooses a default device name to apply to this disk. -
diskName
- (Optional) Name of the disk. When not provided, this defaults to the name of the instance. -
sourceImage
- (Optional) The image from which to initialize this disk. This can be one of: the image'sselfLink
,projects/{project}/global/images/{image}
,projects/{project}/global/images/family/{family}
,global/images/{image}
,global/images/family/{family}
,family/{family}
,{project}/{family}
,{project}/{image}
,{family}
, or{image}
. \~> Note: Eithersource
,sourceImage
, orsourceSnapshot
is required in a disk block unless the disk type islocalSsd
. Check the API docs for details. -
sourceImageEncryptionKey
- (Optional) The customer-supplied encryption key of the source image. Required if the source image is protected by a customer-supplied encryption key.Instance templates do not store customer-supplied encryption keys, so you cannot create disks for instances in a managed instance group if the source images are encrypted with your own keys. Structure documented below.
-
sourceSnapshot
- (Optional) The source snapshot to create this disk. \~> Note: Eithersource
,sourceImage
, orsourceSnapshot
is required in a disk block unless the disk type islocalSsd
. Check the API docs for details. -
sourceSnapshotEncryptionKey
- (Optional) The customer-supplied encryption key of the source snapshot. Structure documented below. -
interface
- (Optional) Specifies the disk interface to use for attaching this disk, which is either SCSI or NVME. The default is SCSI. Persistent disks must always use SCSI and the request will fail if you attempt to attach a persistent disk in any other format than SCSI. Local SSDs can use either NVME or SCSI. -
mode
- (Optional) The mode in which to attach this disk, either READ_WRITE or READ_ONLY. If you are attaching or creating a boot disk, this must read-write mode. -
source
- (Optional) The name (not self_link) of the disk (such as those managed bygoogleComputeDisk
) to attach. \~> Note: Eithersource
,sourceImage
, orsourceSnapshot
is required in a disk block unless the disk type islocalSsd
. Check the API docs for details. -
diskType
- (Optional) The GCE disk type. Such as"pdSsd"
,"localSsd"
,"pdBalanced"
or"pdStandard"
. -
diskSizeGb
- (Optional) The size of the image in gigabytes. If not specified, it will inherit the size of its base image. For SCRATCH disks, the size must be exactly 375GB. -
labels
- (Optional) A set of ket/value label pairs to assign to disk created from this template -
type
- (Optional) The type of GCE disk, can be either"scratch"
or"persistent"
. -
diskEncryptionKey
- (Optional) Encrypts or decrypts a disk using a customer-supplied encryption key.If you are creating a new disk, this field encrypts the new disk using an encryption key that you provide. If you are attaching an existing disk that is already encrypted, this field decrypts the disk using the customer-supplied encryption key.
If you encrypt a disk using a customer-supplied key, you must provide the same key again when you attempt to use this resource at a later time. For example, you must provide the key when you create a snapshot or an image from the disk or when you attach the disk to a virtual machine instance.
If you do not provide an encryption key, then the disk will be encrypted using an automatically generated key and you do not need to provide a key to use the disk later.
Instance templates do not store customer-supplied encryption keys, so you cannot use your own keys to encrypt disks in a managed instance group. Structure documented below.
-
resourcePolicies
(Optional) -- A list (short name or id) of resource policies to attach to this disk for automatic snapshot creations. Currently a max of 1 resource policy is supported.
The sourceImageEncryptionKey
block supports:
-
kmsKeyServiceAccount
- (Optional) The service account being used for the encryption request for the given KMS key. If absent, the Compute Engine default service account is used. -
kmsKeySelfLink
- (Required) The self link of the encryption key that is stored in Google Cloud KMS.
The sourceSnapshotEncryptionKey
block supports:
-
kmsKeyServiceAccount
- (Optional) The service account being used for the encryption request for the given KMS key. If absent, the Compute Engine default service account is used. -
kmsKeySelfLink
- (Required) The self link of the encryption key that is stored in Google Cloud KMS.
The diskEncryptionKey
block supports:
kmsKeySelfLink
- (Required) The self link of the encryption key that is stored in Google Cloud KMS
The networkInterface
block supports:
-
network
- (Optional) The name or self_link of the network to attach this interface to. Usenetwork
attribute for Legacy or Auto subnetted networks andsubnetwork
for custom subnetted networks. -
subnetwork
- (Optional) the name of the subnetwork to attach this interface to. The subnetwork must exist in the sameregion
this instance will be created in. Eithernetwork
orsubnetwork
must be provided. -
subnetworkProject
- (Optional) The ID of the project in which the subnetwork belongs. If it is not provided, the provider project is used. -
networkIp
- (Optional) The private IP address to assign to the instance. If empty, the address will be automatically assigned. -
accessConfig
- (Optional) Access configurations, i.e. IPs via which this instance can be accessed via the Internet. Omit to ensure that the instance is not accessible from the Internet (this means that ssh provisioners will not work unless you are running Terraform can send traffic to the instance's network (e.g. via tunnel or because it is running on another cloud instance on that network). This block can be repeated multiple times. Structure documented below. -
aliasIpRange
- (Optional) An array of alias IP ranges for this network interface. Can only be specified for network interfaces on subnet-mode networks. Structure documented below. -
nicType
- (Optional) The type of vNIC to be used on this interface. Possible values: GVNIC, VIRTIO_NET. -
stackType
- (Optional) The stack type for this network interface to identify whether the IPv6 feature is enabled or not. Values are IPV4_IPV6 or IPV4_ONLY. If not specified, IPV4_ONLY will be used. -
ipv6AccessConfig
- (Optional) An array of IPv6 access configurations for this interface. Currently, only one IPv6 access config, DIRECT_IPV6, is supported. If there is no ipv6AccessConfig specified, then this instance will have no external IPv6 Internet access. Structure documented below. -
queueCount
- (Optional) The networking queue count that's specified by users for the network interface. Both Rx and Tx queues will be set to this number. It will be empty if not specified.
The accessConfig
block supports:
-
natIp
- (Optional) The IP address that will be 1:1 mapped to the instance's network ip. If not given, one will be generated. -
networkTier
- (Optional) The networking tier used for configuring this instance template. This field can take the following values: PREMIUM, STANDARD or FIXED_STANDARD. If this field is not specified, it is assumed to be PREMIUM.
The ipv6AccessConfig
block supports:
networkTier
- (Optional) The service-level to be provided for IPv6 traffic when the subnet has an external subnet. Only PREMIUM and STANDARD tier is valid for IPv6.
The aliasIpRange
block supports:
-
ipCidrRange
- The IP CIDR range represented by this alias IP range. This IP CIDR range must belong to the specified subnetwork and cannot contain IP addresses reserved by system or used by other network interfaces. At the time of writing only a netmask (e.g. /24) may be supplied, with a CIDR format resulting in an API error. -
subnetworkRangeName
- (Optional) The subnetwork secondary range name specifying the secondary range from which to allocate the IP CIDR range for this alias IP range. If left unspecified, the primary range of the subnetwork will be used.
The serviceAccount
block supports:
-
email
- (Optional) The service account e-mail address. If not given, the default Google Compute Engine service account is used. -
scopes
- (Required) A list of service scopes. Both OAuth2 URLs and gcloud short names are supported. To allow full access to all Cloud APIs, use thecloudPlatform
scope. See a complete list of scopes here.The service accounts documentation explains that access scopes are the legacy method of specifying permissions for your instance. If you are following best practices and using IAM roles to grant permissions to service accounts, then you can define this field as an empty list.
The scheduling
block supports:
-
automaticRestart
- (Optional) Specifies whether the instance should be automatically restarted if it is terminated by Compute Engine (not terminated by a user). This defaults to true. -
onHostMaintenance
- (Optional) Defines the maintenance behavior for this instance. -
preemptible
- (Optional) Allows instance to be preempted. This defaults to false. Read more on this here. -
nodeAffinities
- (Optional) Specifies node affinities or anti-affinities to determine which sole-tenant nodes your instances and managed instance groups will use as host systems. Read more on sole-tenant node creation here. Structure documented below. -
provisioningModel
- (Optional) Describe the type of preemptible VM. This field accepts the valuestandard
orspot
. If the value isstandard
, there will be no discount. If this is set tospot
,preemptible
should betrue
andautoRestart
should befalse
. For more info aboutspot
, read here -
instanceTerminationAction
- (Optional) Describe the type of termination action forspot
VM. Can bestop
ordelete
. Read more on here -
maxRunDuration
- (Optional) Beta The duration of the instance. Instance will run and be terminated after then, the termination action could be defined ininstanceTerminationAction
. Only supportdelete
instanceTerminationAction
at this point. Structure is documented below. ThemaxRunDuration
block supports: -
nanos
- (Optional) Span of time that's a fraction of a second at nanosecond resolution. Durations less than one second are represented with a 0seconds
field and a positivenanos
field. Must be from 0 to 999,999,999 inclusive. -
seconds
- (Required) Span of time at a resolution of a second. Must be from 0 to 315,576,000,000 inclusive. Note: these bounds are computed from: 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years. -
maintenanceInterval
- (Optional) Beta Specifies the frequency of planned maintenance events. The accepted values are:periodic
. TheguestAccelerator
block supports: -
type
(Required) - The accelerator type resource to expose to this instance. E.g.nvidiaTeslaK80
. -
count
(Required) - The number of the guest accelerator cards exposed to this instance.
The nodeAffinities
block supports:
-
key
(Required) - The key for the node affinity label. -
operator
(Required) - The operator. Can bein
for node-affinities ornotIn
for anti-affinities. -
value
(Required) - The values for the node affinity label.
The reservationAffinity
block supports:
-
type
- (Required) The type of reservation from which this instance can consume resources. -
specificReservation
- (Optional) Specifies the label selector for the reservation to use.. Structure is documented below.
The specificReservation
block supports:
-
key
- (Required) Corresponds to the label key of a reservation resource. To target a SPECIFIC_RESERVATION by name, specify compute.googleapis.com/reservation-name as the key and specify the name of your reservation as the only value. -
values
- (Required) Corresponds to the label values of a reservation resource.
The shieldedInstanceConfig
block supports:
-
enableSecureBoot
(Optional) -- Verify the digital signature of all boot components, and halt the boot process if signature verification fails. Defaults to false. -
enableVtpm
(Optional) -- Use a virtualized trusted platform module, which is a specialized computer chip you can use to encrypt objects like keys and certificates. Defaults to true. -
enableIntegrityMonitoring
(Optional) -- Compare the most recent boot measurements to the integrity policy baseline and return a pair of pass/fail results depending on whether they match or not. Defaults to true.
The confidentialInstanceConfig
block supports:
enableConfidentialCompute
(Optional) Defines whether the instance should have confidential compute enabled.onHostMaintenance
has to be set to TERMINATE or this will fail to create the VM.
The networkPerformanceConfig
block supports:
totalEgressBandwidthTier
- (Optional) The egress bandwidth tier to enable. Possible values: TIER_1, DEFAULT
The advancedMachineFeatures
block supports:
-
enableNestedVirtualization
(Optional) Defines whether the instance should have nested virtualization enabled. Defaults to false. -
threadsPerCore
(Optional) The number of threads per physical core. To disable simultaneous multithreading (SMT) set this to 1. -
visibleCoreCount
(Optional, Beta) The number of physical cores to expose to an instance. visible cores info (VC).
Attributes Reference
In addition to the arguments listed above, the following computed attributes are exported:
-
id
- an identifier for the resource with formatprojects/{{project}}/global/instanceTemplates/{{name}}
-
metadataFingerprint
- The unique fingerprint of the metadata. -
selfLink
- The URI of the created resource. -
tagsFingerprint
- The unique fingerprint of the tags.
Timeouts
This resource provides the following Timeouts configuration options: configuration options:
create
- Default is 4 minutes.delete
- Default is 4 minutes.
Import
Instance templates can be imported using any of these accepted formats: