在AWS EC2中,可以使用云形成/启动模板来实现实例的扩缩容。以下是一个使用AWS CLI命令行工具创建云形成/启动模板的示例:
template.json
,包含实例的配置信息和启动脚本等:{
"Parameters": {
"InstanceType": {
"Type": "String",
"Default": "t2.micro",
"Description": "EC2实例类型"
},
"MinSize": {
"Type": "Number",
"Default": "1",
"Description": "最小实例数"
},
"MaxSize": {
"Type": "Number",
"Default": "3",
"Description": "最大实例数"
}
},
"Resources": {
"EC2Instance": {
"Type": "AWS::EC2::Instance",
"Properties": {
"InstanceType": { "Ref": "InstanceType" },
"ImageId": "ami-xxxxxxxx",
"UserData": { "Fn::Base64": { "Fn::Join": ["", [
"#!/bin/bash\n",
"echo 'Hello, World!' > /var/www/html/index.html\n",
"sudo service apache2 start\n"
]]}}
}
},
"AutoScalingGroup": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"LaunchTemplate": {
"LaunchTemplateId": { "Ref": "EC2LaunchTemplate" },
"Version": { "Fn::GetAtt": ["EC2LaunchTemplate", "LatestVersionNumber"] }
},
"MinSize": { "Ref": "MinSize" },
"MaxSize": { "Ref": "MaxSize" }
}
},
"EC2LaunchTemplate": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "MyLaunchTemplate",
"LaunchTemplateData": {
"InstanceType": { "Ref": "InstanceType" },
"ImageId": "ami-xxxxxxxx",
"UserData": { "Fn::Base64": { "Fn::Join": ["", [
"#!/bin/bash\n",
"echo 'Hello, World!' > /var/www/html/index.html\n",
"sudo service apache2 start\n"
]]}}
}
}
}
},
"Outputs": {
"LaunchTemplateId": {
"Value": { "Ref": "EC2LaunchTemplate" },
"Description": "云形成/启动模板ID"
}
}
}
aws cloudformation create-stack --stack-name my-template --template-body file://template.json --capabilities CAPABILITY_IAM
这将创建一个名为my-template
的云形成堆栈,并使用template.json
文件中定义的配置信息创建云形成/启动模板。
aws cloudformation describe-stacks --stack-name my-template
这样,你就成功地创建了一个云形成/启动模板,并可以将其用于实例的扩缩容。
下一篇:AWS EC2实例连接超时问题