Skip to content

Resource: awsLaunchTemplate

Provides an EC2 launch template resource. Can be used to create instances or auto scaling groups.

Example Usage

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.launchTemplate.LaunchTemplate(this, "foo", {
  blockDeviceMappings: [
    {
      deviceName: "/dev/sdf",
      ebs: {
        volumeSize: 20,
      },
    },
  ],
  capacityReservationSpecification: {
    capacityReservationPreference: "open",
  },
  cpuOptions: {
    coreCount: 4,
    threadsPerCore: 2,
  },
  creditSpecification: {
    cpuCredits: "standard",
  },
  disableApiStop: true,
  disableApiTermination: true,
  ebsOptimized: true,
  elasticGpuSpecifications: [
    {
      type: "test",
    },
  ],
  elasticInferenceAccelerator: {
    type: "eia1.medium",
  },
  iamInstanceProfile: {
    name: "test",
  },
  imageId: "ami-test",
  instanceInitiatedShutdownBehavior: "terminate",
  instanceMarketOptions: {
    marketType: "spot",
  },
  instanceType: "t2.micro",
  kernelId: "test",
  keyName: "test",
  licenseSpecification: [
    {
      licenseConfigurationArn:
        "arn:aws:license-manager:eu-west-1:123456789012:license-configuration:lic-0123456789abcdef0123456789abcdef",
    },
  ],
  metadataOptions: {
    httpEndpoint: "enabled",
    httpPutResponseHopLimit: 1,
    httpTokens: "required",
    instanceMetadataTags: "enabled",
  },
  monitoring: {
    enabled: true,
  },
  name: "foo",
  networkInterfaces: [
    {
      associatePublicIpAddress: true,
    },
  ],
  placement: {
    availabilityZone: "us-west-2a",
  },
  ramDiskId: "test",
  tagSpecifications: [
    {
      resourceType: "instance",
      tags: {
        name: "test",
      },
    },
  ],
  userData: '${filebase64("${path.module}/example.sh")}',
  vpcSecurityGroupIds: ["sg-12345678"],
});

Argument Reference

