Skip to content
v2.274.0

Instance L2 construct ​

This represents a single EC2 instance.

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) },
});
python
# 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))
)
java
// 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();
csharp
// 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) }
});
go
// 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 ​

ts
new Instance(scope: Construct, id: string, props: InstanceProps)
python
Instance(scope: Construct, id: str, props: InstanceProps)
java
new Instance(Construct scope, String id, InstanceProps props)
csharp
new Instance(Construct scope, string id, InstanceProps props)
go
NewInstance(Scope Construct, Id *string, Props InstanceProps)

Construct Props ​

allowAllIpv6Outboundoptionalbooleanallow_all_ipv6_outboundoptionalboolallowAllIpv6OutboundoptionalBooleanAllowAllIpv6OutboundoptionalboolAllowAllIpv6Outboundoptional*bool= 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.

allowAllOutboundoptionalbooleanallow_all_outboundoptionalboolallowAllOutboundoptionalBooleanAllowAllOutboundoptionalboolAllowAllOutboundoptional*bool= true#
Whether the instance could initiate connections to anywhere by default.

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

associatePublicIpAddressoptionalbooleanassociate_public_ip_addressoptionalboolassociatePublicIpAddressoptionalBooleanAssociatePublicIpAddressoptionalboolAssociatePublicIpAddressoptional*bool#
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.

availabilityZoneoptionalstringavailability_zoneoptionalstravailabilityZoneoptionalStringAvailabilityZoneoptionalstringAvailabilityZoneoptional*string#
In which AZ to place the instance within the VPC.

Default: Random zone.

blockDevicesoptionalBlockDevice[]block_devicesoptionaltyping.List[BlockDevice]blockDevicesoptionalList<BlockDevice>BlockDevicesoptionalBlockDevice[]BlockDevicesoptional*[]BlockDevice#
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

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

detailedMonitoringoptionalbooleandetailed_monitoringoptionalbooldetailedMonitoringoptionalBooleanDetailedMonitoringoptionalboolDetailedMonitoringoptional*bool= false#
Whether "Detailed Monitoring" is enabled for this instance Keep in mind that Detailed Monitoring results in extra charges.
disableApiTerminationoptionalbooleandisable_api_terminationoptionalbooldisableApiTerminationoptionalBooleanDisableApiTerminationoptionalboolDisableApiTerminationoptional*bool= false#
If true, the instance will not be able to be terminated using the Amazon EC2 console, CLI, or API.
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#
Indicates whether the instance is optimized for Amazon EBS I/O.
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#
Whether the instance is enabled for AWS Nitro Enclaves.
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#
Whether the instance is enabled for hibernation.

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

httpEndpointoptionalbooleanhttp_endpointoptionalboolhttpEndpointoptionalBooleanHttpEndpointoptionalboolHttpEndpointoptional*bool= true#
Enables or disables the HTTP metadata endpoint on your instances.
httpProtocolIpv6optionalbooleanhttp_protocol_ipv6optionalboolhttpProtocolIpv6optionalBooleanHttpProtocolIpv6optionalboolHttpProtocolIpv6optional*bool= false#
Enables or disables the IPv6 endpoint for the instance metadata service.
httpPutResponseHopLimitoptionalnumberhttp_put_response_hop_limitoptionalint | floathttpPutResponseHopLimitoptionalNumberHttpPutResponseHopLimitoptionaldoubleHttpPutResponseHopLimitoptional*float64#
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

httpTokensoptionalHttpTokenshttp_tokensoptionalHttpTokenshttpTokensoptionalHttpTokensHttpTokensoptionalHttpTokensHttpTokensoptionalHttpTokens#
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.

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

Default: no CloudFormation init

initOptionsoptionalApplyCloudFormationInitOptionsinit_optionsoptionalApplyCloudFormationInitOptionsinitOptionsoptionalApplyCloudFormationInitOptionsInitOptionsoptionalApplyCloudFormationInitOptionsInitOptionsoptionalApplyCloudFormationInitOptions#
Use the given options for applying CloudFormation Init.

Default: default options

Describes the configsets to use and the timeout to wait

instanceInitiatedShutdownBehavioroptionalInstanceInitiatedShutdownBehaviorinstance_initiated_shutdown_behavioroptionalInstanceInitiatedShutdownBehaviorinstanceInitiatedShutdownBehavioroptionalInstanceInitiatedShutdownBehaviorInstanceInitiatedShutdownBehavioroptionalInstanceInitiatedShutdownBehaviorInstanceInitiatedShutdownBehavioroptionalInstanceInitiatedShutdownBehavior#
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

instanceMetadataTagsoptionalbooleaninstance_metadata_tagsoptionalboolinstanceMetadataTagsoptionalBooleanInstanceMetadataTagsoptionalboolInstanceMetadataTagsoptional*bool= 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.

instanceNameoptionalstringinstance_nameoptionalstrinstanceNameoptionalStringInstanceNameoptionalstringInstanceNameoptional*string#
The name of the instance.

Default: CDK generated name

instanceProfileoptionalIInstanceProfileinstance_profileoptionalIInstanceProfileinstanceProfileoptionalIInstanceProfileInstanceProfileoptionalIInstanceProfileInstanceProfileoptionalIInstanceProfile#
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.

instanceTypeInstanceTypeinstance_typeInstanceTypeinstanceTypeInstanceTypeInstanceTypeInstanceTypeInstanceTypeInstanceTyperequired#
Type of instance to launch.
ipv6AddressCountoptionalnumberipv6_address_countoptionalint | floatipv6AddressCountoptionalNumberIpv6AddressCountoptionaldoubleIpv6AddressCountoptional*float64#
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.

