我想要在每次 AWS CloudFormation 堆疊更新時,對我的 Amazon Elastic Compute Cloud (Amazon EC2) Auto Scaling 群組中進行滾動更新。我不想每次都修改啟動範本。
解決方法
若要啟動 Auto Scaling 群組的滾動更新,請使用 UpdatePolicy 屬性。
在 CloudFormation 範本的啟動組態中,最好的做法是參考 AWS::EC2::LaunchTemplate 資源類型的 UserData 屬性中的 Toggle 參數。當您在堆疊更新期間變更 Toggle 值 (例如從 true 改為 false) 時,您會修改 UserData 的屬性。這個動作會提示 CloudFormation 建立新的啟動範本版本。
下列解決方案假設您已為 Auto Scaling 群組設定了 AutoScalingRollingUpdate 政策,並將 Auto Scaling 群組設定為參照 AWS:: EC2:: LaunchTemplate。
重要: 當您將 Toggle 參數新增至範本時,請確定不會中斷 UserData 屬性中的其他元素。
若要設定滾動更新,請完成下列步驟:
-
在您的 CloudFormation 範本中,將 Toggle 定為參數。
對於 JSON 檔案,請輸入下列程式碼:
"Parameters": {
"Toggle": {
"Type": "String",
"AllowedValues": [
"true",
"false"
],
"Default": "true",
"Description": "Toggle parameter to force ASG update"
}
}
對於 YAML 檔案,請輸入下列程式碼:
Parameters:
Toggle:
Type: String
AllowedValues:
- 'true'
- 'false'
Default: 'true'
Description: 'Toggle parameter to force ASG update'
-
在範本的啟動組態中,請參考 UserData 屬性中的 Toggle 參數。
JSON 範例:
"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 範例:
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
-
建立您的堆疊。
-
若要啟動滾動更新,請根據目前的設定,將 Toggle 參數的值從 true 改為 false 或 false 改為 true。
注意: 您也可以在需要替換的屬性上使用上述解決方案,例如 LaunchTemplateName。