Skip to content

Resource: awsInstance

Provides an EC2 instance resource. This allows instances to be created, updated, and deleted. Instances also support provisioning.

Example Usage

Basic example using AMI lookup

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsAmiUbuntu = new aws.dataAwsAmi.DataAwsAmi(this, "ubuntu", {
  filter: [
    {
      name: "name",
      values: ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"],
    },
    {
      name: "virtualization-type",
      values: ["hvm"],
    },
  ],
  mostRecent: true,
  owners: ["099720109477"],
});
new aws.instance.Instance(this, "web", {
  ami: dataAwsAmiUbuntu.id,
  instanceType: "t3.micro",
  tags: {
    Name: "HelloWorld",
  },
});

Network and credit specification example

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsVpcMyVpc = new aws.vpc.Vpc(this, "my_vpc", {
  cidrBlock: "172.16.0.0/16",
  tags: {
    Name: "tf-example",
  },
});
const awsSubnetMySubnet = new aws.subnet.Subnet(this, "my_subnet", {
  availabilityZone: "us-west-2a",
  cidrBlock: "172.16.10.0/24",
  tags: {
    Name: "tf-example",
  },
  vpcId: awsVpcMyVpc.id,
});
const awsNetworkInterfaceFoo = new aws.networkInterface.NetworkInterface(
  this,
  "foo",
  {
    privateIps: ["172.16.10.100"],
    subnetId: awsSubnetMySubnet.id,
    tags: {
      Name: "primary_network_interface",
    },
  }
);
const awsInstanceFoo = new aws.instance.Instance(this, "foo_3", {
  ami: "ami-005e54dee72cc1d00",
  creditSpecification: {
    cpuCredits: "unlimited",
  },
  instanceType: "t2.micro",
  networkInterface: [
    {
      deviceIndex: 0,
      networkInterfaceId: awsNetworkInterfaceFoo.id,
    },
  ],
});
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsInstanceFoo.overrideLogicalId("foo");

Host resource group or Licence Manager registered AMI example

A host resource group is a collection of Dedicated Hosts that you can manage as a single entity. As you launch instances, License Manager allocates the hosts and launches instances on them based on the settings that you configured. You can add existing Dedicated Hosts to a host resource group and take advantage of automated host management through License Manager.

-> NOTE: A dedicated host is automatically associated with a License Manager host resource group if Allocate hosts automatically is enabled. Otherwise, use the hostResourceGroupArn argument to explicitly associate the instance with the host resource group.

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.instance.Instance(this, "this", {
  ami: "ami-0dcc1e21636832c5d",
  hostResourceGroupArn:
    "arn:aws:resource-groups:us-west-2:012345678901:group/win-testhost",
  instanceType: "m5.large",
  tenancy: "host",
});

Argument Reference

The following arguments are supported:

  • ami - (Optional) AMI to use for the instance. Required unless launchTemplate is specified and the Launch Template specifes an AMI. If an AMI is specified in the Launch Template, setting ami will override the AMI specified in the Launch Template.

  • associatePublicIpAddress - (Optional) Whether to associate a public IP address with an instance in a VPC.

  • availabilityZone - (Optional) AZ to start the instance in.

  • capacityReservationSpecification - (Optional) Describes an instance's Capacity Reservation targeting option. See Capacity Reservation Specification below for more details.

