Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

AWS CLI Auto Scaling Commands: Launch Templates and Groups

We make servers grow and shrink by themselves: a launch template, an Auto Scaling group behind a load balancer, a target tracking policy and an instance refresh.

In this chapter

  • Create a launch template and versions
  • Create an Auto Scaling group
  • Add a target tracking policy
  • Roll out a new version with instance refresh
  • Scale to zero and delete

1. The big picture: staff that matches the crowd

A restaurant calls extra waiters at lunch time and sends them home at night. A recipe card tells every new waiter the same rules.

The recipe is a launch template (aws ec2 create-launch-template). The manager is the Auto Scaling group (aws autoscaling create-auto-scaling-group).

Build ordercreate-launch-templatecreate-auto-scaling-group min/max/desiredattach to ALB target groupput-scaling-policy CPU 50%start-instance-refresh
The group always tries to keep desired capacity between min and max.

2. Create a launch template

Every new server must start with the same AMI, type, security group and startup script.

A launch template stores launch settings. It has numbered versions so you can change it safely.

  1. Create version 1.
UD=$(base64 -w0 userdata.sh)
aws ec2 create-launch-template --launch-template-name cli-web-lt --launch-template-data "{\"ImageId\":\"$AMI\",\"InstanceType\":\"t3.micro\",\"SecurityGroupIds\":[\"$WSG\"],\"UserData\":\"$UD\"}" --query "LaunchTemplate.LatestVersionNumber"

Expected output:

1
  1. Create version 2 with a bigger type.
aws ec2 create-launch-template-version --launch-template-name cli-web-lt --source-version 1 --launch-template-data "{\"InstanceType\":\"t3.small\"}" --query "LaunchTemplateVersion.VersionNumber"

Expected output:

2
  1. Verify.
aws ec2 describe-launch-template-versions --launch-template-name cli-web-lt --query "LaunchTemplateVersions[].[VersionNumber,LaunchTemplateData.InstanceType]" --output text

Expected output:

2  t3.small
1  t3.micro

3. Create the Auto Scaling group

A launch template describes how to create an instance. An Auto Scaling group decides how many instances to maintain and where it can place them. Suppose the group has a minimum of one, desired capacity two and maximum four. At first it aims for two. If one becomes unhealthy, a replacement brings the group back toward two. A scaling policy can change the desired capacity within the bounds, which is a different decision from replacing an unhealthy member.

After the create command, inspect desired capacity, each instance’s lifecycle state and the group’s activity history. An instance still starting does not yet mean the group is ready. When a load balancer is involved, also check that the target is healthy. Compare instance IDs before and after an approved instance refresh to see whether the template revision actually reached the fleet.

If a server dies at night, a new one must start without you.

The group uses the template, spreads servers across subnets, registers them in the target group and replaces unhealthy ones.

  1. Create the group.
aws autoscaling create-auto-scaling-group --auto-scaling-group-name cli-asg --launch-template LaunchTemplateName=cli-web-lt,Version='$Latest' --min-size 1 --max-size 4 --desired-capacity 2 --vpc-zone-identifier "$PRI1,$PRI2" --target-group-arns $TG --health-check-type ELB --health-check-grace-period 120

Expected output:

(no output means success)
  1. Check instances.
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names cli-asg --query "AutoScalingGroups[0].Instances[].[InstanceId,AvailabilityZone,LifecycleState,HealthStatus]" --output text

Expected output:

i-0aaa  ap-south-1a  InService  Healthy
i-0bbb  ap-south-1b  InService  Healthy
  1. Change desired capacity by hand.
aws autoscaling set-desired-capacity --auto-scaling-group-name cli-asg --desired-capacity 3

Expected output:

(no output means success)

4. Target tracking scaling policy

You do not want to watch CPU graphs all day.

Target tracking keeps a metric near a target, like average CPU 50%. AWS creates the alarms for you.

  1. Add the policy.
aws autoscaling put-scaling-policy --auto-scaling-group-name cli-asg --policy-name cpu50 --policy-type TargetTrackingScaling --target-tracking-configuration "{\"PredefinedMetricSpecification\":{\"PredefinedMetricType\":\"ASGAverageCPUUtilization\"},\"TargetValue\":50}" --query "Alarms[].AlarmName" --output text

Expected output:

TargetTracking-cli-asg-AlarmHigh-...  TargetTracking-cli-asg-AlarmLow-...
  1. See scaling history.
aws autoscaling describe-scaling-activities --auto-scaling-group-name cli-asg --max-items 3 --query "Activities[].[StatusCode,Description]" --output text

Expected output:

Successful  Launching a new EC2 instance: i-0ccc...

5. Instance refresh for a new version

In the launch template commands, the initial version specifies a type such as t3.micro and the example new version changes it to t3.small. Making a template version creates a description. Existing instances keep running as they were launched. To roll the new settings through the fleet, review which version the group should use and then start the instance refresh under approved availability settings.

