# Instance

This represents a single EC2 instance.

Extends: Construct › Resource › Instance
Implements: IResource, IConnectable, IInstance, IGrantable, IEnvironmentAware, IInstanceRef, IConstruct, IDependable

- CloudFormation: [`AWS::EC2::Instance`](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-instance.html)
- L1 type: [`CfnInstance`](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.CfnInstance.html)
- Source: [`aws-ec2/lib/instance.ts`](https://github.com/aws/aws-cdk/blob/v2.274.0/packages/aws-cdk-lib/aws-ec2/lib/instance.ts#L501)
- Type last changed: v2.224.0 · 13 Nov 2025

## Example

```ts
// Creates a distribution from an EC2 instance
declare const vpc: ec2.Vpc;
// Create an EC2 instance in a VPC. 'subnetType' can be private.
const instance = new ec2.Instance(this, 'Instance', {
  vpc,
  instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MICRO),
  machineImage: ec2.MachineImage.latestAmazonLinux2023(),
  vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS },
});
new cloudfront.Distribution(this, 'myDist', {
  defaultBehavior: { origin: origins.VpcOrigin.withEc2Instance(instance) },
});
```

## Initializer

```ts
new Instance(scope: Construct, id: string, props: InstanceProps)
```

## Construct Props

- `allowAllIpv6Outbound`: boolean = false — Whether the instance could initiate IPv6 connections to anywhere by default.

  This property is only used when you do not provide a security group.

- `allowAllOutbound`: boolean = true — Whether the instance could initiate connections to anywhere by default.

  This property is only used when you do not provide a security group.

- `associatePublicIpAddress`: boolean — Whether to associate a public IP address to the primary network interface attached to this instance.

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

  You cannot specify this property and `ipv6AddressCount` at the same time.

- `availabilityZone`: string — In which AZ to place the instance within the VPC.

  **Default:** Random zone.

- `blockDevices`: [BlockDevice](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.BlockDevice.html)[] — Specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes.

  **Default:** Uses the block device mapping of the AMI

  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.

- `creditSpecification`: [CpuCredits](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.CpuCredits.html) — Specifying the CPU credit type for burstable EC2 instance types (T2, T3, T3a, etc).

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

  The unlimited CPU credit option is not supported for T3 instances with a dedicated host.

- `detailedMonitoring`: boolean = false — Whether "Detailed Monitoring" is enabled for this instance Keep in mind that Detailed Monitoring results in extra charges.

- `disableApiTermination`: boolean = false — 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.

- `ebsOptimized`: boolean = false — 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.

- `enclaveEnabled`: boolean = false — 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.

- `hibernationEnabled`: boolean = false — Whether the instance is enabled for hibernation.

  You can't set both `enclaveEnabled` and `hibernationEnabled` to true on the same instance.

- `httpEndpoint`: boolean = true — Enables or disables the HTTP metadata endpoint on your instances.

- `httpProtocolIpv6`: boolean = false — Enables or disables the IPv6 endpoint for the instance metadata service.

- `httpPutResponseHopLimit`: number — The desired HTTP PUT response hop limit for instance metadata requests.

  **Default:** No default value specified by CloudFormation

  The larger the number, the further instance metadata requests can travel.

  Possible values: Integers from 1 to 64

- `httpTokens`: [HttpTokens](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.HttpTokens.html) — The state of token usage for your instance metadata requests.

  **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

  Set to 'required' to enforce IMDSv2. This is equivalent to using `requireImdsv2: true`,
  but allows you to configure other metadata options alongside IMDSv2 enforcement.

- `init`: [CloudFormationInit](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.CloudFormationInit.html) — Apply the given CloudFormation Init configuration to the instance at startup.

  **Default:** no CloudFormation init

- `initOptions`: [ApplyCloudFormationInitOptions](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.ApplyCloudFormationInitOptions.html) — Use the given options for applying CloudFormation Init.

  **Default:** default options

  Describes the configsets to use and the timeout to wait

- `instanceInitiatedShutdownBehavior`: [InstanceInitiatedShutdownBehavior](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.InstanceInitiatedShutdownBehavior.html) — 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

- `instanceMetadataTags`: boolean = false — 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.

- `instanceName`: string — The name of the instance.

  **Default:** CDK generated name

- `instanceProfile`: [IInstanceProfile](/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IInstanceProfile.html) — The instance profile used to pass role information to EC2 instances.

  **Default:** No instance profile

  Note: You can provide an instanceProfile or a role, but not both.

- `instanceType`: [InstanceType](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.InstanceType.html) (required) — Type of instance to launch.

- `ipv6AddressCount`: number — The number of IPv6 addresses to associate with the primary network interface.

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

  Amazon EC2 chooses the IPv6 addresses from the range of your subnet.

  You cannot specify this property and `associatePublicIpAddress` at the same time.

- `keyName`: string — - 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

  **Default:** No SSH access will be possible.

- `keyPair`: [IKeyPair](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.IKeyPair.html) — The SSH keypair to grant access to the instance.

  **Default:** No SSH access will be possible.

- `machineImage`: [IMachineImage](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.IMachineImage.html) (required) — AMI to launch.

- `placementGroup`: [IPlacementGroupRef](/cdk/api/v2/docs/aws-cdk-lib.interfaces.aws_ec2.IPlacementGroupRef.html) — The placement group that you want to launch the instance into.

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

- `privateIpAddress`: string — Defines a private IP address to associate with an instance.

  **Default:** no association

  Private IP should be available within the VPC that the instance is build within.

- `propagateTagsToVolumeOnCreation`: boolean = false — Propagate the EC2 instance tags to the EBS volumes.

- `requireImdsv2`: boolean = false — 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.

- `resourceSignalTimeout`: [Duration](/cdk/api/v2/docs/aws-cdk-lib.Duration.html) = Duration.minutes(5) — The length of time to wait for the resourceSignalCount.

  The maximum value is 43200 (12 hours).

- `role`: [IRole](/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IRole.html) — An IAM role to associate with the instance profile assigned to this Auto Scaling Group.

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

  The role must be assumable by the service principal `ec2.amazonaws.com`:
  Note: You can provide an instanceProfile or a role, but not both.

  ```ts
  const role = new iam.Role(this, 'MyRole', {
    assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com')
  });
  ```

- `securityGroup`: [ISecurityGroup](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.ISecurityGroup.html) — Security Group to assign to this instance.

  **Default:** create new security group

- `sourceDestCheck`: boolean = true — 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.

- `ssmSessionPermissions`: boolean = false — 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.

- `userData`: [UserData](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.UserData.html) — Specific UserData to use.

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

  The UserData may still be mutated after creation.

- `userDataCausesReplacement`: boolean — Changes to the UserData force replacement.

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

  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.

- `vpc`: [IVpc](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.IVpc.html) (required) — VPC to launch the instance in.

- `vpcSubnets`: [SubnetSelection](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.SubnetSelection.html) — Where to place the instance within the VPC.

  **Default:** Private subnets.

## Properties

- `connections`: [Connections](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Connections.html) (required) — Allows specify security group connections for the instance.

- `env`: [ResourceEnvironment](/cdk/api/v2/docs/aws-cdk-lib.interfaces.ResourceEnvironment.html) (required) — The environment this resource belongs to.

  For resources that are created and managed in a Stack (those created by
  creating new class instances like `new Role()`, `new Bucket()`, etc.), this
  is always the same as the environment of the stack they belong to.

  For referenced resources (those obtained from referencing methods like
  `Role.fromRoleArn()`, `Bucket.fromBucketName()`, etc.), they might be
  different than the stack they were imported into.

- `grantPrincipal`: [IPrincipal](/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IPrincipal.html) (required) — The principal to grant permissions to.

- `instance`: [CfnInstance](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.CfnInstance.html) (required) — the underlying instance resource.

- `instanceAvailabilityZone`: string (required) — The availability zone the instance was launched in.

- `instanceId`: string (required) — The instance's ID.

- `instancePrivateDnsName`: string (required) — Private DNS name for this instance.

- `instancePrivateIp`: string (required) — Private IP for this instance.

- `instancePublicDnsName`: string (required) — Publicly-routable DNS name for this instance.

  (May be an empty string if the instance does not have a public name).

- `instancePublicIp`: string (required) — Publicly-routable IP address for this instance.

  (May be an empty string if the instance does not have a public IP).

- `instanceRef`: [InstanceReference](/cdk/api/v2/docs/aws-cdk-lib.interfaces.aws_ec2.InstanceReference.html) (required) — A reference to a Instance resource.

- `node`: [Node](/cdk/api/v2/docs/constructs.Node.html) (required) — The tree node.

- `osType`: [OperatingSystemType](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.OperatingSystemType.html) (required) — The type of OS the instance is running.

- `PROPERTY_INJECTION_ID`: string (required) (static) — Uniquely identifies this class.

- `role`: [IRole](/cdk/api/v2/docs/aws-cdk-lib.aws_iam.IRole.html) (required) — The IAM role assumed by the instance.

- `stack`: [Stack](/cdk/api/v2/docs/aws-cdk-lib.Stack.html) (required) — The stack in which this resource is defined.

- `userData`: [UserData](/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.UserData.html) (required) — UserData for the instance.

## Methods

- `addSecurityGroup(securityGroup: ISecurityGroup): void` — Add the security group to the instance.

  **Parameters**

  - `securityGroup` — : The security group to add.

- `addToRolePolicy(statement: PolicyStatement): void` — Adds a statement to the IAM role assumed by the instance.

- `addUserData(...commands: string[]): void` — Add command to the startup script of the instance.

  The command must be in the scripting language supported by the instance's OS (i.e. Linux/Windows).

- `applyCloudFormationInit(init: CloudFormationInit, options?: ApplyCloudFormationInitOptions): void` — Use a CloudFormation Init configuration at instance startup.

  This does the following:

  - Attaches the CloudFormation Init metadata to the Instance resource.
  - Add commands to the instance UserData to run `cfn-init` and `cfn-signal`.
  - Update the instance's CreationPolicy to wait for the `cfn-signal` commands.

- `applyCrossStackReferenceStrength(strength: ReferenceStrength): void` — Override the cross-stack reference strength for this resource.

  When set, any cross-stack reference to this resource will use the specified
  mechanism instead of the global default determined by the
  `@aws-cdk/core:defaultCrossStackReferences` context key. This is useful for
  selectively weakening specific references to avoid the "deadly embrace" problem
  without changing the app-wide default.

  **Parameters**

  - `strength` — - The reference strength to use for this resource.

- `applyRemovalPolicy(policy: RemovalPolicy): void` — Apply the given removal policy to this resource.

  The Removal Policy controls what happens to this resource when it stops
  being managed by CloudFormation, either because you've removed it from the
  CDK application or because you've made a change that requires the resource
  to be replaced.

  The resource can be deleted (`RemovalPolicy.DESTROY`), or left in your AWS
  account for data recovery and cleanup later (`RemovalPolicy.RETAIN`).

- `isConstruct(x: any): boolean` (static) — Checks if `x` is a construct.

  Use this method instead of `instanceof` to properly detect `Construct`
  instances, even when the construct library is symlinked.

  Explanation: in JavaScript, multiple copies of the `constructs` library on
  disk are seen as independent, completely different libraries. As a
  consequence, the class `Construct` in each copy of the `constructs` library
  is seen as a different class, and an instance of one class will not test as
  `instanceof` the other class. `npm install` will not create installations
  like this, but users may manually symlink construct libraries together or
  use a monorepo tool: in those cases, multiple copies of the `constructs`
  library can be accidentally installed, and `instanceof` will behave
  unpredictably. It is safest to avoid using `instanceof`, and using
  this type-testing method instead.

  **Parameters**

  - `x` — Any object.

  **Returns:** true if `x` is an object created from a class which extends `Construct`.

- `isOwnedResource(construct: IConstruct): boolean` (static) — Returns true if the construct was created by CDK, and false otherwise.

- `isResource(construct: IConstruct): boolean` (static) — Check whether the given construct is a Resource.

- `toString(): string` — Returns a string representation of this construct.

- `with(...mixins: IMixin[]): IConstruct` — Applies one or more mixins to this construct.

  Mixins are applied in order. The list of constructs is captured at the
  start of the call, so constructs added by a mixin will not be visited.
  Use multiple `with()` calls if subsequent mixins should apply to added
  constructs.