-> NOTE: Changing cpuCoreCount and/or cpuThreadsPerCore will cause the resource to be destroyed and re-created.

  • cpuCoreCount - (Optional) Sets the number of CPU cores for an instance. This option is only supported on creation of instance type that support CPU Options CPU Cores and Threads Per CPU Core Per Instance Type - specifying this option for unsupported instance types will return an error from the EC2 API.
  • cpuThreadsPerCore - (Optional - has no effect unless cpuCoreCount is also set) If set to 1, hyperthreading is disabled on the launched instance. Defaults to 2 if not set. See Optimizing CPU Options for more information.
  • creditSpecification - (Optional) Configuration block for customizing the credit specification of the instance. See Credit Specification below for more details. Terraform will only perform drift detection of its value when present in a configuration. Removing this configuration on existing instances will only stop managing it. It will not change the configuration back to the default for the instance type.
  • disableApiStop - (Optional) If true, enables EC2 Instance Stop Protection.
  • disableApiTermination - (Optional) If true, enables EC2 Instance Termination Protection.
  • ebsBlockDevice - (Optional) One or more configuration blocks with additional EBS block devices to attach to the instance. Block device configurations only apply on resource creation. See Block Devices below for details on attributes and drift detection. When accessing this as an attribute reference, it is a set of objects.
  • ebsOptimized - (Optional) If true, the launched EC2 instance will be EBS-optimized. Note that if this is not set on an instance type that is optimized by default then this will show as disabled but if the instance type is optimized by default then there is no need to set this and there is no effect to disabling it. See the EBS Optimized section of the AWS User Guide for more information.
  • enclaveOptions - (Optional) Enable Nitro Enclaves on launched instances. See Enclave Options below for more details.
  • ephemeralBlockDevice - (Optional) One or more configuration blocks to customize Ephemeral (also known as "Instance Store") volumes on the instance. See Block Devices below for details. When accessing this as an attribute reference, it is a set of objects.
  • getPasswordData - (Optional) If true, wait for password data to become available and retrieve it. Useful for getting the administrator password for instances running Microsoft Windows. The password data is exported to the passwordData attribute. See GetPasswordData for more information.
  • hibernation - (Optional) If true, the launched EC2 instance will support hibernation.
  • hostId - (Optional) ID of a dedicated host that the instance will be assigned to. Use when an instance is to be launched on a specific dedicated host.
  • hostResourceGroupArn - (Optional) ARN of the host resource group in which to launch the instances. If you specify an ARN, omit the tenancy parameter or set it to host.
  • iamInstanceProfile - (Optional) IAM Instance Profile to launch the instance with. Specified as the name of the Instance Profile. Ensure your credentials have the correct permission to assign the instance profile according to the EC2 documentation, notably iam:passRole.
  • instanceInitiatedShutdownBehavior - (Optional) Shutdown behavior for the instance. Amazon defaults this to stop for EBS-backed instances and terminate for instance-store instances. Cannot be set on instance-store instances. See Shutdown Behavior for more information.
  • instanceType - (Optional) Instance type to use for the instance. Required unless launchTemplate is specified and the Launch Template specifies an instance type. If an instance type is specified in the Launch Template, setting instanceType will override the instance type specified in the Launch Template. Updates to this field will trigger a stop/start of the EC2 instance.
  • ipv6AddressCount- (Optional) Number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet.
  • ipv6Addresses - (Optional) Specify one or more IPv6 addresses from the range of the subnet to associate with the primary network interface
  • keyName - (Optional) Key name of the Key Pair to use for the instance; which can be managed using the awsKeyPair resource.
  • launchTemplate - (Optional) Specifies a Launch Template to configure the instance. Parameters configured on this resource will override the corresponding parameters in the Launch Template. See Launch Template Specification below for more details.
  • maintenanceOptions - (Optional) Maintenance and recovery options for the instance. See Maintenance Options below for more details.
  • metadataOptions - (Optional) Customize the metadata options of the instance. See Metadata Options below for more details.
  • monitoring - (Optional) If true, the launched EC2 instance will have detailed monitoring enabled. (Available since v0.6.0)
  • networkInterface - (Optional) Customize network interfaces to be attached at instance boot time. See Network Interfaces below for more details.
  • placementGroup - (Optional) Placement Group to start the instance in.
  • placementPartitionNumber - (Optional) Number of the partition the instance is in. Valid only if the awsPlacementGroup resource's strategy argument is set to "partition".
  • privateDnsNameOptions - (Optional) Options for the instance hostname. The default values are inherited from the subnet. See Private DNS Name Options below for more details.
  • privateIp - (Optional) Private IP address to associate with the instance in a VPC.
  • rootBlockDevice - (Optional) Configuration block to customize details about the root block device of the instance. See Block Devices below for details. When accessing this as an attribute reference, it is a list containing one object.
  • secondaryPrivateIps - (Optional) List of secondary private IPv4 addresses to assign to the instance's primary network interface (eth0) in a VPC. Can only be assigned to the primary network interface (eth0) attached at instance creation, not a pre-existing network interface i.e., referenced in a networkInterface block. Refer to the Elastic network interfaces documentation to see the maximum number of private IP addresses allowed per instance type.
  • securityGroups - (Optional, EC2-Classic and default VPC only) List of security group names to associate with.