The following arguments are supported:

  • blockDeviceMappings - (Optional) Specify volumes to attach to the instance besides the volumes specified by the AMI. See Block Devices below for details.
  • capacityReservationSpecification - (Optional) Targeting for EC2 capacity reservations. See Capacity Reservation Specification below for more details.
  • cpuOptions - (Optional) The CPU options for the instance. See CPU Options below for more details.
  • creditSpecification - (Optional) Customize the credit specification of the instance. See Credit Specification below for more details.
  • defaultVersion - (Optional) Default Version of the launch template.
  • description - (Optional) Description of the launch template.
  • disableApiStop - (Optional) If true, enables EC2 Instance Stop Protection.
  • disableApiTermination - (Optional) If true, enables EC2 Instance Termination Protection
  • ebsOptimized - (Optional) If true, the launched EC2 instance will be EBS-optimized.
  • elasticGpuSpecifications - (Optional) The elastic GPU to attach to the instance. See Elastic GPU below for more details.
  • elasticInferenceAccelerator - (Optional) Configuration block containing an Elastic Inference Accelerator to attach to the instance. See Elastic Inference Accelerator below for more details.
  • enclaveOptions - (Optional) Enable Nitro Enclaves on launched instances. See Enclave Options below for more details.
  • hibernationOptions - (Optional) The hibernation options for the instance. See Hibernation Options below for more details.
  • iamInstanceProfile - (Optional) The IAM Instance Profile to launch the instance with. See Instance Profile below for more details.
  • imageId - (Optional) The AMI from which to launch the instance.
  • instanceInitiatedShutdownBehavior - (Optional) Shutdown behavior for the instance. Can be stop or terminate. (Default: stop).
  • instanceMarketOptions - (Optional) The market (purchasing) option for the instance. See Market Options below for details.
  • instanceRequirements - (Optional) The attribute requirements for the type of instance. If present then instanceType cannot be present.
  • instanceType - (Optional) The type of the instance. If present then instanceRequirements cannot be present.
  • kernelId - (Optional) The kernel ID.
  • keyName - (Optional) The key name to use for the instance.
  • licenseSpecification - (Optional) A list of license specifications to associate with. See License Specification below for more details.
  • maintenanceOptions - (Optional) The maintenance options for the instance. See Maintenance Options below for more details.
  • metadataOptions - (Optional) Customize the metadata options for the instance. See Metadata Options below for more details.
  • monitoring - (Optional) The monitoring option for the instance. See Monitoring below for more details.
  • name - (Optional) The name of the launch template. If you leave this blank, Terraform will auto-generate a unique name.
  • namePrefix - (Optional) Creates a unique name beginning with the specified prefix. Conflicts with name.
  • networkInterfaces - (Optional) Customize network interfaces to be attached at instance boot time. See Network Interfaces below for more details.
  • placement - (Optional) The placement of the instance. See Placement below for more details.
  • privateDnsNameOptions - (Optional) The options for the instance hostname. The default values are inherited from the subnet. See Private DNS Name Options below for more details.
  • ramDiskId - (Optional) The ID of the RAM disk.
  • securityGroupNames - (Optional) A list of security group names to associate with. If you are creating Instances in a VPC, use vpcSecurityGroupIds instead.
  • tagSpecifications - (Optional) The tags to apply to the resources during launch. See Tag Specifications below for more details.
  • tags - (Optional) A map of tags to assign to the launch template. If configured with a provider defaultTags configuration block present, tags with matching keys will overwrite those defined at the provider-level.
  • updateDefaultVersion - (Optional) Whether to update Default Version each update. Conflicts with defaultVersion.
  • userData - (Optional) The base64-encoded user data to provide when launching the instance.
  • vpcSecurityGroupIds - (Optional) A list of security group IDs to associate with. Conflicts with networkInterfacesSecurityGroups

Block devices

Configure additional volumes of the instance besides specified by the AMI. It's a good idea to familiarize yourself with AWS's Block Device Mapping docs to understand the implications of using these attributes.

To find out more information for an existing AMI to override the configuration, such as deviceName, you can use the AWS CLI ec2 describe-images command.

Each blockDeviceMappings supports the following:

  • deviceName - (Required) The name of the device to mount.
  • ebs - (Optional) Configure EBS volume properties.
  • noDevice - (Optional) Suppresses the specified device included in the AMI's block device mapping.
  • virtualName - (Optional) The Instance Store Device Name (e.g., "ephemeral0").

The ebs block supports the following:

  • deleteOnTermination - (Optional) Whether the volume should be destroyed on instance termination. See Preserving Amazon EBS Volumes on Instance Termination for more information.
  • encrypted - (Optional) Enables EBS encryption on the volume. Cannot be used with snapshotId.
  • iops - (Optional) The amount of provisioned IOPS. This must be set with a volumeType of "io1/io2/gp3".
  • kmsKeyId - (Optional) The ARN of the AWS Key Management Service (AWS KMS) customer master key (CMK) to use when creating the encrypted volume. encrypted must be set to true when this is set.
  • snapshotId - (Optional) The Snapshot ID to mount.
  • throughput - (Optional) The throughput to provision for a gp3 volume in MiB/s (specified as an integer, e.g., 500), with a maximum of 1,000 MiB/s.
  • volumeSize - (Optional) The size of the volume in gigabytes.
  • volumeType - (Optional) The volume type. Can be one of standard, gp2, gp3, io1, io2, sc1 or st1.

Capacity Reservation Specification

The capacityReservationSpecification block supports the following:

  • capacityReservationPreference - Indicates the instance's Capacity Reservation preferences. Can be open or none. (Default none).
  • capacityReservationTarget - Used to target a specific Capacity Reservation:

