Skip to content
v2.274.0

LaunchTemplate L2 construct ​

This represents an EC2 LaunchTemplate.

Example ​

ts
declare const vpc: ec2.Vpc;

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

const template = new ec2.LaunchTemplate(this, 'LaunchTemplate', {
  launchTemplateName: 'MyTemplateV1',
  versionDescription: 'This is my v1 template',
  machineImage: ec2.MachineImage.latestAmazonLinux2023(),
  securityGroup: new ec2.SecurityGroup(this, 'LaunchTemplateSG', {
    vpc: vpc,
  }),
  instanceProfile,
});
python
# vpc: ec2.Vpc


role = iam.Role(self, "Role",
    assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")
)
instance_profile = iam.InstanceProfile(self, "InstanceProfile",
    role=role
)

template = ec2.LaunchTemplate(self, "LaunchTemplate",
    launch_template_name="MyTemplateV1",
    version_description="This is my v1 template",
    machine_image=ec2.MachineImage.latest_amazon_linux2023(),
    security_group=ec2.SecurityGroup(self, "LaunchTemplateSG",
        vpc=vpc
    ),
    instance_profile=instance_profile
)
java
Vpc vpc;


Role role = Role.Builder.create(this, "Role")
        .assumedBy(new ServicePrincipal("ec2.amazonaws.com"))
        .build();
InstanceProfile instanceProfile = InstanceProfile.Builder.create(this, "InstanceProfile")
        .role(role)
        .build();

LaunchTemplate template = LaunchTemplate.Builder.create(this, "LaunchTemplate")
        .launchTemplateName("MyTemplateV1")
        .versionDescription("This is my v1 template")
        .machineImage(MachineImage.latestAmazonLinux2023())
        .securityGroup(SecurityGroup.Builder.create(this, "LaunchTemplateSG")
                .vpc(vpc)
                .build())
        .instanceProfile(instanceProfile)
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
Vpc vpc;


var role = new Role(this, "Role", new RoleProps {
    AssumedBy = new ServicePrincipal("ec2.amazonaws.com")
});
var instanceProfile = new InstanceProfile(this, "InstanceProfile", new InstanceProfileProps {
    Role = role
});

var template = new LaunchTemplate(this, "LaunchTemplate", new LaunchTemplateProps {
    LaunchTemplateName = "MyTemplateV1",
    VersionDescription = "This is my v1 template",
    MachineImage = MachineImage.LatestAmazonLinux2023(),
    SecurityGroup = new SecurityGroup(this, "LaunchTemplateSG", new SecurityGroupProps {
        Vpc = vpc
    }),
    InstanceProfile = instanceProfile
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var vpc Vpc


role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("ec2.amazonaws.com")),
})
instanceProfile := iam.NewInstanceProfile(this, jsii.String("InstanceProfile"), &InstanceProfileProps{
	Role: Role,
})

template := ec2.NewLaunchTemplate(this, jsii.String("LaunchTemplate"), &LaunchTemplateProps{
	LaunchTemplateName: jsii.String("MyTemplateV1"),
	VersionDescription: jsii.String("This is my v1 template"),
	MachineImage: ec2.MachineImage_LatestAmazonLinux2023(),
	SecurityGroup: ec2.NewSecurityGroup(this, jsii.String("LaunchTemplateSG"), &SecurityGroupProps{
		Vpc: vpc,
	}),
	InstanceProfile: InstanceProfile,
})

Initializer ​

ts
new LaunchTemplate(scope: Construct, id: string, props?: LaunchTemplateProps)
python
LaunchTemplate(scope: Construct, id: str, props: typing.Optional[LaunchTemplateProps] = None)
java
new LaunchTemplate(Construct scope, String id, LaunchTemplateProps props)
csharp
new LaunchTemplate(Construct scope, string id, LaunchTemplateProps? props = null)
go
NewLaunchTemplate(Scope Construct, Id *string, Props LaunchTemplateProps)

Construct Props ​

associatePublicIpAddressbooleanassociate_public_ip_addressboolassociatePublicIpAddressBooleanAssociatePublicIpAddressboolAssociatePublicIpAddress*bool#
Whether instances should have a public IP addresses associated with them.