-> NOTE: If you are creating Instances in a VPC, use vpcSecurityGroupIds instead.

  • sourceDestCheck - (Optional) Controls if traffic is routed to the instance when the destination address does not match the instance. Used for NAT or VPNs. Defaults true.
  • subnetId - (Optional) VPC Subnet ID to launch in.
  • tags - (Optional) Map of tags to assign to the resource. Note that these tags apply to the instance and not block storage devices. If configured with a provider defaultTags configuration block present, tags with matching keys will overwrite those defined at the provider-level.
  • tenancy - (Optional) Tenancy of the instance (if the instance is running in a VPC). An instance with a tenancy of dedicated runs on single-tenant hardware. The host tenancy is not supported for the import-instance command. Valid values are default, dedicated, and host.
  • userData - (Optional) User data to provide when launching the instance. Do not pass gzip-compressed data via this argument; see userDataBase64 instead. Updates to this field will trigger a stop/start of the EC2 instance by default. If the userDataReplaceOnChange is set then updates to this field will trigger a destroy and recreate.
  • userDataBase64 - (Optional) Can be used instead of userData to pass base64-encoded binary data directly. Use this instead of userData whenever the value is not a valid UTF-8 string. For example, gzip-encoded user data must be base64-encoded and passed via this argument to avoid corruption. Updates to this field will trigger a stop/start of the EC2 instance by default. If the userDataReplaceOnChange is set then updates to this field will trigger a destroy and recreate.
  • userDataReplaceOnChange - (Optional) When used in combination with userData or userDataBase64 will trigger a destroy and recreate when set to true. Defaults to false if not set.
  • volumeTags - (Optional) Map of tags to assign, at instance-creation time, to root and EBS volumes.

\~> NOTE: Do not use volumeTags if you plan to manage block device tags outside the awsInstance configuration, such as using tags in an awsEbsVolume resource attached via awsVolumeAttachment. Doing so will result in resource cycling and inconsistent behavior.

  • vpcSecurityGroupIds - (Optional, VPC only) List of security group IDs to associate with.

Capacity Reservation Specification

\~> NOTE: You can specify only one argument at a time. If you specify both capacityReservationPreference and capacityReservationTarget, the request fails. Modifying capacityReservationPreference or capacityReservationTarget in this block requires the instance to be in stopped state.

Capacity reservation specification can be applied/modified to the EC2 Instance at creation time or when the instance is stopped.

The capacityReservationSpecification block supports the following:

  • capacityReservationPreference - (Optional) Indicates the instance's Capacity Reservation preferences. Can be "open" or "none". (Default: "open").
  • capacityReservationTarget - (Optional) Information about the target Capacity Reservation. See Capacity Reservation Target below for more details.

For more information, see the documentation on Capacity Reservations.

Capacity Reservation Target

\~> NOTE: Modifying capacityReservationId in this block requires the instance to be in stopped state.

Describes a target Capacity Reservation.

This capacityReservationTarget block supports the following:

  • capacityReservationId - (Optional) ID of the Capacity Reservation in which to run the instance.
  • capacityReservationResourceGroupArn - (Optional) ARN of the Capacity Reservation resource group in which to run the instance.

Credit Specification

The creditSpecification block supports the following:

  • cpuCredits - (Optional) Credit option for CPU usage. Valid values include standard or unlimited. T3 instances are launched as unlimited by default. T2 instances are launched as standard by default.

EBS, Ephemeral, and Root Block Devices

Each of the *BlockDevice attributes control a portion of the EC2 Instance's "Block Device Mapping". For more information, see the AWS Block Device Mapping documentation.

