AMIs and launch templates

Installing software through user data on every boot is slow, and sometimes it fails. So teams bake a ready-made server into an AWS AMI (Amazon Machine Image) once and then launch identical copies from a launch template in seconds, which is how Auto Scaling (Lesson 21) adds servers when traffic spikes.

You’ll build bake01, turn it into an image called saat-web, create the launch template saat-web-lt and launch two copies from it. Along the way you’ll see why $Latest and a deregistered AMI both cause trouble at work.

TimeYou needBy the end you can
60 minutes (instances and endpoints running for under an hour)Everything from Lessons 13 and 14 (endpoints helper scripts, saat-ec2-ssm-profile, the S3 gateway endpoint), your laptop signed in with aws login --profile saat-admin. Cost: about USD 0.10 plus a few cents for the AMI snapshot until you delete it.Create a custom AMI, write a launch template with safe defaults, launch from it, manage template versions, and clean up AMIs without leaving snapshots lying around.

What it is, in one line

An AWS AMI is a saved server image, and a launch template holds everything else you need to start identical servers from it.

In Simple Words

A cake mould and a recipe card

Baking every cake from scratch takes hours, and no two come out quite the same. So a bakery makes one perfect cake, takes a mould of it and pours copies from that; the mould is your AMI. Next to the mould sits a recipe card saying which oven, what temperature and which box to pack it in, and that card is the launch template. When the recipe changes, the bakery writes a new version of the card but keeps the old one in case the new cake goes wrong. And if you throw the mould away, the clay it was made from is still sitting on a shelf until somebody clears it.

Engineer's View

What is inside an AMI and a template

An AMI is some metadata (name, architecture, boot mode) plus one EBS snapshot for each disk. create-image snapshots the instance’s volumes and, by default, reboots the instance first so the file system is consistent. AMIs are Regional, but you can copy them to other Regions and share them with other accounts. Keep an AMI for as long as anything refers to it, and remember that when you deregister one, its snapshots are not deleted for you.

A launch template holds the launch settings: AMI, instance type, security groups, instance profile, metadata options, tags, user data and so on. Each change you save becomes a new numbered version. $Default is whichever version you’ve marked as default, while $Latest is the newest one. Auto Scaling groups and EC2 Fleet launch from templates, and you can override fields like the subnet at launch time.

A good image is small and patched, and it has no secrets in it. Anything that changes per environment, such as database endpoints or passwords, gets fetched at boot from Parameter Store or Secrets Manager (Lesson 31) instead of being baked in. EC2 Image Builder can do the baking and patching for you on a schedule.

How it works, step by step

Today you’ll build this pipeline by hand.

1Build and configure one server

bake01 installs nginx and writes a page through user data. The packages come from Amazon Linux repositories hosted in S3, which it reaches through saat-s3-endpoint, so you don’t need a NAT gateway.

AWS AMI and launch template flow: builder, image, template, instances

2Bake the image

create-image reboots bake01, snapshots its root volume and registers saat-web-YYYYMMDD-HHMM. With dated names you can see at a glance which image is the newest.

3Write the launch template

The template points at the AMI and sets t3.micro, saat-app-sg, the SSM instance profile, IMDSv2 required, and the tags. You pick the subnet when you launch.

4Launch copies

Two instances from $Default, ready as soon as they boot, without any user data.

Versions are where teams usually get hurt.

AWS AMI launch template versions: $Default, $Latest and a fixed number

Production should always launch a version somebody has tested, so either $Default or a fixed number. Use $Latest only when you’re deliberately trying out a new version.

✅ Checkpoint: You can say what’s inside an AMI, why deregistering one leaves its snapshots behind, and how $Default differs from $Latest.

Hands-on lab: bake an AWS AMI and launch from a template

Before you run any command, double-check it

Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.

Start the way you usually do, with the Session Manager endpoints:

