Instance L2 construct
This represents a single EC2 instance.
Example
// 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) },
});
# Creates a distribution from an EC2 instance
# vpc: ec2.Vpc
# Create an EC2 instance in a VPC. 'subnetType' can be private.
instance = ec2.Instance(self, "Instance",
vpc=vpc,
instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MICRO),
machine_image=ec2.MachineImage.latest_amazon_linux2023(),
vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS)
)
cloudfront.Distribution(self, "myDist",
default_behavior=cloudfront.BehaviorOptions(origin=origins.VpcOrigin.with_ec2_instance(instance))
)
// Creates a distribution from an EC2 instance
Vpc vpc;
// Create an EC2 instance in a VPC. 'subnetType' can be private.
Instance instance = Instance.Builder.create(this, "Instance")
.vpc(vpc)
.instanceType(InstanceType.of(InstanceClass.BURSTABLE3, InstanceSize.MICRO))
.machineImage(MachineImage.latestAmazonLinux2023())
.vpcSubnets(SubnetSelection.builder().subnetType(SubnetType.PRIVATE_WITH_EGRESS).build())
.build();
Distribution.Builder.create(this, "myDist")
.defaultBehavior(BehaviorOptions.builder().origin(VpcOrigin.withEc2Instance(instance)).build())
.build();
// Install: dotnet add package Amazon.CDK.Lib
// Creates a distribution from an EC2 instance
Vpc vpc;
// Create an EC2 instance in a VPC. 'subnetType' can be private.
var instance = new Instance(this, "Instance", new InstanceProps {
Vpc = vpc,
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.MICRO),
MachineImage = MachineImage.LatestAmazonLinux2023(),
VpcSubnets = new SubnetSelection { SubnetType = SubnetType.PRIVATE_WITH_EGRESS }
});
new Distribution(this, "myDist", new DistributionProps {
DefaultBehavior = new BehaviorOptions { Origin = VpcOrigin.WithEc2Instance(instance) }
});
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
// Creates a distribution from an EC2 instance
var vpc Vpc
// Create an EC2 instance in a VPC. 'subnetType' can be private.
instance := ec2.NewInstance(this, jsii.String("Instance"), &InstanceProps{
Vpc: Vpc,
InstanceType: ec2.InstanceType_Of(ec2.InstanceClass_BURSTABLE3, ec2.InstanceSize_MICRO),
MachineImage: ec2.MachineImage_LatestAmazonLinux2023(),
VpcSubnets: &SubnetSelection{
SubnetType: ec2.SubnetType_PRIVATE_WITH_EGRESS,
},
})
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
DefaultBehavior: &BehaviorOptions{
Origin: origins.VpcOrigin_WithEc2Instance(instance),
},
})
Initializer
new Instance(scope: Construct, id: string, props: InstanceProps)
Instance(scope: Construct, id: str, props: InstanceProps)
new Instance(Construct scope, String id, InstanceProps props)
new Instance(Construct scope, string id, InstanceProps props)
NewInstance(Scope Construct, Id *string, Props InstanceProps)
Construct Props
allowAllIpv6Outboundoptionalbooleanallow_all_ipv6_outboundoptionalboolallowAllIpv6OutboundoptionalBooleanAllowAllIpv6OutboundoptionalboolAllowAllIpv6Outboundoptional*bool= false#This property is only used when you do not provide a security group.
allowAllOutboundoptionalbooleanallow_all_outboundoptionalboolallowAllOutboundoptionalBooleanAllowAllOutboundoptionalboolAllowAllOutboundoptional*bool= true#This property is only used when you do not provide a security group.
associatePublicIpAddressoptionalbooleanassociate_public_ip_addressoptionalboolassociatePublicIpAddressoptionalBooleanAssociatePublicIpAddressoptionalboolAssociatePublicIpAddressoptional*bool#Default: public IP address is automatically assigned based on default behavior
You cannot specify this property and ipv6AddressCount at the same time.
availabilityZoneoptionalstringavailability_zoneoptionalstravailabilityZoneoptionalStringAvailabilityZoneoptionalstringAvailabilityZoneoptional*string#Default: Random zone.
blockDevicesoptionalBlockDevice[]block_devicesoptionaltyping.List[BlockDevice]blockDevicesoptionalList<BlockDevice>BlockDevicesoptionalBlockDevice[]BlockDevicesoptional*[]BlockDevice#Default: Uses the block device mapping of the AMI
notes
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.
creditSpecificationoptionalCpuCreditscredit_specificationoptionalCpuCreditscreditSpecificationoptionalCpuCreditsCreditSpecificationoptionalCpuCreditsCreditSpecificationoptionalCpuCredits#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.
detailedMonitoringoptionalbooleandetailed_monitoringoptionalbooldetailedMonitoringoptionalBooleanDetailedMonitoringoptionalboolDetailedMonitoringoptional*bool= false#disableApiTerminationoptionalbooleandisable_api_terminationoptionalbooldisableApiTerminationoptionalBooleanDisableApiTerminationoptionalboolDisableApiTerminationoptional*bool= false#notes
To change this attribute after launch, use ModifyInstanceAttribute. Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate, you can terminate the instance by running the shutdown command from the instance.
ebsOptimizedoptionalbooleanebs_optimizedoptionalboolebsOptimizedoptionalBooleanEbsOptimizedoptionalboolEbsOptimizedoptional*bool= false#notes
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.
enclaveEnabledoptionalbooleanenclave_enabledoptionalboolenclaveEnabledoptionalBooleanEnclaveEnabledoptionalboolEnclaveEnabledoptional*bool= false#notes
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.
hibernationEnabledoptionalbooleanhibernation_enabledoptionalboolhibernationEnabledoptionalBooleanHibernationEnabledoptionalboolHibernationEnabledoptional*bool= false#You can't set both enclaveEnabled and hibernationEnabled to true on the same instance.
httpEndpointoptionalbooleanhttp_endpointoptionalboolhttpEndpointoptionalBooleanHttpEndpointoptionalboolHttpEndpointoptional*bool= true#httpProtocolIpv6optionalbooleanhttp_protocol_ipv6optionalboolhttpProtocolIpv6optionalBooleanHttpProtocolIpv6optionalboolHttpProtocolIpv6optional*bool= false#httpPutResponseHopLimitoptionalnumberhttp_put_response_hop_limitoptionalint | floathttpPutResponseHopLimitoptionalNumberHttpPutResponseHopLimitoptionaldoubleHttpPutResponseHopLimitoptional*float64#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
httpTokensoptionalHttpTokenshttp_tokensoptionalHttpTokenshttpTokensoptionalHttpTokensHttpTokensoptionalHttpTokensHttpTokensoptionalHttpTokens#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.
initoptionalCloudFormationInitinitoptionalCloudFormationInitinitoptionalCloudFormationInitInitoptionalCloudFormationInitInitoptionalCloudFormationInit#Default: no CloudFormation init
initOptionsoptionalApplyCloudFormationInitOptionsinit_optionsoptionalApplyCloudFormationInitOptionsinitOptionsoptionalApplyCloudFormationInitOptionsInitOptionsoptionalApplyCloudFormationInitOptionsInitOptionsoptionalApplyCloudFormationInitOptions#Default: default options
Describes the configsets to use and the timeout to wait
instanceInitiatedShutdownBehavioroptionalInstanceInitiatedShutdownBehaviorinstance_initiated_shutdown_behavioroptionalInstanceInitiatedShutdownBehaviorinstanceInitiatedShutdownBehavioroptionalInstanceInitiatedShutdownBehaviorInstanceInitiatedShutdownBehavioroptionalInstanceInitiatedShutdownBehaviorInstanceInitiatedShutdownBehavioroptionalInstanceInitiatedShutdownBehavior#Default: InstanceInitiatedShutdownBehavior.STOP
instanceMetadataTagsoptionalbooleaninstance_metadata_tagsoptionalboolinstanceMetadataTagsoptionalBooleanInstanceMetadataTagsoptionalboolInstanceMetadataTagsoptional*bool= false#Set to disabled to turn off access to instance tags from the instance metadata.
instanceNameoptionalstringinstance_nameoptionalstrinstanceNameoptionalStringInstanceNameoptionalstringInstanceNameoptional*string#Default: CDK generated name
instanceProfileoptionalIInstanceProfileinstance_profileoptionalIInstanceProfileinstanceProfileoptionalIInstanceProfileInstanceProfileoptionalIInstanceProfileInstanceProfileoptionalIInstanceProfile#Default: No instance profile
Note: You can provide an instanceProfile or a role, but not both.
instanceTypeInstanceTypeinstance_typeInstanceTypeinstanceTypeInstanceTypeInstanceTypeInstanceTypeInstanceTypeInstanceTyperequired#ipv6AddressCountoptionalnumberipv6_address_countoptionalint | floatipv6AddressCountoptionalNumberIpv6AddressCountoptionaldoubleIpv6AddressCountoptional*float64#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.
keyNameoptionalstringkey_nameoptionalstrkeyNameoptionalStringKeyNameoptionalstringKeyNameoptional*stringdeprecated#Default: No SSH access will be possible.
keyPairoptionalIKeyPairkey_pairoptionalIKeyPairkeyPairoptionalIKeyPairKeyPairoptionalIKeyPairKeyPairoptionalIKeyPair#Default: No SSH access will be possible.
machineImageIMachineImagemachine_imageIMachineImagemachineImageIMachineImageMachineImageIMachineImageMachineImageIMachineImagerequired#placementGroupoptionalIPlacementGroupRefplacement_groupoptionalIPlacementGroupRefplacementGroupoptionalIPlacementGroupRefPlacementGroupoptionalIPlacementGroupRefPlacementGroupoptionalIPlacementGroupRef#Default: no placement group will be used for this instance.
privateIpAddressoptionalstringprivate_ip_addressoptionalstrprivateIpAddressoptionalStringPrivateIpAddressoptionalstringPrivateIpAddressoptional*string#Default: no association
Private IP should be available within the VPC that the instance is build within.
propagateTagsToVolumeOnCreationoptionalbooleanpropagate_tags_to_volume_on_creationoptionalboolpropagateTagsToVolumeOnCreationoptionalBooleanPropagateTagsToVolumeOnCreationoptionalboolPropagateTagsToVolumeOnCreationoptional*bool= false#requireImdsv2optionalbooleanrequire_imdsv2optionalboolrequireImdsv2optionalBooleanRequireImdsv2optionalboolRequireImdsv2optional*bool= false#notes
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.
resourceSignalTimeoutoptionalDurationresource_signal_timeoutoptionalDurationresourceSignalTimeoutoptionalDurationResourceSignalTimeoutoptionalDurationResourceSignalTimeoutoptionalDuration= Duration.minutes(5)#The maximum value is 43200 (12 hours).
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.
example
const role = new iam.Role(this, 'MyRole', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com')
});
securityGroupoptionalISecurityGroupsecurity_groupoptionalISecurityGroupsecurityGroupoptionalISecurityGroupSecurityGroupoptionalISecurityGroupSecurityGroupoptionalISecurityGroup#Default: create new security group
sourceDestCheckoptionalbooleansource_dest_checkoptionalboolsourceDestCheckoptionalBooleanSourceDestCheckoptionalboolSourceDestCheckoptional*bool= true#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.
ssmSessionPermissionsoptionalbooleanssm_session_permissionsoptionalboolssmSessionPermissionsoptionalBooleanSsmSessionPermissionsoptionalboolSsmSessionPermissionsoptional*bool= false#notes
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 in the SSM Developer Guide.
userDataoptionalUserDatauser_dataoptionalUserDatauserDataoptionalUserDataUserDataoptionalUserDataUserDataoptionalUserData#Default: A UserData object appropriate for the MachineImage's Operating System is created.
The UserData may still be mutated after creation.
userDataCausesReplacementoptionalbooleanuser_data_causes_replacementoptionalbooluserDataCausesReplacementoptionalBooleanUserDataCausesReplacementoptionalboolUserDataCausesReplacementoptional*bool#Default: true if initOptions is specified, false otherwise.
notes
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.
vpcSubnetsoptionalSubnetSelectionvpc_subnetsoptionalSubnetSelectionvpcSubnetsoptionalSubnetSelectionVpcSubnetsoptionalSubnetSelectionVpcSubnetsoptionalSubnetSelection#Default: Private subnets.
Properties
connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#envResourceEnvironmentenvResourceEnvironmentenvResourceEnvironmentEnvResourceEnvironmentEnvResourceEnvironmentrequired#notes
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.
grantPrincipalIPrincipalgrant_principalIPrincipalgrantPrincipalIPrincipalGrantPrincipalIPrincipalGrantPrincipalIPrincipalrequired#instanceCfnInstanceinstanceCfnInstanceinstanceCfnInstanceInstanceCfnInstanceInstanceCfnInstancerequired#instanceAvailabilityZonestringinstance_availability_zonestrinstanceAvailabilityZoneStringInstanceAvailabilityZonestringInstanceAvailabilityZone*stringrequired#instancePrivateDnsNamestringinstance_private_dns_namestrinstancePrivateDnsNameStringInstancePrivateDnsNamestringInstancePrivateDnsName*stringrequired#instancePrivateIpstringinstance_private_ipstrinstancePrivateIpStringInstancePrivateIpstringInstancePrivateIp*stringrequired#instancePublicDnsNamestringinstance_public_dns_namestrinstancePublicDnsNameStringInstancePublicDnsNamestringInstancePublicDnsName*stringrequired#(May be an empty string if the instance does not have a public name).
instancePublicIpstringinstance_public_ipstrinstancePublicIpStringInstancePublicIpstringInstancePublicIp*stringrequired#(May be an empty string if the instance does not have a public IP).
instanceRefInstanceReferenceinstance_refInstanceReferenceinstanceRefInstanceReferenceInstanceRefInstanceReferenceInstanceRefInstanceReferencerequired#osTypeOperatingSystemTypeos_typeOperatingSystemTypeosTypeOperatingSystemTypeOsTypeOperatingSystemTypeOsTypeOperatingSystemTyperequired#PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#Methods
addSecurityGroup(securityGroup: ISecurityGroup): voiddef add_security_group(self, security_group: ISecurityGroup) -> Nonepublic void addSecurityGroup(ISecurityGroup securityGroup)public void AddSecurityGroup(ISecurityGroup securityGroup)func AddSecurityGroup(SecurityGroup ISecurityGroup)#1 parameter
Parameters
securityGroupsecurity_groupsecurityGroupsecurityGroupSecurityGroup— : The security group to add.
addToRolePolicy(statement: PolicyStatement): voiddef add_to_role_policy(self, statement: PolicyStatement) -> Nonepublic void addToRolePolicy(PolicyStatement statement)public void AddToRolePolicy(PolicyStatement statement)func AddToRolePolicy(Statement PolicyStatement)#addUserData(...commands: string[]): voiddef add_user_data(self, commands: str) -> Nonepublic void addUserData(String commands)public void AddUserData(string commands)func AddUserData(Commands *string)#The command must be in the scripting language supported by the instance's OS (i.e. Linux/Windows).
applyCloudFormationInit(init: CloudFormationInit, options?: ApplyCloudFormationInitOptions): voiddef apply_cloud_formation_init(self, init: CloudFormationInit, options: typing.Optional[ApplyCloudFormationInitOptions] = None) -> Nonepublic void applyCloudFormationInit(CloudFormationInit init, ApplyCloudFormationInitOptions options)public void ApplyCloudFormationInit(CloudFormationInit init, ApplyCloudFormationInitOptions? options = null)func ApplyCloudFormationInit(Init CloudFormationInit, Options ApplyCloudFormationInitOptions)#notes
This does the following:
- Attaches the CloudFormation Init metadata to the Instance resource.
- Add commands to the instance UserData to run
cfn-initandcfn-signal. - Update the instance's CreationPolicy to wait for the
cfn-signalcommands.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#notes · 1 parameter
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
strengthstrengthstrengthstrengthStrength— - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#notes
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@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#notes · 1 parameter · returns
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
xxxxX— Any object.
Returns: true if x is an object created from a class which extends Construct.
isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#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.