AWS Fundamentals Logo
AWS Fundamentals
L2 Construct

Instance

This represents a single EC2 instance.

Import

import { Instance } from 'aws-cdk-lib/aws-ec2';

Or use the module namespace:

import * as ec2 from 'aws-cdk-lib/aws-ec2';
// ec2.Instance

Properties

Configuration passed to the constructor as InstanceProps.

instanceTypeRequired
InstanceType

Type of instance to launch.

machineImageRequired
IMachineImage

AMI to launch.

vpcRequired
IVpc

VPC to launch the instance in.

allowAllIpv6OutboundOptional
boolean

Whether the instance could initiate IPv6 connections to anywhere by default. This property is only used when you do not provide a security group.

Default: false

allowAllOutboundOptional
boolean

Whether the instance could initiate connections to anywhere by default. This property is only used when you do not provide a security group.

Default: true

associatePublicIpAddressOptional
boolean

Whether to associate a public IP address to the primary network interface attached to this instance. You cannot specify this property and `ipv6AddressCount` at the same time.

Default: - public IP address is automatically assigned based on default behavior

availabilityZoneOptional
string

In which AZ to place the instance within the VPC.

Default: - Random zone.

blockDevicesOptional
BlockDevice[]

Specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes. Each instance that is launched has an associated root device volume, either an Amazon EBS volume or an instance store volume. You can use block device mappings to specify additional EBS volumes or instance store volumes to attach to an instance when it is launched.

Default: - Uses the block device mapping of the AMI

creditSpecificationOptional
CpuCredits

Specifying the CPU credit type for burstable EC2 instance types (T2, T3, T3a, etc). The unlimited CPU credit option is not supported for T3 instances with a dedicated host.

Default: - T2 instances are standard, while T3, T4g, and T3a instances are unlimited.

detailedMonitoringOptional
boolean

Whether "Detailed Monitoring" is enabled for this instance Keep in mind that Detailed Monitoring results in extra charges.

Default: - false

disableApiTerminationOptional
boolean

If true, the instance will not be able to be terminated using the Amazon EC2 console, CLI, or API. To change this attribute after launch, use [ModifyInstanceAttribute](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceAttribute.html). Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate, you can terminate the instance by running the shutdown command from the instance.

Default: false

ebsOptimizedOptional
boolean

Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance.

Default: false

enclaveEnabledOptional
boolean

Whether the instance is enabled for AWS Nitro Enclaves. Nitro Enclaves requires a Nitro-based virtualized parent instance with specific Intel/AMD with at least 4 vCPUs or Graviton with at least 2 vCPUs instance types and Linux/Windows host OS, while the enclave itself supports only Linux OS. You can't set both `enclaveEnabled` and `hibernationEnabled` to true on the same instance.

Default: - false

hibernationEnabledOptional
boolean

Whether the instance is enabled for hibernation. You can't set both `enclaveEnabled` and `hibernationEnabled` to true on the same instance.

Default: - false

httpEndpointOptional
boolean

Enables or disables the HTTP metadata endpoint on your instances.

Default: true

httpProtocolIpv6Optional
boolean

Enables or disables the IPv6 endpoint for the instance metadata service.

Default: false

httpPutResponseHopLimitOptional
number

The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. Possible values: Integers from 1 to 64

Default: - No default value specified by CloudFormation

httpTokensOptional
HttpTokens

The state of token usage for your instance metadata requests. Set to 'required' to enforce IMDSv2. This is equivalent to using `requireImdsv2: true`, but allows you to configure other metadata options alongside IMDSv2 enforcement.

Default: - The default is conditional based on the AMI and account-level settings: - If the AMI's `ImdsSupport` is `v2.0` and the account level default is `no-preference`, the default is `HttpTokens.REQUIRED` - If the AMI's `ImdsSupport` is `v2.0` and the account level default is `V1 or V2`, the default is `HttpTokens.OPTIONAL` - See https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-options.html#instance-metadata-options-order-of-precedence

initOptional
CloudFormationInit

Apply the given CloudFormation Init configuration to the instance at startup.

Default: - no CloudFormation init

initOptionsOptional
ApplyCloudFormationInitOptions

Use the given options for applying CloudFormation Init. Describes the configsets to use and the timeout to wait