cd C:\aws-lab
aws login --profile saat-admin
$env:AWS_PROFILE = 'saat-admin'
$env:Path += ';C:\Program Files\Amazon\SessionManagerPlugin\bin'
$v = Get-Content C:\aws-lab\saat-vpc.json | ConvertFrom-Json
.\Start-SsmEndpoints.ps1

1Build bake01

Paste this whole block:

$ud = @'
#!/bin/bash
dnf install -y nginx
echo "<h1>Hello from the saat-web AMI</h1>" > /usr/share/nginx/html/index.html
systemctl enable nginx
'@
[IO.File]::WriteAllText('C:\aws-lab\bake-userdata.sh', ($ud -replace "`r`n", "`n"))
$base = aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --query Parameter.Value --output text
$bake = aws ec2 run-instances --image-id $base --instance-type t3.micro --subnet-id $v.PrivateA --security-group-ids $v.AppSg --iam-instance-profile Name=saat-ec2-ssm-profile --metadata-options HttpTokens=required --user-data file://bake-userdata.sh --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=bake01},{Key=course,Value=saatvedha-aws},{Key=lesson,Value=15}]' 'ResourceType=volume,Tags=[{Key=course,Value=saatvedha-aws},{Key=lesson,Value=15}]' --query "Instances[0].InstanceId" --output text
do { Start-Sleep 20; $ping = aws ssm describe-instance-information --filters "Key=InstanceIds,Values=$bake" --query "InstanceInformationList[0].PingStatus" --output text } until ($ping -eq 'Online')
aws ssm start-session --target $bake --document-name AWS-StartInteractiveCommand --parameters command="cloud-init status --wait"

You should see something like this (the dots appear while user data runs):

Starting session with SessionId: yourname.admin-0a1b2c3d4e5f67890
.....
status: done

Exiting session with sessionId: yourname.admin-0a1b2c3d4e5f67890.

2Create the AMI

Paste this whole block (the wait normally takes three to six minutes):

$name = "saat-web-$(Get-Date -Format yyyyMMdd-HHmm)"
$ami = aws ec2 create-image --instance-id $bake --name $name --description "AL2023 + nginx + page" --tag-specifications 'ResourceType=image,Tags=[{Key=course,Value=saatvedha-aws},{Key=lesson,Value=15}]' 'ResourceType=snapshot,Tags=[{Key=course,Value=saatvedha-aws},{Key=lesson,Value=15}]' --query ImageId --output text
aws ec2 wait image-available --image-ids $ami
$amiSnap = aws ec2 describe-images --image-ids $ami --query "Images[0].BlockDeviceMappings[0].Ebs.SnapshotId" --output text
aws ec2 describe-images --image-ids $ami --query "Images[0].[Name,State,BlockDeviceMappings[0].Ebs.SnapshotId]" --output text

You should see something like this:

saat-web-20261020-1415   available       snap-0d1e2f3a4b5c69788

bake01’s job is done, and the image doesn’t need it any more, so terminate it now:

aws ec2 terminate-instances --instance-ids $bake | Out-Null

3Create the launch template

Paste this whole block:

@'
{
  "ImageId": "AMI_ID",
  "InstanceType": "t3.micro",
  "SecurityGroupIds": ["APP_SG"],
  "IamInstanceProfile": { "Name": "saat-ec2-ssm-profile" },
  "MetadataOptions": { "HttpTokens": "required" },
  "TagSpecifications": [
    { "ResourceType": "instance", "Tags": [ { "Key": "Name", "Value": "web-lt" }, { "Key": "course", "Value": "saatvedha-aws" }, { "Key": "lesson", "Value": "15" } ] },
    { "ResourceType": "volume", "Tags": [ { "Key": "course", "Value": "saatvedha-aws" }, { "Key": "lesson", "Value": "15" } ] }
  ]
}
'@ -replace 'AMI_ID', $ami -replace 'APP_SG', $v.AppSg | Set-Content lt-v1.json
aws ec2 create-launch-template --launch-template-name saat-web-lt --version-description "v1 saat-web AMI" --launch-template-data file://lt-v1.json --query "LaunchTemplate.[LaunchTemplateName,DefaultVersionNumber]" --output text

