Sub topic 11
Launch Templates as the Blueprint for Instances
A launch template is a saved set of EC2 launch parameters. An Auto Scaling group reads the template each time it needs a new instance, so every instance it creates starts from the same definition. This chapter covers what a template holds, how versions work, and the mistakes that most often cause launch failures.
This chapter assumes you know what an EC2 instance, an AMI, and a security group are. You should also be able to run AWS CLI commands and know what a subnet is.
What a launch template contains
A launch template stores the same choices you make in the "Launch instance" wizard or in run-instances. All fields are optional. A template can be a partial definition, and you can supply missing values when you launch.
| Setting | Purpose | Notes for Auto Scaling |
|---|---|---|
| AMI ID | The image the instance boots from | Needed for any group that uses the template without overrides |
| Instance type | CPU and memory size | Can be overridden by a mixed instances policy |
| Key pair | SSH key for login | Optional. Many teams use Systems Manager Session Manager instead |
| Security groups | Network rules for the instance | Use the `SecurityGroupIds` field when launching into a VPC |
| IAM instance profile | Role the instance assumes | Gives the application AWS permissions without stored keys |
| User data | Script or cloud-init config run at first boot | Limited to 16 KB before base64 encoding |
| Block device mappings | EBS volumes, sizes, encryption | Set the root volume size here |
| Metadata options | IMDSv2 requirement, hop limit | Set `HttpTokens` to `required` |
| Tags | Tags applied to instances and volumes | Use `TagSpecifications` to name each resource type |
The subnet is not part of the template for an Auto Scaling group. The group's --vpc-zone-identifier chooses subnets, which is how instances end up spread across Availability Zones. Security groups still need to belong to the same VPC as those subnets.
Versions are immutable
Each template has a numbered list of versions. Once you create a version, you cannot edit it. To change anything, you create a new version, and optionally make it the default.
Three version selectors matter:
- A specific number, such as
3, always means that exact version. $Defaultmeans whichever version is currently marked as the default.$Latestmeans the highest-numbered version.
The Auto Scaling group example in this tutorial uses Version='$Latest'. That means a new version takes effect for the next instance the group launches, with no change to the group. This is convenient, but it also means a broken version can affect scale-out immediately. For production, many teams pin an explicit version number and move the group to a new version deliberately, which gives them a controlled rollout.
Existing instances are not changed when you publish a new version. Only instances launched afterward use it. To replace running instances, you use instance refresh, covered in a later chapter.
Creating a template with the CLI
The create-launch-template command takes the template data as JSON. This example defines a web server with IMDSv2 required, an instance profile, and an encrypted root volume. Replace the AMI ID, security group ID, and profile name with your own.
cat > template-data.json <<'EOF'
{
"ImageId": "ami-0123456789abcdef0",
"InstanceType": "t3.micro",
"SecurityGroupIds": ["sg-0123456789abcdef0"],
"IamInstanceProfile": { "Name": "web-instance-profile" },
"MetadataOptions": { "HttpTokens": "required", "HttpEndpoint": "enabled" },
"BlockDeviceMappings": [
{
"DeviceName": "/dev/xvda",
"Ebs": { "VolumeSize": 20, "VolumeType": "gp3", "Encrypted": true }
}
],
"TagSpecifications": [
{
"ResourceType": "instance",
"Tags": [{ "Key": "Name", "Value": "web" }]
}
]
}
EOF
aws ec2 create-launch-template \
--launch-template-name web-lt \
--version-description "initial web server" \
--launch-template-data file://template-data.jsonThe root device name depends on the AMI. Amazon Linux uses /dev/xvda. Some other images use /dev/sda1. If the name does not match the AMI's root device, EC2 adds a second volume instead of resizing the root volume.
Adding a version
To change one setting, base the new version on an existing one. Only the fields you give are overridden.
aws ec2 create-launch-template-version \
--launch-template-name web-lt \
--source-version 1 \
--version-description "larger instance type" \
--launch-template-data '{"InstanceType":"t3.small"}'
aws ec2 modify-launch-template \
--launch-template-name web-lt \
--default-version 2The second command only moves the $Default pointer. A group that references $Latest already sees version 2. A group that references $Default sees it after the second command. A group pinned to 1 sees neither.
You can inspect what exists with a short script. This checks the default and latest version numbers, which is useful when you are unsure why a group launched an unexpected configuration.
import boto3
ec2 = boto3.client("ec2")
def show_versions(template_name):
response = ec2.describe_launch_template_versions(
LaunchTemplateName=template_name
)
for version in response["LaunchTemplateVersions"]:
data = version["LaunchTemplateData"]
print(
version["VersionNumber"],
"default" if version["DefaultVersion"] else "",
data.get("InstanceType"),
data.get("ImageId"),
)
show_versions("web-lt")User data and bootstrapping
User data runs once, at first boot, through cloud-init on most Linux AMIs. In a launch template it must be base64 encoded when you write the JSON yourself. The console and some CLI wrappers encode it for you.
Keep user data short and idempotent. A slow script delays the moment the instance can pass its health check. This is why the Auto Scaling group has a health check grace period: 300 seconds in the earlier example. If your bootstrap takes longer than the grace period plus the health check thresholds, the load balancer can report the instance unhealthy and the group may terminate it before it ever serves traffic.
Prefer baking dependencies into the AMI and using user data only for environment-specific settings. This shortens the time between launch and healthy, which also makes scale-out react faster.
Common errors
- Launch fails with an invalid AMI or a Region mismatch. AMI IDs are Region-specific. A template that works in one Region fails in another.
- Security group not found. The group exists in a different VPC than the subnets the Auto Scaling group uses.
- Instance profile permission error. The user or role that creates the Auto Scaling group needs
iam:PassRolefor the role in the profile. - Instance type unavailable in an Availability Zone. Some types are not offered in every zone. The group will try other zones but may leave capacity short. Allowing several instance types through a mixed instances policy reduces this risk.
- Group still uses old settings. The group references a pinned version or
$Default, but you only created a new version. Check which selector the group uses. - Public IP behavior surprises. Whether instances get a public IPv4 address depends on the template's network interface settings and the subnet's auto-assign setting. Instances behind an internal tier normally should not have public addresses.
Auto Scaling shows these failures in the group's scaling activity history, which is the first place to look when desired capacity is not reached.
aws autoscaling describe-scaling-activities \
--auto-scaling-group-name web-asg \
--max-items 5Launch templates versus launch configurations
Launch configurations are the older mechanism. They are immutable with no versions, and they do not support newer EC2 features. AWS recommends launch templates, and new accounts cannot create launch configurations in current Regions. Use launch templates for all new groups.
Exercise
Your Auto Scaling group uses Version='$Latest' for web-lt. You publish version 4 with a new AMI, and 10 minutes later a scale-out event occurs. Which AMI do the new instances use, what happens to the existing instances, and how would you make a future change less risky?
Show answer
The new instances use the AMI from version 4, because $Latest resolves to the highest version at launch time. The existing instances keep running their original AMI, since a new template version does not modify running instances. To make changes less risky, pin the group to an explicit version number and move it to the new version on purpose, then use instance refresh to replace the old instances in a controlled way.
Exercise
A group fails to launch instances and the scaling activity shows an error about a security group that does not exist. The security group ID in the template is correct and exists in the account. What is the most likely cause?
Show answer
The security group belongs to a different VPC than the subnets listed in the group's --vpc-zone-identifier. A security group can only be attached to instances in its own VPC. Fix it by using a security group from the same VPC as the subnets.