The capacityReservationTarget block supports the following:

  • capacityReservationId - The ID of the Capacity Reservation in which to run the instance.
  • capacityReservationResourceGroupArn - The ARN of the Capacity Reservation resource group in which to run the instance.

CPU Options

The cpuOptions block supports the following:

  • coreCount - The number of CPU cores for the instance.
  • threadsPerCore - The number of threads per CPU core. To disable Intel Hyper-Threading Technology for the instance, specify a value of 1. Otherwise, specify the default value of 2.

Both number of CPU cores and threads per core must be specified. Valid number of CPU cores and threads per core for the instance type can be found in the CPU Options Documentation

Credit Specification

Credit specification can be applied/modified to the EC2 Instance at any time.

The creditSpecification block supports the following:

  • cpuCredits - The credit option for CPU usage. Can be "standard" or "unlimited". T3 instances are launched as unlimited by default. T2 instances are launched as standard by default.

Elastic GPU

Attach an elastic GPU the instance.

The elasticGpuSpecifications block supports the following:

Elastic Inference Accelerator

Attach an Elastic Inference Accelerator to the instance. Additional information about Elastic Inference in EC2 can be found in the EC2 User Guide.

The elasticInferenceAccelerator configuration block supports the following:

  • type - (Required) Accelerator type.

Enclave Options

The enclaveOptions block supports the following:

  • enabled - If set to true, Nitro Enclaves will be enabled on the instance.

For more information, see the documentation on Nitro Enclaves.

Hibernation Options

The hibernationOptions block supports the following:

  • configured - If set to true, the launched EC2 instance will hibernation enabled.

Instance Profile

The IAM Instance Profile to attach.

The iamInstanceProfile block supports the following:

  • arn - The Amazon Resource Name (ARN) of the instance profile.
  • name - The name of the instance profile.

Instance Requirements

This configuration block supports the following:

