/
cluster-template.yml
507 lines (472 loc) · 19.3 KB
/
cluster-template.yml
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
Description: Typesense multi-node stack
Parameters:
LatestLinuxAmiId:
Type: "AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>"
Default: "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-arm64-gp2"
EnvironmentType:
Description: "Environment Type"
Type: String
Default: "dev"
InstanceType:
Description: "Instance Size"
Type: String
Default: t4g.nano
AllowedValues:
- t4g.nano
- t4g.micro
- t4g.small
- t4g.medium
- t4g.large
- t4g.xlarge
- t4g.2xlarge
TypesenseVersion:
Description: "Typesense Version"
Type: String
Default: 0.23.1
TypesenseApiPort:
Description: "Typesense API Port"
Type: Number
Default: 8108
TypesensePeeringPort:
Description: "Typesense Peering Port"
Type: Number
Default: 8107
TypesenseNodes:
Description: "Typesense Nodes Count"
Type: Number
Default: 3
MinValue: 3
TypesenseMinNodes:
Description: "Typesense Nodes Count"
Type: Number
Default: 3
MinValue: 3
TypesenseMaxNodes:
Description: "Typesense Nodes Count"
Type: Number
Default: 9
MinValue: 3
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: "Node Configuration"
Parameters:
- LatestLinuxAmiId
- InstanceType
- Label:
default: "Cluster Configuration"
Parameters:
- EnvironmentType
- TypesenseVersion
- TypesenseApiPort
- TypesensePeeringPort
- TypesenseNodes
- TypesenseMinNodes
- TypesenseMaxNodes
Conditions:
IsProduction: !Equals
- !Ref EnvironmentType
- prod
Resources:
# Launch Config
LaunchConfig:
Type: AWS::AutoScaling::LaunchConfiguration
Properties:
InstanceType: !Ref InstanceType # Graviton2 powered instances
ImageId: !Ref LatestLinuxAmiId
IamInstanceProfile: !GetAtt EC2InstanceProfile.Arn # assign cloudwatch role
SecurityGroups:
- !Ref EC2SecurityGroup
UserData:
Fn::Base64: !Sub |
#!/usr/bin/env bash
# install cloudwatch agent
yum -y install amazon-cloudwatch-agent
# get instance private IP & ID
EC2_INSTANCE_IP=$(curl -s http://instance-data/latest/meta-data/local-ipv4)
EC2_INSTANCE_ID=$(curl -s http://instance-data/latest/meta-data/instance-id)
# create typesense folders
mkdir -p /opt/typesense/data
mkdir -p /opt/typesense/log
# create the nodes file
echo "$EC2_INSTANCE_IP:${TypesensePeeringPort}:${TypesenseApiPort}" > /opt/typesense/nodes
# create typesense server config file
echo "[server]
api-key = ${TypesenseApiKey.Value}
data-dir = /opt/typesense/data
log-dir = /opt/typesense/log
enable-cors = true
api-port = ${TypesenseApiPort}
peering-port = ${TypesensePeeringPort}
peering-address = $EC2_INSTANCE_IP
nodes = /opt/typesense/nodes" > /opt/typesense/typesense.ini
# download & unarchive typesense
curl -O https://dl.typesense.org/releases/${TypesenseVersion}/typesense-server-${TypesenseVersion}-linux-arm64.tar.gz
tar -xzf typesense-server-${TypesenseVersion}-linux-arm64.tar.gz -C /opt/typesense
# remove archive
rm typesense-server-${TypesenseVersion}-linux-arm64.tar.gz
# change typesense files & folders permissions
chown -R ec2-user:ec2-user /opt/typesense
# create typesense service
echo "[Unit]
Description=Typesense service
After=network.target
[Service]
Type=simple
Restart=always
RestartSec=5
User=ec2-user
ExecStart=/opt/typesense/typesense-server --config=/opt/typesense/typesense.ini
[Install]
WantedBy=default.target" > /etc/systemd/system/typesense.service
# start typesense service
systemctl start typesense
# enable typesense daemon
systemctl enable typesense
# auto configure cloudwatch agent
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c ssm:${CloudWatchAgentConfig} -s
# notify sns topic of the new instance
aws sns publish --message "New Instance Ready (instanceId:$EC2_INSTANCE_IP)" --topic-arn ${EC2EventsTopic} --region ${AWS::Region}
# ASG
AutoScalingGroup:
Type: AWS::AutoScaling::AutoScalingGroup
Properties:
LaunchConfigurationName: !Ref LaunchConfig
DesiredCapacity: !Ref TypesenseNodes
MinSize: !Ref TypesenseMinNodes
MaxSize: !Ref TypesenseMaxNodes
# notify events topic on instance termination (downsizing)
NotificationConfigurations:
- NotificationTypes:
- autoscaling:EC2_INSTANCE_TERMINATE
TopicARN: !Ref EC2EventsTopic
TargetGroupARNs:
- !Ref ALBTargetGroup
VPCZoneIdentifier:
- !ImportValue typesense-vpc-PublicSubnet1
- !ImportValue typesense-vpc-PublicSubnet2
- !ImportValue typesense-vpc-PublicSubnet3
Tags:
- Key: Name
PropagateAtLaunch: true
Value: !Sub ${AWS::StackName}-${EnvironmentType}
- Key: InstanceType
PropagateAtLaunch: true
Value: !Sub ${AWS::StackName}-${EnvironmentType}-node
# Instance profile
EC2InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
InstanceProfileName: !Sub ${AWS::StackName}-${EnvironmentType}-instance-profile
Path: /
Roles:
- !Ref EC2InstanceRole
# Instance Role
EC2InstanceRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Sub ${AWS::StackName}-${EnvironmentType}-instance-role
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- sts:AssumeRole
Path: /
ManagedPolicyArns:
- arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy
- arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
Policies:
- PolicyName: !Sub ${AWS::StackName}-${EnvironmentType}-ec2-policy
PolicyDocument:
Version: "2012-10-17"
Statement:
# Allow publishing messagest to SNS Topic
- Effect: Allow
Action:
- sns:Publish
Resource:
- !Ref EC2EventsTopic
# SNS Topic to listen for instance events
EC2EventsTopic:
Type: AWS::SNS::Topic
Properties:
TopicName: !Sub ${AWS::StackName}-${EnvironmentType}-ec2-events
# SNS Topic Policy allow any service under account to trigger this - too broad maybe?
EC2EventsTopicPolicy:
Type: AWS::SNS::TopicPolicy
Properties:
Topics:
- !Ref EC2EventsTopic
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action: sns:Publish
Resource: !Ref EC2EventsTopic
Principal:
Service:
- autoscaling.amazonaws.com
# Subscribe Lambda to SNS Topic
EC2EventsTopicSubscription:
Type: AWS::SNS::Subscription
Properties:
TopicArn: !Ref EC2EventsTopic
Protocol: lambda
Endpoint: !GetAtt InstanceEventsListener.Arn
# Instance Security Group
EC2SecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: allow connections from ALB and SSH, from other instances within VPC
VpcId: !ImportValue typesense-vpc-VPCID
SecurityGroupIngress:
# Allow HTTP on Typesense port only from ALB SG
- IpProtocol: tcp
FromPort: !Ref TypesenseApiPort
ToPort: !Ref TypesenseApiPort
SourceSecurityGroupId: !GetAtt ALBSecurityGroup.GroupId
# Allow Typesense node to communicate with each other on the peering port within the VPC IP range
- IpProtocol: tcp
FromPort: !Ref TypesensePeeringPort
ToPort: !Ref TypesensePeeringPort
CidrIp: !ImportValue typesense-vpc-VPCCidrBlock # the VPC CidrIp from VPC stack
# Allow Typesense node to communicate with each other on the api port within the VPC IP range for status checks
- IpProtocol: tcp
FromPort: !Ref TypesenseApiPort
ToPort: !Ref TypesenseApiPort
CidrIp: !ImportValue typesense-vpc-VPCCidrBlock # the VPC CidrIp from VPC stack
# Allow SSH from anywhere - just for testing - !! remove
# "If you need to ssh to your instance, change your deployment process"
- IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: 0.0.0.0/0
# ALB Security Group allowing Port 80 from anywhere
ALBSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: allow traffic on port 80
VpcId: !ImportValue typesense-vpc-VPCID
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
# Load Balancer
ALB:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Properties:
Name: !Sub ${AWS::StackName}-${EnvironmentType}
Subnets:
- !ImportValue typesense-vpc-PublicSubnet1
- !ImportValue typesense-vpc-PublicSubnet2
- !ImportValue typesense-vpc-PublicSubnet3
SecurityGroups:
- !GetAtt ALBSecurityGroup.GroupId
# HTTP Listener
ALBListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
DefaultActions:
- Type: forward
TargetGroupArn: !Ref ALBTargetGroup
LoadBalancerArn: !Ref ALB
Port: 80
Protocol: HTTP
# Target Group
ALBTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
HealthCheckIntervalSeconds: 30
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 15
HealthyThresholdCount: 5
HealthCheckPath: /health
Matcher:
HttpCode: 200
Name: !Sub ${AWS::StackName}-${EnvironmentType}
Port: !Ref TypesenseApiPort
Protocol: HTTP
UnhealthyThresholdCount: 3
VpcId: !ImportValue typesense-vpc-VPCID
# Lambda Execution Role
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Policies:
- PolicyName: !Sub ${AWS::StackName}-${EnvironmentType}-lambda-policy
PolicyDocument:
Version: "2012-10-17"
Statement:
# describe autoscaling groups
- Effect: Allow
Action:
- autoscaling:DescribeAutoScalingGroups
- autoscaling:DescribeScalingActivities
Resource: "*"
# describe ec2 instances
- Effect: Allow
Action:
- ec2:DescribeInstances
Resource: "*"
# send SSM command
- Effect: Allow
Action:
- ssm:SendCommand
Resource: "*"
# permission to write logs into CloudWatch
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: "*"
# Instance Events Listener function
InstanceEventsListener:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub ${AWS::StackName}-${EnvironmentType}-instance-listener
Code:
S3Bucket: !ImportValue typesense-vpc-LambdaZipsBucket
S3Key: instance-listener.zip
Handler: index.handler
Role: !GetAtt LambdaExecutionRole.Arn
Environment:
Variables:
TypesenseApiKey: !GetAtt TypesenseApiKey.Value
TypesenseApiPort: !Ref TypesenseApiPort
TypesensePeeringPort: !Ref TypesensePeeringPort
AutoScalingGroupName: !Ref AutoScalingGroup
DocumentName: !Ref UpdateNodesCommand
Runtime: nodejs16.x
MemorySize: 128
Timeout: 60
# SNS permission to invoke Lambda
LambdaInvokePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref InstanceEventsListener
Principal: sns.amazonaws.com
# Random String Generator
RandomStringGenerator:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub ${AWS::StackName}-${EnvironmentType}-random-string
Code:
ZipFile: >
const response = require("cfn-response"), crypto = require("crypto");
exports.handler = (event, context) =>{
response.send(event, context, response.SUCCESS, {Value:crypto.randomBytes(parseInt(event['ResourceProperties']['Length'])).toString('hex')});
};
Handler: index.handler
Role: !GetAtt LambdaExecutionRole.Arn
Runtime: nodejs16.x
MemorySize: 128
Timeout: 10
# Typesense Admin API Key
TypesenseApiKey:
Type: AWS::CloudFormation::CustomResource
Properties:
Length: 32 # Keep in mind this is sent as String to Lambda
ServiceToken: !GetAtt RandomStringGenerator.Arn
# SSM Document
UpdateNodesCommand:
Type: AWS::SSM::Document
Properties:
Content:
schemaVersion: "2.2"
description: Update Typesense Nodes
parameters:
NodeList:
type: String
description: Nodes string
mainSteps:
- action: aws:runShellScript
name: restartTypesense
inputs:
runCommand:
- sudo yum update -y
- echo "{{NodeList}}" > /opt/typesense/nodes
- sudo systemctl restart typesense
DocumentFormat: YAML
DocumentType: Command
Name: !Sub ${AWS::StackName}-${EnvironmentType}-update-nodes
TargetType: /AWS::EC2::Instance
# SSM CloudWatch agent config
CloudWatchAgentConfig:
Type: AWS::SSM::Parameter
Properties:
Name: AmazonCloudWatchConfig
Type: String
Value: |
{
"agent": {
"metrics_collection_interval": 60,
"run_as_user": "root"
},
"logs": {
"logs_collected": {
"files": {
"collect_list": [
{
"file_path": "/opt/typesense/log/typesense.log",
"log_group_name": "typesense.log",
"log_stream_name": "{instance_id}",
"retention_in_days": 7
}
]
}
}
},
"metrics": {
"aggregation_dimensions": [["InstanceId"]],
"append_dimensions": {
"AutoScalingGroupName": "${aws:AutoScalingGroupName}",
"ImageId": "${aws:ImageId}",
"InstanceId": "${aws:InstanceId}",
"InstanceType": "${aws:InstanceType}"
},
"metrics_collected": {
"disk": {
"measurement": ["used_percent"],
"metrics_collection_interval": 60,
"resources": ["*"]
},
"mem": {
"measurement": ["mem_used_percent"],
"metrics_collection_interval": 60
},
"statsd": {
"metrics_aggregation_interval": 60,
"metrics_collection_interval": 10,
"service_address": ":8125"
}
}
}
}
Outputs:
ALBDnsName:
Value: !GetAtt ALB.DNSName
Description: The URL of the Load Balancer
Export:
Name: !Sub ${AWS::StackName}-ALBDnsName
APIKey:
Value: !GetAtt TypesenseApiKey.Value
Description: Typesense admin API Key
Export:
Name: !Sub ${AWS::StackName}-TypesenseApiKey