The rootBlockDevice block supports the following:

  • deleteOnTermination - (Optional) Whether the volume should be destroyed on instance termination. Defaults to true.
  • encrypted - (Optional) Whether to enable volume encryption. Defaults to false. Must be configured to perform drift detection.
  • iops - (Optional) Amount of provisioned IOPS. Only valid for volume_type of io1, io2 or gp3.
  • kmsKeyId - (Optional) Amazon Resource Name (ARN) of the KMS Key to use when encrypting the volume. Must be configured to perform drift detection.
  • tags - (Optional) Map of tags to assign to the device.
  • throughput - (Optional) Throughput to provision for a volume in mebibytes per second (MiB/s). This is only valid for volumeType of gp3.
  • volumeSize - (Optional) Size of the volume in gibibytes (GiB).
  • volumeType - (Optional) Type of volume. Valid values include standard, gp2, gp3, io1, io2, sc1, or st1. Defaults to gp2.

Modifying the encrypted or kmsKeyId settings of the rootBlockDevice requires resource replacement.

Each ebsBlockDevice block supports the following:

  • deleteOnTermination - (Optional) Whether the volume should be destroyed on instance termination. Defaults to true.
  • deviceName - (Required) Name of the device to mount.
  • encrypted - (Optional) Enables EBS encryption on the volume. Defaults to false. Cannot be used with snapshotId. Must be configured to perform drift detection.
  • iops - (Optional) Amount of provisioned IOPS. Only valid for volume_type of io1, io2 or gp3.
  • kmsKeyId - (Optional) Amazon Resource Name (ARN) of the KMS Key to use when encrypting the volume. Must be configured to perform drift detection.
  • snapshotId - (Optional) Snapshot ID to mount.
  • tags - (Optional) Map of tags to assign to the device.
  • throughput - (Optional) Throughput to provision for a volume in mebibytes per second (MiB/s). This is only valid for volumeType of gp3.
  • volumeSize - (Optional) Size of the volume in gibibytes (GiB).
  • volumeType - (Optional) Type of volume. Valid values include standard, gp2, gp3, io1, io2, sc1, or st1. Defaults to gp2.

\~> NOTE: Currently, changes to the ebsBlockDevice configuration of existing resources cannot be automatically detected by Terraform. To manage changes and attachments of an EBS block to an instance, use the awsEbsVolume and awsVolumeAttachment resources instead. If you use ebsBlockDevice on an awsInstance, Terraform will assume management over the full set of non-root EBS block devices for the instance, treating additional block devices as drift. For this reason, ebsBlockDevice cannot be mixed with external awsEbsVolume and awsVolumeAttachment resources for a given instance.

Each ephemeralBlockDevice block supports the following:

  • deviceName - Name of the block device to mount on the instance.
  • noDevice - (Optional) Suppresses the specified device included in the AMI's block device mapping.
  • virtualName - (Optional) Instance Store Device Name (e.g., ephemeral0).

Each AWS Instance type has a different set of Instance Store block devices available for attachment. AWS publishes a list of which ephemeral devices are available on each type. The devices are always identified by the virtualName in the format ephemeral{0N}.

Enclave Options

-> NOTE: Changing enabled will cause the resource to be destroyed and re-created.

Enclave options apply to the instance at boot time.

The enclaveOptions block supports the following:

  • enabled - (Optional) Whether Nitro Enclaves will be enabled on the instance. Defaults to false.

For more information, see the documentation on Nitro Enclaves.

Maintenance Options

The maintenanceOptions block supports the following:

  • autoRecovery - (Optional) Automatic recovery behavior of the Instance. Can be "default" or "disabled". See Recover your instance for more details.

Metadata Options

Metadata options can be applied/modified to the EC2 Instance at any time.

The metadataOptions block supports the following:

  • httpEndpoint - (Optional) Whether the metadata service is available. Valid values include enabled or disabled. Defaults to enabled.
  • httpPutResponseHopLimit - (Optional) Desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. Valid values are integer from 1 to 64. Defaults to 1.
  • httpTokens - (Optional) Whether or not the metadata service requires session tokens, also referred to as Instance Metadata Service Version 2 (IMDSv2). Valid values include optional or required. Defaults to optional.
  • instanceMetadataTags - (Optional) Enables or disables access to instance tags from the instance metadata service. Valid values include enabled or disabled. Defaults to disabled.

