

# Auto Scaling launch templates
<a name="launch-templates"></a>

A launch template is similar to a [launch configuration](launch-configurations.md), in that it specifies instance configuration information. It includes the ID of the Amazon Machine Image (AMI), the instance type, a key pair, security groups, and other parameters used to launch EC2 instances. However, defining a launch template instead of a launch configuration allows you to have multiple versions of a launch template. 

With versioning of launch templates, you can create a subset of the full set of parameters. Then, you can reuse it to create other versions of the same launch template. For example, you can create a launch template that defines a base configuration without an AMI or user data script. After you create your launch template, you can create a new version and add the AMI and user data that has the latest version of your application for testing. This results in two versions of the launch template. Storing a base configuration helps you to maintain the required general configuration parameters. You can create a new version of your launch template from the base configuration whenever you want. You can also delete the versions used for testing your application when you no longer need them. 

We recommend that you use launch templates to ensure that you're accessing the latest features and improvements. Not all Amazon EC2 Auto Scaling features are available when you use launch configurations. For example, you cannot create an Auto Scaling group that launches both Spot and On-Demand Instances or that specifies multiple instance types. You must use a launch template to configure these features. For more information, see [Auto Scaling groups with multiple instance types and purchase options](ec2-auto-scaling-mixed-instances-groups.md).

With launch templates, you can also use newer features of Amazon EC2. This includes Systems Manager parameters (AMI ID), the current generation of EBS Provisioned IOPS volumes (io2), EBS volume tagging, T2 Unlimited instances, Capacity Reservations, Capacity Blocks, and Dedicated Hosts, to name a few. 

When you create a launch template, all parameters are optional. However, if a launch template does not specify an AMI, you cannot add the AMI when you create your Auto Scaling group. If you specify an AMI but no instance type, you can add one or more instance types when you create your Auto Scaling group.

