使用serverless framework建置AWS EC2
serverless framework除了可以deploy lambda, API Gateway和DynamoDB等infra之外,也可以部署EC2和設定auto scaling。寫好yaml檔之後,執行deploy就可以透過AWS CloudFormation做自動化部署,當不需要使用時,刪除CloudFormation的stack就可以簡單地刪除不要的機器。
在yaml檔撰寫Resources,並指定type為AWS::EC2::Instance和指定ImageId,設定好network的config,就可以準備開ec2。
service: gitlab-serverless-ci-cd
provider:
name: aws
stage: ${opt:stage}
region: ${opt:region}
resources:
Resources:
testBlueGreen:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-0885b1f6bd170450c
KeyName: test-blue-green
InstanceType: t2.micro
SubnetId: subnet-12345678
SecurityGroupIds:
- sg-987654321
ImageId就是ami的id,這個欄位是必填,如果自己有build好的ami,可以使用自己的,沒有的話可以從public裡面挑一個適合的。
KeyName不一定需要,但是如果想要透過ssh連線到deploy的ec2,還是建議在Key pairs準備key給ec2使用。
InstanceType也是非必填,沒有填的話,AWS會根據要deploy的region給那個region的預設值,每個region的預設值有些微差異,大部分是m1.small或t2.small。
SubnetId和SecurityGroupIds也都是非必填,但是如果該region沒有default的subnet,還是得指定一個subnet,不然會跳出No subnets found for the default VPC的錯誤訊息。
No subnets found for the default VPC ‘vpc-xxxxx’. Please specify a subnet. (Service: AmazonEC2; Status Code: 400; Error Code: MissingInput; Request ID: a6631496-afc6–4218-b409-d8bc9ddbff79; Proxy: null)
Reference:
- https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-ec2-default-instance-types.html
- https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html
- https://docs.aws.amazon.com/codedeploy/latest/userguide/instances-ec2-create-cloudformation-template.html
- https://forum.serverless.com/t/creating-ec2-instance-directly-with-serverless/14877/2
- https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-instance.html