You should see this:

saat-web-lt     1
AWS AMI lab: image available, template versions and a baked page
The image, the template versions and a baked page. Yours will look much like this.

4Launch two copies from $Default

Paste this whole block:

$ids = (aws ec2 run-instances --launch-template 'LaunchTemplateName=saat-web-lt,Version=$Default' --subnet-id $v.PrivateA --count 2 --query "Instances[].InstanceId" --output text) -split '\s+'
foreach ($i in $ids) { do { Start-Sleep 20; $p = aws ssm describe-instance-information --filters "Key=InstanceIds,Values=$i" --query "InstanceInformationList[0].PingStatus" --output text } until ($p -eq 'Online') }
aws ssm start-session --target $ids[0] --document-name AWS-StartInteractiveCommand --parameters command="curl -s localhost"

You should see something like this:

Starting session with SessionId: yourname.admin-0b1c2d3e4f5a6b7c8
<h1>Hello from the saat-web AMI</h1>

Exiting session with sessionId: yourname.admin-0b1c2d3e4f5a6b7c8.

The page is there as soon as the server boots, because nothing gets installed at launch; it was all in the image. The single quotes around '...Version=$Default' stop PowerShell from treating $Default as one of its own variables.

✅ Checkpoint: saat-web-YYYYMMDD-HHMM is available, saat-web-lt version 1 is the default, and both copies serve the baked page. Leave everything in place for the break lab.

Break It, Then Fix It

Here are two problems real teams run into: an untested template version, and an AMI that was “deleted” but is still costing money. The second one doubles as your cleanup.

1Break it: a bad new version and $Latest

Save version 2 with a one-letter typo in the instance profile name, then launch with $Latest:

'{ "IamInstanceProfile": { "Name": "saat-ec2-ssm-profil" } }' | Set-Content lt-v2.json
aws ec2 create-launch-template-version --launch-template-name saat-web-lt --source-version 1 --version-description "v2 typo" --launch-template-data file://lt-v2.json --query "LaunchTemplateVersion.VersionNumber" --output text
aws ec2 run-instances --launch-template 'LaunchTemplateName=saat-web-lt,Version=$Latest' --subnet-id $v.PrivateA

You’ll get this error (something like this):

2

An error occurred (InvalidParameterValue) when calling the RunInstances operation: Value (saat-ec2-ssm-profil) for parameter iamInstanceProfile.name is invalid. Invalid IAM Instance Profile name
AWS AMI break lab: bad $Latest version and a leftover snapshot
Both problems, a broken $Latest and a leftover snapshot. Yours will look much like this.

Anything that launches with $Latest, whether it’s a script or an Auto Scaling group, is now broken by somebody else’s untested save. Anything on $Default carries on working, because version 1 is still the default:

aws ec2 describe-launch-template-versions --launch-template-name saat-web-lt --query "LaunchTemplateVersions[].[VersionNumber,DefaultVersion,LaunchTemplateData.IamInstanceProfile.Name]" --output text
aws ec2 delete-launch-template-versions --launch-template-name saat-web-lt --versions 2 | Out-Null

The first command shows:

2       False   saat-ec2-ssm-profil
1       True    saat-ec2-ssm-profile

Fix: point production at $Default, test each new version by launching it by its number, and only then make it the default with modify-launch-template --default-version.

2Break it: deregister the AMI and stop there

Terminate the copies and deregister the AMI, then go looking for its snapshot:

aws ec2 terminate-instances --instance-ids $ids | Out-Null
aws ec2 deregister-image --image-id $ami
aws ec2 describe-snapshots --snapshot-ids $amiSnap --query "Snapshots[0].[SnapshotId,State,VolumeSize]" --output text

You should see something like this:

snap-0d1e2f3a4b5c69788   completed       8