keyNameoptionalstringkey_nameoptionalstrkeyNameoptionalStringKeyNameoptionalstringKeyNameoptional*stringdeprecated#
- 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.

keyPairoptionalIKeyPairkey_pairoptionalIKeyPairkeyPairoptionalIKeyPairKeyPairoptionalIKeyPairKeyPairoptionalIKeyPair#
The SSH keypair to grant access to the instance.

Default: No SSH access will be possible.

machineImageIMachineImagemachine_imageIMachineImagemachineImageIMachineImageMachineImageIMachineImageMachineImageIMachineImagerequired#
AMI to launch.
placementGroupoptionalIPlacementGroupRefplacement_groupoptionalIPlacementGroupRefplacementGroupoptionalIPlacementGroupRefPlacementGroupoptionalIPlacementGroupRefPlacementGroupoptionalIPlacementGroupRef#
The placement group that you want to launch the instance into.

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

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

propagateTagsToVolumeOnCreationoptionalbooleanpropagate_tags_to_volume_on_creationoptionalboolpropagateTagsToVolumeOnCreationoptionalBooleanPropagateTagsToVolumeOnCreationoptionalboolPropagateTagsToVolumeOnCreationoptional*bool= false#
Propagate the EC2 instance tags to the EBS volumes.
requireImdsv2optionalbooleanrequire_imdsv2optionalboolrequireImdsv2optionalBooleanRequireImdsv2optionalboolRequireImdsv2optional*bool= false#
Whether IMDSv2 should be required on this instance.
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 length of time to wait for the resourceSignalCount.

The maximum value is 43200 (12 hours).

roleoptionalIRoleroleoptionalIRoleroleoptionalIRoleRoleoptionalIRoleRoleoptionalIRole#
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.

example
ts
const role = new iam.Role(this, 'MyRole', {
  assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com')
});
securityGroupoptionalISecurityGroupsecurity_groupoptionalISecurityGroupsecurityGroupoptionalISecurityGroupSecurityGroupoptionalISecurityGroupSecurityGroupoptionalISecurityGroup#
Security Group to assign to this instance.

Default: create new security group

sourceDestCheckoptionalbooleansource_dest_checkoptionalboolsourceDestCheckoptionalBooleanSourceDestCheckoptionalboolSourceDestCheckoptional*bool= 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.

ssmSessionPermissionsoptionalbooleanssm_session_permissionsoptionalboolssmSessionPermissionsoptionalBooleanSsmSessionPermissionsoptionalboolSsmSessionPermissionsoptional*bool= false#
Add SSM session permissions to the instance role.
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#
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.

userDataCausesReplacementoptionalbooleanuser_data_causes_replacementoptionalbooluserDataCausesReplacementoptionalBooleanUserDataCausesReplacementoptionalboolUserDataCausesReplacementoptional*bool#
Changes to the UserData force replacement.

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.

vpcIVpcvpcIVpcvpcIVpcVpcIVpcVpcIVpcrequired#
VPC to launch the instance in.
vpcSubnetsoptionalSubnetSelectionvpc_subnetsoptionalSubnetSelectionvpcSubnetsoptionalSubnetSelectionVpcSubnetsoptionalSubnetSelectionVpcSubnetsoptionalSubnetSelection#
Where to place the instance within the VPC.

Default: Private subnets.

Properties ​

connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#
Allows specify security group connections for the instance.
The environment this resource belongs to.
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#
The principal to grant permissions to.
instanceCfnInstanceinstanceCfnInstanceinstanceCfnInstanceInstanceCfnInstanceInstanceCfnInstancerequired#
the underlying instance resource.
instanceAvailabilityZonestringinstance_availability_zonestrinstanceAvailabilityZoneStringInstanceAvailabilityZonestringInstanceAvailabilityZone*stringrequired#
The availability zone the instance was launched in.
instanceIdstringinstance_idstrinstanceIdStringInstanceIdstringInstanceId*stringrequired#
The instance's ID.
instancePrivateDnsNamestringinstance_private_dns_namestrinstancePrivateDnsNameStringInstancePrivateDnsNamestringInstancePrivateDnsName*stringrequired#
Private DNS name for this instance.
instancePrivateIpstringinstance_private_ipstrinstancePrivateIpStringInstancePrivateIpstringInstancePrivateIp*stringrequired#
Private IP for this instance.
instancePublicDnsNamestringinstance_public_dns_namestrinstancePublicDnsNameStringInstancePublicDnsNamestringInstancePublicDnsName*stringrequired#
Publicly-routable DNS name for this instance.

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

instancePublicIpstringinstance_public_ipstrinstancePublicIpStringInstancePublicIpstringInstancePublicIp*stringrequired#
Publicly-routable IP address for this instance.

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

instanceRefInstanceReferenceinstance_refInstanceReferenceinstanceRefInstanceReferenceInstanceRefInstanceReferenceInstanceRefInstanceReferencerequired#
A reference to a Instance resource.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
The type of OS the instance is running.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
roleIRoleroleIRoleroleIRoleRoleIRoleRoleIRolerequired#
The IAM role assumed by the instance.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
userDataUserDatauser_dataUserDatauserDataUserDataUserDataUserDataUserDataUserDatarequired#
UserData for the instance.

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)#
Add the security group to the instance.
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)#
Adds a statement to the IAM role assumed by the instance.
addUserData(...commands: string[]): voiddef add_user_data(self, commands: str) -> Nonepublic void addUserData(String commands)public void AddUserData(string commands)func AddUserData(Commands *string)#
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): 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)#
Use a CloudFormation Init configuration at instance startup.
notes

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): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
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)#
Apply the given removal policy to this resource.
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#
Checks if `x` is a construct.
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#
Returns true if the construct was created by CDK, and false otherwise.
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#
Check whether the given construct is a Resource.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func 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.