Skip to content

googleComputeInstance

Manages a VM instance 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 googleServiceAccountDefault = new google.serviceAccount.ServiceAccount(
  this,
  "default",
  {
    account_id: "service_account_id",
    display_name: "Service Account",
  }
);
const googleComputeInstanceDefault = new google.computeInstance.ComputeInstance(
  this,
  "default_1",
  {
    boot_disk: [
      {
        initialize_params: [
          {
            image: "debian-cloud/debian-11",
            labels: [
              {
                my_label: "value",
              },
            ],
          },
        ],
      },
    ],
    machine_type: "e2-medium",
    metadata: [
      {
        foo: "bar",
      },
    ],
    metadata_startup_script: "echo hi > /test.txt",
    name: "test",
    network_interface: [
      {
        access_config: [{}],
        network: "default",
      },
    ],
    scratch_disk: [
      {
        interface: "SCSI",
      },
    ],
    service_account: [
      {
        email: googleServiceAccountDefault.email,
        scopes: ["cloud-platform"],
      },
    ],
    tags: ["foo", "bar"],
    zone: "us-central1-a",
  }
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
googleComputeInstanceDefault.overrideLogicalId("default");

Argument Reference

The following arguments are supported:

  • bootDisk - (Required) The boot disk for the instance. Structure is documented below.

  • machineType - (Required) The machine type to create.

    Note: If you want to update this value (resize the VM) after initial creation, you must set allowStoppingForUpdate to true.

    Custom machine types can be formatted as customNumberOfCpusAmountOfMemoryMb, e.g. custom620480 for 6 vCPU and 20GB of RAM.

    There is a limit of 6.5 GB per CPU unless you add extended memory. You must do this explicitly by adding the suffix ext, e.g. custom215360Ext for 2 vCPU and 15 GB of memory.

  • name - (Required) A unique name for the resource, required by GCE. Changing this forces a new resource to be created.

  • zone - (Optional) The zone that the machine should be created in. If it is not provided, the provider zone is used.

  • networkInterface - (Required) Networks to attach to the instance. This can be specified multiple times. Structure is documented below.


  • allowStoppingForUpdate - (Optional) If true, allows Terraform to stop the instance to update its properties. If you try to update a property that requires stopping the instance without setting this field, the update will fail.

  • attachedDisk - (Optional) Additional disks to attach to the instance. Can be repeated multiple times for multiple disks. Structure is documented below.

  • 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.

  • desiredStatus - (Optional) Desired status of the instance. Either "running" or "terminated".

  • deletionProtection - (Optional) Enable deletion protection on this instance. Defaults to false. Note: you must disable deletion protection before removing the resource (e.g., via terraformDestroy), or the instance cannot be deleted and the Terraform run will not complete successfully.

  • hostname - (Optional) A custom hostname for the instance. Must be a fully qualified DNS name and RFC-1035-valid. Valid format is a series of labels 1-63 characters long matching the regular expression [aZ]([AZ09]*[aZ09]), concatenated with periods. The entire hostname must not exceed 253 characters. Changing this forces a new resource to be created.

  • guestAccelerator - (Optional) List of the type and count of accelerator cards attached to the instance. Structure documented below. Note: GPU accelerators can only be used with onHostMaintenance option set to TERMINATE. Note: This field uses attr-as-block mode to avoid breaking users during the 0.12 upgrade. To explicitly send a list of zero objects you must use the following syntax: example=[] For more details about this behavior, see this section.

  • labels - (Optional) A map of key/value label pairs to assign to the instance.

  • metadata - (Optional) Metadata key/value pairs to make available from within the instance. Ssh keys attached in the Cloud Console will be removed. Add them to your config in order to keep them attached to your instance. A list of default metadata values (e.g. ssh-keys) can be found here

-> Depending on the OS you choose for your instance, some metadata keys have special functionality. Most linux-based images will run the content of metadataStartupScript in a shell on every boot. At a minimum, Debian, CentOS, RHEL, SLES, Container-Optimized OS, and Ubuntu images support this key. Windows instances require other keys depending on the format of the script and the time you would like it to run - see this table. For the convenience of the users of metadataStartupScript, we provide a special attribute, metadataStartupScript, which is documented below.

  • metadataStartupScript - (Optional) An alternative to using the startup-script metadata key, except this one forces the instance to be recreated (thus re-running the script) if it is changed. This replaces the startup-script metadata key on the created instance and thus the two mechanisms are not allowed to be used simultaneously. Users are free to use either mechanism - the only distinction is that this separate attribute will cause a recreate on modification. On import, metadataStartupScript will not be set - if you choose to specify it you will see a diff immediately after import causing a destroy/recreate operation. If importing an instance and specifying this value is desired, you will need to modify your state file manually using terraformState commands.

  • minCpuPlatform - (Optional) Specifies a minimum CPU platform for the VM instance. Applicable values are the friendly names of CPU platforms, such as intelHaswell or intelSkylake. See the complete list here. Note: allowStoppingForUpdate must be set to true or your instance must have a desiredStatus of terminated in order to update this field.

  • project - (Optional) The ID of the project in which the resource belongs. If it is not provided, the provider project is used.

  • scheduling - (Optional) The scheduling strategy to use. More details about this configuration option are detailed below.

  • scratchDisk - (Optional) Scratch disks to attach to the instance. This can be specified multiple times for multiple scratch disks. Structure is documented below.

  • serviceAccount - (Optional) Service account to attach to the instance. Structure is documented below. Note: allowStoppingForUpdate must be set to true or your instance must have a desiredStatus of terminated in order to update this field.

  • tags - (Optional) A list of network tags to attach to the instance.

  • 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. Note: allowStoppingForUpdate must be set to true or your instance must have a desiredStatus of terminated in order to update this field.

  • enableDisplay - (Optional) Enable Virtual Displays on this instance. Note: allowStoppingForUpdate must be set to true or your instance must have a desiredStatus of terminated in order to update this field.

  • 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.

  • 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

  • networkPerformanceConfig (Optional, Beta Configures network performance settings for the instance. Structure is documented below. Note: machineType must be a supported type, the image used must include the gvnic in guestOsFeatures, and networkInterface0NicType must be gvnic in order for this setting to take effect.


The bootDisk block supports:

  • autoDelete - (Optional) Whether the disk will be auto-deleted when the instance is deleted. Defaults to true.

  • deviceName - (Optional) Name with which attached disk will be accessible. On the instance, this device will be /dev/disk/byId/google-{{deviceName}}.

  • mode - (Optional) The mode in which to attach this disk, either readWrite or readOnly. If not specified, the default is to attach the disk in readWrite mode.

  • diskEncryptionKeyRaw - (Optional) A 256-bit [customer-supplied encryption key] (https://cloud.google.com/compute/docs/disks/customer-supplied-encryption), encoded in RFC 4648 base64 to encrypt this disk. Only one of kmsKeySelfLink and diskEncryptionKeyRaw may be set.

  • kmsKeySelfLink - (Optional) The self_link of the encryption key that is stored in Google Cloud KMS to encrypt this disk. Only one of kmsKeySelfLink and diskEncryptionKeyRaw may be set.

  • initializeParams - (Optional) Parameters for a new disk that will be created alongside the new instance. Either initializeParams or source must be set. Structure is documented below.

  • source - (Optional) The name or self_link of the existing disk (such as those managed by googleComputeDisk) or disk image. To create an instance from a snapshot, first create a googleComputeDisk from a snapshot and reference it here.

The initializeParams block supports:

  • size - (Optional) The size of the image in gigabytes. If not specified, it will inherit the size of its base image.

  • type - (Optional) The GCE disk type. Such as pd-standard, pd-balanced or pd-ssd.

  • image - (Optional) The image from which to initialize this disk. This can be one of: the image's selfLink, 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}. If referred by family, the images names must include the family name. If they don't, use the google_compute_image data source. For instance, the image centos6V20180104 includes its family name centos6. These images can be referred by family name here.

  • labels - (Optional) A set of key/value label pairs assigned to the disk. This\ field is only applicable for persistent disks.

The scratchDisk block supports:

  • interface - (Required) The disk interface to use for attaching this disk; either SCSI or NVME.

The attachedDisk block supports:

  • source - (Required) The name or self_link of the disk to attach to this instance.

  • deviceName - (Optional) Name with which the attached disk will be accessible under /dev/disk/byId/google-*

  • mode - (Optional) Either "READ_ONLY" or "READ_WRITE", defaults to "READ_WRITE" If you have a persistent disk with data that you want to share between multiple instances, detach it from any read-write instances and attach it to one or more instances in read-only mode.

  • diskEncryptionKeyRaw - (Optional) A 256-bit [customer-supplied encryption key] (https://cloud.google.com/compute/docs/disks/customer-supplied-encryption), encoded in RFC 4648 base64 to encrypt this disk. Only one of kmsKeySelfLink and diskEncryptionKeyRaw may be set.

  • kmsKeySelfLink - (Optional) The self_link of the encryption key that is stored in Google Cloud KMS to encrypt this disk. Only one of kmsKeySelfLink and diskEncryptionKeyRaw may be set.

The networkPerformanceConfig block supports:

  • totalEgressBandwidthTier - (Optional) The egress bandwidth tier to enable. Possible values: TIER_1, DEFAULT

The networkInterface block supports:

  • network - (Optional) The name or self_link of the network to attach this interface to. Either network or subnetwork must be provided. If network isn't provided it will be inferred from the subnetwork.

  • subnetwork - (Optional) The name or self_link of the subnetwork to attach this interface to. Either network or subnetwork must be provided. If network isn't provided it will be inferred from the subnetwork. The subnetwork must exist in the same region this instance will be created in. If the network resource is in legacy mode, do not specify this field. If the network is in auto subnet mode, specifying the subnetwork is optional. If the network is in custom subnet mode, specifying the subnetwork is required.

  • subnetworkProject - (Optional) The project in which the subnetwork belongs. If the subnetwork is a self_link, this field is ignored in favor of the project defined in the subnetwork self_link. If the subnetwork is a name and this field 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. If omitted, ssh provisioners will not work unless 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.

  • publicPtrDomainName - (Optional) The DNS domain name for the public PTR record. To set this field on an instance, you must be verified as the owner of the domain. See the docs for how to become verified as a domain owner.

  • networkTier - (Optional) The networking tier used for configuring this instance. This field can take the following values: PREMIUM, FIXED_STANDARD or STANDARD. If this field is not specified, it is assumed to be PREMIUM.

The ipv6AccessConfig block supports:

  • publicPtrDomainName - (Optional) The domain name to be used when creating DNSv6 records for the external IPv6 ranges..

  • networkTier - (Optional) The service-level to be provided for IPv6 traffic when the subnet has an external subnet. Only PREMIUM or 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. This range may be a single IP address (e.g. 10.2.3.4), a netmask (e.g. /24) or a CIDR format string (e.g. 10.1.2.0/24).

  • 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. Note: allowStoppingForUpdate must be set to true or your instance must have a desiredStatus of terminated in order to update this field.

  • 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 the cloudPlatform scope. See a complete list of scopes here. Note: allowStoppingForUpdate must be set to true or your instance must have a desiredStatus of terminated in order to update this field.

The scheduling block supports:

  • preemptible - (Optional) Specifies if the instance is preemptible. If this field is set to true, then automaticRestart must be set to false. Defaults to false.

  • onHostMaintenance - (Optional) Describes maintenance behavior for the instance. Can be MIGRATE or TERMINATE, for more info, read here.

  • automaticRestart - (Optional) Specifies if the instance should be restarted if it was terminated by Compute Engine (not a user). Defaults to true.

  • 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.

  • minNodeCpus - (Optional) The minimum number of virtual CPUs this instance will consume when running on a sole-tenant node.

  • provisioningModel - (Optional) Describe the type of preemptible VM. This field accepts the value standard or spot. If the value is standard, there will be no discount. If this is set to spot, preemptible should be true and autoRestart should be false. For more info about spot, read here

  • instanceTerminationAction - (Optional) Describe the type of termination action for VM. Can be stop or delete. 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 in instanceTerminationAction. Only support delete instanceTerminationAction at this point. Structure is documented below. The maxRunDuration 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 0 seconds field and a positive nanos 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. The guestAccelerator 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 be in for node-affinities or notIn for anti-affinities.

  • values (Required) - The values for the node affinity label.

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. Note: allowStoppingForUpdate must be set to true or your instance must have a desiredStatus of terminated in order to update this field.

  • 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. Note: allowStoppingForUpdate must be set to true or your instance must have a desiredStatus of terminated in order to update this field.

  • 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. Note: allowStoppingForUpdate must be set to true or your instance must have a desiredStatus of terminated in order to update this field.

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 advancedMachineFeatures block supports:

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.

Attributes Reference

In addition to the arguments listed above, the following computed attributes are exported:

  • id - an identifier for the resource with format projects/{{project}}/zones/{{zone}}/instances/{{name}}

  • instanceId - The server-assigned unique identifier of this instance.

  • metadataFingerprint - The unique fingerprint of the metadata.

  • selfLink - The URI of the created resource.

  • tagsFingerprint - The unique fingerprint of the tags.

  • labelFingerprint - The unique fingerprint of the labels.

  • cpuPlatform - The CPU platform used by this instance.

  • ipv6AccessType - One of EXTERNAL, INTERNAL to indicate whether the IP can be accessed from the Internet. This field is always inherited from its subnetwork.

  • networkInterface0NetworkIp - The internal ip address of the instance, either manually or dynamically assigned.

  • networkInterface0AccessConfig0NatIp - If the instance has an access config, either the given external ip (in the natIp field) or the ephemeral (generated) ip (if you didn't provide one).

  • networkInterface0Ipv6AccessConfig0ExternalIpv6 - The first IPv6 address of the external IPv6 range associated with this instance, prefix length is stored in externalIpv6PrefixLength in ipv6AccessConfig. The field is output only, an IPv6 address from a subnetwork associated with the instance will be allocated dynamically.

  • networkInterface0Ipv6AccessConfig0ExternalIpv6PrefixLength - The prefix length of the external IPv6 range.

  • attachedDisk0DiskEncryptionKeySha256 - The RFC 4648 base64 encoded SHA-256 hash of the [customer-supplied encryption key] (https://cloud.google.com/compute/docs/disks/customer-supplied-encryption) that protects this resource.

  • bootDiskDiskEncryptionKeySha256 - The RFC 4648 base64 encoded SHA-256 hash of the [customer-supplied encryption key] (https://cloud.google.com/compute/docs/disks/customer-supplied-encryption) that protects this resource.

  • disk0DiskEncryptionKeySha256 - The RFC 4648 base64 encoded SHA-256 hash of the [customer-supplied encryption key] (https://cloud.google.com/compute/docs/disks/customer-supplied-encryption) that protects this resource.

Timeouts

This resource provides the following Timeouts configuration options: configuration options:

  • create - Default is 20 minutes.
  • update - Default is 20 minutes.
  • delete - Default is 20 minutes.

Import

\~> Note: The fields bootDisk0DiskEncryptionRaw and attachedDisk.*DiskEncryptionKeyRaw cannot be imported automatically. The API doesn't return this information. If you are setting one of these fields in your config, you will need to update your state manually after importing the resource.

-> Note: The desiredStatus field will not be set on import. If you have it set, Terraform will update the field on the next terraformApply, bringing your instance to the desired status.

Instances can be imported using any of these accepted formats:

$ terraform import google_compute_instance.default projects/{{project}}/zones/{{zone}}/instances/{{name}}
$ terraform import google_compute_instance.default {{project}}/{{zone}}/{{name}}
$ terraform import google_compute_instance.default {{name}}