The image has gone from the AMI list, but its 8 GiB snapshot is still stored and you’re still billed for it every month. Fix: delete the snapshot yourself after you deregister, then finish the cleanup:

aws ec2 delete-snapshot --snapshot-id $amiSnap
aws ec2 delete-launch-template --launch-template-name saat-web-lt | Out-Null
aws ec2 wait instance-terminated --instance-ids $ids $bake
.\Stop-SsmEndpoints.ps1
.\Find-LabResources.ps1

✅ Checkpoint: You watched $Latest pick up a broken version while $Default kept working, and you found and deleted the snapshot the deregistered AMI left behind. All lesson 15 resources are gone.

This happened at work

The 18-month-old image that slowed a sale

An online electronics shop ran its web tier in an Auto Scaling group from an AMI that was 18 months old. To stay patched, user data ran dnf update -y and installed the app on every new server, and each one took about 25 minutes to become healthy. Nobody worried much until the first day of a big sale, when traffic tripled in ten minutes. Auto Scaling did launch servers, but they were still busy updating packages when the existing ones ran out of capacity, and the site crawled for more than half an hour, which happened to be the most valuable half hour of the year.

The team switched to an EC2 Image Builder pipeline that bakes and tests a new AMI every month, and again after critical patches, with the app already installed. User data is now a few lines that read settings from Parameter Store, and new servers turn healthy in about two minutes. The launch template’s default version only moves once the new image has passed a test launch.

Common mistakes and troubleshooting

MistakeWhat happensWhat to do
Launching production from $LatestAn untested template change goes straight to productionUse $Default or a fixed version number
Deregistering an AMI and forgetting its snapshotsStorage keeps chargingDelete the snapshot IDs listed in the AMI’s block device mappings
Baking secrets or passwords into the imageAnyone who has the AMI has the secret tooFetch secrets at boot from Secrets Manager or Parameter Store
Images that are never rebuiltNew servers start unpatched, or spend ages patching at bootRebuild monthly, for example with EC2 Image Builder
Heavy user data instead of bakingScale-out is slow exactly when you need itBake the software in and keep user data small
Passing JSON inline in Windows PowerShell 5.1Quotes get stripped and the CLI reports invalid JSONWrite JSON to a file and use file://

Interview questions

Click a question to open it. They’re worded the way an interviewer would ask them, and under each one you’ll find why they ask it and one way to answer, which you should put in your own words.

Fresher level

1. Can you explain in simple words what an AMI really contains?

Why they ask this: They want EC2 knowledge that goes past the name. If you know it’s built from snapshots and tied to a Region, sharing and cost questions later get much easier.

How you might answer: It’s the template for an instance’s disks plus metadata like the architecture and boot mode, and behind the scenes it’s backed by EBS snapshots. It’s Regional too, so if I want it in another Region I have to copy it there.

2. How would you explain a launch template to a new team member?

Why they ask this: They’re checking you know how launch settings get saved and reused, since launch templates sit underneath Auto Scaling.

How you might answer: I’d tell them it’s a saved, versioned set of launch settings: the AMI, instance type, security groups, instance profile, metadata options, tags and user data. Auto Scaling and our scripts launch from it, so every server comes up the same way.

3. You deregistered a bunch of old AMIs to save money, but the bill didn’t change. What did you miss?

Why they ask this: It’s a common cost trap, and forgotten snapshots quietly add up over the years.

How you might answer: Deregistering an AMI leaves its snapshots alone, so they’re still there costing money, and I’d have to delete them separately.

2–5 years experience

4. Your team argues about baking software into the AMI versus installing it at boot. Where do you stand?

Why they ask this: They want to hear you weigh both sides, because the choice affects how quickly and reliably you can scale.

How you might answer: I’d bake in anything slow or stable, like OS patches, runtimes and the app version, and keep boot-time steps small and quick, like fetching config and secrets. Baking gives you faster, more reliable scale-out while boot-time setup gives you flexibility. Most teams end up doing both, but I lean strongly towards baking.