Default: - default options

instanceInitiatedShutdownBehaviorOptional
InstanceInitiatedShutdownBehavior

Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown).

Default: InstanceInitiatedShutdownBehavior.STOP

instanceMetadataTagsOptional
boolean

Set to enabled to allow access to instance tags from the instance metadata. Set to disabled to turn off access to instance tags from the instance metadata.

Default: false

instanceNameOptional
string

The name of the instance.

Default: - CDK generated name

instanceProfileOptional
IInstanceProfile

The instance profile used to pass role information to EC2 instances. Note: You can provide an instanceProfile or a role, but not both.

Default: - No instance profile

ipv6AddressCountOptional
number

The number of IPv6 addresses to associate with the primary network interface. Amazon EC2 chooses the IPv6 addresses from the range of your subnet. You cannot specify this property and `associatePublicIpAddress` at the same time.

Default: - For instances associated with an IPv6 subnet, use 1; otherwise, use 0.

keyNameOptionalDeprecated
string

Name of SSH keypair to grant access to instance.

Default: - No SSH access will be possible.

Deprecated: - Use `keyPair` instead - https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2-readme.html#using-an-existing-ec2-key-pair

keyPairOptional
IKeyPair

The SSH keypair to grant access to the instance.

Default: - No SSH access will be possible.

placementGroupOptional
IPlacementGroupRef

The placement group that you want to launch the instance into.

Default: - no placement group will be used for this instance.

privateIpAddressOptional
string

Defines a private IP address to associate with an instance. Private IP should be available within the VPC that the instance is build within.

Default: - no association

propagateTagsToVolumeOnCreationOptional
boolean

Propagate the EC2 instance tags to the EBS volumes.

Default: - false

requireImdsv2Optional
boolean

Whether IMDSv2 should be required on this instance. This is a simple boolean flag that enforces IMDSv2 by creating a Launch Template with `httpTokens: 'required'`. Use this for straightforward IMDSv2 enforcement. For more granular control over metadata options (like disabling the metadata endpoint, configuring hop limits, or enabling instance tags), use the individual metadata option properties instead.

Default: - false

resourceSignalTimeoutOptional
Duration

The length of time to wait for the resourceSignalCount. The maximum value is 43200 (12 hours).

Default: Duration.minutes(5)

roleOptional
IRole

An IAM role to associate with the instance profile assigned to this Auto Scaling Group. The role must be assumable by the service principal `ec2.amazonaws.com`: Note: You can provide an instanceProfile or a role, but not both.

Default: - A role will automatically be created, it can be accessed via the `role` property

securityGroupOptional
ISecurityGroup

Security Group to assign to this instance.

Default: - create new security group

sourceDestCheckOptional
boolean

Specifies whether to enable an instance launched in a VPC to perform NAT. This controls whether source/destination checking is enabled on the instance. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform NAT.

Default: true

ssmSessionPermissionsOptional
boolean

Add SSM session permissions to the instance role. Setting this to `true` adds the necessary permissions to connect to the instance using SSM Session Manager. You can do this from the AWS Console. NOTE: Setting this flag to `true` may not be enough by itself. You must also use an AMI that comes with the SSM Agent, or install the SSM Agent yourself. See [Working with SSM Agent](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html) in the SSM Developer Guide.

Default: false

userDataOptional
UserData

Specific UserData to use. The UserData may still be mutated after creation.

Default: - A UserData object appropriate for the MachineImage's Operating System is created.

userDataCausesReplacementOptional
boolean

Changes to the UserData force replacement. Depending the EC2 instance type, changing UserData either restarts the instance or replaces the instance. - Instance store-backed instances are replaced. - EBS-backed instances are restarted. By default, restarting does not execute the new UserData so you will need a different mechanism to ensure the instance is restarted. Setting this to `true` will make the instance's Logical ID depend on the UserData, which will cause CloudFormation to replace it if the UserData changes.

Default: - true if `initOptions` is specified, false otherwise.

vpcSubnetsOptional
SubnetSelection

Where to place the instance within the VPC.

Default: - Private subnets.

Get the Amazon EC2 Cheat Sheet

Everything you need to know about Amazon EC2 on one page. HD quality, print-friendly.

Download Free Infographic