-
Notifications
You must be signed in to change notification settings - Fork 52
/
cf-ec2.yaml
349 lines (326 loc) · 9.71 KB
/
cf-ec2.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
AWSTemplateFormatVersion: '2010-09-09'
Description: A very simple RESTful API service based on ALB with EC2 service and CloudWatch monitorings
Parameters:
InfraStackName:
Description: CF Infra. stack name
Type: String
KeyName:
Description: SSH key for EC2
Type: String
Default: cicd
ArtifactsBucketName:
Description: S3 bucket name for artifacts
Type: String
Default: codepipeline-us-east-1-876496930831
ArtifactObjectKey:
Description: Object key for artifact
Type: String
ASGInfo:
Default: 't2.micro,2'
Description: |
ASGInfo[0] => EC2 type,
ASGInfo[1] => Desire capacity in ASG,
Type: CommaDelimitedList
ALBP95LatencyAlarmThreshold:
Description: p95 Latency alarm threshold (sec)
Type: Number
Default: 10
AlarmEmail:
Description: Alarm email
Type: String
SecretName:
Description: Secret name stored in SSM parameter store
Type: String
Mappings:
EcsAmi:
us-east-1:
AMI: ami-8c1be5f6
us-west-2:
AMI: ami-e689729e
Resources:
ALBSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
VpcId:
Fn::ImportValue: !Sub "${InfraStackName}-VPC1"
GroupDescription: Rules for making connection with ALB
SecurityGroupIngress:
- IpProtocol: "tcp"
FromPort: "80"
ToPort: "80"
CidrIp: "0.0.0.0/0"
- IpProtocol: "tcp"
FromPort: "80"
ToPort: "80"
CidrIpv6: "::/0"
Tags:
- Key: Name
Value: !Sub 'alb-securitygroup'
EC2SecurityGroup:
Type: AWS::EC2::SecurityGroup
DependsOn: ALBSecurityGroup
Properties:
VpcId:
Fn::ImportValue: !Sub "${InfraStackName}-VPC1"
GroupDescription: Rules for making connection with EC2
SecurityGroupIngress:
- IpProtocol: "tcp"
FromPort: "8080"
ToPort: "8080"
SourceSecurityGroupId: !Ref ALBSecurityGroup
Tags:
- Key: Name
Value: !Sub 'ec2-securitygroup'
EC2Role:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- sts:AssumeRole
Path: /
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
Policies:
- PolicyName: KMSKeyDecryption
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action: kms:Decrypt
Resource: '*'
- PolicyName: SSMGetParameters
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- ssm:GetParameter
- ssm:GetParameters
Resource: '*'
EC2RoleProfile:
Type: AWS::IAM::InstanceProfile
DependsOn: EC2Role
Properties:
Path: /
Roles:
- !Ref EC2Role
ALB:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
DependsOn: ALBSecurityGroup
Properties:
Name: !Sub 'ec2-alb' # cannot > 32 char
Type: application
Scheme: internet-facing
Subnets:
- Fn::ImportValue: !Sub "${InfraStackName}-VPC1PublicSubnet1"
- Fn::ImportValue: !Sub "${InfraStackName}-VPC1PublicSubnet2"
SecurityGroups:
- !Ref ALBSecurityGroup
Tags:
- { Key: Name, Value: !Sub 'ec2-alb' }
ALBTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
HealthCheckIntervalSeconds: 30
HealthCheckPath: /healthcheck
HealthCheckPort: traffic-port
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 5
HealthyThresholdCount: 5
UnhealthyThresholdCount: 2
Port: 8080
Protocol: HTTP
VpcId:
Fn::ImportValue: !Sub "${InfraStackName}-VPC1"
Tags:
- { Key: Name, Value: !Sub 'ec2-targetgroup' }
ALBListener:
Type: AWS::ElasticLoadBalancingV2::Listener
DependsOn:
- ALB
- ALBTargetGroup
Properties:
DefaultActions:
- Type: forward
TargetGroupArn: !Ref ALBTargetGroup
LoadBalancerArn: !Ref ALB
Port: 80
Protocol: HTTP
EC2AutoScalingGroup:
Type: AWS::AutoScaling::AutoScalingGroup
DependsOn: ALBTargetGroup
Properties:
LaunchConfigurationName: !Ref EC2LaunchConfiguration
VPCZoneIdentifier:
- Fn::ImportValue: !Sub "${InfraStackName}-VPC1PrivateSubnet1"
- Fn::ImportValue: !Sub "${InfraStackName}-VPC1PrivateSubnet2"
DesiredCapacity: !Select [1, !Ref ASGInfo]
MinSize: !Select [1, !Ref ASGInfo]
MaxSize: 8
HealthCheckType: ELB
HealthCheckGracePeriod: 60
TargetGroupARNs:
- !Ref ALBTargetGroup
MetricsCollection:
- Granularity: 1Minute # default all metrics
Tags:
- Key: Name
Value: !Sub 'ec2-auto-scaling-group'
PropagateAtLaunch: True
CreationPolicy:
ResourceSignal:
Count: !Select [1, !Ref ASGInfo]
Timeout: PT5M
UpdatePolicy:
AutoScalingReplacingUpdate:
WillReplace: true
EC2LaunchConfiguration:
Type: AWS::AutoScaling::LaunchConfiguration
DependsOn:
- EC2RoleProfile
Properties:
IamInstanceProfile: !Ref EC2RoleProfile
ImageId: !FindInMap [EcsAmi, !Ref "AWS::Region", AMI]
InstanceType: !Select [0, !Ref ASGInfo]
KeyName: !Ref KeyName
SecurityGroups:
- Fn::ImportValue: !Sub "${InfraStackName}-CommonSecurityGroup"
- !Ref EC2SecurityGroup
AssociatePublicIpAddress: False
BlockDeviceMappings:
- DeviceName: /dev/xvda
Ebs:
VolumeSize: 8
VolumeType: gp2
DeleteOnTermination: True
UserData:
"Fn::Base64": !Sub |
#!/bin/bash
pip install bottle
pip install boto3
cd ~ec2-user/
aws s3 cp s3://${ArtifactsBucketName}/${ArtifactObjectKey} ./artifacts.zip
unzip ./artifacts.zip
mv dist/aws-cicd-*.tar.gz ./
tar -zxvf aws-cicd-*.tar.gz
ln -f -s aws-cicd-*/ aws-cicd
yum install -y aws-cfn-bootstrap
# create conf file
/opt/aws/bin/cfn-init -v --region ${AWS::Region} --stack ${AWS::StackName} --resource EC2LaunchConfiguration
python aws-cicd/api/main.py &> server.log &
# healthcheck for service
sleep 5
curl http://localhost:8080/healthcheck
# send signal status to ASG
/opt/aws/bin/cfn-signal -e $? --region ${AWS::Region} --stack ${AWS::StackName} --resource EC2AutoScalingGroup
Metadata:
'AWS::CloudFormation::Init':
config:
files:
"/home/ec2-user/aws-cicd/api/conf/secret.ini":
mode: "000755"
owner: root
group: root
content: !Sub |
[secret]
var_name=${SecretName}
[aws]
region=${AWS::Region}
AlarmSNSTopic:
Type: AWS::SNS::Topic
Properties:
Subscription:
-
Endpoint: !Ref AlarmEmail
Protocol: email
DisplayName: !Sub ${AWS::StackName}-Topic
ALBP95LatencyAlarm:
DependsOn: AlarmSNSTopic
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: !Sub "Alarm for ALB p95 latency > ${ALBP95LatencyAlarmThreshold} secs"
Namespace: AWS/ApplicationELB
MetricName: TargetResponseTime
Dimensions:
- Name: LoadBalancer
Value: !GetAtt ALB.LoadBalancerFullName
ExtendedStatistic: p95
Period: 60
EvaluationPeriods: 1
Threshold: !Ref ALBP95LatencyAlarmThreshold
ComparisonOperator: GreaterThanOrEqualToThreshold
AlarmActions:
- !Ref AlarmSNSTopic
OKActions:
- !Ref AlarmSNSTopic
TreatMissingData: notBreaching
Unit: Seconds
Dashboard:
Type: AWS::CloudWatch::Dashboard
DependsOn: ALB
Properties:
DashboardName: !Sub ${AWS::StackName}-dashboard
# an example for picking the same metric to two widgets in the same dashboard
# first is a normal metrics view, second is a alarm metrics view
DashboardBody: !Sub
- |
{
"widgets": [
{
"type": "metric",
"x": 0,
"y": 0,
"width": 12,
"height": 6,
"properties": {
"metrics": [
[
"AWS/ApplicationELB",
"TargetResponseTime",
"LoadBalancer",
"${ALBFullName}"
]
],
"period": 60,
"stat": "p95",
"region": "${AWS::Region}",
"title": "ALB P95 Response time"
}
},
{
"type": "metric",
"x": 12,
"y": 0,
"width": 12,
"height": 6,
"properties": {
"title": "${AlarmName}",
"annotations": {
"alarms": [
"${AlarmARN}"
]
},
"view": "timeSeries",
"stacked": false
}
}
]
}
- {
ALBFullName: !GetAtt ALB.LoadBalancerFullName,
AlarmName: !Ref ALBP95LatencyAlarm,
AlarmARN: !GetAtt ALBP95LatencyAlarm.Arn
}
Outputs:
ALBDNSName:
Description: ALB DNS name
Value: !GetAtt ALB.DNSName