A launch template is a blueprint for starting EC2 virtual machines. It defines the image, size, and configuration each new instance should receive. An Auto Scaling group uses the template to launch uniform instances; the group decides how many to run, checks their health, and replaces failed instances. section 13.2.2 section 17.1
In a CloudFormation resource of type `AWS::EC2::LaunchTemplate`, put the instance settings under `LaunchTemplateData`:
- `ImageId` selects an Amazon Machine Image (AMI), and `InstanceType` sets the machine size. section 17.1
- `UserData` supplies a bootstrap script. `NetworkInterfaces` can configure a public IP address and security groups; `IamInstanceProfile` attaches an IAM instance profile. section 17.1
Keep placement and capacity in the Auto Scaling group, not the launch template. Reference the template by ID and version, choose the subnets, and set minimum and maximum instance counts. A minimum can preserve capacity across availability zones; a maximum limits how many machines may run and therefore helps bound spending. section 13.2.2 section 17.1
Listing 17.1 Auto Scaling group and launch template for a web app
# [...]
LaunchTemplate:
Type: 'AWS::EC2::LaunchTemplate'
Properties:
LaunchTemplateData:
IamInstanceProfile:
Name: !Ref InstanceProfile
ImageId: 'ami-028f2b5ee08012131' #1
InstanceType: 't2.micro' #2
NetworkInterfaces:
- AssociatePublicIpAddress: true #3
DeviceIndex: 0
Groups: #4
- !Ref WebServerSecurityGroup
UserData: #5
'Fn::Base64': !Sub |
#!/bin/bash -x
yum -y install httpd
AutoScalingGroup:
Type: 'AWS::AutoScaling::AutoScalingGroup'
Properties:
TargetGroupARNs: #6
- !Ref LoadBalancerTargetGroup
LaunchTemplate: #7
LaunchTemplateId: !Ref LaunchTemplate
Version: !GetAtt 'LaunchTemplate.LatestVersionNumber'
MinSize: 2 #8
MaxSize: 4 #9
HealthCheckGracePeriod: 300 #10
HealthCheckType: ELB #11
VPCZoneIdentifier: #12
- !Ref SubnetA
- !Ref SubnetB
# [...]
A compact CloudFormation example pairs a web server launch template with the Auto Scaling group that uses it. section 17.1
Replace a failed Jenkins instance
A Jenkins launch template specifies the AMI, `t2.micro` size, security group, and bootstrap script. Its Auto Scaling group keeps one instance running and can start a replacement in a subnet in another availability zone after a failure. The replacement follows the template; the group chooses its placement. section 13.2.2
The same pairing supports deployments and scaling. For a rolling Etherpad update, CloudFormation updates the launch template, the group starts an instance that runs the new user data script, then terminates the old instance. For a WordPress pool, a target-tracking policy adjusts group capacity with load while each new server follows the template. Disposable instances suit rolling updates; applications that retain data only on an instance’s local disk or in memory do not meet that condition. section 15.2 section 17.3.1