\~> NOTE: Both memoryMibMin and vcpuCountMin must be specified.

  • acceleratorCount - (Optional) Block describing the minimum and maximum number of accelerators (GPUs, FPGAs, or AWS Inferentia chips). Default is no minimum or maximum.

    • min - (Optional) Minimum.
    • max - (Optional) Maximum. Set to 0 to exclude instance types with accelerators.
  • acceleratorManufacturers - (Optional) List of accelerator manufacturer names. Default is any manufacturer.

    Valid names:
      * amazon-web-services
      * amd
      * nvidia
      * xilinx
    
  • acceleratorNames - (Optional) List of accelerator names. Default is any acclerator.

    Valid names:
      * a100            - NVIDIA A100 GPUs
      * v100            - NVIDIA V100 GPUs
      * k80             - NVIDIA K80 GPUs
      * t4              - NVIDIA T4 GPUs
      * m60             - NVIDIA M60 GPUs
      * radeon-pro-v520 - AMD Radeon Pro V520 GPUs
      * vu9p            - Xilinx VU9P FPGAs
    
  • acceleratorTotalMemoryMib - (Optional) Block describing the minimum and maximum total memory of the accelerators. Default is no minimum or maximum.

    • min - (Optional) Minimum.
    • max - (Optional) Maximum.
  • acceleratorTypes - (Optional) List of accelerator types. Default is any accelerator type.

    Valid types:
      * fpga
      * gpu
      * inference
    
  • allowedInstanceTypes - (Optional) List of instance types to apply your specified attributes against. All other instance types are ignored, even if they match your specified attributes. You can use strings with one or more wild cards, represented by an asterisk (*), to allow an instance type, size, or generation. The following are examples: m58Xlarge, c5*.*, m5A.*, r*, *3*. For example, if you specify c5*, you are allowing the entire C5 instance family, which includes all C5a and C5n instance types. If you specify m5A.*, you are allowing all the M5a instance types, but not the M5n instance types. Maximum of 400 entries in the list; each entry is limited to 30 characters. Default is all instance types.

    \~> NOTE: If you specify allowedInstanceTypes, you can't specify excludedInstanceTypes.

  • bareMetal - (Optional) Indicate whether bare metal instace types should be included, excluded, or required. Default is excluded.

  • baselineEbsBandwidthMbps - (Optional) Block describing the minimum and maximum baseline EBS bandwidth, in Mbps. Default is no minimum or maximum.

    • min - (Optional) Minimum.
    • max - (Optional) Maximum.
  • burstablePerformance - (Optional) Indicate whether burstable performance instance types should be included, excluded, or required. Default is excluded.

  • cpuManufacturers (Optional) List of CPU manufacturer names. Default is any manufacturer.

    \~> NOTE: Don't confuse the CPU hardware manufacturer with the CPU hardware architecture. Instances will be launched with a compatible CPU architecture based on the Amazon Machine Image (AMI) that you specify in your launch template.

    Valid names:
      * amazon-web-services
      * amd
      * intel
    
  • excludedInstanceTypes - (Optional) List of instance types to exclude. You can use strings with one or more wild cards, represented by an asterisk (*), to exclude an instance type, size, or generation. The following are examples: m58Xlarge, c5*.*, m5A.*, r*, *3*. For example, if you specify c5*, you are excluding the entire C5 instance family, which includes all C5a and C5n instance types. If you specify m5A.*, you are excluding all the M5a instance types, but not the M5n instance types. Maximum of 400 entries in the list; each entry is limited to 30 characters. Default is no excluded instance types.

    \~> NOTE: If you specify excludedInstanceTypes, you can't specify allowedInstanceTypes.

  • instanceGenerations - (Optional) List of instance generation names. Default is any generation.

    Valid names:
      * current  - Recommended for best performance.
      * previous - For existing applications optimized for older instance types.
    
  • localStorage - (Optional) Indicate whether instance types with local storage volumes are included, excluded, or required. Default is included.

  • localStorageTypes - (Optional) List of local storage type names. Default any storage type.

    Value names:
      * hdd - hard disk drive
      * ssd - solid state drive
    
  • memoryGibPerVcpu - (Optional) Block describing the minimum and maximum amount of memory (GiB) per vCPU. Default is no minimum or maximum.

    • min - (Optional) Minimum. May be a decimal number, e.g. 05.
    • max - (Optional) Maximum. May be a decimal number, e.g. 05.
  • memoryMib - (Required) Block describing the minimum and maximum amount of memory (MiB). Default is no maximum.

    • min - (Required) Minimum.
    • max - (Optional) Maximum.
  • networkBandwidthGbps - (Optional) Block describing the minimum and maximum amount of network bandwidth, in gigabits per second (Gbps). Default is no minimum or maximum.

    • min - (Optional) Minimum.
    • max - (Optional) Maximum.
  • networkInterfaceCount - (Optional) Block describing the minimum and maximum number of network interfaces. Default is no minimum or maximum.

    • min - (Optional) Minimum.
    • max - (Optional) Maximum.
  • onDemandMaxPricePercentageOverLowestPrice - (Optional) The price protection threshold for On-Demand Instances. This is the maximum you’ll pay for an On-Demand Instance, expressed as a percentage higher than the cheapest M, C, or R instance type with your specified attributes. When Amazon EC2 Auto Scaling selects instance types with your attributes, we will exclude instance types whose price is higher than your threshold. The parameter accepts an integer, which Amazon EC2 Auto Scaling interprets as a percentage. To turn off price protection, specify a high value, such as 999999. Default is 20.

    If you set DesiredCapacityType to vcpu or memory-mib, the price protection threshold is applied based on the per vCPU or per memory price instead of the per instance price.

  • requireHibernateSupport - (Optional) Indicate whether instance types must support On-Demand Instance Hibernation, either true or false. Default is false.

  • spotMaxPricePercentageOverLowestPrice - (Optional) The price protection threshold for Spot Instances. This is the maximum you’ll pay for a Spot Instance, expressed as a percentage higher than the cheapest M, C, or R instance type with your specified attributes. When Amazon EC2 Auto Scaling selects instance types with your attributes, we will exclude instance types whose price is higher than your threshold. The parameter accepts an integer, which Amazon EC2 Auto Scaling interprets as a percentage. To turn off price protection, specify a high value, such as 999999. Default is 100.

    If you set DesiredCapacityType to vcpu or memory-mib, the price protection threshold is applied based on the per vCPU or per memory price instead of the per instance price.

  • totalLocalStorageGb - (Optional) Block describing the minimum and maximum total local storage (GB). Default is no minimum or maximum.

    • min - (Optional) Minimum. May be a decimal number, e.g. 05.
    • max - (Optional) Maximum. May be a decimal number, e.g. 05.
  • vcpuCount - (Required) Block describing the minimum and maximum number of vCPUs. Default is no maximum.

    • min - (Required) Minimum.
    • max - (Optional) Maximum.