5. Someone saved a new launch template version, and production started launching broken servers. How could $Default versus $Latest explain that?

Why they ask this: They’re checking you understand template versions, because pointing production at the wrong one is a real and very common mistake.

How you might answer: $Default is whichever version you’ve explicitly marked as default, and $Latest is just the newest one saved. If production was on $Latest, the untested version went live the moment it was saved, which is why production should use $Default or a pinned version number.

6. Another team needs to use your AMI in their account. How would you share it securely?

Why they ask this: They want cross-account skills, including the encryption part, since sharing often fails because of the KMS key.

How you might answer: I’d add their account ID to the image’s launch permissions, and if the snapshot is encrypted with a customer managed KMS key, I’d let that account use the key as well. An AMI encrypted with the default aws/ebs key can’t be shared, so in that case I’d re-encrypt it with a customer managed key first.

Senior level

7. Forty teams each build their own server images in different ways. How would you design one image pipeline for all of them?

Why they ask this: It’s platform thinking. A senior engineer is expected to make the secure path the easy one for many teams at once.

How you might answer: I’d run a central EC2 Image Builder pipeline that builds a hardened base image every month, tests and scans it, and distributes it to the accounts and Regions, and teams build their app images on top of that. The image IDs get published to Parameter Store so launch templates can read them, and old images are deprecated and cleaned up with lifecycle policies.

8. Your Auto Scaling group suddenly can’t launch any instances. How do you investigate?

Why they ask this: They want to see you troubleshoot launches in order. The exact error message usually points straight at the cause.

How you might answer: I’d read the Auto Scaling activity history for the exact error and see which template version it’s using. Then I’d check the AMI still exists and is shared, and that the instance profile name, security group and subnet IDs are right. I’d also look at service quotas and capacity in the zone, and finally launch the same template version by hand to reproduce it.

Quick quiz

Q1. What is an AMI made of?

  1. Only a name
  2. Metadata plus EBS snapshots
  3. A running instance
  4. A launch template
Show answer

B: An EBS-backed AMI is metadata plus one snapshot per disk.

Q2. After deregistering an AMI, what still costs money?

  1. Nothing
  2. Its EBS snapshots
  3. The launch template
  4. The instance profile
Show answer

B: The snapshots stay until you delete them.

Q3. Which launch template version should production use?

  1. $Latest
  2. $Default or a fixed number
  3. Version 0
  4. Any
Show answer

B: $Latest can pick up untested changes, while $Default only changes when you decide.

Q4. Why do teams bake software into AMIs?

  1. AMIs cost nothing to store
  2. New servers become ready faster and more reliably
  3. User data is not allowed
  4. It avoids security groups
Show answer

B: Baked servers skip the slow installs at boot, and that matters during scale-out.

Q5. Why did the lab write launch template JSON to a file?

  1. Files are faster
  2. Windows PowerShell 5.1 strips quotes from inline JSON
  3. The CLI only reads files
  4. For encryption
Show answer

B: PowerShell 5.1 mangles quotes passed to native programs, so file:// is the safer route.

Quick recap

  • An AMI is metadata plus snapshots, and create-image reboots the source by default.
  • A launch template holds everything else, and each change becomes a new version.
  • Production launches from $Default or a fixed version, never from $Latest.
  • Deregistering an AMI leaves its snapshots behind, so delete them yourself.
  • Bake the slow steps into the image, keep user data small and rebuild your images regularly.

Next lesson

Lesson 16: Amazon S3 basics → You’ll create buckets, upload and list objects and pick storage classes, all from the CLI.

Further reading: AWS AMI

Want to go deeper into AWS AMI? Read Amazon Machine Images in Amazon EC2 and Store instance launch parameters in Amazon EC2 launch templates. You can also see the full plan for this course on the AWS Cloud Administration course page.

Scroll to Top

This website uses cookies

We use a few cookies to keep this site working. If you allow it, we also use Google Analytics to count visits so we can improve our lessons. You can accept all, deny the optional ones, or choose what to allow.