For more information, see the documentation on the Instance Metadata Service.

Network Interfaces

Each of the networkInterface blocks attach a network interface to an EC2 Instance during boot time. However, because the network interface is attached at boot-time, replacing/modifying the network interface WILL trigger a recreation of the EC2 Instance. If you should need at any point to detach/modify/re-attach a network interface to the instance, use the awsNetworkInterface or awsNetworkInterfaceAttachment resources instead.

The networkInterface configuration block does, however, allow users to supply their own network interface to be used as the default network interface on an EC2 Instance, attached at eth0.

Each networkInterface block supports the following:

  • deleteOnTermination - (Optional) Whether or not to delete the network interface on instance termination. Defaults to false. Currently, the only valid value is false, as this is only supported when creating new network interfaces when launching an instance.
  • deviceIndex - (Required) Integer index of the network interface attachment. Limited by instance type.
  • networkCardIndex - (Optional) Integer index of the network card. Limited by instance type. The default index is 0.
  • networkInterfaceId - (Required) ID of the network interface to attach.

Private DNS Name Options

The privateDnsNameOptions block supports the following:

  • enableResourceNameDnsAaaaRecord - Indicates whether to respond to DNS queries for instance hostnames with DNS AAAA records.
  • enableResourceNameDnsARecord - Indicates whether to respond to DNS queries for instance hostnames with DNS A records.
  • hostnameType - Type of hostname for Amazon EC2 instances. For IPv4 only subnets, an instance DNS name must be based on the instance IPv4 address. For IPv6 native subnets, an instance DNS name must be based on the instance ID. For dual-stack subnets, you can specify whether DNS names use the instance IPv4 address or the instance ID. Valid values: ipName and resourceName.

Launch Template Specification

-> Note: Launch Template parameters will be used only once during instance creation. If you want to update existing instance you need to change parameters directly. Updating Launch Template specification will force a new instance.

Any other instance parameters that you specify will override the same parameters in the launch template.

The launchTemplate block supports the following:

  • id - ID of the launch template. Conflicts with name.
  • name - Name of the launch template. Conflicts with id.
  • version - Template version. Can be a specific version number, $latest or $default. The default value is $default.

Attributes Reference

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

  • arn - ARN of the instance.
  • capacityReservationSpecification - Capacity reservation specification of the instance.
  • instanceState - State of the instance. One of: pending, running, shuttingDown, terminated, stopping, stopped. See Instance Lifecycle for more information.
  • outpostArn - ARN of the Outpost the instance is assigned to.
  • passwordData - Base-64 encoded encrypted password data for the instance. Useful for getting the administrator password for instances running Microsoft Windows. This attribute is only exported if getPasswordData is true. Note that this encrypted value will be stored in the state file, as with all exported attributes. See GetPasswordData for more information.
  • primaryNetworkInterfaceId - ID of the instance's primary network interface.
  • privateDns - Private DNS name assigned to the instance. Can only be used inside the Amazon EC2, and only available if you've enabled DNS hostnames for your VPC.
  • publicDns - Public DNS name assigned to the instance. For EC2-VPC, this is only available if you've enabled DNS hostnames for your VPC.
  • publicIp - Public IP address assigned to the instance, if applicable. NOTE: If you are using an awsEip with your instance, you should refer to the EIP's address directly and not use publicIp as this field will change after the EIP is attached.
  • tagsAll - Map of tags assigned to the resource, including those inherited from the provider defaultTags configuration block.

For ebsBlockDevice, in addition to the arguments above, the following attribute is exported:

  • volumeId - ID of the volume. For example, the ID can be accessed like this, awsInstanceWebEbsBlockDevice2VolumeId.

For rootBlockDevice, in addition to the arguments above, the following attributes are exported:

  • volumeId - ID of the volume. For example, the ID can be accessed like this, awsInstanceWebRootBlockDevice0VolumeId.
  • deviceName - Device name, e.g., /dev/sdh or xvdh.

Timeouts

Configuration options:

  • create - (Default 10M)
  • update - (Default 10M)
  • delete - (Default 20M)

Import

Instances can be imported using the id, e.g.,

$ terraform import aws_instance.web i-12345678