License Specification

Associate one of more license configurations.

The licenseSpecification block supports the following:

  • licenseConfigurationArn - (Required) ARN of the license configuration.

Maintenance Options

The maintenanceOptions block supports the following:

  • autoRecovery - (Optional) Disables the automatic recovery behavior of your instance or sets it to default. Can be "default" or "disabled". See Recover your instance for more details.

Market Options

The market (purchasing) option for the instances.

The instanceMarketOptions block supports the following:

  • marketType - The market type. Can be spot.
  • spotOptions - The options for Spot Instance

The spotOptions block supports the following:

  • blockDurationMinutes - The required duration in minutes. This value must be a multiple of 60.
  • instanceInterruptionBehavior - The behavior when a Spot Instance is interrupted. Can be hibernate, stop, or terminate. (Default: terminate).
  • maxPrice - The maximum hourly price you're willing to pay for the Spot Instances.
  • spotInstanceType - The Spot Instance request type. Can be oneTime, or persistent.
  • validUntil - The end date of the request.

Metadata Options

The metadata options for the instances.

The metadataOptions block supports the following:

  • httpEndpoint - (Optional) Whether the metadata service is available. Can be "enabled" or "disabled". (Default: "enabled").
  • httpTokens - (Optional) Whether or not the metadata service requires session tokens, also referred to as Instance Metadata Service Version 2 (IMDSv2). Can be "optional" or "required". (Default: "optional").
  • httpPutResponseHopLimit - (Optional) The desired HTTP PUT response hop limit for instance metadata requests. The larger the number, the further instance metadata requests can travel. Can be an integer from 1 to 64. (Default: 1).
  • httpProtocolIpv6 - (Optional) Enables or disables the IPv6 endpoint for the instance metadata service. (Default: disabled).
  • instanceMetadataTags - (Optional) Enables or disables access to instance tags from the instance metadata service. (Default: disabled).

For more information, see the documentation on the Instance Metadata Service.

Monitoring

The monitoring block supports the following:

  • enabled - If true, the launched EC2 instance will have detailed monitoring enabled.

Network Interfaces

Attaches one or more Network Interfaces to the instance.

Check limitations for autoscaling group in Creating an Auto Scaling Group Using a Launch Template Guide

