-
Notifications
You must be signed in to change notification settings - Fork 5
/
4-Base-Partner.yml
1129 lines (1080 loc) · 38.5 KB
/
4-Base-Partner.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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
AWSTemplateFormatVersion: "2010-09-09"
Description: Partner Instance - Node server for partner dashboard.
Parameters:
Environment:
Type: String
Description: Name of the environment to bring up.
# Optional
UbuntuAMI:
Type: String
Description: AMI
Default: ""
InstanceType:
Type: String
Description: Instance Type
Default: t3.micro
AllowedIp:
Type: String
Description: IP allowed to access Partner
Default: 192.168.0.0/32
Conditions:
OverrideAMI: !Not [!Equals [!Ref UbuntuAMI, ""]]
Mappings:
RegionMap:
us-east-1:
AMI: ami-0b93ce03dcbcb10f6
InstanceType: t3.small
EbsOptimized: true
us-east-2:
AMI: ami-0cbea92f2377277a4
InstanceType: t3.small
EbsOptimized: true
us-west-1:
AMI: ami-0d4360d9166cfc9cb
InstanceType: t3.small
EbsOptimized: true
us-west-2:
AMI: ami-0d31d7c9fc9503726
InstanceType: t3.small
EbsOptimized: true
ap-south-1:
AMI: ami-0ef82eeba2c7a0eeb
InstanceType: t2.small
EbsOptimized: false
ap-northeast-2:
AMI: ami-003bb1772f36a39a3
InstanceType: t2.small
EbsOptimized: false
ap-southeast-1:
AMI: ami-09f03fa5572692399
InstanceType: t3.small
EbsOptimized: true
ap-southeast-2:
AMI: ami-06139e5e22cc2f7b1
InstanceType: t2.small
EbsOptimized: false
ap-northeast-1:
AMI: ami-0c7cb70d3eb61492b
InstanceType: t3.small
EbsOptimized: true
ca-central-1:
AMI: ami-07a69147786eb0731
InstanceType: t3.small
EbsOptimized: true
eu-central-1:
AMI: ami-0b81e95bb0a06ea8c
InstanceType: t3.small
EbsOptimized: true
eu-west-1:
AMI: ami-029cfca952b331b52
InstanceType: t3.small
EbsOptimized: true
eu-west-2:
AMI: ami-035469b606478d63d
InstanceType: t3.small
EbsOptimized: true
eu-west-3:
AMI: ami-01952eddad7516aa7
InstanceType: t2.small
EbsOptimized: false
sa-east-1:
AMI: ami-055ecc74f0a802e8f
InstanceType: t2.small
EbsOptimized: false
Resources:
# ==================================================
# ============= Instance Role ======================
# ==================================================
PartnerRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, SSMManagedPolicy ] ]
Policies:
- PolicyName: !Sub ${Environment}-Partner
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- ssm:GetParametersByPath
Resource:
- !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${Environment}/COMMON
- !Sub arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${Environment}/PARTNER
- Effect: Allow
Action:
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:${Environment}-Partner
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:${Environment}-Partner:log-stream:*
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:${Environment}-Partner-Node
- !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:${Environment}-Partner-Node:log-stream:*
- Effect: Allow
Action:
- ses:SendEmail
- ses:SendRawEmail
Resource: "*"
PartnerInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles:
- !Ref PartnerRole
# ==================================================
# =================== SECURITY GROUPS ==============
# ==================================================
PartnerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
VpcId:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, VPCId ] ]
GroupDescription: Database Postgres In
Tags:
- Key: Name
Value: Partner
- Key: Environment
Value: !Ref Environment
PartnerLoadBalancerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
VpcId:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, VPCId ] ]
GroupDescription: HTTPS In
Tags:
- Key: Name
Value: PartnerLoadBalancer
- Key: Environment
Value: !Ref Environment
PartnerLoadBalancerPartnerSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
IpProtocol: tcp
FromPort: 80
ToPort: 80
Description: Allow HTTP from Partner Load Balancer to Partner
SourceSecurityGroupId: !Ref PartnerLoadBalancerSecurityGroup
GroupId: !Ref PartnerSecurityGroup
PartnerRedisSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
IpProtocol: tcp
FromPort: 6379
ToPort: 6379
Description: Allow Redis from Partner to Redis
SourceSecurityGroupId: !Ref PartnerSecurityGroup
GroupId:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, RedisSecurityGroupId ] ]
AllowedIpHTTPPartnerLoadBalancerSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
IpProtocol: tcp
FromPort: 80
ToPort: 80
Description: Allow HTTP from allowed IP to Partner Load Balancer
CidrIp: !Ref AllowedIp
GroupId: !Ref PartnerLoadBalancerSecurityGroup
AllowedIpPartnerLoadBalancerSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
IpProtocol: tcp
FromPort: 443
ToPort: 443
Description: Allow HTTPS from allowed IP to Partner Load Balancer
CidrIp: !Ref AllowedIp
GroupId: !Ref PartnerLoadBalancerSecurityGroup
PartnerDatabaseSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
IpProtocol: tcp
FromPort: 5432
ToPort: 5432
Description: Allow Postgres from Partner to Database
SourceSecurityGroupId: !Ref PartnerSecurityGroup
GroupId:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, DatabaseSecurityGroupId ] ]
# ==================================================
# ================== CODEPIPELINE ==================
# ==================================================
PartnerCodeBuildProject:
Type: AWS::CodeBuild::Project
Properties:
Name: !Join [ '-', [ !Ref Environment, Partner ] ]
ServiceRole:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CodeBuildRoleArn ] ]
Artifacts:
Type: CODEPIPELINE
BadgeEnabled: false
Environment:
ComputeType: BUILD_GENERAL1_SMALL
EnvironmentVariables:
- Name: ENVIRONMENT
Type: PLAINTEXT
Value: !Ref Environment
- Name: CURRENT_SOURCE_ID
Type: PLAINTEXT
Value: localsource
- Name: PG_PARTNER_PASSWORD
Type: PLAINTEXT
Value: partner_pw
- Name: AWS_REGION
Type: PLAINTEXT
Value: !Ref AWS::Region
- Name: GIT_BRANCH
Type: PLAINTEXT
Value:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, GitBranch ] ]
- Name: NODE_TLS_REJECT_UNAUTHORIZED
Type: PLAINTEXT
Value: 0
Type: LINUX_CONTAINER
Image: aws/codebuild/standard:6.0
Source:
Type: CODEPIPELINE
TimeoutInMinutes: 15
VpcConfig:
SecurityGroupIds:
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, TestCodeBuildSecurityGroupId ] ]
Subnets:
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, TestPrivateSubnet ] ]
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, TestPrivateSubnet2 ] ]
VpcId:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, TestVPCId ] ]
Tags:
- Key: Environment
Value: !Ref Environment
PartnerCodePipeline:
Type: AWS::CodePipeline::Pipeline
DependsOn:
- PartnerDeploymentGroup
- PartnerCodeBuildProject
- PartnerLaunchConfiguration
Properties:
ArtifactStore:
EncryptionKey:
Id:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CodePipelineKeyId ] ]
Type: KMS
Location:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, ArtifactBucket ] ]
Type: S3
Name: !Join [ '-', [ !Ref Environment, Partner ] ]
RoleArn:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CodePipelineRoleArn ] ]
Stages:
- Name: CodeCommit
Actions:
- Name: PartnerCodeCommit
RunOrder: 1
ActionTypeId:
Category: Source
Owner: AWS
Provider: CodeCommit
Version: 1
Configuration:
RepositoryName: !Sub ${Environment}-Partner
BranchName:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, GitBranch ] ]
OutputArtifacts:
- Name: CodeCommitArtifact
- Name: CodeBuild
Actions:
- Name: PartnerCodeBuild
RunOrder: 2
ActionTypeId:
Category: Build
Owner: AWS
Provider: CodeBuild
Version: 1
Configuration:
ProjectName: !Ref PartnerCodeBuildProject
InputArtifacts:
- Name: CodeCommitArtifact
OutputArtifacts:
- Name: CodeBuildArtifact
- Name: CodeDeploy
Actions:
- Name: PartnerCodeDeploy
RunOrder: 3
ActionTypeId:
Category: Deploy
Owner: AWS
Provider: CodeDeploy
Version: 1
Configuration:
ApplicationName: !Ref PartnerApplication
DeploymentGroupName: !Ref PartnerDeploymentGroup
InputArtifacts:
- Name: CodeBuildArtifact
PartnerApplication:
Type: AWS::CodeDeploy::Application
Properties:
ApplicationName: !Join [ '-', [ !Ref Environment, Partner ] ]
PartnerDeploymentGroup:
Type: AWS::CodeDeploy::DeploymentGroup
Properties:
ApplicationName: !Ref PartnerApplication
AutoScalingGroups:
- !Ref PartnerAutoScalingGroup
DeploymentConfigName: CodeDeployDefault.OneAtATime
DeploymentStyle:
DeploymentOption: WITH_TRAFFIC_CONTROL
DeploymentType: IN_PLACE
LoadBalancerInfo:
TargetGroupInfoList:
- Name: !GetAtt PartnerTargetGroup.TargetGroupName
ServiceRoleArn:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CodeDeployRoleArn ] ]
# ==================================================
# =================== Partner ==================
# ==================================================
PartnerLoadBalancer:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Properties:
#LoadBalancerAttributes: # prod only
# - Key: deletion_protection.enabled
# Value: true
Scheme: internet-facing
SecurityGroups:
- !Ref PartnerLoadBalancerSecurityGroup
Subnets:
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, SubnetId ] ]
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, Subnet2Id ] ]
Tags:
- Key: Name
Value: PartnerLoadBalancer
- Key: Environment
Value: !Ref Environment
Type: application
IpAddressType: ipv4
PartnerDNSRecordSet:
Type: AWS::Route53::RecordSet
Properties:
AliasTarget:
DNSName: !GetAtt PartnerLoadBalancer.DNSName
EvaluateTargetHealth: false
HostedZoneId: !GetAtt PartnerLoadBalancer.CanonicalHostedZoneID
Comment: !Join [ '-', [ !Ref Environment, PartnerLoadBalancer ] ]
HostedZoneName: !Sub
- ${Domain}.
- Domain:
Fn::ImportValue: !Sub ${Environment}-Domain
Name: !Sub
- partner.${Domain}
- Domain:
Fn::ImportValue: !Sub ${Environment}-Domain
Type: A
PartnerTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
HealthCheckIntervalSeconds: 10
HealthCheckPath: /health
HealthCheckPort: traffic-port
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 3
HealthyThresholdCount: 2
UnhealthyThresholdCount: 2
Matcher:
HttpCode: 200
Name: !Join [ '-', [ !Ref Environment, Partner ] ]
Port: 80
Protocol: HTTP
Tags:
- Key: Name
Value: PartnerTargetGroup
- Key: Environment
Value: !Ref Environment
TargetGroupAttributes:
- Key: deregistration_delay.timeout_seconds
Value: 300
- Key: stickiness.enabled
Value: false
VpcId:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, VPCId ] ]
PartnerLoadBalancerListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
Certificates:
- CertificateArn:
Fn::ImportValue: !Sub ${Environment}-DomainCertificate
DefaultActions:
- TargetGroupArn: !Ref PartnerTargetGroup
Type: forward
LoadBalancerArn: !Ref PartnerLoadBalancer
Port: 443
Protocol: HTTPS
SslPolicy: ELBSecurityPolicy-TLS-1-2-Ext-2018-06
PartnerLoadBalancerHttpRedirectListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
DefaultActions:
- Type: redirect
RedirectConfig:
Port: 443
Protocol: HTTPS
StatusCode: HTTP_301
LoadBalancerArn: !Ref PartnerLoadBalancer
Port: 80
Protocol: HTTP
PartnerAutoScalingGroup:
Type: AWS::AutoScaling::AutoScalingGroup
CreationPolicy:
AutoScalingCreationPolicy:
MinSuccessfulInstancesPercent: 100
ResourceSignal:
Count: 1
Timeout: PT20M
UpdatePolicy:
AutoScalingReplacingUpdate:
WillReplace: true
Properties:
VPCZoneIdentifier:
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, SubnetId ] ]
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, Subnet2Id ] ]
Cooldown: 300
DesiredCapacity: 1
MinSize: 1
MaxSize: 1
HealthCheckGracePeriod: 300
HealthCheckType: EC2
TerminationPolicies:
- OldestInstance
LaunchConfigurationName: !Ref PartnerLaunchConfiguration
Tags:
- Key: Name
Value: !Join [ '-', [ !Ref Environment, Partner ] ]
PropagateAtLaunch: true
- Key: Environment
Value: !Ref Environment
PropagateAtLaunch: true
TargetGroupARNs:
- !Ref PartnerTargetGroup
PartnerLaunchConfiguration:
Type: AWS::AutoScaling::LaunchConfiguration
Properties:
AssociatePublicIpAddress: true
BlockDeviceMappings:
- DeviceName: /dev/sda1
Ebs:
DeleteOnTermination: true
VolumeSize: 8
VolumeType: gp2
EbsOptimized: true
IamInstanceProfile: !Ref PartnerInstanceProfile
ImageId: !If [OverrideAMI, !Ref UbuntuAMI, !FindInMap [RegionMap, !Ref "AWS::Region", AMI]]
InstanceMonitoring: true
InstanceType: !Ref InstanceType
SecurityGroups:
- !Ref PartnerSecurityGroup
UserData:
"Fn::Base64":
!Sub |
#!/bin/bash -ex
# Install Updates and Python3
export DEBIAN_FRONTEND=noninteractive
apt-get update && apt-get dist-upgrade -yq
apt-get -yq install python3.8-distutils python3-pip python3 python3-setuptools
# Install CloudFormation Bootstrap
wget https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz
tar -xvzf aws-cfn-bootstrap-py3-latest.tar.gz
cd aws-cfn-bootstrap-2.0
python3 setup.py install
# Run CloudFormation Init
cfn-init -c default --stack ${AWS::StackName} --resource PartnerLaunchConfiguration --region ${AWS::Region}
# Signal success to CloudFormation on reboot
echo "@reboot root /usr/local/bin/cfn-signal --success true --stack ${AWS::StackName} --resource PartnerAutoScalingGroup --region ${AWS::Region} 2>&1 | /usr/bin/logger -t cfn_success" >> /etc/cron.d/success_on_reboot
echo "@reboot root /home/ubuntu/install-codedeploy.sh 2>&1 | /usr/bin/logger -t install_codedeploy" >> /etc/cron.d/install_codedeploy_on_reboot
# Reboot to pick up latest patches
reboot
Metadata:
AWS::CloudFormation::Init:
configSets:
default:
- "unattended-upgrades"
- "enable-swap"
- "install-pip-and-curl-and-ruby"
- "set-region-and-environment"
- "install-aws-cloudwatch-and-cli"
- "install-node"
- "forward-node-port-on-reboot"
- "install-pm2"
- "install-codedeploy"
updateable:
- "update-nothing"
unattended-upgrades:
files:
'/etc/apt/apt.conf.d/10periodic':
content: |
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";
mode: '000644'
owner: root
group: root
'/etc/apt/apt.conf.d/50unattended-upgrades':
content: |
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}";
"${distro_id}:${distro_codename}-security";
"${distro_id}ESM:${distro_codename}";
};
mode: '000644'
owner: root
group: root
enable-swap:
commands:
0_enable_swap:
command: |
dd if=/dev/zero of=/var/spool/swap bs=1M count=1k
mkswap /var/spool/swap
chmod 0600 /var/spool/swap
swapon /var/spool/swap
1_persist_on_reboot:
command: |
echo "/var/spool/swap swap swap defaults 0 0" >> /etc/fstab
update-nothing:
commands:
0_do_nothing:
command: echo "Nothing to Update for Cfn"
forward-node-port-on-reboot:
commands:
0_net_tools:
command: apt install net-tools
1_forward:
command: |
ETHDEVICE=$(ifconfig -s | grep BMRU | head -n 1 | cut -d" " -f1)
echo "@reboot root /sbin/iptables -A PREROUTING -t nat -i $ETHDEVICE -p tcp --dport 80 -j REDIRECT --to-port 3000 2>&1 | /usr/bin/logger -t forward_node_port_on_reboot" > /etc/cron.d/forward_node_port_on_reboot
chmod 0644 /etc/cron.d/forward_node_port_on_reboot
iptables -A PREROUTING -t nat -i $ETHDEVICE -p tcp --dport 80 -j REDIRECT --to-port 3000
install-pip-and-curl-and-ruby:
packages:
apt:
curl: []
python3-pip: []
ruby: []
set-region-and-environment:
commands:
0_set_environment:
command: !Sub echo ENVIRONMENT=${Environment} >> /etc/environment
1_set_region:
command: !Sub echo AWS_DEFAULT_REGION=${AWS::Region} >> /etc/environment
2_set_region_node:
command: !Sub echo AWS_REGION=${AWS::Region} >> /etc/environment
3_set_git_branch:
command: !Sub
- echo GIT_BRANCH=${Branch} >> /etc/environment
- Branch:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, GitBranch ] ]
install-aws-cloudwatch-and-cli:
packages:
apt:
awscli: []
files:
'/home/ubuntu/cloudwatch.config':
content: !Sub |
{
"logs": {
"logs_collected": {
"files": {
"collect_list": [
{
"file_path": "/home/node/logs/app.log",
"log_group_name": "${Environment}-Partner-Node",
"log_stream_name": "{instance_id}-node-log"
},
{
"file_path": "/var/log/cloud-init.log",
"log_group_name": "${Environment}-Partner-Node",
"log_stream_name": "{instance_id}-cloud-init-placeholder"
},
{
"file_path": "/var/log/syslog",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-syslog"
},
{
"file_path": "/var/log/cloud-init.log",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-cloud-init"
},
{
"file_path": "/var/log/cloud-init-output.log",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-cloud-init-output"
},
{
"file_path": "/var/log/cfn-init.log",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-cfn-init"
},
{
"file_path": "/var/log/cfn-init-cmd.log",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-cfn-init-cmd"
},
{
"file_path": "/var/log/amazon/ssm/amazon-ssm-agent.log",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-aws-ssm"
},
{
"file_path": "/var/log/aws/codedeploy-agent/codedeploy-agent.log",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-aws-codedeploy-agent"
},
{
"file_path": "/opt/codedeploy-agent/deployment-root/deployment-logs/codedeploy-agent-deployments.log",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-aws-codedeploy-deployments"
},
{
"file_path": "/opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-cloudwatch-logs"
},
{
"file_path": "/var/log/unattended-upgrades/unattended-upgrades.log",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-unattended-upgrades"
},
{
"file_path": "/var/log/unattended-upgrades/unattended-upgrades-dpkg.log",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-unattended-upgrades-dpkg"
},
{
"file_path": "/var/run/reboot-required.pkgs",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-reboot-required"
},
{
"file_path": "/tmp/CURRENT_NODE_VERSION",
"log_group_name": "${Environment}-Partner",
"log_stream_name": "{instance_id}-current-node-version"
}
]
}
}
},
"metrics": {
"append_dimensions": {
"InstanceId": "${!aws:InstanceId}",
"AutoScalingGroupName": "${!aws:AutoScalingGroupName}"
},
"aggregation_dimensions": [["AutoScalingGroupName"]],
"metrics_collected": {
"cpu": {
"measurement": [
"cpu_usage_active",
"cpu_usage_iowait",
"cpu_usage_user",
"cpu_usage_system"
],
"metrics_collection_interval": 60,
"totalcpu": true
},
"disk": {
"measurement": [
"used_percent",
"inodes_free"
],
"metrics_collection_interval": 60,
"resources": [
"/"
]
},
"diskio": {
"measurement": [
"io_time"
],
"metrics_collection_interval": 60,
"resources": [
"/"
]
},
"mem": {
"measurement": [
"mem_used_percent"
],
"metrics_collection_interval": 60
},
"swap": {
"measurement": [
"swap_used_percent"
],
"metrics_collection_interval": 60
}
}
}
}
mode: '000644'
owner: root
group: root
commands:
0_install_cloudwatch:
command: |
apt-get -yq install unzip
wget -q https://s3.amazonaws.com/amazoncloudwatch-agent/linux/amd64/latest/AmazonCloudWatchAgent.zip -P /tmp
unzip /tmp/AmazonCloudWatchAgent.zip -d /home/ubuntu/cloudwatch_agent
cd /home/ubuntu/cloudwatch_agent
./install.sh
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c file:/home/ubuntu/cloudwatch.config -s
install-node:
commands:
0_create_user:
command: |
adduser \
--system \
--shell /bin/bash \
--gecos 'Node user' \
--group \
--disabled-password \
--home /home/node \
node
1_setup:
command: curl -sL https://deb.nodesource.com/setup_16.x | bash -
2_install:
command: apt-get install -yq nodejs
3_update_npm:
command: npm install -g npm@8
4_install_n:
command: npm install -g n
install-pm2:
commands:
0_install:
command: npm install pm2 -g
1_restart_on_reboot:
command: env PATH=$PATH:/usr/local/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u node --hp /home/node
install-codedeploy:
files:
'/home/ubuntu/install-codedeploy.sh':
content: !Sub |
export PATH=$PATH:/usr/local/sbin:/usr/sbin:/sbin
wget -nv "https://aws-codedeploy-${AWS::Region}.s3.amazonaws.com/latest/install" -O /tmp/install
/bin/chmod +x /tmp/install && /tmp/install auto
mode: '000544'
owner: root
group: root
# ==================================================
# ============ APPLICATION ERROR ALERTS ============
# ==================================================
PartnerNodeEmailerSubscriptionFilter:
Type: AWS::Logs::SubscriptionFilter
DependsOn:
- PartnerAutoScalingGroup
Properties:
DestinationArn:
Fn::ImportValue:
!Join [ '-', [ !Ref Environment, ErrorEmailerFunctionArn ] ]
FilterPattern: '{ $.level = "error" }'
LogGroupName: !Join [ '-', [ !Ref Environment, Partner-Node ] ]
# ==================================================
# ================= CLOUDWATCH ALARMS ==============
# ==================================================
PartnerTargetGroupUnhealthyHostAlarm:
Type: AWS::CloudWatch::Alarm
DependsOn:
- PartnerAutoScalingGroup
Properties:
ActionsEnabled: true
AlarmActions:
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CloudWatchAlarmEmailerTopic ] ]
AlarmDescription: !Sub ${Environment} | Partner Unhealthy Host
MetricName: UnHealthyHostCount
Namespace: AWS/ApplicationELB
Statistic: Minimum
Period: '60'
EvaluationPeriods: '2'
Threshold: '1'
ComparisonOperator: GreaterThanOrEqualToThreshold
TreatMissingData: breaching
Dimensions:
- Name: TargetGroup
Value: !GetAtt PartnerTargetGroup.TargetGroupFullName
- Name: LoadBalancer
Value: !GetAtt PartnerLoadBalancer.LoadBalancerFullName
PartnerTargetGroupHealthyHostAlarm:
Type: AWS::CloudWatch::Alarm
DependsOn:
- PartnerAutoScalingGroup
- PartnerTargetGroupUnhealthyHostAlarm
Properties:
ActionsEnabled: true
AlarmActions:
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CloudWatchAlarmEmailerTopic ] ]
AlarmDescription: !Sub ${Environment} | Partner Healthy Host
MetricName: HealthyHostCount
Namespace: AWS/ApplicationELB
Statistic: Maximum
Period: '60'
EvaluationPeriods: '2'
Threshold: '1'
ComparisonOperator: LessThanThreshold
TreatMissingData: breaching
Dimensions:
- Name: TargetGroup
Value: !GetAtt PartnerTargetGroup.TargetGroupFullName
- Name: LoadBalancer
Value: !GetAtt PartnerLoadBalancer.LoadBalancerFullName
PartnerTargetGroupLatencyAlarm:
Type: AWS::CloudWatch::Alarm
DependsOn:
- PartnerAutoScalingGroup
- PartnerTargetGroupHealthyHostAlarm
Properties:
ActionsEnabled: true
AlarmActions:
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CloudWatchAlarmEmailerTopic ] ]
AlarmDescription: !Sub ${Environment} | Partner Latency
MetricName: TargetResponseTime
Namespace: AWS/ApplicationELB
Statistic: Average
Period: '60'
EvaluationPeriods: '2'
Threshold: '2'
ComparisonOperator: GreaterThanOrEqualToThreshold
TreatMissingData: ignore
Dimensions:
- Name: TargetGroup
Value: !GetAtt PartnerTargetGroup.TargetGroupFullName
- Name: LoadBalancer
Value: !GetAtt PartnerLoadBalancer.LoadBalancerFullName
CpuAlarm:
Type: AWS::CloudWatch::Alarm
DependsOn:
- PartnerAutoScalingGroup
- PartnerTargetGroupLatencyAlarm
Properties:
ActionsEnabled: true
AlarmActions:
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CloudWatchAlarmEmailerTopic ] ]
AlarmDescription: !Sub ${Environment} | Partner CPU
MetricName: "cpu_usage_active"
Namespace: CWAgent
Statistic: Average
Period: '60'
EvaluationPeriods: '2'
Threshold: '60'
ComparisonOperator: GreaterThanOrEqualToThreshold
TreatMissingData: breaching
Dimensions:
- Name: AutoScalingGroupName
Value: !Ref PartnerAutoScalingGroup
LowMemoryAlarm:
Type: AWS::CloudWatch::Alarm
DependsOn:
- PartnerAutoScalingGroup
- PartnerTargetGroupLatencyAlarm
Properties:
ActionsEnabled: true
AlarmActions:
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CloudWatchAlarmEmailerTopic ] ]
AlarmDescription: !Sub ${Environment} | Partner Low Memory
MetricName: "mem_used_percent"
Namespace: CWAgent
Statistic: Maximum
Period: '300'
EvaluationPeriods: '1'
Threshold: '80'
ComparisonOperator: GreaterThanOrEqualToThreshold
TreatMissingData: breaching
Dimensions:
- Name: AutoScalingGroupName
Value: !Ref PartnerAutoScalingGroup
SwapUsageAlarm:
Type: AWS::CloudWatch::Alarm
DependsOn:
- PartnerAutoScalingGroup
- LowMemoryAlarm
Properties:
ActionsEnabled: true
AlarmActions:
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CloudWatchAlarmEmailerTopic ] ]
AlarmDescription: !Sub ${Environment} | Partner Swap Usage
MetricName: "swap_used_percent"
Namespace: CWAgent
Statistic: Maximum
Period: '300'
EvaluationPeriods: '1'
Threshold: '15'
ComparisonOperator: GreaterThanThreshold
TreatMissingData: breaching
Dimensions:
- Name: AutoScalingGroupName
Value: !Ref PartnerAutoScalingGroup
DiskUsageAlarm:
Type: AWS::CloudWatch::Alarm
DependsOn:
- PartnerAutoScalingGroup
- SwapUsageAlarm
Properties:
ActionsEnabled: true
AlarmActions:
- Fn::ImportValue:
!Join [ '-', [ !Ref Environment, CloudWatchAlarmEmailerTopic ] ]
AlarmDescription: !Sub ${Environment} | Partner Disk Usage
MetricName: "disk_used_percent"
Namespace: CWAgent
Statistic: Maximum