**Topics**
+ [Permissions to work with launch templates](#launch-templates-permissions)
+ [API operations supported by launch templates](#launch-templates-api-operations)
+ [Create a launch template for an Auto Scaling group](create-launch-template.md)
+ [Create a launch template using advanced settings](advanced-settings-for-your-launch-template.md)
+ [Migrate your Auto Scaling groups to launch templates](migrate-to-launch-templates.md)
+ [Migrate AWS CloudFormation stacks to launch templates](migrate-launch-configurations-with-cloudformation.md)
+ [Examples for creating and managing launch templates with the AWS CLI](examples-launch-templates-aws-cli.md)
+ [Use AWS Systems Manager parameters instead of AMI IDs in launch templates](using-systems-manager-parameters.md)

## Permissions to work with launch templates
<a name="launch-templates-permissions"></a>

The procedures in this section assume that you already have the required permissions to create launch templates. For information about how an administrator grants you permissions, see [Control access to launch templates with IAM permissions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/permissions-for-launch-templates.html) in the *Amazon EC2 User Guide*.

Note that if you do not have sufficient permissions to use and create resources specified in a launch template, you receive an error that you're not authorized to use the launch template when you try to specify it for an Auto Scaling group. For more information, see [Troubleshoot Amazon EC2 Auto Scaling: Launch templates](ts-as-launch-template.md).

For examples of IAM policies that let you call the `CreateAutoScalingGroup`, `UpdateAutoScalingGroup`, and `RunInstances` API operations with a launch template, see [Control Amazon EC2 launch template usage in Auto Scaling groups](ec2-auto-scaling-launch-template-permissions.md).

## API operations supported by launch templates
<a name="launch-templates-api-operations"></a>

For a list of API operations supported by launch templates, see [Amazon EC2 actions](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/OperationList-query-ec2.html) in the *[Amazon EC2 API Reference](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/)*.

# Create a launch template for an Auto Scaling group
<a name="create-launch-template"></a>

Before you can create an Auto Scaling group using a launch template, you must create a launch template that contains the configuration information to launch an instance, including the ID of the Amazon Machine Image (AMI).

To create new launch templates, use the following procedures.

**Contents**
+ [Create your launch template (console)](#create-launch-template-for-auto-scaling)
+ [Change the default network interface settings (console)](#change-network-interface)
+ [Modify the storage configuration (console)](#modify-storage-configuration)
+ [Create a launch template from an existing instance (console)](#create-launch-template-from-instance)
+ [Related resources](#create-launch-template-related-resources)
+ [Limitations](#create-launch-template-limitations)

**Important**  
Launch template parameters are not fully validated when you create the launch template. If you specify incorrect values for parameters, or if you do not use supported parameter combinations, no instances can launch using this launch template. Be sure to specify the correct values for the parameters and use supported parameter combinations. For example, to launch instances with an Arm-based AWS Graviton or Graviton2 AMI, you must specify an Arm-compatible instance type. For more information, see [Launch template restrictions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/launch-template-restrictions.html) in the *Amazon EC2 User Guide*.

## Create your launch template (console)
<a name="create-launch-template-for-auto-scaling"></a>

The following steps describe how to configure a basic launch template: 
+ Specify the Amazon Machine Image (AMI) from which to launch the instances.
+ Choose an instance type that is compatible with the AMI that you specify. 
+ Specify the key pair to use when connecting to instances, for example, using SSH.
+ Add one or more security groups to allow network access to the instances.
+ Specify whether to attach additional volumes to each instance. 
+ Add custom tags (key-value pairs) to the instances and volumes.

**To create a launch template**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Instances**, choose **Launch Templates**.

1. Choose **Create launch template**. Enter a name and provide a description for the initial version of the launch template.

1. (Optional) Under **Auto Scaling guidance**, select the check box to have Amazon EC2 provide guidance to help create a template to use with Amazon EC2 Auto Scaling. 

1. Under **Launch template contents**, fill out each required field and any optional fields as needed.

   1. **Application and OS Images (Amazon Machine Image)**: (Required) Choose the ID of the AMI for your instances. You can search through all available AMIs, or select an AMI from the **Recents** or **Quick Start** list. If you don't see the AMI that you need, choose **Browse more AMIs** to browse the full AMI catalog.

      To choose a custom AMI, you must first create your AMI from a customized instance. For more information, see [Create an Amazon EBS-backed AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html) in the *Amazon EC2 User Guide*.

   1. For **Instance type**, choose a single instance type that's compatible with the AMI that you specified.

      Alternatively, to use attribute-based instance type selection, choose **Advanced**, **Specify instance type attributes**, and then specify the following options:
      + **Number of vCPUs**: Enter the minimum and maximum number of vCPUs. To indicate no limits, enter a minimum of 0, and keep the maximum blank. 
      + **Amount of memory (MiB)**: Enter the minimum and maximum amount of memory, in MiB. To indicate no limits, enter a minimum of 0, and keep the maximum blank. 
      + Expand **Optional instance type attributes** and choose **Add attribute** to further limit the types of instances that can be used to fulfill your desired capacity. For information about each attribute, see [InstanceRequirementsRequest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InstanceRequirementsRequest.html) in the *Amazon EC2 API Reference*. 
      + **Resulting instance types**: You can view the instance types that match the specified compute requirements, such as vCPUs, memory, and storage.
      + To exclude instance types, choose **Add attribute**. From the **Attribute** list, choose **Excluded instance types**. From the **Attribute value** list, select the instance types to exclude.

   1. **Key pair (login)**: For **Key pair name**, choose an existing key pair, or choose **Create new key pair** to create a new one. For more information, see [Amazon EC2 key pairs and Linux instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) in the *Amazon EC2 User Guide*.

   1. **Network settings**: For **Firewall (security groups)**, use one or more security groups, or keep this blank and configure one or more security groups as part of the network interface. For more information, see [Amazon EC2 security groups for Linux instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html) in the *Amazon EC2 User Guide*.

      If you don't specify any security groups in your launch template, Amazon EC2 uses the default security group for the VPC that your Auto Scaling group will launch instances into. By default, this security group doesn't allow inbound traffic from external networks. For more information, see [Default security groups for your VPCs](https://docs.aws.amazon.com/vpc/latest/userguide/default-security-group.html) in the *Amazon VPC User Guide*.

   1. Do one of the following:
      + Change the default network interface settings. For example, you can enable or disable the public IPv4 addressing feature, which overrides the auto-assign public IPv4 addresses setting on the subnet. For more information, see [Change the default network interface settings (console)](#change-network-interface).
      + Skip this step to keep the default network interface settings. 

   1. Do one of the following:
      + Modify the storage configuration. For more information, see [Modify the storage configuration (console)](#modify-storage-configuration).
      + Skip this step to keep the default storage configuration.

   1. For **Resource tags**, specify tags by providing key and value combinations. If you specify instance tags in your launch template and then you choose to propagate your Auto Scaling group's tags to its instances, all the tags are merged. If the same tag key is specified for a tag in your launch template and a tag in your Auto Scaling group, then the tag value from the group takes precedence. 

1. (Optional) Configure advanced settings. For example, you can choose an IAM role that your application can use when it accesses other AWS resources or specify the instance user data that can be used to perform common automated configuration tasks after an instance starts. For more information, see [Create a launch template using advanced settings](advanced-settings-for-your-launch-template.md).

1. When you are ready to create the launch template, choose **Create launch template**.

1. To create an Auto Scaling group, choose **Create Auto Scaling group** from the confirmation page.

## Change the default network interface settings (console)
<a name="change-network-interface"></a>

Network interfaces provide connectivity to other resources in your VPC and the internet. For more information, see [Provide network connectivity for your Auto Scaling instances using Amazon VPC](asg-in-vpc.md).

This section shows you how to change the default network interface settings. For example, you can define whether you want to assign a public IPv4 address to each instance instead of defaulting to the auto-assign public IPv4 addresses setting on the subnet.

**Considerations and limitations**

When changing the default network interface settings, keep in mind the following considerations and limitations:
+ You must configure the security groups as part of the network interface, not in the **Security groups** section of the template. You cannot specify security groups in both places.
+ If you specify an existing network interface ID, you can launch only one instance. To do this, you must use the AWS CLI or an SDK to create the Auto Scaling group. When you create the group, you must specify the Availability Zone, but not the subnet ID. Also, you can specify an existing network interface only if it has a device index of 0. 
+ You cannot auto-assign a public IPv4 address if you specify more than one network interface. You also cannot specify duplicate device indexes across network interfaces. Both the primary and secondary network interfaces reside in the same subnet. 
+ When an instance launches, a private address is automatically allocated to each network interface. The address comes from the CIDR range of the subnet in which the instance is launched. For information on specifying CIDR blocks (or IP address ranges) for your VPC or subnet, see the [Amazon VPC User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/).

**To change the default network interface settings**

1. Under **Network settings**, expand **Advanced network configuration**.

1. Choose **Add network interface** to configure the primary network interface, paying attention to the following fields:

   1. **Device index**: Keep the default value, 0, to apply your changes to the primary network interface (eth0).

   1. **Network interface**: Keep the default value, **New interface**, to have Amazon EC2 Auto Scaling automatically create a new network interface when an instance is launched. Alternatively, you can choose an existing, available network interface with a device index of 0, but this limits your Auto Scaling group to one instance. 

   1. **Description**: (Optional) Enter a descriptive name.

   1. **Subnet**: Keep the default **Don't include in launch template** setting. 

      If the AMI specifies a subnet for the network interface, this results in an error. We recommend turning off **Auto Scaling guidance** as a workaround. After you make this change, you will not receive an error message. However, regardless of where the subnet is specified, the subnet settings of the Auto Scaling group take precedence and cannot be overridden.

   1. **Auto-assign public IP**: Change whether your network interface with a device index of 0 receives a public IPv4 address. By default, instances in a default subnet receive a public IPv4 address, while instances in a nondefault subnet do not. Select **Enable** or **Disable** to override the subnet's default setting.

   1. **Security groups**: Choose one or more security groups for the network interface. Each security group must be configured for the VPC that your Auto Scaling group will launch instances into. For more information, see [Amazon EC2 security groups for Linux instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html) in the *Amazon EC2 User Guide*.

   1. **Delete on termination**: Choose **Yes** to delete the network interface when the instance is terminated, or choose **No** to keep the network interface.

   1. **Elastic Fabric Adapter**: To support high performance computing and machine learning use cases, change the network interface into an Elastic Fabric Adapter network interface. For more information, see [Elastic Fabric Adapter](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa.html) in the *Amazon EC2 User Guide*. 

   1. **Network card index**: Choose **0** to attach the primary network interface to the network card with a device index of 0. If this option isn't available, keep the default value, **Don't include in launch template**. Attaching the network interface to a specific network card is available only for supported instance types. For more information, see [Network cards](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#network-cards) in the *Amazon EC2 User Guide*. 

   1. **ENA Express**: For instance types that support ENA Express, choose **Enable** to enable ENA Express or **Disable** to disable it. For more information, see [Improve network performance with ENA Express on Linux instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ena-express.html) in the *Amazon EC2 User Guide*. 

   1. **ENA Express UDP**: If you enable **ENA Express**, you can optionally use it for UDP traffic. Choose **Enable** to enable ENA Express UDP or **Disable** to disable it.

1. To add a secondary network interface, choose **Add network interface**.

## Modify the storage configuration (console)
<a name="modify-storage-configuration"></a>

You can modify the storage configuration for instances launched from an Amazon EBS-backed AMI or an instance store-backed AMI. You can also specify additional EBS volumes to attach to the instances. The AMI includes one or more volumes of storage, including the root volume (**Volume 1 (AMI Root)**). 

**To modify the storage configuration**

1. In **Configure storage**, modify the size or type of volume. 

   If the value you specify for volume size is outside the limits of the volume type, or smaller than the snapshot size, an error message is displayed. To help you address the issue, this message gives the minimum or maximum value that the field can accept.

   Only volumes associated with an Amazon EBS-backed AMI appear. To display information about the storage configuration for an instance launched from an instance store-backed AMI, choose **Show details** from the **Instance store volumes** section.

   To specify all EBS volume parameters, switch to the **Advanced** view in the top right corner. 

1. For advanced options, expand the volume that you want to modify and configure the volume as follows:

   1. **Storage type**: The type of volume (EBS or ephemeral) to associate with your instance. The instance store (ephemeral) volume type is only available if you select an instance type that supports it. For more information, see [Amazon EBS volumes](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-volumes.html) in the *Amazon EBS User Guide* and [Amazon EC2 instance store](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html) in the *Amazon EC2 User Guide*.

   1. **Device name**: Select from the list of available device names for the volume.

   1. **Snapshot**: Select the snapshot from which to create the volume. You can search for available shared and public snapshots by entering text into the **Snapshot** field.

   1. **Size (GiB)**: For EBS volumes, you can specify a storage size. If you have selected an AMI and instance that are eligible for the free tier, keep in mind that to stay within the free tier, you must stay under 30 GiB of total storage. For more information, see [Constraints on the size and configuration of an EBS volume](https://docs.aws.amazon.com/ebs/latest/userguide/volume_constraints.html) in the *Amazon EBS User Guide*.

   1. **Volume type**: For EBS volumes, choose the volume type. For more information, see [Amazon EBS volume types](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-volume-types.html) in the *Amazon EBS User Guide*.

   1. **IOPS**: If you have selected a Provisioned IOPS SSD (`io1` and `io2`) or General Purpose SSD (`gp3`) volume type, then you can enter the number of I/O operations per second (IOPS) that the volume can support. This is required for io1, io2, and gp3 volumes. It is not supported for gp2, st1, sc1, or standard volumes.

   1. **Delete on termination**: For EBS volumes, choose **Yes** to delete the volume when the instance is terminated, or choose **No** to keep the volume.

   1. **Encrypted**: If the instance type supports EBS encryption, you can choose **Yes** to enable encryption for the volume. If you have enabled encryption by default in this Region, encryption is enabled for you. For more information, see [Amazon EBS encryption](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-encryption.html) and [Enable Amazon EBS encryption by default](https://docs.aws.amazon.com/ebs/latest/userguide/encryption-by-default.html) in the *Amazon EBS User Guide*. 

      The default effect of setting this parameter varies with the choice of volume source, as described in the following table. In all cases, you must have permission to use the specified AWS KMS key.   
**Encryption outcomes**    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/autoscaling/ec2/userguide/create-launch-template.html)

      \$1 If encryption by default is enabled, all newly created volumes (whether or not the **Encrypted** parameter is set to **Yes**) are encrypted using the default KMS key. If you set both the **Encrypted** and **KMS key** parameters, then you can specify a non-default KMS key. 

   1. **KMS key**: If you chose **Yes** for **Encrypted**, then you must select a customer managed key to use to encrypt the volume. If you have enabled encryption by default in this Region, the default customer managed key is selected for you. You can select a different key or specify the ARN of any customer managed key that you previously created using the AWS Key Management Service.

1. To specify additional volumes to attach to the instances launched by this launch template, choose **Add new volume**.

## Create a launch template from an existing instance (console)
<a name="create-launch-template-from-instance"></a>

**To create a launch template from an existing instance**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Instances**, choose **Instances**.

1. Select the instance and choose **Actions**, **Image and templates**, **Create template from instance**.

1. Provide a name and description. 

1. Under **Auto Scaling guidance**, select the check box. 

1. Adjust any settings as required, and choose **Create launch template**. 

1. To create an Auto Scaling group, choose **Create Auto Scaling group** from the confirmation page.

## Related resources
<a name="create-launch-template-related-resources"></a>

We provide a few JSON and YAML template snippets that you can use to understand how to declare launch templates in your CloudFormation stack templates. For more information, see the [AWS::EC2::LaunchTemplate](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html) and [Create launch templates with CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-ec2-launch-templates.html) sections of the *AWS CloudFormation User Guide*.

For more information about launch templates, see [Launching an instance from a launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) in the *Amazon EC2 User Guide*.

## Limitations
<a name="create-launch-template-limitations"></a>
+ While you can specify a subnet in a launch template, doing so isn't necessary if you only use the launch template to create Auto Scaling groups. You can't specify the subnet for an Auto Scaling group by specifying the subnet in a launch template. The subnets for the Auto Scaling group are taken from the Auto Scaling group's own resource definition. 
+ For other limitations on user-defined network interfaces, see [Change the default network interface settings (console)](#change-network-interface).

# Create a launch template using advanced settings
<a name="advanced-settings-for-your-launch-template"></a>

This topic describes how to create a launch template with advanced settings from the AWS Management Console.

**To create a launch template using advanced settings**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Instances**, choose **Launch Templates**, and then choose **Create launch template**.

1. Configure your launch template as described in the following topics:
   +  [Required settings](#configure-required-settings) 
   +  [Advanced settings](#configure-advanced-settings) 

1. Choose **Create launch template**.

## Required settings
<a name="configure-required-settings"></a>

When you create a launch template, you must include the following required settings.

**Launch template name**  
Enter a unique name that describes the launch template.

**Application and OS Images (Amazon Machine Image)**  
Choose the Amazon Machine Image (AMI) that you want to use. You can either search or browse for the AMI you want to use. For best scaling efficiency, choose a custom AMI that is fully configured to launch an instance with your application code and requires few modifications on launch.

**Instance type**  
Choose an instance type that is compatible with your AMI. You can skip adding an instance type to your launch template if you plan to use multiple instances types that are embedded in the Auto Scaling group's own resource definition. An instance type is only required if you don't plan to create a [mixed instances group](ec2-auto-scaling-mixed-instances-groups.md).

## Advanced settings
<a name="configure-advanced-settings"></a>

The advanced settings are optional. If you do not configure any advanced settings, the specific capabilities will not be added to your instances.

Expand the **Advanced details** section to view the advanced settings. The following sections describe the most useful advanced settings to focus on when creating a launch template for an Auto Scaling group. For more information, see [Advanced details](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-launch-template.html#lt-advanced-details) in the *Amazon EC2 User Guide*.

**IAM instance profile**  
The instance profile contains the IAM role that you want to use. When your Auto Scaling group launches an EC2 instance, the permissions defined in the associated IAM role are granted to applications running on the instance. For more information, see [IAM role for applications that run on Amazon EC2 instances](us-iam-role.md).

**Termination protection**  
When enabled, this feature prevents users from terminating an instance using the Amazon EC2 console, CLI commands, and API operations. Termination protection provides an extra safeguard against accidental termination. It does not prevent Amazon EC2 Auto Scaling from terminating an instance. To control which instances Amazon EC2 Auto Scaling can terminate, see [Use instance scale-in protection to control instance termination](ec2-auto-scaling-instance-protection.md).

**Detailed CloudWatch monitoring**  
You can enable detailed monitoring for your EC2 instances to allow them to send metric data to Amazon CloudWatch at 1-minute intervals. By default, EC2 instances send metric data to CloudWatch at 5-minute intervals. Additional charges apply. For more information, see [Configure monitoring for Auto Scaling instances](enable-as-instance-metrics.md).

**Credit specification**  
Amazon EC2 provides burstable performance instances, such as T2, T3, and T3a, that allow applications to burst beyond the baseline CPU performance when required. By default, these instances can burst for a limited time before their CPU usage is throttled. You can optionally enable unlimited mode so that the instances can burst beyond the baseline for as long as needed. This allows applications to sustain high CPU performance when required. Additional charges may apply. For more information, see [Use an Auto Scaling group to launch a burstable performance instance as Unlimited](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances-how-to.html#burstable-performance-instances-auto-scaling-grp) in the *Amazon EC2 User Guide*.

**Placement group name**  
You can specify a placement group and use a cluster or a partition strategy to influence how your instances are physically located in the AWS data center. For small Auto Scaling groups, you can also use the spread strategy. For more information, see [Placement groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) in the *Amazon EC2 User Guide*.  
There are some considerations when using placement groups with Auto Scaling groups:  
+ If a placement group is specified in both the launch template and the Auto Scaling group, the placement group for the Auto Scaling group takes precedence.
+ In CloudFormation, be careful if you define a placement group in the launch template. Amazon EC2 Auto Scaling will launch instances into the specified placement group. However, CloudFormation will not receive signals from those instances if you use an [UpdatePolicy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-updatepolicy.html) with your Auto Scaling group (though this could change in the future). 

**Purchasing option**  
You can choose **Request Spot Instances** to request Spot Instances at the Spot price, capped at the On-Demand price, and choose **Customize** to change the default Spot Instance settings. For an Auto Scaling group, you must specify a one-time request with no end date (the default). For more information, see [Request Spot Instances for fault-tolerant and flexible applications](launch-template-spot-instances.md). This setting may be useful in special circumstances, but in general it's best to leave it unspecified and create a mixed instances group instead. For more information, see [Auto Scaling groups with multiple instance types and purchase options](ec2-auto-scaling-mixed-instances-groups.md).   
If you specify a Spot Instance request in your launch template, you can't create a mixed instances group. If you try to use a launch template that requests Spot Instances with a mixed instances group, you receive the following error message: `Incompatible launch template: You cannot use a launch template that is set to request Spot Instances (InstanceMarketOptions) when you configure an Auto Scaling group with a mixed instances policy. Add a different launch template to the group and try again.`

**Capacity Reservation**  
Capacity Reservations allow you to reserve capacity for your Amazon EC2 instances in a specific Availability Zone for any duration. For more information, see [On-Demand Capacity Reservations](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-capacity-reservations.html) in the *Amazon EC2 User Guide*.  
You can choose whether to launch instances into:  
+ any open Capacity Reservation (**Open**)
+ a specific Capacity Reservation (**Target by ID**)
+ a group of Capacity Reservations (**Target by group**)
To target a specific Capacity Reservation, the instance type in your launch template must match the instance type of the reservation. When you create your Auto Scaling group, use the same Availability Zone as the Capacity Reservation. Depending on the AWS Region you choose, you can choose to target a Capacity Block instead. For more information, see [Use Capacity Blocks for machine learning workloads](launch-template-capacity-blocks.md).  
To target a group of Capacity Reservations, see [Reserve capacity in specific Availability Zones with Capacity Reservations](use-ec2-capacity-reservations.md). By targeting a group of Capacity Reservations, you can have capacity distributed across multiple Availability Zones to improve resiliency.

**Tenancy**  
Amazon EC2 provides three options for the tenancy of your EC2 instances:   
+ Shared (**Shared**) – Multiple AWS accounts may share the same physical hardware. This is the default tenancy option when launching an instance.
+ Dedicated instances (**Dedicated**) – Your instance runs on single-tenant hardware. No other AWS customer shares the same physical server. For more information, see [Dedicated Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-instance.html) in the *Amazon EC2 User Guide*.
+ Dedicated Hosts (**Dedicated host**) – The instance runs on a physical server that is dedicated to your use. Using Dedicated Hosts makes it easier to bring your own licenses (BYOL) that have dedicated hardware requirements to EC2 and meet compliance use cases. If you choose this option, you must provide a host resource group for **Tenancy host resource group**. For more information, see [Dedicated Hosts](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-hosts-overview.html) in the *Amazon EC2 User Guide*.
Support for Dedicated Hosts is only available if you specify a host resource group. You can't target a specific host ID or use host placement affinity.   
+ If you try to use a launch template that specifies a host ID, you receive the following error message: `Incompatible launch template: Tenancy host ID is not supported for Auto Scaling.`
+ If you try to use a launch template that specifies host placement affinity, you receive the following error message: `Incompatible launch template: Auto Scaling does not support host placement affinity.`

**Tenancy host resource group**  
With AWS License Manager, you can bring your own licenses to AWS and manage them centrally. A host resource group is a group of Dedicated Hosts that are linked to a specific License Manager license configuration. Host resource groups allow you to easily launch EC2 instances onto Dedicated Hosts that match your software licensing needs. You do not need to manually allocate Dedicated Hosts ahead of time. They are automatically created as needed. Note that when you associate an AMI with a license configuration, that AMI can only be associated with one host resource group at a time. For more information, see [Host resource groups in AWS License Manager](https://docs.aws.amazon.com/license-manager/latest/userguide/host-resource-groups.html) in the *License Manager User Guide*. 

**License configurations**  
With this setting, you can specify a license configuration for your instances without restricting their tenancy to Dedicated Hosts. The license configuration tracks the software licenses deployed on the instances so you can monitor your license usage and compliance. For more information, see [Create a self-managed license](https://docs.aws.amazon.com/license-manager/latest/userguide/create-license-configuration.html) in the *License Manager User Guide*.

**Metadata accessible**  
You can choose whether to enable or disable access to the HTTP endpoint of the instance metadata service. By default, the HTTP endpoint is enabled. If you choose to disable the endpoint, access to your instance metadata is turned off. You can specify the condition to require IMDSv2 only when the HTTP endpoint is enabled. For more information, see [Configure the instance metadata options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-options.html) in the *Amazon EC2 User Guide*.

**Metadata version**  
You can choose to require the use of Instance Metadata Service Version 2 (IMDSv2) when requesting instance metadata. If you do not specify a value, the default is to support both IMDSv1 and IMDSv2. For more information, see [Configure the instance metadata options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-options.html) in the *Amazon EC2 User Guide*.

**Metadata token response hop limit**  
You can set the allowable number of network hops for the metadata token. If you do not specify a value, the default is 1. For more information, see [Configure the instance metadata options](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-options.html) in the *Amazon EC2 User Guide*.

**User data**  
You can customize and finish configuring your instances at launch time by specifying shell scripts or cloud-init directives as user data. The user data runs when the instance initially starts up, allowing you to automatically install applications, dependencies, or customizations at launch time. For more information, see [Run commands on your Linux instance at launch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) in the *Amazon EC2 User Guide*.  
If you have large downloads or complex scripts, this adds to the time it takes for the instance to become ready for use. In which case, you may need to configure a lifecycle hook to delay an instance from reaching the `InService` state until it's fully provisioned. For more information about adding a lifecycle hook to your Auto Scaling group, see [Amazon EC2 Auto Scaling lifecycle hooks](lifecycle-hooks.md).

# Request Spot Instances for fault-tolerant and flexible applications
<a name="launch-template-spot-instances"></a>

In your launch template, you can optionally request Spot Instances with no end date or duration. Amazon EC2 Spot Instances are spare capacity available at steep discounts compared to the EC2 On-Demand price. Spot Instances are a cost-effective choice if you can be flexible about when your applications run and if your applications can be interrupted. For more information about creating a launch template that requests Spot Instances, see [Create a launch template using advanced settings](advanced-settings-for-your-launch-template.md). 

**Important**  
Spot Instances are typically used to supplement On-Demand Instances. For this scenario, you can specify the same settings that are used to launch Spot Instances as part of the settings of your Auto Scaling group. When you specify the settings as part of the Auto Scaling group, you can request to launch Spot Instances only after launching a certain number of On-Demand Instances and then continue to launch some combination of On-Demand Instances and Spot Instances as the group scales. For more information, see [Auto Scaling groups with multiple instance types and purchase options](ec2-auto-scaling-mixed-instances-groups.md). 

This topic describes how to launch only Spot Instances in your Auto Scaling group by specifying settings in a launch template, rather than in the Auto Scaling group itself. The information in this topic also applies to Auto Scaling groups that request Spot Instances with a [launch configuration](create-launch-config.md). The difference is that a launch configuration requires a maximum price, but for launch templates, the maximum price is optional.

When you create a launch template to launch only Spot Instances, keep the following considerations in mind:
+ **Spot price.** You pay only the current Spot price for the Spot Instances that you launch. This pricing changes slowly over time based on long-term trends in supply and demand. For more information, see [Spot Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances.html) and [Pricing and savings](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances.html#spot-pricing) in the *Amazon EC2 User Guide*. 
+ **Setting your maximum price.** You can optionally include a maximum price per hour for Spot Instances in your launch template. If your maximum price exceeds the current Spot price, the Amazon EC2 Spot service fulfills your request immediately if capacity is available. If the price for Spot Instances rises above your maximum price for a running instance in your Auto Scaling group, it terminates your instance.
**Warning**  
Your application might not run if you do not receive any Spot Instances, such as when your maximum price is too low. To take advantage of the Spot Instances available for as long as possible, set your maximum price close to the On-Demand price.
+ **Balancing across Availability Zones.** If you specify multiple Availability Zones, Amazon EC2 Auto Scaling distributes the Spot requests across the specified zones. If your maximum price is too low in one Availability Zone for any requests to be fulfilled, Amazon EC2 Auto Scaling checks whether requests were fulfilled in the other zones. If so, Amazon EC2 Auto Scaling cancels the requests that failed and redistributes them across the Availability Zones that have requests fulfilled. If the price in an Availability Zone with no fulfilled requests drops enough that future requests succeed, Amazon EC2 Auto Scaling rebalances across all of the Availability Zones.
+ **Spot Instance termination.** Spot Instances can be terminated at any time. The Amazon EC2 Spot service can terminate Spot Instances in your Auto Scaling group as the availability of, or price for, Spot Instances changes. When scaling or performing health checks, Amazon EC2 Auto Scaling can also terminate Spot Instances in the same way that it can terminate On-Demand Instances. When an instance is terminated, any storage is deleted. 
+ **Maintaining your desired capacity.** When a Spot Instance is terminated, Amazon EC2 Auto Scaling attempts to launch another Spot Instance to maintain the desired capacity for the group. If the current Spot price is less than your maximum price, it launches a Spot Instance. If the request for a Spot Instance is unsuccessful, it keeps trying. 
+ **Changing your maximum price.** To change your maximum price, create a new launch template or update an existing launch template with the new maximum price, and then associate it with your Auto Scaling group. The existing Spot Instances continue to run as long as the maximum price specified in the launch template used for those instances is higher than the current Spot price. If you did not set a maximum price, the default maximum price is the On-Demand price.

# Use Capacity Blocks for machine learning workloads
<a name="launch-template-capacity-blocks"></a>

Capacity Blocks help you reserve highly sought-after GPU instances on a future date to support your short-duration, machine learning (ML) workloads.

For an overview of Capacity Blocks and how they work, see [Capacity Blocks for ML](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-capacity-blocks.html) in the *Amazon EC2 User Guide*. 

To start using Capacity Blocks, you create a capacity reservation in a specific Availability Zone. Capacity Blocks are delivered as `targeted` capacity reservations in a single Availability Zone. When you create your launch template, specify the Capacity Block's reservation ID and instance type. Then, update your Auto Scaling group to use the launch template you created and the Capacity Block's Availability Zone. When your Capacity Block reservation begins, use scheduled scaling to launch the same number of instances as your Capacity Block reservation.

**Important**  
Capacity Blocks are only available for certain Amazon EC2 instance types and AWS Regions. For more information, see [Prerequisites](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-blocks-using.html#capacity-blocks-prerequisites) in the *Amazon EC2 User Guide*.

**Topics**
+ [Operational guidelines](#capacity-blocks-operational-guidelines)
+ [Specify a Capacity Block in your launch template](#specify-a-capacity-block-in-your-launch-template)
+ [Limitations](#capacity-blocks-limitations)
+ [Related resources](#capacity-blocks-related-resources)

## Operational guidelines
<a name="capacity-blocks-operational-guidelines"></a>

The following are basic operational guidelines that you should follow when using a Capacity Block with an Auto Scaling group.
+ Scale in your Auto Scaling group to zero more than 30 minutes before the Capacity Block reservation end time. Amazon EC2 will terminate any instances that are still running 30 minutes before the end time of the Capacity Block.
+ We recommend that you use scheduled scaling to scale out (add instances) and scale in (remove instances) at the appropriate reservation times. For more information, see [Scheduled scaling for Amazon EC2 Auto Scaling](ec2-auto-scaling-scheduled-scaling.md).
+ Add lifecycle hooks as needed to perform a graceful shutdown of your application inside the instances when scaling in. Leave enough time for the lifecycle action to complete *before* Amazon EC2 starts forcibly terminating your instances 30 minutes before the Capacity Block reservation end time. For more information, see [Amazon EC2 Auto Scaling lifecycle hooks](lifecycle-hooks.md).
+ Make sure that the Auto Scaling group points to the correct version of the launch template for the entire duration of the reservation. We recommend pointing to a specific version of the launch template instead of the `$Default` or `$Latest` version.

**Note**  
If you leave a Capacity Block instance running until the end of the reservation and Amazon EC2 reclaims it, the scaling activities for your Auto Scaling group state that it was "`taken out of service in response to an EC2 health check that indicated it had been terminated or stopped`", even though it was purposely reclaimed at the end of the Capacity Block. Similarly, Amazon EC2 Auto Scaling will attempt to replace the instance in the same manner as it does for any instance that fails a health check. For more information, see [Health checks for instances in an Auto Scaling group](ec2-auto-scaling-health-checks.md).

## Specify a Capacity Block in your launch template
<a name="specify-a-capacity-block-in-your-launch-template"></a>

To create a launch template that targets a specific Capacity Block for your Auto Scaling group, use one of the following methods:

------
#### [ Console ]

**To specify a Capacity Block in your launch template (console)**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the top navigation bar, select the AWS Region where you created your Capacity Block. 

1. On the navigation pane, under **Instances**, choose **Launch Templates**.

1. Choose **Create launch template**, and create the launch template. Include the ID of the Amazon Machine Image (AMI), the instance type, and any other launch template settings as needed.

1. Expand the **Advanced details** section to view the advanced settings.

1. For **Purchasing option**, choose **Capacity Blocks**.

1. For **Capacity reservation**, choose **Target by ID**, and then for **Capacity reservation - Target by ID**, choose the capacity reservation ID of an existing Capacity Block.

1. When you have finished, choose **Create launch template**.

   For help creating an Auto Scaling group with a launch template, see [Create an Auto Scaling group using a launch template](create-asg-launch-template.md). 

------
#### [ AWS CLI ]

**To specify a Capacity Block in your launch template (AWS CLI)**  
Use the following [create-launch-template](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template.html) command to create a launch template that specifies an existing Capacity Block reservation ID. Replace each *user input placeholder* with your own information.

```
aws ec2 create-launch-template --launch-template-name my-template-for-capacity-block  \
  --version-description AutoScalingVersion1 --region us-east-2 \
  --launch-template-data file://config.json
```

**Tip**  
If this command throws an error, make sure that you have updated the AWS CLI locally to the latest version.

Contents of `config.json`.

```
{
    "ImageId": "ami-04d5cc9b88example",
    "InstanceType": "p4d.24xlarge",
    "SecurityGroupIds": [
        "sg-903004f88example"
    ], 
    "KeyName": "MyKeyPair",
    "InstanceMarketOptions": {
        "MarketType": "capacity-block"
    },
    "CapacityReservationSpecification": {
        "CapacityReservationTarget": {
            "CapacityReservationId": "cr-02168da1478b509e0"
        }
    }
}
```

The following is example output. 

```
{
    "LaunchTemplate": {
        "LaunchTemplateId": "lt-068f72b724example",
        "LaunchTemplateName": "my-template-for-capacity-block",
        "CreateTime": "2023-10-27T15:12:44.000Z",
        "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
        "DefaultVersionNumber": 1,
        "LatestVersionNumber": 1
    }
}
```

You can use the following [describe-launch-template-versions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-launch-template-versions.html) command to verify the Capacity Block reservation ID associated with the launch template.

```
aws ec2 describe-launch-template-versions --launch-template-names my-template-for-capacity-block \
  --region us-east-2
```

The following is example output for a launch template that specifies a Capacity Block reservation.

```
{
    "LaunchTemplateVersions": [
        {
            "LaunchTemplateId": "lt-068f72b724example",
            "LaunchTemplateName": "my-template-for-capacity-block",
            "VersionNumber": 1,
            "CreateTime": "2023-10-27T15:12:44.000Z",
            "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
            "DefaultVersion": true,
            "LaunchTemplateData": {
                "ImageId": "ami-04d5cc9b88example",
                "InstanceType": "p5.48xlarge",
                "SecurityGroupIds": [
                    "sg-903004f88example"
                ], 
                "KeyName": "MyKeyPair",
                "InstanceMarketOptions": {
                    "MarketType": "capacity-block"
                },
                "CapacityReservationSpecification": {
                    "CapacityReservationTarget": {
                        "CapacityReservationId": "cr-02168da1478b509e0"
                    }
                }
            }
        }
    ]
}
```

------

## Limitations
<a name="capacity-blocks-limitations"></a>
+ Support for Capacity Blocks is only available if your Auto Scaling group has a compatible configuration. Mixed instances groups and warm pools are not supported.
+ You can only target one Capacity Block at a time.

## Related resources
<a name="capacity-blocks-related-resources"></a>
+ For the prerequisites and recommendations for using P5 Instances, see [Get started with P5 instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/p5-instances-started.html) in the *Amazon EC2 User Guide*. 
+ Amazon EKS supports using Capacity Blocks to support your short duration, machine learning (ML) workloads on Amazon EKS clusters. For more information, see [Capacity Blocks for ML](https://docs.aws.amazon.com/eks/latest/userguide/capacity-blocks.html) in the **Amazon EKS User Guide**.
+ You can use Capacity Blocks with supported instance types and Regions. However, On-Demand Capacity Reservations provide flexibility to reserve capacity for other instances types and Regions. For a tutorial that shows you how to use the On-Demand Capacity Reservation option, see [Reserve capacity in specific Availability Zones with Capacity Reservations](use-ec2-capacity-reservations.md).

# Migrate your Auto Scaling groups to launch templates
<a name="migrate-to-launch-templates"></a>

As of **January 1, 2023**, new instance types are no longer supported in launch configurations. This applies to any instance types added to an AWS Region after the initial Region launch. In addition, you might be able to create a launch configuration with an instance type that is no longer supported in a Region. For more information, see [Auto Scaling launch configurations](launch-configurations.md).

To migrate your Auto Scaling groups from launch configurations to launch templates, see the following steps. 

**Important**  
Verify that you have the permissions required to work with launch templates. For more information, see [Permissions to work with launch templates](launch-templates.md#launch-templates-permissions).  
Make sure that resources associated with the launch configuration, such as security groups and IAM instance profiles, are not deleted unintentionally.  
Test the rollback operation to make sure that changes can be safely reverted.

## Step 1: Find Auto Scaling groups that use launch configurations
<a name="find-groups-that-use-launch-configurations"></a>

To identify whether you have Auto Scaling groups that are still using launch configurations, run the following [describe-auto-scaling-groups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-auto-scaling-groups.html) command using the AWS CLI. Replace *REGION* with your AWS Region.

```
aws autoscaling describe-auto-scaling-groups --region REGION \
  --query 'AutoScalingGroups[?LaunchConfigurationName!=`null`]'
```

The following is example output.

```
[
    {
	"AutoScalingGroupName": "group-1",
	"AutoScalingGroupARN": "arn",
	"LaunchConfigurationName": "my-launch-config",
	"MinSize": 1,
	"MaxSize": 5,
	"DesiredCapacity": 2,
	"DefaultCooldown": 300,
	"AvailabilityZones": [
            "us-west-2a",
            "us-west-2b",
            "us-west-2c"
        ],
	"LoadBalancerNames": [],
	"TargetGroupARNs": [],
	"HealthCheckType": "EC2",
	"HealthCheckGracePeriod": 300,
	"Instances": [
            {
                "ProtectedFromScaleIn": false,
                "AvailabilityZone": "us-west-2a",
                "LaunchConfigurationName": "my-launch-config",
                "InstanceId": "i-05b4f7d5be44822a6",
                "InstanceType": "t3.micro",
                "HealthStatus": "Healthy",
                "LifecycleState": "InService"
            },
            {
                "ProtectedFromScaleIn": false,
                "AvailabilityZone": "us-west-2b",
                "LaunchConfigurationName": "my-launch-config",
                "InstanceId": "i-0c20ac468fa3049e8",
                "InstanceType": "t3.micro",
                "HealthStatus": "Healthy",
                "LifecycleState": "InService"
            }
	],
	"CreatedTime": "2023-03-09T22:15:11.611Z",
	"SuspendedProcesses": [],
	"VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782",
	"EnabledMetrics": [],
	"Tags": [
            {
		"ResourceId": "group-1",
		"ResourceType": "auto-scaling-group",
		"Key": "environment",
		"Value": "production",
		"PropagateAtLaunch": true
            }
        ],
	"TerminationPolicies": [
	    "Default"
	],
	"NewInstancesProtectedFromScaleIn": false,
	"ServiceLinkedRoleARN": "arn",
       "TrafficSources": []
    },

    ... additional groups ...

]
```

Alternatively, to remove everything except the Auto Scaling group names with the names of their respective launch configurations and tags in the output, run the following command:

```
aws autoscaling describe-auto-scaling-groups --region REGION \
  --query 'AutoScalingGroups[?LaunchConfigurationName!=`null`].{AutoScalingGroupName: AutoScalingGroupName, LaunchConfigurationName: LaunchConfigurationName, Tags: Tags}'
```

The following shows example output.

```
[
    {
        "AutoScalingGroupName": "group-1",
        "LaunchConfigurationName": "my-launch-config",
        "Tags": [
            {
                "ResourceId": "group-1",
                "ResourceType": "auto-scaling-group",
                "Key": "environment",
                "Value": "production",
                "PropagateAtLaunch": true
            }
        ]
    },

    ... additional groups ...

]
```

For more information about filtering, see [Filtering AWS CLI output](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-filter.html) in the *AWS Command Line Interface User Guide*.

## Step 2: Copy a launch configuration to a launch template
<a name="copy-launch-config"></a>

You can copy a launch configuration to a launch template using the following procedure. Then, you can add it to your Auto Scaling group.

Copying multiple launch configurations results in identically named launch templates. To change the name given to a launch template during the copying process, you must copy the launch configurations one by one.

**Note**  
The copying feature is available only from the console. 

**To copy a launch configuration to a launch template (console)**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the left navigation pane, under **Auto Scaling**, choose **Auto Scaling Groups**. 

1. Choose **Launch configurations** near the top of the page. When prompted for confirmation, choose **View launch configurations** to confirm that you want to view the **Launch configurations** page. 

1. Select the launch configuration you want to copy and choose **Copy to launch template, Copy selected**. This sets up a new launch template with the same name and options as the launch configuration that you selected.

1. For **New launch template name**, you can use the name of the launch configuration (the default) or enter a new name. Launch template names must be unique.

1. (Optional) Select **Create an Auto Scaling group using the new template**.

   You can skip this step to finish copying the launch configuration. You do not need to create a new Auto Scaling group.

1. Choose **Copy**.

**To copy all launch configurations to launch templates (console)**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the navigation pane, under **Auto Scaling**, choose **Launch Configurations**.

1. Choose **Copy to launch template, Copy all**. This copies each launch configuration in the current Region to a new launch template with the same name and options.

1. Choose **Copy**.

## Step 3: Update an Auto Scaling group to use a launch template
<a name="replace-launch-config"></a>

After creating a launch template, you're ready to add it to your Auto Scaling group. 

**To update an Auto Scaling group to use a launch template (console)**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/), and choose **Auto Scaling Groups** from the navigation pane.

1. Select the check box next to your Auto Scaling group. 

   A split pane opens up in the bottom part of the page, showing information about the group that's selected. 

1. On the **Details** tab, choose **Launch configuration**, **Edit**.

1. Choose **Switch to launch template**.

1. For **Launch template**, select your launch template.

1. For **Version**, select the launch template version, as needed. After you create versions of a launch template, you can choose whether the Auto Scaling group uses the default or the latest version of the launch template when scaling out.

1. Choose **Update**. 

**To update an Auto Scaling group to use a launch template (AWS CLI)**  
The following [update-auto-scaling-group](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/update-auto-scaling-group.html) command updates the specified Auto Scaling group to use the initial version of the specified launch template.

```
aws autoscaling update-auto-scaling-group --auto-scaling-group-name my-asg \
  --launch-template LaunchTemplateName=my-template-for-auto-scaling,Version='1'
```

For more examples of using CLI commands to update an Auto Scaling group to use a launch template, see [Update an Auto Scaling group to use a launch template](examples-launch-templates-aws-cli.md#update-asg-launch-template-cli).

## Step 4: Replace your instances
<a name="replace-instances"></a>

After you replace the launch configuration with a launch template, any new instances will use the new launch template. Existing instances are not affected. 

To update the existing instances, you can start an instance refresh to replace the instances in your Auto Scaling group instead of manually replacing instances a few at a time. For more information, see [Use an instance refresh to update instances in an Auto Scaling group](asg-instance-refresh.md). If the group is large, an instance refresh can be particularly helpful.

Alternatively, you can allow automatic scaling to gradually replace existing instances with new instances based on the group's [termination policies](as-instance-termination.md), or you can terminate them. Manual termination forces your Auto Scaling group to launch new instances to maintain the group's desired capacity. For more information, see [Terminate an instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#terminating-instances-console) in the *Amazon EC2 User Guide*.

## Additional information
<a name="migrating-to-launch-templates-more-info"></a>

For more information, see [Amazon EC2 Auto Scaling will no longer add support for new EC2 features to Launch Configurations](https://aws.amazon.com/blogs/compute/amazon-ec2-auto-scaling-will-no-longer-add-support-for-new-ec2-features-to-launch-configurations/) on the AWS Compute Blog. 

For a topic that takes you through how to migrate AWS CloudFormation stacks from launch configurations to launch templates, see [Migrate AWS CloudFormation stacks to launch templates](migrate-launch-configurations-with-cloudformation.md).

# Migrate AWS CloudFormation stacks to launch templates
<a name="migrate-launch-configurations-with-cloudformation"></a>

You can migrate your existing CloudFormation stack templates from launch configurations to launch templates. To do this, add a launch template directly to an existing stack template and then associate the launch template with the Auto Scaling group in the stack template. Then, use your modified template to update your stack. 

When migrating to launch templates, this topic saves you time by providing instructions for rewriting the launch configurations in your CloudFormation stack templates as launch templates. For more information about migrating launch configurations to launch templates, see [Migrate your Auto Scaling groups to launch templates](migrate-to-launch-templates.md).

**Topics**
+ [Find Auto Scaling groups that use a launch configuration](#find-auto-scaling-groups-to-migrate)
+ [Update a stack to use a launch template](#update-stack-to-use-launch-template)
+ [Understand update behavior of stack resources](#understand-update-behavior)
+ [Track the migration](#track-the-migration)
+ [Launch configuration mapping reference](#launch-configuration-mapping-reference)

## Find Auto Scaling groups that use a launch configuration
<a name="find-auto-scaling-groups-to-migrate"></a>

**To find Auto Scaling groups that use a launch configuration**
+ Use the following [describe-auto-scaling-groups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-auto-scaling-groups.html) command to list the names of Auto Scaling groups that are using launch configurations in the specified Region. Include the `--filters` option to narrow the results to groups associated with a CloudFormation stack (by filtering by the `aws:cloudformation:stack-name` tag key). 

  ```
  aws autoscaling describe-auto-scaling-groups --region REGION \
    --filters Name=tag-key,Values=aws:cloudformation:stack-name \
    --query 'AutoScalingGroups[?LaunchConfigurationName!=`null`].AutoScalingGroupName'
  ```

  The following shows example output.

  ```
  [
      "{stack-name}-group-1",
      "{stack-name}-group-2",
      "{stack-name}-group-3"
  ]
  ```

  You can find additional useful AWS CLI commands for finding Auto Scaling groups to migrate and filtering the output in [Migrate your Auto Scaling groups to launch templates](migrate-to-launch-templates.md).

**Important**  
If your stack resources have `AWSEB` in their name, this means they were created through AWS Elastic Beanstalk. In this case, you must update the Beanstalk environment to direct Elastic Beanstalk to remove the launch configuration and replace it with a launch template.

## Update a stack to use a launch template
<a name="update-stack-to-use-launch-template"></a>

Follow the steps in this section to do the following:
+ Rewrite the launch configuration as a launch template using the equivalent launch template properties. 
+ Associate the new launch template with the Auto Scaling group. 
+ Deploy these updates.

**To modify the stack template and update the stack**

1. Follow the same general procedures for modifying the stack template described in [Modifying a stack template](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-get-template.html) in the *AWS CloudFormation User Guide*.

1. Rewrite the launch configuration as a launch template. See the following example: 

   **Example: A simple launch configuration**

   ```
   ---
   Resources:
     myLaunchConfig: 
       Type: AWS::AutoScaling::LaunchConfiguration
       Properties: 
         ImageId: ami-02354e95b3example
         InstanceType: t3.micro
         SecurityGroups:
           - !Ref EC2SecurityGroup
         KeyName: MyKeyPair
         BlockDeviceMappings: 
           - DeviceName: /dev/xvda
             Ebs: 
               VolumeSize: 150
               DeleteOnTermination: true
         UserData: 
           Fn::Base64: !Sub |
             #!/bin/bash -xe
             yum install -y aws-cfn-bootstrap
             /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource myASG --region ${AWS::Region}
   ```

   **Example: The launch template equivalent**

   ```
   ---
   Resources:
     myLaunchTemplate:
       Type: AWS::EC2::LaunchTemplate
       Properties:
         LaunchTemplateName: !Sub ${AWS::StackName}-launch-template
         LaunchTemplateData:
           ImageId: ami-02354e95b3example
           InstanceType: t3.micro
           SecurityGroupIds:
             - Ref! EC2SecurityGroup
           KeyName: MyKeyPair
           BlockDeviceMappings: 
             - DeviceName: /dev/xvda
               Ebs: 
                 VolumeSize: 150
                 DeleteOnTermination: true
           UserData: 
             Fn::Base64: !Sub |
               #!/bin/bash -x
               yum install -y aws-cfn-bootstrap
               /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource myASG --region ${AWS::Region}
   ```

   For reference information for all the properties that Amazon EC2 supports, see [AWS::EC2::LaunchTemplate](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html) in the *AWS CloudFormation User Guide*. 

   Note how the launch template includes the `LaunchTemplateName` property with a value of `!Sub ${AWS::StackName}-launch-template`. This is required if you want the name of the launch template to include the stack name.

1. If the `IamInstanceProfile` property is present in your launch configuration, you must convert it to a structure and specify either the name or the ARN of the instance profile. For an example, see [AWS::EC2::LaunchTemplate](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html). 

1. If the `AssociatePublicIpAddress`, `InstanceMonitoring`, or `PlacementTenancy` properties are present in your launch configuration, you must convert these to a structure. For examples, see [AWS::EC2::LaunchTemplate](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html). 

   An exception is when the value for the `MapPublicIpOnLaunch` property on the subnets you used for your Auto Scaling group matches the value for the `AssociatePublicIpAddress` property in your launch configuration. In this case, you can ignore the `AssociatePublicIpAddress` property. The `AssociatePublicIpAddress` property is only used to override the `MapPublicIpOnLaunch` property to change whether instances receive a public IPv4 address at launch. 

1. You can copy security groups from the `SecurityGroups` property to one of two places in your launch template. Normally, you copy the security groups to the `SecurityGroupIds` property. However, if you create a `NetworkInterfaces` structure within your launch template to specify the `AssociatePublicIpAddress` property, then you must copy the security groups to the `Groups` property of the network interface instead.

1. If any `BlockDeviceMapping` structures are present in your launch configuration with `NoDevice` set to `true`, then you must specify an empty string for `NoDevice` in your launch template to have Amazon EC2 omit the device.

1. If the `SpotPrice` property is present in your launch configuration, we recommend that you omit it from your launch template. Your Spot Instances will launch at the current Spot price. This price will never exceed the On-Demand price.

   To request Spot Instances, you have two mutually exclusive options:
   + The first is to use the `InstanceMarketOptions` structure in your launch template (not recommended). For more information, see [AWS::EC2::LaunchTemplate InstanceMarketOptions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-instancemarketoptions.html) in the *AWS CloudFormation User Guide*.
   + The other is to add a `MixedInstancesPolicy` structure to your Auto Scaling group. Doing so provides you with more options for how you make the request. A Spot Instance request in your launch template doesn't support more than one instance type selection per Auto Scaling group. However, a mixed instances policy does support more than one instance type selection per Auto Scaling group. Spot Instance requests benefit from having more than one instance type to choose from. For more information, see [AWS::AutoScaling::AutoScalingGroup MixedInstancesPolicy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-autoscalinggroup-mixedinstancespolicy.html) in the *AWS CloudFormation User Guide*.

1. Remove the `LaunchConfigurationName` property from the [AWS::AutoScaling::AutoScalingGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-autoscaling-autoscalinggroup.html) resource. Add the launch template in its place.

   In the following examples, the [Ref](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html) intrinsic function gets the ID of the [AWS::EC2::LaunchTemplate](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html) resource with the logical ID `myLaunchTemplate`. The [GetAtt](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html) function gets the latest version number (for example, `1`) of the launch template for the `Version` property.

   **Example: Without a mixed instances policy**

   ```
   ---
   Resources:
     myASG:
       Type: AWS::AutoScaling::AutoScalingGroup
       Properties:
         LaunchTemplate:
           LaunchTemplateId: !Ref myLaunchTemplate
           Version: !GetAtt myLaunchTemplate.LatestVersionNumber
         ...
   ```

   **Example: With a mixed instances policy**

   ```
   ---
   Resources:
     myASG:
       Type: AWS::AutoScaling::AutoScalingGroup
       Properties:        
         MixedInstancesPolicy:
           LaunchTemplate:
             LaunchTemplateSpecification:
               LaunchTemplateId: !Ref myLaunchTemplate
               Version: !GetAtt myLaunchTemplate.LatestVersionNumber
         ...
   ```

   For reference information for all the properties that Amazon EC2 Auto Scaling supports, see [AWS::AutoScaling::AutoScalingGroup](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-autoscaling-autoscalinggroup.html) in the *AWS CloudFormation User Guide*.

1. When you are ready to deploy these updates, follow the CloudFormation procedures to update the stack with your modified stack template. For more information, see [Modifying a stack template](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-get-template.html) in the *AWS CloudFormation User Guide*. 

## Understand update behavior of stack resources
<a name="understand-update-behavior"></a>

CloudFormation updates stack resources by comparing changes between the updated template you provide, and resource configurations you described in the previous version of your stack template. Resource configurations that haven't changed remain unaffected during the update process.

CloudFormation supports the [UpdatePolicy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-updatepolicy.html) attribute for Auto Scaling groups. During an update, if `UpdatePolicy` is set to `AutoScalingRollingUpdate`, CloudFormation replaces `InService` instances after you perform the steps in this procedure. If `UpdatePolicy` is set to `AutoScalingReplacingUpdate`, CloudFormation replaces the Auto Scaling group and its warm pool (if one exists).

If you didn't specify an `UpdatePolicy` attribute for your Auto Scaling group, the launch template is checked for correctness, but CloudFormation does not deploy any change across the instances in the Auto Scaling group. All new instances will use your launch template, but existing instances continue to run with the launch configuration that they were originally launched with (despite the launch configuration not existing). The exception is when you change your purchase options, for example, by adding a mixed instances policy. In this case, your Auto Scaling group gradually replaces the existing instances with new instances to match the new purchase options.

If you have to roll back a change to move from launch configurations to launch templates, make sure to test the roll back operation.

## Track the migration
<a name="track-the-migration"></a>

**To track the migration**

1. In the [CloudFormation console](https://console.aws.amazon.com/cloudformation), select the stack that you updated and then choose the **Events** tab to view the stacks events.

1. To update the event list with the most recent events, choose the refresh button in the CloudFormation console.

1. While your stack is updating, you will notice multiple events for each resource update. If you see an exception in the **Status reason** column that indicates a problem when trying to create the launch template, see [Troubleshoot Amazon EC2 Auto Scaling: Launch templates](ts-as-launch-template.md) for potential causes.

1. (Optional) Depending on your use of the `UpdatePolicy` attribute, you can monitor the progress of your Auto Scaling group from the [Auto Scaling groups page](https://console.aws.amazon.com/ec2/v2/home?#AutoScalingGroups) of the Amazon EC2 console. Select the Auto Scaling group. On the **Activity** tab, under **Activity history**, the **Status** column shows whether your Auto Scaling group has successfully launched or terminated instances, or whether the scaling activity is still in progress. 

1. When the stack update is complete, CloudFormation issues an `UPDATE_COMPLETE` stack event. For more information, see [Monitoring the progress of a stack update](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-monitor-stack.html) in the *AWS CloudFormation User Guide*. 

1. After the stack update is complete, open the [Launch templates page](https://console.aws.amazon.com/ec2/v2/#LaunchTemplates) and [Launch configurations page](https://console.aws.amazon.com/ec2/v2/home?#LaunchConfigurations) of the Amazon EC2 console. You will notice a new launch template is created, and the launch configuration is deleted. 

## Launch configuration mapping reference
<a name="launch-configuration-mapping-reference"></a>

For reference purposes, the following table lists all the top-level properties in the [AWS::AutoScaling::LaunchConfiguration](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-autoscaling-launchconfiguration.html) resource with their corresponding property in the [AWS::EC2::LaunchTemplate](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-launchtemplate.html) resource.


| Launch configuration source property | Launch template target property | 
| --- | --- | 
| AssociatePublicIpAddress | NetworkInterfaces.AssociatePublicIpAddress | 
| BlockDeviceMappings | BlockDeviceMappings | 
| ClassicLinkVPCId | Not available¹ | 
| ClassicLinkVPCSecurityGroups | Not available¹ | 
| EbsOptimized | EbsOptimized | 
| IamInstanceProfile | Either IamInstanceProfile.Arn or IamInstanceProfile.Name, but not both  | 
| ImageId | ImageId | 
| InstanceId | InstanceId | 
| InstanceMonitoring | Monitoring.Enabled | 
| InstanceType | InstanceType | 
| KernelId | KernelId | 
| KeyName | KeyName | 
| LaunchConfigurationName | LaunchTemplateName | 
| MetadataOptions | MetadataOptions | 
| PlacementTenancy | Placement.Tenancy  | 
| RamDiskId | RamDiskId | 
| SecurityGroups | Either SecurityGroupIds or NetworkInterfaces.Groups, but not both | 
| SpotPrice | InstanceMarketOptions.SpotOptions.MaxPrice | 
| UserData | UserData | 

¹ The `ClassicLinkVPCId` and `ClassicLinkVPCSecurityGroups` properties are not available to use in a launch template because EC2-Classic is no longer available.

# Examples for creating and managing launch templates with the AWS CLI
<a name="examples-launch-templates-aws-cli"></a>

You can create and manage launch templates through the AWS Management Console, AWS Command Line Interface (AWS CLI), or SDKs. This section shows you examples of creating and managing launch templates for Amazon EC2 Auto Scaling from the AWS CLI.

**Topics**
+ [Example usage](#example-usage)
+ [Create a basic launch template](#example-simple-launch-template)
+ [Specify tags that tag instances at launch](#example-tag-instances)
+ [Specify an IAM role to pass to instances](#example-iam-profile)
+ [Assign public IP addresses](#example-primary-network-interface)
+ [Specify a user data script that configures instances at launch](#example-user-data)
+ [Specify a block device mapping](#example-block-device-mapping)
+ [Specify Dedicated Hosts to bring software licenses from external vendors](#example-dedicated-hosts)
+ [Specify an existing network interface](#example-existing-eni-launch-template)
+ [Create multiple network interfaces](#example-multiple-efa-enabled-network-interfaces)
+ [Manage your launch templates](#launch-templates-additional-cli-commands)
+ [Update an Auto Scaling group to use a launch template](#update-asg-launch-template-cli)

## Example usage
<a name="example-usage"></a>

```
{
    "LaunchTemplateName": "my-template-for-auto-scaling",
    "VersionDescription": "test description",
    "LaunchTemplateData": {
        "ImageId": "ami-04d5cc9b88example",
        "InstanceType": "t2.micro",
        "SecurityGroupIds": [
            "sg-903004f88example"
        ], 
        "KeyName": "MyKeyPair",
        "Monitoring": {
            "Enabled": true
        },
        "Placement": {
            "Tenancy": "dedicated"
        },
        "CreditSpecification": {
            "CpuCredits": "unlimited"
        },
        "MetadataOptions": {
            "HttpTokens": "required",
            "HttpPutResponseHopLimit": 1,
            "HttpEndpoint": "enabled"
        }
    }
}
```

## Create a basic launch template
<a name="example-simple-launch-template"></a>

To create a basic launch template, use the [create-launch-template](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template.html) command as follows, with these modifications: 
+ Replace `ami-04d5cc9b88example` with the ID of the AMI from which to launch the instances.
+ Replace `t2.micro` with an instance type that is compatible with the AMI that you specified.

This example creates a launch template with the name *my-template-for-auto-scaling*. If the instances created by this launch template are launched in a default VPC, they receive a public IP address by default. If the instances are launched in a nondefault VPC, they do not receive a public IP address by default.

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
  --launch-template-data '{"ImageId":"ami-04d5cc9b88example","InstanceType":"t2.micro"}'
```

For more information about quoting JSON-formatted parameters, see [Using quotation marks with strings in the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html) in the *AWS Command Line Interface User Guide*.

Alternatively, you can specify the JSON-formatted parameters in a configuration file.

The following example creates a basic launch template, referencing a configuration file for launch template parameter values. 

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
  --launch-template-data file://config.json
```

Contents of `config.json`:

```
{ 
    "ImageId":"ami-04d5cc9b88example",
    "InstanceType":"t2.micro"
}
```

## Specify tags that tag instances at launch
<a name="example-tag-instances"></a>

The following example adds a tag (for example, `purpose=webserver`) to instances at launch.

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
  --launch-template-data '{"TagSpecifications":[{"ResourceType":"instance","Tags":[{"Key":"purpose","Value":"webserver"}]}],"ImageId":"ami-04d5cc9b88example","InstanceType":"t2.micro"}'
```

**Note**  
If you specify instance tags in your launch template and then you choose to propagate your Auto Scaling group's tags to its instances, all the tags are merged. If the same tag key is specified for a tag in your launch template and a tag in your Auto Scaling group, then the tag value from the group takes precedence. 

## Specify an IAM role to pass to instances
<a name="example-iam-profile"></a>

The following example specifies the name of the instance profile associated with the IAM role to pass to instances at launch. For more information, see [IAM role for applications that run on Amazon EC2 instances](us-iam-role.md).

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
--launch-template-data '{"IamInstanceProfile":{"Name":"my-instance-profile"},"ImageId":"ami-04d5cc9b88example","InstanceType":"t2.micro"}'
```

## Assign public IP addresses
<a name="example-primary-network-interface"></a>

The following [create-launch-template](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template.html) example configures the launch template to assign public addresses to instances launched in a nondefault VPC. 

**Note**  
When you specify a network interface, specify a value for `Groups` that corresponds to security groups for the VPC that your Auto Scaling group will launch instances into. Specify the VPC subnets as properties of the Auto Scaling group. 



```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
  --launch-template-data '{"NetworkInterfaces":[{"DeviceIndex":0,"AssociatePublicIpAddress":true,"Groups":["sg-903004f88example"],"DeleteOnTermination":true}],"ImageId":"ami-04d5cc9b88example","InstanceType":"t2.micro"}'
```

## Specify a user data script that configures instances at launch
<a name="example-user-data"></a>

The following example specifies a user data script as a base64-encoded string that configures instances at launch. The [create-launch-template](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template.html) command requires base64-encoded user data.

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
--launch-template-data '{"UserData":"IyEvYmluL2Jhc...","ImageId":"ami-04d5cc9b88example","InstanceType":"t2.micro"}'
```

## Specify a block device mapping
<a name="example-block-device-mapping"></a>

The following [create-launch-template](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template.html) example creates a launch template with a block device mapping: a 22-gigabyte EBS volume mapped to `/dev/xvdcz`. The `/dev/xvdcz` volume uses the General Purpose SSD (gp2) volume type and is deleted when terminating the instance it is attached to. 

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
  --launch-template-data '{"BlockDeviceMappings":[{"DeviceName":"/dev/xvdcz","Ebs":{"VolumeSize":22,"VolumeType":"gp2","DeleteOnTermination":true}}],"ImageId":"ami-04d5cc9b88example","InstanceType":"t2.micro"}'
```

## Specify Dedicated Hosts to bring software licenses from external vendors
<a name="example-dedicated-hosts"></a>

If you specify *host* tenancy, you can specify a host resource group and a License Manager license configuration to bring eligible software licenses from external vendors. Then, you can use the licenses on EC2 instances by using the following [create-launch-template](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template.html) command.

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
  --launch-template-data '{"Placement":{"Tenancy":"host","HostResourceGroupArn":"arn"},"LicenseSpecifications":[{"LicenseConfigurationArn":"arn"}],"ImageId":"ami-04d5cc9b88example","InstanceType":"t2.micro"}'
```

## Specify an existing network interface
<a name="example-existing-eni-launch-template"></a>

The following [create-launch-template](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template.html) example configures the primary network interface to use an existing network interface.

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
  --launch-template-data '{"NetworkInterfaces":[{"DeviceIndex":0,"NetworkInterfaceId":"eni-b9a5ac93","DeleteOnTermination":false}],"ImageId":"ami-04d5cc9b88example","InstanceType":"t2.micro"}'
```

## Create multiple network interfaces
<a name="example-multiple-efa-enabled-network-interfaces"></a>

The following [create-launch-template](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template.html) example adds a secondary network interface. The primary network interface has a device index of 0, and the secondary network interface has a device index of 1. 

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
  --launch-template-data '{"NetworkInterfaces":[{"DeviceIndex":0,"Groups":["sg-903004f88example"],"DeleteOnTermination":true},{"DeviceIndex":1,"Groups":["sg-903004f88example"],"DeleteOnTermination":true}],"ImageId":"ami-04d5cc9b88example","InstanceType":"t2.micro"}'
```

If you use an instance type that supports multiple network cards and Elastic Fabric Adapters (EFAs), you can add a secondary interface to a secondary network card and enable EFA by using the following [create-launch-template](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template.html) command. For more information, see [Add an EFA to a launch template](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-efa.html#efa-launch-template) in the *Amazon EC2 User Guide*. 

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
  --launch-template-data '{"NetworkInterfaces":[{"NetworkCardIndex":0,"DeviceIndex":0,"Groups":["sg-7c2270198example"],"InterfaceType":"efa","DeleteOnTermination":true},{"NetworkCardIndex":1,"DeviceIndex":1,"Groups":["sg-7c2270198example"],"InterfaceType":"efa","DeleteOnTermination":true}],"ImageId":"ami-09d95fab7fexample","InstanceType":"p4d.24xlarge"}'
```

**Warning**  
The p4d.24xlarge instance type incurs higher costs than the other examples in this section. For more information about pricing for P4d instances, see [Amazon EC2 P4d Instances pricing](https://aws.amazon.com/ec2/instance-types/p4/).

**Note**  
Attaching multiple network interfaces from the same subnet to an instance can introduce asymmetric routing, especially on instances using a variant of non-Amazon Linux. If you need this type of configuration, you must configure the secondary network interface within the OS. For an example, see [How can I make my secondary network interface work in my Ubuntu EC2 instance?](https://repost.aws/knowledge-center/ec2-ubuntu-secondary-network-interface) in the AWS Knowledge Center.

## Manage your launch templates
<a name="launch-templates-additional-cli-commands"></a>

The AWS CLI includes several other commands that help you manage your launch templates. 

**Topics**
+ [List and describe your launch templates](#describe-launch-template-aws-cli)
+ [Create a launch template version](#example-create-launch-template-version)
+ [Delete a launch template version](#example-delete-launch-template-version)
+ [Delete a launch template](#example-delete-launch-template)

### List and describe your launch templates
<a name="describe-launch-template-aws-cli"></a>

You can use two AWS CLI commands to get information about your launch templates: [describe-launch-templates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-launch-templates.html) and [describe-launch-template-versions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-launch-template-versions.html). 

The [describe-launch-templates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-launch-templates.html) command enables you to get a list of any of the launch templates that you have created. You can use an option to filter results on a launch template name, create time, tag key, or tag key-value combination. This command returns summary information about any of your launch templates, including the launch template identifier, latest version, and default version. 

The following example provides a summary of the specified launch template.

```
aws ec2 describe-launch-templates --launch-template-names my-template-for-auto-scaling
```

The following is an example response.

```
{
    "LaunchTemplates": [
        {
            "LaunchTemplateId": "lt-068f72b729example",
            "LaunchTemplateName": "my-template-for-auto-scaling",
            "CreateTime": "2020-02-28T19:52:27.000Z",
            "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
            "DefaultVersionNumber": 1,
            "LatestVersionNumber": 1
        }
    ]
}
```

If you don't use the `--launch-template-names` option to limit the output to one launch template, information on all of your launch templates is returned.

The following [describe-launch-template-versions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-launch-template-versions.html) command provides information describing the versions of the specified launch template.

```
aws ec2 describe-launch-template-versions --launch-template-id lt-068f72b729example
```

The following is an example response.

```
{
    "LaunchTemplateVersions": [
        {
            "VersionDescription": "version1",
            "LaunchTemplateId": "lt-068f72b729example",
            "LaunchTemplateName": "my-template-for-auto-scaling",
            "VersionNumber": 1,
            "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
            "LaunchTemplateData": {
                "TagSpecifications": [
                    {
                        "ResourceType": "instance",
                        "Tags": [
                            {
                                "Key": "purpose",
                                "Value": "webserver"
                            }
                        ]
                    }
                ],
                "ImageId": "ami-04d5cc9b88example",
                "InstanceType": "t2.micro",
                "NetworkInterfaces": [
                    {
                        "DeviceIndex": 0,
                        "DeleteOnTermination": true,
                        "Groups": [
                            "sg-903004f88example"
                        ],
                        "AssociatePublicIpAddress": true
                    }
                ]
            },
            "DefaultVersion": true,
            "CreateTime": "2020-02-28T19:52:27.000Z"
        }
    ]
}
```

### Create a launch template version
<a name="example-create-launch-template-version"></a>

The following [create-launch-template-version](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template-version.html) command creates a new launch template version based on version 1 of the launch template and specifies a different AMI ID.

```
aws ec2 create-launch-template-version --launch-template-id lt-068f72b729example --version-description version2 \
  --source-version 1 --launch-template-data "ImageId=ami-c998b6b2example"
```

To set the default version of the launch template, use the [modify-launch-template](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-launch-template.html) command.

### Delete a launch template version
<a name="example-delete-launch-template-version"></a>

The following [delete-launch-template-versions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-launch-template-versions.html) command deletes the specified launch template version.

```
aws ec2 delete-launch-template-versions --launch-template-id lt-068f72b729example --versions 1
```

### Delete a launch template
<a name="example-delete-launch-template"></a>

If you no longer require a launch template, you can delete it using the following [delete-launch-template](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-launch-template.html) command. Deleting a launch template deletes all of its versions. 

```
aws ec2 delete-launch-template --launch-template-id lt-068f72b729example
```

## Update an Auto Scaling group to use a launch template
<a name="update-asg-launch-template-cli"></a>

You can use the [update-auto-scaling-group](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/update-auto-scaling-group.html) command to add a launch template to an existing Auto Scaling group.

### Update an Auto Scaling group to use the latest version of a launch template
<a name="example-update-asg-launch-template-latest-version"></a>

The following [update-auto-scaling-group](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/update-auto-scaling-group.html) command updates the specified Auto Scaling group to use the latest version of the specified launch template.

```
aws autoscaling update-auto-scaling-group --auto-scaling-group-name my-asg \
  --launch-template LaunchTemplateId=lt-068f72b729example,Version='$Latest'
```

### Update an Auto Scaling group to use a specific version of a launch template
<a name="example-update-asg-launch-template-specific-version"></a>

The following [update-auto-scaling-group](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/update-auto-scaling-group.html) command updates the specified Auto Scaling group to use a specific version of the specified launch template.

```
aws autoscaling update-auto-scaling-group --auto-scaling-group-name my-asg \
  --launch-template LaunchTemplateName=my-template-for-auto-scaling,Version='2'
```

# Use AWS Systems Manager parameters instead of AMI IDs in launch templates
<a name="using-systems-manager-parameters"></a>

This section shows you how to create a launch template that specifies an AWS Systems Manager parameter that references an Amazon Machine Image (AMI) ID. You can use a parameter stored in your same AWS account, a parameter shared from another AWS account, or a public parameter for a public AMI maintained by AWS.

With Systems Manager parameters, you can update your Auto Scaling groups to use new AMI IDs without needing to create new launch templates or new versions of launch templates each time an AMI ID changes. These IDs can change regularly, such as when an AMI is updated with the latest operating system or software updates.

You can create, update, or delete your own Systems Manager parameters using the [Parameter Store, a capability of AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html). You must create a Systems Manager parameter before you can use it in a launch template. To get started, create a parameter with the data type `aws:ec2:image`, and for its value, enter the ID of an AMI. The AMI ID has the form `ami-<identifier>`, for example, `ami-123example456`. The correct AMI ID depends on the instance type and AWS Region that you're launching your Auto Scaling group in. 

For more information about creating a valid parameter for an AMI ID, see [Creating Systems Manager parameters](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-su-create.html).

## Create a launch template that specifies a parameter for the AMI
<a name="using-systems-manager-parameters-create-launch-template"></a>

To create a launch template that specifies a parameter for the AMI, use one of the following methods:

------
#### [ Console ]

**To create a launch template using an AWS Systems Manager parameter**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. In the navigation pane, choose **Launch Templates**, and then choose **Create launch template**. 

1. For **Launch template name**, enter a descriptive name for the launch template.

1. Under **Application and OS Images (Amazon Machine Image)**, choose **Browse more AMIs**.

1. Choose the arrow button to the right of the search bar, and then choose **Specify custom value/Systems Manager parameter**.

1. In the **Specify custom value or Systems Manager parameter** dialog box, do the following:

   1. For **AMI ID or Systems Manager parameter string**, enter the Systems Manager parameter name using one of the following formats:

      To reference a public parameter:
      + **resolve:ssm:*public-parameter***

      To reference a parameter stored in the same account:
      + **resolve:ssm:*parameter-name***
      + **resolve:ssm:*parameter-name*:*version-number***
      + **resolve:ssm:*parameter-name*:*label***

      To reference a parameter shared from another AWS account:
      + **resolve:ssm:*parameter-ARN***
      + **resolve:ssm:*parameter-ARN*:*version-number***
      + **resolve:ssm:*parameter-ARN*:*label***

   1. Choose **Save**.

1. Configure any other launch template settings as needed, and then choose **Create launch template**. For more information, see [Create a launch template for an Auto Scaling group](create-launch-template.md). 

------
#### [ AWS CLI ]

To create a launch template that specifies a Systems Manager parameter, you can use one of the following example commands. Replace each *user input placeholder* with your own information.

**Example: Create a launch template that specifies an AWS-owned public parameter**  
Use the following syntax: `resolve:ssm:public-parameter`, where `resolve:ssm` is the standard prefix and `public-parameter` is the path and name of the public parameter.

In this example, the launch template uses an AWS-provided public parameter to launch instances using the latest Amazon Linux 2 AMI in the AWS Region that is configured for your profile. 

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
  --launch-template-data file://config.json
```

Contents of `config.json`:

```
{ 
    "ImageId":"resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
    "InstanceType":"t2.micro"
}
```

The following is an example response.

```
{
    "LaunchTemplate": {
        "LaunchTemplateId": "lt-089c023a30example",
        "LaunchTemplateName": "my-template-for-auto-scaling",
        "CreateTime": "2022-12-28T19:52:27.000Z",
        "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
        "DefaultVersionNumber": 1,
        "LatestVersionNumber": 1
    }
}
```

**Example: Create a launch template that specifies a parameter stored in the same account**  
Use the following syntax: `resolve:ssm:parameter-name`, where `resolve:ssm` is the standard prefix and `parameter-name` is the Systems Manager parameter name.

The following example creates a launch template that gets the AMI ID from an existing Systems Manager parameter named `golden-ami`. 

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling \
  --launch-template-data file://config.json
```

Contents of `config.json`:

```
{ 
    "ImageId":"resolve:ssm:golden-ami",
    "InstanceType":"t2.micro"
}
```

The default version of the parameter, if it is not specified, is the latest version. 

The following example references a specific version of the *`golden-ami`* parameter. The example uses version *`3`* of the *`golden-ami`* parameter, but you can use any valid version number. 

```
{ 
    "ImageId":"resolve:ssm:golden-ami:3",
    "InstanceType":"t2.micro"
}
```

The following similar example references the parameter label *`prod`* that maps to a specific version of the *`golden-ami`* parameter.

```
{ 
    "ImageId":"resolve:ssm:golden-ami:prod",
    "InstanceType":"t2.micro"
}
```

The following is example output. 

```
{
    "LaunchTemplate": {
        "LaunchTemplateId": "lt-068f72b724example",
        "LaunchTemplateName": "my-template-for-auto-scaling",
        "CreateTime": "2022-12-27T17:11:21.000Z",
        "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
        "DefaultVersionNumber": 1,
        "LatestVersionNumber": 1
    }
}
```

**Example: Create a launch template that specifies a parameter shared from another AWS account**  
Use the following syntax: `resolve:ssm:parameter-ARN`, where `resolve:ssm` is the standard prefix and `parameter-ARN` is the ARN of the Systems Manager parameter.

The following example creates a launch template that gets the AMI ID from an existing Systems Manager parameter with the ARN of `arn:aws:ssm:us-east-2:123456789012:parameter/MyParameter`.

```
aws ec2 create-launch-template --launch-template-name my-template-for-auto-scaling --version-description version1 \
  --launch-template-data file://config.json
```

Contents of `config.json`:

```
{ 
    "ImageId":"resolve:ssm:arn:aws:ssm:us-east-2:123456789012:parameter/MyParameter",
    "InstanceType":"t2.micro"
}
```

The default version of the parameter, if it is not specified, is the latest version. 

The following example references a specific version of the `MyParameter` parameter. The example uses version *`3`* of the `MyParameter` parameter, but you can use any valid version number. 

```
{ 
    "ImageId":"resolve:ssm:arn:aws:ssm:us-east-2:123456789012:parameter/MyParameter:3",
    "InstanceType":"t2.micro"
}
```

The following similar example references the parameter label *`prod`* that maps to a specific version of the `MyParameter` parameter.

```
{ 
    "ImageId":"resolve:ssm:arn:aws:ssm:us-east-2:123456789012:parameter/MyParameter:prod",
    "InstanceType":"t2.micro"
}
```

The following is an example response.

```
{
    "LaunchTemplate": {
        "LaunchTemplateId": "lt-00f93d4588example",
        "LaunchTemplateName": "my-template-for-auto-scaling",
        "CreateTime": "2024-01-08T12:43:21.000Z",
        "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
        "DefaultVersionNumber": 1,
        "LatestVersionNumber": 1
    }
}
```

------

To specify a parameter from the Parameter Store in a launch template, you must have the `ssm:GetParameters` permission for the specified parameter. Anyone who uses the launch template also needs the `ssm:GetParameters` permission in order for the parameter value to be validated. For more information, see [Restricting access to Systems Manager parameters using IAM policies](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-access.html) in the *AWS Systems Manager User Guide*.

## Verify a launch template gets the correct AMI ID
<a name="using-systems-manager-parameters-verify-launch-template"></a>

Use the [describe-launch-template-versions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-launch-template-versions.html) command and include the `--resolve-alias` option to resolve the parameter to the actual AMI ID.

```
aws ec2 describe-launch-template-versions --launch-template-name my-template-for-auto-scaling \
   --versions 1 --resolve-alias
```

The example returns the AMI ID for `ImageId`. When an instance is launched using this launch template, the AMI ID resolves to `ami-0ac394d6a3example`.

```
{
    "LaunchTemplateVersions": [
        {
            "LaunchTemplateId": "lt-089c023a30example",
            "LaunchTemplateName": "my-template-for-auto-scaling",
            "VersionNumber": 1,
            "CreateTime": "2022-12-28T19:52:27.000Z",
            "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
            "DefaultVersion": true,
            "LaunchTemplateData": {
                "ImageId": "ami-0ac394d6a3example",
                "InstanceType": "t2.micro",
            }
        }
    ]
}
```

## Related resources
<a name="using-systems-manager-parameters-related-resources"></a>

For more details about specifying a Systems Manager parameter in your launch template, see [Use a Systems Manager parameter instead of an AMI ID](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-launch-template.html#use-an-ssm-parameter-instead-of-an-ami-id) in the *Amazon EC2 User Guide*.

For more information about working with Systems Manager parameters, see the following reference materials in the Systems Manager documentation.
+ To create parameter versions and labels, see [Working with parameter versions](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-versions.html) and [Working with parameter labels](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html). 
+ For information about how to look up the AMI public parameters supported by Amazon EC2, see [Calling AMI public parameters](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-public-parameters-ami.html).
+ For information about sharing parameters with other AWS accounts or through AWS Organizations, see [Working with shared parameters](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-shared-parameters.html).
+ For information about monitoring whether your parameters are created successfully, see [Native parameter support for Amazon Machine Image IDs](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-ec2-aliases.html).

## Limitations
<a name="using-systems-manager-parameters-limitations"></a>

When working with Systems Manager parameters, note the following limitations:
+ Amazon EC2 Auto Scaling only supports specifying AMI IDs as parameters.
+ Creating or updating [mixed instances groups](ec2-auto-scaling-mixed-instances-groups.md) with [attribute-based instance type selection](create-mixed-instances-group-attribute-based-instance-type-selection.md) using a launch template that specifies a Systems Manager parameter is not supported.
+ If your Auto Scaling group uses a launch template that specifies a Systems Manager parameter, you will not be able to start an instance refresh with a desired configuration or using skip matching.
+ If your Auto Scaling group uses a launch template that specifies a Systems Manager parameter, warm pools are not supported.
+ On each call to create or update your Auto Scaling group, Amazon EC2 Auto Scaling will resolve the Systems Manager parameter in the launch template. If you are using advanced parameters or higher throughput limits, the frequent calls to the Parameter Store (that is, the `GetParameters` operation) can increase your costs for Systems Manager because charges are incurred per Parameter Store API interaction. For more information, see [AWS Systems Manager pricing](https://aws.amazon.com/systems-manager/pricing/). 