Make a before-and-after record for the practice group. List two current instance IDs, their launch-template versions and health. After starting the refresh, read the refresh status and compare new members as they become healthy. When the refresh completes, verify the intended number of healthy members and the version on each replacement. A launch or health failure can stop progress. Inspect the group’s activity and state before starting another refresh.

You changed the template. Old servers still run the old version.

Instance refresh replaces instances in batches while keeping a minimum healthy percentage.

  1. Start it.
aws autoscaling start-instance-refresh --auto-scaling-group-name cli-asg --preferences MinHealthyPercentage=50,InstanceWarmup=60

Expected output:

{ "InstanceRefreshId": "08b9..." }
  1. Track progress.
aws autoscaling describe-instance-refreshes --auto-scaling-group-name cli-asg --query "InstanceRefreshes[0].[Status,PercentageComplete]" --output text

Expected output:

InProgress  50

6. Same action in Python, Node.js, Java, Go, .NET and PHP

Scripts start in the CLI. Apps call the same API through an SDK. Knowing both helps you move a tested command into real code.

Low-level CLI commands expose service operations. A high-level command or an automatically paginated list can make multiple requests. For example, aws autoscaling create-auto-scaling-group --auto-scaling-group-name web maps to the CreateAutoScalingGroup API.

Same action (CreateAutoScalingGroup) from code. Set the intended profile and Region for the SDK. Provider support and precedence can differ by SDK, and an explicit client setting can override defaults.

StackCode
Python (boto3)boto3.client("autoscaling").create_auto_scaling_group(AutoScalingGroupName="web",MinSize=1,MaxSize=4,LaunchTemplate={"LaunchTemplateName":"lt"},VPCZoneIdentifier="s1,s2")
Node.js (v3)await asg.send(new CreateAutoScalingGroupCommand({AutoScalingGroupName:"web",MinSize:1,MaxSize:4,LaunchTemplate:{LaunchTemplateName:"lt"},VPCZoneIdentifier:"s1,s2"}));
Java (v2)asg.createAutoScalingGroup(r -> r.autoScalingGroupName("web").minSize(1).maxSize(4).launchTemplate(t -> t.launchTemplateName("lt")).vpcZoneIdentifier("s1,s2"));
Go (v2)c.CreateAutoScalingGroup(ctx, &autoscaling.CreateAutoScalingGroupInput{AutoScalingGroupName: aws.String("web"), MinSize: aws.Int32(1), MaxSize: aws.Int32(4)})
.NETawait asg.CreateAutoScalingGroupAsync(new CreateAutoScalingGroupRequest{AutoScalingGroupName="web",MinSize=1,MaxSize=4});
PHP$asg->createAutoScalingGroup(["AutoScalingGroupName"=>"web","MinSize"=>1,"MaxSize"=>4]);

7. Clean up so nothing keeps costing

Lab resources left running cost money and can be a security risk.

Delete in reverse order: children first, then parents.

  1. Scale to zero.
aws autoscaling update-auto-scaling-group --auto-scaling-group-name cli-asg --min-size 0 --desired-capacity 0

Expected output:

(no output means success)
  1. Delete the group and its instances.
aws autoscaling delete-auto-scaling-group --auto-scaling-group-name cli-asg --force-delete

Expected output:

(no output means success)
  1. Delete the launch template.
aws ec2 delete-launch-template --launch-template-name cli-web-lt --query "LaunchTemplate.LaunchTemplateName" --output text

Expected output:

cli-web-lt
  1. Verify.
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names cli-asg --query "length(AutoScalingGroups)"

Expected output:

0

Ravindra Bagale's Tip

If you terminate an instance by hand, the group starts a new one. To really reduce servers, change desired capacity instead.

Common errors: cause and safe next check

Desired capacity is set above the maximum or below the minimum

Desired capacity must stay between the group minimum and maximum. Inspect those three numbers together before you update the group. Changing only desired capacity cannot exceed the maximum you already set.

A new launch template version exists, but the group still launches the old one

The group uses the launch template and version you configured on the group. Creating a new version does not switch the group by itself. Inspect the group’s launch template version before you expect new instances to pick up the change.

Instances are replaced faster than the application can become healthy

A health check can mark an instance unhealthy before the application has finished starting. Inspect the health-check type and the grace period before you shorten timers or raise desired capacity again.

Practical questions and full answers

What do minimum, maximum, and desired capacity each mean?

Minimum is the fewest instances the group should keep. Maximum is the most it may run. Desired capacity is the count the group should have now, and it stays between those limits. Inspect all three before you scale.

Why use a launch template with an Auto Scaling group?

The launch template is the recipe for each new instance, including the image and instance settings the group should use. The group then adds or removes instances from that recipe. Inspect the template version the group actually references.

Does raising desired capacity fix an unhealthy target?

Not by itself. New instances use the same recipe and health checks. If the application or health-check path is wrong, extra instances can fail the same way. Inspect a failed instance’s health reason before you add more capacity.

8. Interview questions and answers

Q. Launch template vs launch configuration?

Templates have versions and newer features. Launch configurations are legacy.

Q. What do min, max and desired mean?

Desired is the current target. It always stays between min and max.