Default: Use subnet settings

blockDevicesBlockDevice[]block_devicestyping.List[BlockDevice]blockDevicesList<BlockDevice>BlockDevicesBlockDevice[]BlockDevices*[]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.

cpuCreditsCpuCreditscpu_creditsCpuCreditscpuCreditsCpuCreditsCpuCreditsCpuCreditsCpuCreditsCpuCredits#
CPU credit type for burstable EC2 instance types.

Default: No credit type is specified in the Launch Template.

The CPU options for the instance.

Default: The CPU options are not specified in the launch template.

detailedMonitoringbooleandetailed_monitoringbooldetailedMonitoringBooleanDetailedMonitoringboolDetailedMonitoring*bool#
If set to true, then detailed monitoring will be enabled on instances created with this launch template.

Default: False - Detailed monitoring is disabled.

disableApiTerminationbooleandisable_api_terminationbooldisableApiTerminationBooleanDisableApiTerminationboolDisableApiTermination*bool#
If you set this parameter to true, you cannot terminate the instances launched with this launch template using the Amazon EC2 console, CLI, or API;

Default: The API termination setting is not specified in the Launch Template.

otherwise, you can.

ebsOptimizedbooleanebs_optimizedboolebsOptimizedBooleanEbsOptimizedboolEbsOptimized*bool#
Indicates whether the instances are optimized for Amazon EBS I/O.

Default: EBS optimization is not specified in the launch template.

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.

hibernationConfiguredbooleanhibernation_configuredboolhibernationConfiguredBooleanHibernationConfiguredboolHibernationConfigured*bool#
If you set this parameter to true, the instance is enabled for hibernation.

Default: Hibernation configuration is not specified in the launch template; defaulting to false.

httpEndpointbooleanhttp_endpointboolhttpEndpointBooleanHttpEndpointboolHttpEndpoint*bool= true#
Enables or disables the HTTP metadata endpoint on your instances.
httpProtocolIpv6booleanhttp_protocol_ipv6boolhttpProtocolIpv6BooleanHttpProtocolIpv6boolHttpProtocolIpv6*bool= true#
Enables or disables the IPv6 endpoint for the instance metadata service.
httpPutResponseHopLimitnumberhttp_put_response_hop_limitint | floathttpPutResponseHopLimitNumberHttpPutResponseHopLimitdoubleHttpPutResponseHopLimit*float64= 1#
The desired HTTP PUT response hop limit for instance metadata requests.

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

The state of token usage for your instance metadata requests.

Default: LaunchTemplateHttpTokens.OPTIONAL

The default state is optional if not specified. However, if requireImdsv2 is true, the state must be required.

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

Default: Shutdown behavior is not specified in the launch template; defaults to STOP.

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

instanceProfileIInstanceProfileinstance_profileIInstanceProfileinstanceProfileIInstanceProfileInstanceProfileIInstanceProfileInstanceProfileIInstanceProfile#
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_typeInstanceTypeinstanceTypeInstanceTypeInstanceTypeInstanceTypeInstanceTypeInstanceType#
Type of instance to launch.

Default: This Launch Template does not specify a default Instance Type.

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

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

Default: No SSH access will be possible.

launchTemplateNamestringlaunch_template_namestrlaunchTemplateNameStringLaunchTemplateNamestringLaunchTemplateName*string#
Name for this launch template.

Default: Automatically generated name

machineImageIMachineImagemachine_imageIMachineImagemachineImageIMachineImageMachineImageIMachineImageMachineImageIMachineImage#
The AMI that will be used by instances.

Default: This Launch Template does not specify a default AMI.

nitroEnclaveEnabledbooleannitro_enclave_enabledboolnitroEnclaveEnabledBooleanNitroEnclaveEnabledboolNitroEnclaveEnabled*bool#
If this parameter is set to true, the instance is enabled for AWS Nitro Enclaves;

Default: Enablement of Nitro enclaves is not specified in the launch template; defaulting to false.

