Skip to main content

Cloud and deployment · Intermediate · 24 min

Scale EC2 instances automatically with a launch template and an Auto Scaling group

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4

You will run a small Nginx web tier as an Auto Scaling group of disposable Ubuntu 26.04 instances that keeps between one and four servers running, follows average CPU, rolls out a new launch template version with an instance refresh, and is scaled to zero and deleted at the end.

On this page

One server is easy to understand and easy to lose. An Auto Scaling group replaces that single server with a rule: "keep this many copies of this machine running". You describe the machine once in a launch template (image, size, network rule, first-boot script), tell the group how many copies you want and where, and AWS launches, health-checks and replaces instances to match.

In this tutorial you build a small web tier called scale-demo. Each instance boots Ubuntu 26.04, installs Nginx with cloud-init and serves a page naming the instance that served it. The group keeps at least one instance, normally two, and never more than four, spread over two Availability Zones. You add a policy that follows average CPU, ship a change by publishing a new template version and refreshing the instances, and finish by scaling to zero and deleting everything.

The idea that makes all of this work is that instances are disposable. The group terminates instances when it scales in, when a health check fails, and during every refresh. Nothing you care about may live only on one instance: no hand edits, no uploaded files, no logs you have not shipped elsewhere. Everything an instance needs comes from the template and its user data, so a new one is identical to the one it replaces.