Q. EC2 vs ELB health check type?

ELB uses the load balancer health check, so a broken app is replaced, not just a dead server.

Q. How do you deploy a new AMI to the group?

New template version, then start-instance-refresh.

Q. What is target tracking?

A policy that keeps a metric near a target value, like a thermostat.

Try at home

  1. Create the group with desired 2, terminate one instance and watch a new one start.
  2. Run stress on one server and watch the policy add a server.

In short

  1. Launch template = recipe.
  2. ASG keeps desired between min and max.
  3. ELB health check replaces broken apps.
  4. Target tracking like a thermostat.
  5. Instance refresh rolls out versions.

Follow the launch template version and current instances

Record the launch template ID/version, then inspect scaling activities after a test update. Updating the reference does not retroactively change the current instances. Use a controlled instance refresh if required, and watch the application's health.

Interview check What is the difference between desired and minimum capacity?

Desired is the number the group tries to maintain. Minimum is the lower bound. Cleanup must account for replacement launches while the group is still active.

Reference documentation

Practise this chapter

Interview questions and answers

What is the difference between scaling and replacing an unhealthy instance?

Scaling changes the group’s desired capacity in response to policy or control input. Replacement tries to reach the existing desired capacity after a member becomes unhealthy. I would inspect the group’s activities and health status to decide which event occurred.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. A group with desired=2 loses one unhealthy instance. What is the expected group goal without a scaling action?

Answer and explanation

B. Return toward two healthy instances

Replacement works toward the existing desired capacity. A scaling action changes the desired value separately.

2. Which object describes how an instance should be launched?

Answer and explanation

A. The launch template

The launch template supplies image, size and other creation settings.

3. What proves an instance refresh applied a new revision?

Answer and explanation

C. Group members show the expected new launch template revision

Check instance identities and versions. Desired capacity describes count only.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Cape Town Safaris is a tourism business in Cape Town. Thabo Nkosi looks after its IT and cloud work. They count money in ZAR and run their AWS resources in the af-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 10

Easy Describe an Auto Scaling group

See current instances and sizes of the group.

Describe the Auto Scaling group capetownsafari-asg.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Change desired capacity

Before a big sale, raise desired capacity so servers are ready in time.

Set the desired capacity of capetownsafari-asg to 4.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Change min and max size

Max protects your bill; min keeps the site up.

Update capetownsafari-asg to min 1 and max 10.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Check target health

If targets are unhealthy the site shows 502/503 errors.

Show the health of the targets in arn:aws:elasticloadbalancing:af-south-1:122836786824:targetgroup/capetownsafari-tg/6d0ecf831eec9f09.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Kubernetes LoadBalancer Service

A Service of type LoadBalancer gets an AWS load balancer.

Write a Service of type LoadBalancer selecting app: web, port 80 to targetPort 8080.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Hard Create an Auto Scaling group

Min, max and desired decide how many servers run; the group replaces unhealthy ones.

Create ASG capetownsafari-asg from launch template capetownsafari-lt with min 2, max 6, desired 2, in subnets subnet-022c3abcac24bb1,subnet-02c3abcac24bb2.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Create a launch template

The launch template is the recipe Auto Scaling uses to build each new server.

Create launch template capetownsafari-lt using the settings in lt.json.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Roll out a new AMI with instance refresh

Instance refresh replaces servers a few at a time, so the site stays up.

Start an instance refresh on capetownsafari-asg.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Create an Application Load Balancer

An ALB needs at least two subnets in different AZs for high availability.

Create an ALB named capetownsafari-alb in subnets subnet-022c3abcac24bb1 and subnet-02c3abcac24bb2 with security group sg-022b36ab6b244c3b2.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Add an HTTP listener

The listener is what accepts traffic on a port and forwards it to a target group.

On load balancer arn:aws:elasticloadbalancing:af-south-1:122836786824:loadbalancer/app/capetownsafari-alb/50dc6c495c0c9188, create an HTTP listener on port 80 that forwards to arn:aws:elasticloadbalancing:af-south-1:122836786824:targetgroup/capetownsafari-tg/6d0ecf831eec9f09.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Launch templates. Every new server must start the same way. A launch template stores AMI, type, SG and user data, with versions. Change safely with create-launch-template-version. Verify versions with describe-launch-template-versions.
Revision card: Launch templates · Download PNG · Open card page
Auto Scaling groups. If a server dies at night, a new one must start alone. The group keeps desired between min and max. Add a TargetTracking policy at CPU 50%. New version? start-instance-refresh.
Revision card: Auto Scaling groups · Download PNG · Open card page
Target tracking vs Step scaling. Keeps a metric near a target. / Adds steps per alarm range.
Comparison: Target tracking vs Step scaling · Download PNG · Open card page
EC2 vs ELB health checks?. EC2 checks only that the server is running. ELB checks the app path, so broken apps are replaced. Set a grace period so booting servers are not killed.
Interview card: EC2 vs ELB health checks? · Download PNG · Open card page

More cards: Ravi Sir's Cards.