otherwise, it is not enabled for AWS Nitro Enclaves.

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

Default: no placement group will be used for this launch template.

requireImdsv2booleanrequire_imdsv2boolrequireImdsv2BooleanRequireImdsv2boolRequireImdsv2*bool= false#
Whether IMDSv2 should be required on launched instances.
roleIRoleroleIRoleroleIRoleRoleIRoleRoleIRole#
An IAM role to associate with the instance profile that is used by instances.

Default: No new role is created.

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')
});
securityGroupISecurityGroupsecurity_groupISecurityGroupsecurityGroupISecurityGroupSecurityGroupISecurityGroupSecurityGroupISecurityGroup#
Security group to assign to instances created with the launch template.

Default: No security group is assigned.

If this property is defined, then the Launch Template's InstanceMarketOptions will be set to use Spot instances, and the options for the Spot instances will be as defined.

Default: Instance launched with this template will not be spot instances.

userDataUserDatauser_dataUserDatauserDataUserDataUserDataUserDataUserDataUserData#
The user data to make available to the instance.

Default: This Launch Template creates a UserData based on the type of provided machineImage; no UserData is created if a machineImage is not provided

versionDescriptionstringversion_descriptionstrversionDescriptionStringVersionDescriptionstringVersionDescription*string#
A description for the first version of the launch template.

Default: No description

The version description must be maximum 255 characters long.

Properties ​

connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#
Allows specifying security group connections for the instance.
defaultVersionNumberstringdefault_version_numberstrdefaultVersionNumberStringDefaultVersionNumberstringDefaultVersionNumber*stringrequired#
The default version for the launch template.
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#
Principal to grant permissions to.
imageIdstringimage_idstrimageIdStringImageIdstringImageId*string#
The AMI ID of the image to use.
instanceTypeInstanceTypeinstance_typeInstanceTypeinstanceTypeInstanceTypeInstanceTypeInstanceTypeInstanceTypeInstanceType#
Type of instance to launch.
latestVersionNumberstringlatest_version_numberstrlatestVersionNumberStringLatestVersionNumberstringLatestVersionNumber*stringrequired#
The latest version of the launch template.
launchTemplateIdstringlaunch_template_idstrlaunchTemplateIdStringLaunchTemplateIdstringLaunchTemplateId*string#
The identifier of the Launch Template.

Exactly one of launchTemplateId and launchTemplateName will be set.

launchTemplateNamestringlaunch_template_namestrlaunchTemplateNameStringLaunchTemplateNamestringLaunchTemplateName*string#
The name of the Launch Template.

Exactly one of launchTemplateId and launchTemplateName will be set.

launchTemplateRefLaunchTemplateReferencelaunch_template_refLaunchTemplateReferencelaunchTemplateRefLaunchTemplateReferenceLaunchTemplateRefLaunchTemplateReferenceLaunchTemplateRefLaunchTemplateReferencerequired#
A reference to a LaunchTemplate 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.
roleIRoleroleIRoleroleIRoleRoleIRoleRoleIRole#
IAM Role assumed by instances that are launched from this template.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
userDataUserDatauser_dataUserDatauserDataUserDataUserDataUserDataUserDataUserData#
UserData executed by instances that are launched from this template.
versionNumberstringversion_numberstrversionNumberStringVersionNumberstringVersionNumber*stringrequired#
The version number of this launch template to use.

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

fromLaunchTemplateAttributes(scope: Construct, id: string, attrs: LaunchTemplateAttributes): ILaunchTemplate@staticmethod def from_launch_template_attributes(scope: Construct, id: str, attrs: LaunchTemplateAttributes) -> ILaunchTemplatepublic static ILaunchTemplate fromLaunchTemplateAttributes(Construct scope, String id, LaunchTemplateAttributes attrs)public static ILaunchTemplate FromLaunchTemplateAttributes(Construct scope, string id, LaunchTemplateAttributes attrs)func FromLaunchTemplateAttributes(Scope Construct, Id *string, Attrs LaunchTemplateAttributes) ILaunchTemplatestatic#
Import an existing LaunchTemplate.
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.