I want rolling updates in my Amazon Elastic Compute Cloud (Amazon EC2) Auto Scaling group on each AWS CloudFormation stack update. I don't want to modify the launch template each time.
Resolution
To initiate rolling updates for an Auto Scaling group, use the UpdatePolicy attribute.
In your CloudFormation template's launch configuration, it's a best practice to reference the Toggle parameter in the UserData property of your AWS::EC2::LaunchTemplate resource type. When you change the Toggle value, for example from true to false, during a stack update, you modify the UserData property. This action prompts CloudFormation to create a new launch template version.
The following resolution assumes that you configured the AutoScalingRollingUpdate policy for your Auto Scaling group, and you configured your Auto Scaling group to reference AWS::EC2::LaunchTemplate.
Important: Make sure that you don't disrupt other elements in the UserData property when you add the Toggle parameter to your template.
To set up rolling updates, complete the following steps:
-
In your CloudFormation template, define Toggle as a parameter.
For a JSON file, enter the following code:
"Parameters": {
"Toggle": {
"Type": "String",
"AllowedValues": [
"true",
"false"
],
"Default": "true",
"Description": "Toggle parameter to force ASG update"
}
}
For a YAML file, enter the following code:
Parameters:
Toggle:
Type: String
AllowedValues:
- 'true'
- 'false'
Default: 'true'
Description: 'Toggle parameter to force ASG update'
-
In your template's launch configuration, reference the Toggle parameter in the UserData property.
JSON example:
"LaunchTemplate": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateData": {
"ImageId": { "Ref": "ImageId" },
"UserData": {
"Fn::Base64": {
"Fn::Join": [
"",
[
"#!/bin/bash\n",
"echo \"Toggle parameter is set to ",
{
"Ref": "Toggle"
},
"\"\n"
...
...
]
]
}
},
"InstanceType": { "Ref": "InstanceType" }
}
}
YAML example:
LaunchTemplate:
Type: AWS::EC2::LaunchTemplate
Properties:
LaunchTemplateData:
ImageId: !Ref ImageId
UserData:
Fn::Base64:
!Sub |
#!/bin/bash
echo "Toggle parameter is set to ${Toggle}"
...
...
InstanceType: !Ref InstanceType
-
Create your stack.
-
To initiate rolling updates, change the value of the Toggle parameter from true to false or false to true, depending on its current setting.
Note: You can also use the preceding resolution on properties where an update requires a replacement, such as LaunchTemplateName.