This costs money. Auto Scaling itself has no extra fee, but the instances it launches, their disks and their public IPv4 addresses bill for as long as they exist, and the policy uses CloudWatch alarms (AWS's Auto Scaling pricing page, checked 26 November 2026). You run two to four t3.micro instances for the length of the tutorial, which is a small amount, but a forgotten group keeps replacing whatever you terminate by hand. Check current prices on the EC2 and VPC pricing pages for your Region, and do not skip the last step.

Step 1 · Point the CLI at a Region and find two subnets

Use a sandbox account. If you use a named profile, run export AWS_PROFILE=<your-sandbox-profile> first (replace the placeholder), and make sure a Region is set in the profile or with AWS_REGION. If your users are in southern Africa, Cape Town (af-south-1) is an opt-in Region: enable it for the account first, and check that t3.micro is offered there with aws ec2 describe-instance-type-offerings --region af-south-1 --filters Name=instance-type,Values=t3.micro.

Bash
aws --version
aws sts get-caller-identity --query Arn --output text
echo "region=${AWS_REGION:-${AWS_DEFAULT_REGION:-$(aws configure get region)}}"
mkdir -p ~/scale-demo
cd ~/scale-demo

The group needs subnets to launch into. The default VPC has one public subnet per Availability Zone, and instances launched there get a public address, which is enough to reach Nginx directly. Take the first two default subnets; they are always in different zones:

Bash
VPC_ID=$(aws ec2 describe-vpcs --filters Name=is-default,Values=true \
  --query 'Vpcs[0].VpcId' --output text)
SUBNETS=$(aws ec2 describe-subnets \
  --filters Name=vpc-id,Values="$VPC_ID" Name=default-for-az,Values=true \
  --query 'Subnets[0:2].SubnetId' --output text | tr '\t' ',')
echo "vpc=$VPC_ID subnets=$SUBNETS"
aws ec2 describe-subnets --subnet-ids $(echo "$SUBNETS" | tr ',' ' ') \
  --query 'Subnets[].[SubnetId,AvailabilityZone]' --output text

Two zones matter because a zone can fail as a whole. With subnets in both, the group spreads instances across them and launches replacements in the healthy zone if one goes down. A production web tier usually puts instances in private subnets behind a load balancer instead; this tutorial keeps them public so you can see each instance's page, and the blue-green tutorial adds the load balancer.

Check it worked

aws --version starts with aws-cli/2.42, and region= is followed by a Region code such as eu-west-2; the CLI checks AWS_REGION, then AWS_DEFAULT_REGION, then the profile, and the line does the same. If it prints region= with nothing after it, run export AWS_REGION=<your-region> and repeat it. The second echo shows a vpc- ID and two subnet- IDs joined by a comma, and the last command lists those two subnets with two different zone names, such as eu-west-2a and eu-west-2b. If vpc=None, the account has no default VPC; create one with aws ec2 create-default-vpc or use two public subnets of your own.

Step 2 · Write user data that makes every instance the same

The instance's whole setup goes in one cloud-init file. It installs Nginx, writes the page, and fills in the instance ID by asking the instance metadata service. The launch template in the next step requires IMDSv2, which means every metadata request needs a short-lived session token first; that is why the script makes a PUT for a token before it reads instance-id. IMDSv1-style requests without a token get refused, which closes off a class of attacks where a tricked web app fetches metadata for an attacker.

Bash
cat > user-data.yaml <<'EOF'
#cloud-config
package_update: true
packages:
  - nginx
write_files:
  - path: /var/www/html/index.html
    permissions: "0644"
    content: |
      <!doctype html>
      <meta charset="utf-8">
      <title>scale-demo</title>
      <h1>scale-demo v1</h1>
      <p>Served by INSTANCE_ID</p>
runcmd:
  - |
    TOKEN=$(curl -sS -X PUT http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds: 300")
    ID=$(curl -sS -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id)
    sed -i "s/INSTANCE_ID/$ID/" /var/www/html/index.html
EOF

Notice what the file does not contain: no SSH key, no user account, no copy of a database. You never log in to these instances to fix them. If one misbehaves, you terminate it and the group starts a fresh one from the same file. If you need something different on every instance, change the file and roll it out, as you will in a later step. For a longer tour of what cloud-init can do, see the cloud-init user data tutorial.

The page itself is about 150 bytes, so checking it from a phone on prepaid data costs nothing worth counting.

Check it worked

head -n 1 user-data.yaml prints #cloud-config, and grep -c 'metadata-token' user-data.yaml prints 2: one header for the token request, one for the metadata read. If you have cloud-init installed locally, cloud-init schema --config-file user-data.yaml prints Valid schema user-data.yaml.

Step 3 · Create a security group and the launch template

The instances need one inbound rule: HTTP on port 80. There is no SSH rule, because nobody logs in.

Bash
SG_ID=$(aws ec2 create-security-group --vpc-id "$VPC_ID" \
  --group-name scale-demo-web --description "scale-demo: HTTP to Nginx" \
  --query GroupId --output text)
aws ec2 authorize-security-group-ingress --group-id "$SG_ID" \
  --protocol tcp --port 80 --cidr 0.0.0.0/0
echo "$SG_ID"

Next, find the current Ubuntu 26.04 image. Canonical publishes the latest AMI ID for each Region as a public SSM parameter, so you never copy an ID from a web page:

Bash
AMI_ID=$(aws ssm get-parameter \
  --name /aws/service/canonical/ubuntu/server/26.04/stable/current/amd64/hvm/ebs-gp3/ami-id \
  --query Parameter.Value --output text)
echo "$AMI_ID"

A launch template could also name the parameter itself (resolve:ssm:...) and look the image up at every launch. That sounds convenient, but it means a group can end up running two different images without anyone deciding so, the day Canonical publishes an update. Pinning the ID you just looked up keeps every instance identical, and moving to a new image becomes a deliberate change.

Launch template user data must be base64 text. base64 | tr -d '\n' gives one unwrapped line on both Linux and macOS:

Bash
USER_DATA=$(base64 < user-data.yaml | tr -d '\n')
cat > template-v1.json <<EOF
{
  "ImageId": "${AMI_ID}",
  "InstanceType": "t3.micro",
  "SecurityGroupIds": ["${SG_ID}"],
  "UserData": "${USER_DATA}",
  "MetadataOptions": {
    "HttpTokens": "required",
    "HttpPutResponseHopLimit": 1,
    "HttpEndpoint": "enabled"
  },
  "TagSpecifications": [
    {
      "ResourceType": "instance",
      "Tags": [{ "Key": "Name", "Value": "scale-demo-web" }]
    }
  ]
}
EOF
aws ec2 create-launch-template --launch-template-name scale-demo-web \
  --version-description "page v1" \
  --launch-template-data file://template-v1.json \
  --query 'LaunchTemplate.[LaunchTemplateId,LatestVersionNumber]' --output text

HttpTokens: required is the IMDSv2 switch. A hop limit of 1 keeps the token from travelling beyond the instance itself, for example into a Docker bridge network running on it. A template is versioned: you never edit version 1, you add version 2, so you always know exactly what a given instance was launched from.

Check it worked

create-launch-template prints an ID starting lt- and the number 1. Read the metadata setting back from the stored version:

Bash
aws ec2 describe-launch-template-versions --launch-template-name scale-demo-web --versions 1 \
  --query 'LaunchTemplateVersions[0].LaunchTemplateData.[InstanceType, MetadataOptions.HttpTokens]' \
  --output text

It prints t3.micro and required.

Step 4 · Create the Auto Scaling group

Now the rule itself. The group launches from the latest template version into both subnets, and keeps between one and four instances with two as the normal number:

Bash
aws autoscaling create-auto-scaling-group \
  --auto-scaling-group-name scale-demo-web \
  --launch-template 'LaunchTemplateName=scale-demo-web,Version=$Latest' \
  --min-size 1 --desired-capacity 2 --max-size 4 \
  --vpc-zone-identifier "$SUBNETS" \
  --health-check-type EC2 \
  --health-check-grace-period 120 \
  --default-instance-warmup 120

The $Latest is in single quotes so your shell does not treat it as a variable. What the settings mean:

  • Min, desired, max. Desired is how many instances the group runs right now. Scaling policies and you can move it, but never below min or above max. Max is your cost ceiling: whatever happens, there will be no fifth instance.
  • $Latest. New launches use the newest template version. The alternative, $Default (what you get if you leave Version out), uses whichever version you have marked as default, which lets you publish a version before it goes live. Either way, running instances are not touched when the template changes.
  • Health checks. With type EC2, an instance is replaced when EC2 reports it as impaired or it stops running. With a load balancer you would add ELB, so an instance whose web server has crashed is also replaced. The grace period gives a new instance 120 seconds to boot before health checks can count against it. From the CLI the grace period defaults to 0, so set it.
  • Default instance warmup. For 120 seconds after a launch, an instance's CPU is left out of the group's average, so a busy first boot (installing Nginx) does not look like load and trigger more scaling.

Check it worked

Wait until the instances are running, then list the group's sizes and its instances:

Bash
aws ec2 wait instance-running --filters Name=tag:aws:autoscaling:groupName,Values=scale-demo-web
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names scale-demo-web \
  --query 'AutoScalingGroups[0].[MinSize,DesiredCapacity,MaxSize]' --output text
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names scale-demo-web \
  --query 'AutoScalingGroups[0].Instances[].[InstanceId,AvailabilityZone,LifecycleState,HealthStatus]' \
  --output text

The first line is 1 2 4. Below it, two instances, one per zone, each InService and Healthy (an instance shows Pending for its first minute or so). Give cloud-init another minute to install Nginx, then fetch each instance's page:

Bash
IPS=$(aws ec2 describe-instances \
  --filters Name=tag:aws:autoscaling:groupName,Values=scale-demo-web Name=instance-state-name,Values=running \
  --query 'Reservations[].Instances[].PublicIpAddress' --output text)
for ip in $IPS; do curl -s "http://$ip/" | grep -E 'v1|Served'; done

Each address answers scale-demo v1 and Served by a different i- ID.

Step 5 · Terminate an instance and watch it come back

This is how you prove the instances really are disposable. Pick one of the group's instances and terminate it, as if its hardware had failed:

Bash
VICTIM=$(aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names scale-demo-web \
  --query 'AutoScalingGroups[0].Instances[0].InstanceId' --output text)
echo "terminating $VICTIM"
aws ec2 terminate-instances --instance-ids "$VICTIM" --query 'TerminatingInstances[0].CurrentState.Name' --output text

The group's desired capacity is still 2, so within a minute or two it notices that only one instance is running and launches a replacement from the template. The scaling activity log tells the story:

Bash
aws autoscaling describe-scaling-activities --auto-scaling-group-name scale-demo-web \
  --max-items 3 --query 'Activities[].[StatusCode,Description]' --output text

Nothing was lost, because nothing lived on the old instance. This is also why Auto Scaling may pick any instance when it scales in. By default it balances the zones first, so the instance it removes comes from whichever zone has the most. If your app kept session data in memory or wrote uploads to the local disk, those users would lose them here. The fix is to keep state elsewhere: sessions in a cache or database, files in S3, logs shipped off the box.

Check it worked

terminate-instances prints shutting-down. The activity log shows something like a Successful line for terminating the instance and another for launching a new one. describe-auto-scaling-groups lists two instances again, one with an ID you have not seen before, and its page shows its own ID.

Step 6 · Scale out by hand, then let CPU decide

Changing desired capacity is the simplest way to scale. Ask for three:

Bash
aws autoscaling set-desired-capacity --auto-scaling-group-name scale-demo-web --desired-capacity 3
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names scale-demo-web \
  --query 'length(AutoScalingGroups[0].Instances)'

Doing that by hand every evening does not scale, so add a target tracking policy. You give it a metric and a target, and Auto Scaling adds instances when the group's average CPU stays above 50% and removes them when it stays well below, like a thermostat:

Bash
cat > cpu50.json <<'EOF'
{
  "PredefinedMetricSpecification": { "PredefinedMetricType": "ASGAverageCPUUtilization" },
  "TargetValue": 50.0
}
EOF
aws autoscaling put-scaling-policy --auto-scaling-group-name scale-demo-web \
  --policy-name cpu-50 --policy-type TargetTrackingScaling \
  --target-tracking-configuration file://cpu50.json \
  --query PolicyARN --output text

Things to know about this policy:

  • It creates its own CloudWatch alarms, one for scaling out and one for scaling in. Do not edit or delete them; Auto Scaling manages them and may replace them.
  • Scale-in is deliberately slow. After a quiet period it removes instances gradually, never going below min. Your three idle instances will drift back down, which is the policy working, not a fault.
  • 50% leaves headroom. A higher target uses instances more fully but leaves less room for a sudden spike while new instances boot. Pick the target from what your app does under load, not from this tutorial.
  • CPU must reflect load. It works for this kind of stateless web tier where every instance gets a similar share of requests. For queue workers, scale on messages per instance instead.
  • Metrics arrive every five minutes by default. For faster reactions, turn on detailed monitoring in the template ("Monitoring": {"Enabled": true}), which is billed by CloudWatch.

Check it worked

set-desired-capacity prints nothing and the count that follows is 3 (on AWS, give the new instance a minute to appear). put-scaling-policy prints an ARN containing policyName/cpu-50. Then read the policy back:

Bash
aws autoscaling describe-policies --auto-scaling-group-name scale-demo-web \
  --query 'ScalingPolicies[].[PolicyName, PolicyType, TargetTrackingConfiguration.PredefinedMetricSpecification.PredefinedMetricType, TargetTrackingConfiguration.TargetValue]' \
  --output text

You see cpu-50 TargetTrackingScaling ASGAverageCPUUtilization 50.0. In your account, the two alarms it created are listed by:

Bash
aws cloudwatch describe-alarms --alarm-name-prefix TargetTracking-scale-demo-web \
  --query 'MetricAlarms[].[AlarmName,StateValue]' --output text

Step 7 · Ship a change with a new template version and an instance refresh

You never change a running instance. To ship a new page, or a patched image, you publish a new template version and replace the instances. Make version 2 of the user data with a changed heading, and look up the image again in case Canonical has published a newer one:

Bash
sed 's/scale-demo v1/scale-demo v2/' user-data.yaml > user-data-v2.yaml
grep -F 'scale-demo v2' user-data-v2.yaml
Bash
AMI_ID=$(aws ssm get-parameter \
  --name /aws/service/canonical/ubuntu/server/26.04/stable/current/amd64/hvm/ebs-gp3/ami-id \
  --query Parameter.Value --output text)
echo "$AMI_ID"

Create version 2 from version 1. --source-version 1 copies everything from version 1, and the data you pass replaces only the fields it names, here the image and the user data:

Bash
USER_DATA=$(base64 < user-data-v2.yaml | tr -d '\n')
cat > template-v2.json <<EOF
{
  "ImageId": "${AMI_ID}",
  "UserData": "${USER_DATA}"
}
EOF
aws ec2 create-launch-template-version --launch-template-name scale-demo-web \
  --source-version 1 --version-description "page v2" \
  --launch-template-data file://template-v2.json \
  --query 'LaunchTemplateVersion.VersionNumber' --output text

Because the group uses $Latest, any instance launched from now on gets version 2, but the running ones are still on version 1. An instance refresh replaces them in a controlled way. With MinHealthyPercentage at 50, at least half the group must stay in service, so with two instances it replaces one at a time and waits for the 120-second warmup between them. Left unset, the minimum is 90%. If the CPU policy has scaled the idle group down to one instance, the refresh replaces that only instance and the page is gone for a minute or two, so set the group back to two first:

Bash
aws autoscaling set-desired-capacity --auto-scaling-group-name scale-demo-web --desired-capacity 2
Bash
aws autoscaling start-instance-refresh --auto-scaling-group-name scale-demo-web \
  --preferences '{"MinHealthyPercentage": 50, "InstanceWarmup": 120}'

Follow its progress until the status is Successful:

Bash
aws autoscaling describe-instance-refreshes --auto-scaling-group-name scale-demo-web \
  --query 'InstanceRefreshes[0].[Status,PercentageComplete,StatusReason]' --output text

If the new version is broken (say, a typo in the user data stops Nginx from installing), EC2 health checks will not catch it, because the instance itself is running fine. That is the gap a load balancer health check closes, and it is why production web tiers put one in front of the group before using refreshes to deploy.

Check it worked

create-launch-template-version prints 2, and decoding the stored user data shows the new heading:

Bash
aws ec2 describe-launch-template-versions --launch-template-name scale-demo-web --versions 2 \
  --query 'LaunchTemplateVersions[0].LaunchTemplateData.UserData' --output text | base64 -d | grep -F 'scale-demo v2'

In your account, describe-instance-refreshes moves from Pending to InProgress to Successful over a few minutes, the group lists instance IDs you have not seen before, and fetching their pages (the loop from the group step) prints scale-demo v2.

Step 8 · Scale to zero and delete everything

If an instance refresh is still running, wait for it to finish (or cancel it with aws autoscaling cancel-instance-refresh --auto-scaling-group-name scale-demo-web) before you continue. Then remove the policy, so it cannot scale the group back out while you shrink it:

Bash
aws autoscaling delete-policy --auto-scaling-group-name scale-demo-web --policy-name cpu-50

Do not terminate the instances yourself; the group would replace them. Set min and desired to zero, so the group terminates them and launches nothing new, and wait until they are gone:

Bash
IDS=$(aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names scale-demo-web \
  --query 'AutoScalingGroups[0].Instances[].InstanceId' --output text)
echo "terminating: $IDS"
aws autoscaling update-auto-scaling-group --auto-scaling-group-name scale-demo-web \
  --min-size 0 --desired-capacity 0
aws ec2 wait instance-terminated --instance-ids $IDS

Now the group is empty and can be deleted, followed by the template and the security group. The security group can only go once no instance uses it, which the wait above made sure of. Check that $SG_ID is the group this tutorial created (echo "$SG_ID") before you run this:

Bash
aws autoscaling delete-auto-scaling-group --auto-scaling-group-name scale-demo-web
aws ec2 delete-launch-template --launch-template-name scale-demo-web --query 'LaunchTemplate.LaunchTemplateName' --output text
aws ec2 delete-security-group --group-id "$SG_ID"
cd ~
rm -rf ~/scale-demo
unset VPC_ID SUBNETS SG_ID AMI_ID USER_DATA IDS

The default VPC and its subnets were there before you started, so they stay.

Check it worked

All three lines print 0: no group, no template and no instance left with the group's tag in a running or pending state. ls ~/scale-demo reports that the folder does not exist.

Bash
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names scale-demo-web \
  --query 'length(AutoScalingGroups)'
aws ec2 describe-launch-templates --query "length(LaunchTemplates[?LaunchTemplateName=='scale-demo-web'])"
aws ec2 describe-instances \
  --filters Name=tag:aws:autoscaling:groupName,Values=scale-demo-web Name=instance-state-name,Values=pending,running \
  --query 'length(Reservations[].Instances[])'

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.