-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtemplate.yaml
1159 lines (1067 loc) · 36.2 KB
/
template.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
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: 'Express API developed in Typescript and deployed to ECS Fargate that sits behind a private Application Load Balancer and exposed to the world using an Http API Gateway.'
################################### APPLICATION PARAMETERS ###################################
Parameters:
CodestarConnectionId:
Type: String
Description: Specify Codestar connection identifier that is configured and authenticated for the source provider.
FullRepositoryId:
Type: String
Description: 'Specify the owner and name of the repository where source changes are to be detected. Example: some-user/my-repo.'
BranchName:
Type: String
Description: Specify the name of the branch where source changes are to be detected.
ArtifactStoreS3Location:
Type: String
Description: Specify the name of the S3 bucket to store the CodePipeline artifacts.
AutoScalingMinCapacity:
Type: Number
Description: Specify the maximum value that you plan to scale out to.
Default: 0
AutoScalingMaxCapacity:
Type: Number
Description: Specify the minimum value that you plan to scale in to
Default: 0
DockerHubUsername:
Type: String
Description: Specify the DockerHub username to be used when building the docker image.
DockerHubPassword:
Type: String
Description: Specify the DockerHub password to be used when building the docker image.
NoEcho: true
################################### APPLICATION MAPPINGS ###################################
Mappings:
SubnetConfig:
VPC:
CIDR: 10.2.0.0/16
PublicSubnet1:
CIDR: 10.2.0.0/24
PublicSubnet2:
CIDR: 10.2.1.0/24
PrivateSubnet1:
CIDR: 10.2.2.0/24
PrivateSubnet2:
CIDR: 10.2.3.0/24
NameConfig:
ECRRepository:
Name: pets-api
Container:
Name: pets-api
CodeBuildProject:
Name: pets-api
CodeBuildLogGroup:
Name: /aws/codebuild/pets-api
DatabaseSecret:
Name: rds-db-credentials/petsdb5
DockerHubSecret:
Name: docker-hub-credentials/pets-api
################################### APPLICATION RESOURCES ###################################
Resources:
################################### VPC ###################################
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: !FindInMap [SubnetConfig, VPC, CIDR]
InstanceTenancy: default
EnableDnsHostnames: false
EnableDnsSupport: true
Tags:
- Key: Name
Value: PetsAPI-VPC
################################### INTERNET GATEWAY ###################################
InternetGateway:
Type: AWS::EC2::InternetGateway
Properties:
Tags:
- Key: Name
Value: PetsAPI-VPC-IG
InternetGatewayAttachment:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
InternetGatewayId: !Ref InternetGateway
VpcId: !Ref VPC
################################## PUBLIC ROUTE TABLE ###################################
PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: PetsAPI-VPC-PubRT
DefaultPublicRoute:
DependsOn:
- InternetGatewayAttachment
Type: AWS::EC2::Route
Properties:
RouteTableId: !Ref PublicRouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
################################### PUBLIC SUBNETS ###################################
################################### SUBNET1 ###################################
PublicSubnet1:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone: !Select [0, !GetAZs '']
CidrBlock: !FindInMap [SubnetConfig, PublicSubnet1, CIDR]
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: PetsAPI-VPC-PubSN1
VpcId: !Ref VPC
PublicSubnet1RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref PublicSubnet1
PublicSubnet1ElasticIP:
Type: AWS::EC2::EIP
Properties:
Domain: vpc
Tags:
- Key: Name
Value: PetsAPI-VPC-PubSN1-NG-EIP
PublicSubnet1NatGateway:
Type: AWS::EC2::NatGateway
Properties:
AllocationId: !GetAtt PublicSubnet1ElasticIP.AllocationId
SubnetId: !Ref PublicSubnet1
Tags:
- Key: Name
Value: PetsAPI-VPC-PubSN1-NG
################################### SUBNET2 ###################################
PublicSubnet2:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone: !Select [1, !GetAZs '']
CidrBlock: !FindInMap [SubnetConfig, PublicSubnet2, CIDR]
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: PetsAPI-VPC-PubSN2
VpcId: !Ref VPC
PublicSubnet2RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref PublicSubnet2
PublicSubnet2ElasticIP:
Type: AWS::EC2::EIP
Properties:
Domain: vpc
Tags:
- Key: Name
Value: PetsAPI-VPC-PubSN2-NG-EIP
PublicSubnet2NatGateway:
Type: AWS::EC2::NatGateway
Properties:
AllocationId: !GetAtt PublicSubnet2ElasticIP.AllocationId
SubnetId: !Ref PublicSubnet2
Tags:
- Key: Name
Value: PetsAPI-VPC-PubSN2-NG
################################### PRIVATE SUBNETS ###################################
################################### SUBNET1 ###################################
PrivateSubnet1:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone: !Select [0, !GetAZs '']
CidrBlock: !FindInMap [SubnetConfig, PrivateSubnet1, CIDR]
Tags:
- Key: Name
Value: PetsAPI-VPC-PrivSN1
VpcId:
Ref: VPC
PrivateSubnet1RouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: PetsAPI-VPC-PrivSN1-RT
PrivateSubnet1RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PrivateSubnet1RouteTable
SubnetId: !Ref PrivateSubnet1
RouteToPublicSubnet1NatGateway:
Type: AWS::EC2::Route
Properties:
RouteTableId: !Ref PrivateSubnet1RouteTable
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId: !Ref PublicSubnet1NatGateway
################################### SUBNET2 ###################################
PrivateSubnet2:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone: !Select [1, !GetAZs '']
CidrBlock: !FindInMap [SubnetConfig, PrivateSubnet2, CIDR]
Tags:
- Key: Name
Value: PetsAPI-VPC-PrivSN2
VpcId:
Ref: VPC
PrivateSubnet2RouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: PetsAPI-VPC-PrivSN2-RT
PrivateSubnet2RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PrivateSubnet2RouteTable
SubnetId: !Ref PrivateSubnet2
RouteToPublicSubnet2NatGateway:
Type: AWS::EC2::Route
Properties:
RouteTableId: !Ref PrivateSubnet2RouteTable
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId: !Ref PublicSubnet2NatGateway
################################### VPC LINK ###################################
VPCLinkSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupName: PetsAPI-VPCLink-SG
GroupDescription: PetsAPI VPCLink SG
SecurityGroupIngress:
- Description: Allow traffic from the internet
CidrIp: 0.0.0.0/0
IpProtocol: tcp
FromPort: 80
ToPort: 80
Tags:
- Key: Name
Value: PetsAPI-VPCLink-SG
VpcId: !Ref VPC
VPCLink:
Type: AWS::ApiGatewayV2::VpcLink
Properties:
Name: PetsAPI-VPCLink
SecurityGroupIds:
- !Ref VPCLinkSecurityGroup
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
################################### LOAD BALANCER ###################################
LoadBalancerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupName: PetsAPI-LB-SG
GroupDescription: PetsAPI LoadBalancer SecurityGroup
SecurityGroupIngress:
- Description: Allow traffic from VPCLinkSecurityGroup
IpProtocol: tcp
FromPort: 80
ToPort: 80
SourceSecurityGroupId: !Ref VPCLinkSecurityGroup
Tags:
- Key: Name
Value: PetsAPI-LB-SG
VpcId: !Ref VPC
LoadBalancer:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Properties:
Name: PetsAPI-LB
Type: application
Scheme: internal
Subnets:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
SecurityGroups:
- !Ref LoadBalancerSecurityGroup
LoadBalancerTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
Name: PetsAPI-LB-TG
VpcId: !Ref VPC
Port: 3000
Protocol: HTTP
Matcher:
HttpCode: 200-299
HealthCheckIntervalSeconds: 10
HealthCheckPath: /health
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 5
HealthyThresholdCount: 2
TargetType: ip
TargetGroupAttributes:
- Key: deregistration_delay.timeout_seconds
Value: 30
LoadBalancerListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
LoadBalancerArn: !Ref LoadBalancer
Port: 80
Protocol: HTTP
DefaultActions:
- Type: forward
TargetGroupArn: !Ref LoadBalancerTargetGroup
################################### API GATEWAY ###################################
APIGateway:
Type: AWS::ApiGatewayV2::Api
Properties:
Name: PetsAPI-APIGateway
Description: PetsAPI APIGateway
ProtocolType: HTTP
APIGatewayIntegration:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref APIGateway
Description: Private ALB Integration
IntegrationType: HTTP_PROXY
IntegrationMethod: ANY
ConnectionType: VPC_LINK
ConnectionId: !Ref VPCLink
IntegrationUri: !Ref LoadBalancerListener
PayloadFormatVersion: 1.0
APIGatewayRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref APIGateway
RouteKey: $default
Target: !Join ['/', [integrations, !Ref APIGatewayIntegration]]
APIGatewayLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: /aws/apigateway/pets-api
RetentionInDays: 1
APIGatewayStage:
Type: AWS::ApiGatewayV2::Stage
Properties:
StageName: $default
AutoDeploy: true
AccessLogSettings:
DestinationArn:
!Join [':', [!Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group', !Ref APIGatewayLogGroup]]
Format: '{
"accountId": "$context.accountId",
"apiId": "$context.apiId",
"endpointRequestId": "$context.awsEndpointRequestId",
"endpointRequestId2": "$context.awsEndpointRequestId2",
"customDomain.basePathMatched": "$context.customDomain.basePathMatched",
"dataProcessed": "$context.dataProcessed",
"domainName": "$context.domainName",
"domainPrefix": "$context.domainPrefix",
"error.message": "$context.error.message",
"error.messageString": "$context.error.messageString",
"error.responseType": "$context.error.responseType",
"extendedRequestId": "$context.extendedRequestId",
"httpMethod": "$context.httpMethod",
"identity.accountId": "$context.identity.accountId",
"identity.caller": "$context.identity.caller",
"identity.sourceIp": "$context.identity.sourceIp",
"identity.userAgent": "$context.identity.userAgent",
"integration.error": "$context.integration.error",
"integration.integrationStatus": "$context.integration.integrationStatus",
"integration.latency": "$context.integration.latency",
"integration.requestId": "$context.integration.requestId",
"integration.status": "$context.integration.status",
"integration.error.message": "$context.integrationErrorMessage"
"integration.latency": "$context.integrationLatency"
"integration.status": "$context.integrationStatus",
"path": "$context.path",
"requestId": "$context.requestId",
}'
ApiId: !Ref APIGateway
################################### ECR ###################################
ECRRepository:
Type: AWS::ECR::Repository
Properties:
ImageScanningConfiguration:
ScanOnPush: true
ImageTagMutability: MUTABLE
RepositoryName: !FindInMap [NameConfig, ECRRepository, Name]
################################### ECS ###################################
ECSCluster:
Type: AWS::ECS::Cluster
Properties:
CapacityProviders:
- FARGATE
ClusterName: PetsAPI-ECSCluster
ECSTaskExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: PetsAPI-ECSTaskExecutionRole
Description: PetsAPI-ECSTaskExecutionRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- ecs-tasks.amazonaws.com
Action:
- sts:AssumeRole
ECSTaskRole:
Type: AWS::IAM::Role
Properties:
RoleName: PetsAPI-ECSTaskRole
Description: PetsAPI-ECSTaskRole
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- ecs-tasks.amazonaws.com
Action:
- sts:AssumeRole
ECSTaskRolePolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: PetsAPI-ECSTaskRolePolicy
Roles:
- !Ref ECSTaskRole
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: '*'
- Effect: Allow
Action:
- s3:ListBucket
- s3:PutObject
- s3:GetObject
Resource: '*'
ECSLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: /aws/ecs/pets-api
RetentionInDays: 1
ECSTaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
ContainerDefinitions:
- Name: !FindInMap [NameConfig, Container, Name]
Image: !Join [':', [!GetAtt ECRRepository.RepositoryUri, latest]]
HealthCheck:
Command:
- CMD-SHELL
- curl -f http://localhost:3000/health || exit 1
Interval: 30
Retries: 3
Timeout: 5
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-group: !Ref ECSLogGroup
awslogs-region: !Ref AWS::Region
awslogs-stream-prefix: pets-api
Essential: true
PortMappings:
# For task definitions that use the awsvpc network mode, you should only specify the containerPort. The hostPort can be left blank or it must be the same value as the containerPort.
- ContainerPort: 3000
Protocol: tcp
Cpu: 256
Memory: 1024
ExecutionRoleArn: !Ref ECSTaskExecutionRole
Family: PetsAPI-ECSTaskDefinition
NetworkMode: awsvpc
RequiresCompatibilities:
- FARGATE
TaskRoleArn: !Ref ECSTaskRole
ECSServiceSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupName: PetsAPI-ECS-SG
GroupDescription: PetsAPI-ECS-SG
SecurityGroupIngress:
- Description: Allow traffic from LoadBalancerSecurityGroup
IpProtocol: tcp
FromPort: 3000
ToPort: 3000
SourceSecurityGroupId: !Ref LoadBalancerSecurityGroup
Tags:
- Key: Name
Value: PetsAPI-ECS-SG
VpcId: !Ref VPC
ECSService:
Type: AWS::ECS::Service
DependsOn:
- LoadBalancerListener
Properties:
ServiceName: PetsAPI-ECSService
Cluster: !Ref ECSCluster
# Capacity will be handle exclusively by the ECSServiceAutoScalingTarget
DesiredCount: 0
TaskDefinition: !Ref ECSTaskDefinition
LaunchType: FARGATE
NetworkConfiguration:
AwsvpcConfiguration:
AssignPublicIp: DISABLED
SecurityGroups:
- !Ref ECSServiceSecurityGroup
Subnets:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
LoadBalancers:
# The name of the container (as it appears in a container definition)
- ContainerName: !FindInMap [NameConfig, Container, Name]
ContainerPort: 3000
TargetGroupArn: !Ref LoadBalancerTargetGroup
ECSServiceAutoScalingRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Join ['', [!GetAtt ECSService.Name, AutoScalingRole]]
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: ecs-tasks.amazonaws.com
Action: 'sts:AssumeRole'
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceAutoscaleRole
ECSServiceAutoScalingPolicy:
Type: AWS::ApplicationAutoScaling::ScalingPolicy
Properties:
PolicyName: !Join ['', [!GetAtt ECSService.Name, AutoScalingPolicy]]
PolicyType: TargetTrackingScaling
ScalingTargetId: !Ref ECSServiceAutoScalingTarget
TargetTrackingScalingPolicyConfiguration:
PredefinedMetricSpecification:
PredefinedMetricType: ECSServiceAverageCPUUtilization
ScaleInCooldown: 10
ScaleOutCooldown: 10
# Keep things at or lower than 50% CPU utilization, for example
TargetValue: 50
ECSServiceAutoScalingTarget:
Type: AWS::ApplicationAutoScaling::ScalableTarget
Properties:
MinCapacity: !Ref AutoScalingMinCapacity
MaxCapacity: !Ref AutoScalingMaxCapacity
ResourceId: !Join ['/', [service, !Ref ECSCluster, !GetAtt ECSService.Name]]
ScalableDimension: ecs:service:DesiredCount
ServiceNamespace: ecs
RoleARN: !GetAtt ECSServiceAutoScalingRole.Arn
################################### DATABASE ###################################
DatabaseSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupName: PetsAPI-Database-SG
GroupDescription: PetsAPI-Database-SG
SecurityGroupIngress:
- Description: Allow traffic from ECSServiceSecurityGroup
IpProtocol: tcp
FromPort: 5432
ToPort: 5432
SourceSecurityGroupId: !Ref ECSServiceSecurityGroup
- Description: Allow traffic from CodeBuildSecurityGroup
IpProtocol: tcp
FromPort: 5432
ToPort: 5432
SourceSecurityGroupId: !Ref CodeBuildSecurityGroup
Tags:
- Key: Name
Value: PetsAPI-Database-SG
VpcId: !Ref VPC
DatabaseSubnetGroup:
Type: AWS::RDS::DBSubnetGroup
Properties:
DBSubnetGroupName: PetsAPI-Database-SN-G
DBSubnetGroupDescription: PetsAPI-Database-SN-G
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
DatabaseSecret:
Type: AWS::SecretsManager::Secret
Properties:
Description: Secret for database instance
Name: !FindInMap [NameConfig, DatabaseSecret, Name]
GenerateSecretString:
SecretStringTemplate: '{"username": "pets"}'
GenerateStringKey: password
PasswordLength: 15
ExcludeCharacters: '"@/\'
DatabaseInstance:
DeletionPolicy: Delete
Type: AWS::RDS::DBInstance
Properties:
AllocatedStorage: 20
AllowMajorVersionUpgrade: false
AutoMinorVersionUpgrade: true
BackupRetentionPeriod: 0
CopyTagsToSnapshot: true
DBInstanceClass: db.t3.micro
DBInstanceIdentifier: PetsAPI-DatabaseInstance
DBName: petsdb
DBParameterGroupName: default.postgres13
DBSubnetGroupName: !Ref DatabaseSubnetGroup
EnableIAMDatabaseAuthentication: false
Engine: postgres
EngineVersion: 13.3
MasterUsername: !Join ['', ['{{resolve:secretsmanager:', !Ref DatabaseSecret, ':SecretString:username}}']]
MasterUserPassword: !Join ['', ['{{resolve:secretsmanager:', !Ref DatabaseSecret, ':SecretString:password}}']]
MultiAZ: false
StorageType: gp2
StorageEncrypted: false
VPCSecurityGroups:
- !Ref DatabaseSecurityGroup
DatabaseSecretAttachment:
Type: AWS::SecretsManager::SecretTargetAttachment
Properties:
SecretId: !Ref DatabaseSecret
TargetId: !Ref DatabaseInstance
TargetType: AWS::RDS::DBInstance
################################### CODE BUILD ###################################
DockerHubSecret:
Type: AWS::SecretsManager::Secret
Properties:
Description: Secret for DockerHub credentials
Name: !FindInMap [NameConfig, DockerHubSecret, Name]
SecretString: !Sub '{"username": "${DockerHubUsername}", "password": "${DockerHubPassword}"}'
CodeBuildSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupName: PetsAPI-CodeBuild-SG
GroupDescription: PetsAPI-CodeBuild-SG
SecurityGroupEgress:
- CidrIp: 0.0.0.0/0
IpProtocol: -1
FromPort: -1
ToPort: -1
Tags:
- Key: Name
Value: PetsAPI-CodeBuild-SG
VpcId: !Ref VPC
CodeBuildRole:
Type: AWS::IAM::Role
Properties:
RoleName: PetsAPI-CodeBuildRole
Description: PetsAPI-CodeBuildRole
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: codebuild.amazonaws.com
Action: sts:AssumeRole
CodeBuildBasePolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: PetsAPI-CodeBuildBasePolicy
Roles:
- !Ref CodeBuildRole
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Resource:
- !Join [
'',
[
!Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/',
!FindInMap [NameConfig, CodeBuildProject, Name]
]
]
- !Join [
'',
[
!Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/',
!FindInMap [NameConfig, CodeBuildProject, Name],
':*'
]
]
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- Effect: Allow
Resource:
- !Sub arn:aws:s3:::codepipeline-${AWS::Region}-*
Action:
- s3:PutObject
- s3:GetObject
- s3:GetObjectVersion
- s3:GetBucketAcl
- s3:GetBucketLocation
- Effect: Allow
Resource:
- !Join [
'',
[
!Sub 'arn:aws:codebuild:${AWS::Region}:${AWS::AccountId}:report-group/',
!FindInMap [NameConfig, CodeBuildProject, Name],
'-*'
]
]
Action:
- codebuild:CreateReportGroup
- codebuild:CreateReport
- codebuild:UpdateReport
- codebuild:BatchPutTestCases
- codebuild:BatchPutCodeCoverages
- Effect: Allow
Resource:
- !Ref DatabaseSecret
- !Ref DockerHubSecret
Action:
- secretsmanager:GetSecretValue
- Effect: Allow
Resource: '*'
Action:
- ecr:BatchCheckLayerAvailability
- ecr:InitiateLayerUpload
- ecr:UploadLayerPart
- ecr:CompleteLayerUpload
- ecr:PutImage
- ecr:GetAuthorizationToken
- Effect: Allow
Resource: '*'
Action:
- ec2:CreateNetworkInterface
- ec2:DescribeDhcpOptions
- ec2:DescribeNetworkInterfaces
- ec2:DeleteNetworkInterface
- ec2:DescribeSubnets
- ec2:DescribeSecurityGroups
- ec2:DescribeVpcs
- Effect: Allow
Resource: !Sub arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:network-interface/*
Action:
- ec2:CreateNetworkInterfacePermission
Condition:
StringEquals:
ec2:AuthorizedService: codebuild.amazonaws.com
ArnEquals:
ec2:Subnet:
- !Join ['/', [!Sub 'arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:subnet', !Ref PrivateSubnet1]]
- !Join ['/', [!Sub 'arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:subnet', !Ref PrivateSubnet2]]
CodeBuildCloudwatchPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: PetsAPI-CodeBuildCloudwatchPolicy
Roles:
- !Ref CodeBuildRole
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Resource:
- !Join [
'',
[
!Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:',
!FindInMap [NameConfig, CodeBuildLogGroup, Name]
]
]
- !Join [
'',
[
!Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:',
!FindInMap [NameConfig, CodeBuildLogGroup, Name],
':*'
]
]
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
CodeBuildProject:
Type: AWS::CodeBuild::Project
DependsOn:
- DatabaseSecretAttachment
Properties:
Artifacts:
Type: CODEPIPELINE
EncryptionDisabled: false
Name: pets-api
Packaging: NONE
Cache:
Type: NO_CACHE
BadgeEnabled: false
ConcurrentBuildLimit: 1
Description: pets api codebuild
Environment:
ComputeType: BUILD_GENERAL1_SMALL
EnvironmentVariables:
- Name: ACCOUNT_ID
Type: PLAINTEXT
Value: !Ref AWS::AccountId
- Name: REGION
Type: PLAINTEXT
Value: !Ref AWS::Region
- Name: REPOSITORY_NAME
Type: PLAINTEXT
Value: !FindInMap [NameConfig, ECRRepository, Name]
- Name: CONTAINER_NAME
Type: PLAINTEXT
Value: !FindInMap [NameConfig, Container, Name]
- Name: DOCKERHUB_USERNAME
Type: SECRETS_MANAGER
Value: !Join [':', [!FindInMap [NameConfig, DockerHubSecret, Name], username]]
- Name: DOCKERHUB_PASSWORD
Type: SECRETS_MANAGER
Value: !Join [':', [!FindInMap [NameConfig, DockerHubSecret, Name], password]]
- Name: DB_HOST
Type: SECRETS_MANAGER
Value: !Join [':', [!FindInMap [NameConfig, DatabaseSecret, Name], host]]
- Name: DB_PORT
Type: SECRETS_MANAGER
Value: !Join [':', [!FindInMap [NameConfig, DatabaseSecret, Name], port]]
- Name: DB_NAME
Type: SECRETS_MANAGER
Value: !Join [':', [!FindInMap [NameConfig, DatabaseSecret, Name], dbname]]
- Name: DB_USERNAME
Type: SECRETS_MANAGER
Value: !Join [':', [!FindInMap [NameConfig, DatabaseSecret, Name], username]]
- Name: DB_PASSWORD
Type: SECRETS_MANAGER
Value: !Join [':', [!FindInMap [NameConfig, DatabaseSecret, Name], password]]
Image: aws/codebuild/standard:5.0
ImagePullCredentialsType: CODEBUILD
PrivilegedMode: true
Type: LINUX_CONTAINER
LogsConfig:
CloudWatchLogs:
GroupName: !FindInMap [NameConfig, CodeBuildLogGroup, Name]
Status: ENABLED
StreamName: pets-api
S3Logs:
Status: DISABLED
Name: !FindInMap [NameConfig, CodeBuildProject, Name]
QueuedTimeoutInMinutes: 480
ServiceRole: !GetAtt CodeBuildRole.Arn
Source:
Type: CODEPIPELINE
TimeoutInMinutes: 60
VpcConfig:
SecurityGroupIds:
- !Ref CodeBuildSecurityGroup
Subnets:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
VpcId: !Ref VPC
################################### S3 ###################################
OpenAPIBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub pets-api-open-api-${AWS::Region}
################################### CODE PIPELINE ###################################
CodePipelineServiceRole:
Type: AWS::IAM::Role
Properties:
RoleName: PetsAPI-CodePipelineServiceRole
Description: PetsAPI-CodePipelineServiceRole
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: codepipeline.amazonaws.com
Action: sts:AssumeRole
CodePipelinePolicy:
Type: AWS::IAM::Policy
Properties:
PolicyName: PetsAPI-CodePipelinePolicy
Roles:
- !Ref CodePipelineServiceRole
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Resource: '*'
Action:
- iam:PassRole
Condition:
StringEqualsIfExists:
iam:PassedToService:
- cloudformation.amazonaws.com
- elasticbeanstalk.amazonaws.com
- ec2.amazonaws.com
- ecs-tasks.amazonaws.com
- Effect: Allow
Resource: '*'
Action:
- codecommit:CancelUploadArchive
- codecommit:GetBranch
- codecommit:GetCommit
- codecommit:GetRepository
- codecommit:GetUploadArchiveStatus
- codecommit:UploadArchive
- Effect: Allow
Resource: '*'
Action:
- codedeploy:CreateDeployment
- codedeploy:GetApplication
- codedeploy:GetApplicationRevision
- codedeploy:GetDeployment
- codedeploy:GetDeploymentConfig
- codedeploy:RegisterApplicationRevision
- Effect: Allow
Resource:
- !Sub arn:aws:codestar-connections:${AWS::Region}:${AWS::AccountId}:connection/${CodestarConnectionId}
Action:
- codestar-connections:UseConnection
- Effect: Allow
Resource: '*'
Action:
- elasticbeanstalk:*
- ec2:*
- elasticloadbalancing:*
- autoscaling:*
- cloudwatch:*
- s3:*
- sns:*