Each networkInterfaces block supports the following:

  • associateCarrierIpAddress - (Optional) Associate a Carrier IP address with eth0 for a new network interface. Use this option when you launch an instance in a Wavelength Zone and want to associate a Carrier IP address with the network interface. Boolean value, can be left unset.
  • associatePublicIpAddress - (Optional) Associate a public ip address with the network interface. Boolean value, can be left unset.
  • deleteOnTermination - (Optional) Whether the network interface should be destroyed on instance termination.
  • description - (Optional) Description of the network interface.
  • deviceIndex - (Optional) The integer index of the network interface attachment.
  • interfaceType - (Optional) The type of network interface. To create an Elastic Fabric Adapter (EFA), specify efa.
  • ipv4PrefixCount - (Optional) The number of IPv4 prefixes to be automatically assigned to the network interface. Conflicts with ipv4Prefixes
  • ipv4Prefixes - (Optional) One or more IPv4 prefixes to be assigned to the network interface. Conflicts with ipv4PrefixCount
  • ipv6Addresses - (Optional) One or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet. Conflicts with ipv6AddressCount
  • ipv6AddressCount - (Optional) The number of IPv6 addresses to assign to a network interface. Conflicts with ipv6Addresses
  • ipv6PrefixCount - (Optional) The number of IPv6 prefixes to be automatically assigned to the network interface. Conflicts with ipv6Prefixes
  • ipv6Prefixes - (Optional) One or more IPv6 prefixes to be assigned to the network interface. Conflicts with ipv6PrefixCount
  • networkInterfaceId - (Optional) The ID of the network interface to attach.
  • networkCardIndex - (Optional) The index of the network card. Some instance types support multiple network cards. The primary network interface must be assigned to network card index 0. The default is network card index 0.
  • privateIpAddress - (Optional) The primary private IPv4 address.
  • ipv4AddressCount - (Optional) The number of secondary private IPv4 addresses to assign to a network interface. Conflicts with ipv4Addresses
  • ipv4Addresses - (Optional) One or more private IPv4 addresses to associate. Conflicts with ipv4AddressCount
  • securityGroups - (Optional) A list of security group IDs to associate.
  • subnetId - (Optional) The VPC Subnet ID to associate.

Placement

The Placement Group of the instance.

The placement block supports the following:

  • affinity - (Optional) The affinity setting for an instance on a Dedicated Host.
  • availabilityZone - (Optional) The Availability Zone for the instance.
  • groupName - (Optional) The name of the placement group for the instance.
  • hostId - (Optional) The ID of the Dedicated Host for the instance.
  • hostResourceGroupArn - (Optional) The ARN of the Host Resource Group in which to launch instances.
  • spreadDomain - (Optional) Reserved for future use.
  • tenancy - (Optional) The tenancy of the instance (if the instance is running in a VPC). Can be default, dedicated, or host.
  • partitionNumber - (Optional) The number of the partition the instance should launch in. Valid only if the placement group strategy is set to partition.

Private DNS Name Options

The privateDnsNameOptions block supports the following:

  • enableResourceNameDnsAaaaRecord - (Optional) Indicates whether to respond to DNS queries for instance hostnames with DNS AAAA records.
  • enableResourceNameDnsARecord - (Optional) Indicates whether to respond to DNS queries for instance hostnames with DNS A records.
  • hostnameType - (Optional) The type of hostname for Amazon EC2 instances. For IPv4 only subnets, an instance DNS name must be based on the instance IPv4 address. For IPv6 native subnets, an instance DNS name must be based on the instance ID. For dual-stack subnets, you can specify whether DNS names use the instance IPv4 address or the instance ID. Valid values: ipName and resourceName.

Tag Specifications

The tags to apply to the resources during launch. You can tag instances, volumes, elastic GPUs and spot instance requests. More information can be found in the EC2 API documentation.

Each tagSpecifications block supports the following:

  • resourceType - (Optional) The type of resource to tag.
  • tags -(Optional) A map of tags to assign to the resource.

Attributes Reference

In addition to all arguments above, the following attributes are exported:

  • arn - Amazon Resource Name (ARN) of the launch template.
  • id - The ID of the launch template.
  • latestVersion - The latest version of the launch template.
  • tagsAll - A map of tags assigned to the resource, including those inherited from the provider defaultTags configuration block.

Import

Launch Templates can be imported using the id, e.g.,

$ terraform import aws_launch_template.web lt-12345678