-
Notifications
You must be signed in to change notification settings - Fork 6
/
Twelve-Factor-App-Stack.yml
1337 lines (1336 loc) · 42.3 KB
/
Twelve-Factor-App-Stack.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: AWS ECS Fargate cluster running a Twelve Factor app in the private subnet
Parameters:
BranchName:
Description: CodeCommit branch name
Type: String
Default: main
SourceCodeS3BucketPrefix:
Description: Source Code Bucket Prefix
Type: String
Default: source-code-bucket-12fa
GitHubHost:
Description: GitHub Source Host
Type: String
Default: codeload.github.com
GitHubPath:
Description: GitHub Source Path
Type: String
Default: /aws-samples/twelve-factor-app-ecs-blog/zip/main
S3SourcePath:
Description: S3 source zip path
Type: String
Default: /Source.zip
RepositoryName:
Description: CodeCommit repository name
Type: String
Default: twelve-factor-app
SourceZipKey:
Description: Source Zip Key
Type: String
Default: Source.zip
EnvironmentName:
Type: String
Default: Prod
Description: "Environment name"
ECRRepositoryName:
Type: String
Default: "twelvefactor-app-main-repo"
Description: "Name of the ECR repository."
ECSServiceName:
Type: String
Default: twelve-factor-app-service
Description: A name for the service
ECSClusterName:
Type: String
Default: twelve-factor-app
Description: A name for the cluster
ProjectName:
Type: String
Description: The name of the project.
Default: twelve-factor-app
ContainerPort:
Type: Number
Default: 80
Description: The port number the application inside the docker container binds to
ContainerCpu:
Type: Number
Default: 256
ContainerMemory:
Type: Number
Default: 512
Description: Container Memory
TableName:
Type: String
Default: TwelveFactorDatastore
Description: "DynamoDB table name"
Path:
Type: String
Default: "*"
Description: asterisk will send all load balancer traffic to this service.
HealthCheckPath:
Type: String
Default: "/"
Description: The path on the service the Healthcheck will check for HTTP 200
Priority:
Type: Number
Default: 1
Description: The priority for the routing rule
DesiredCount:
Type: Number
Default: 2
Description: Number of copies of the task to run
MaximumPercent:
Type: Number
Default: 200
Description: Upper limit on the number of tasks in a service that are allowed in the RUNNING or PENDING state during a deployment, as a percentage of the desired number of tasks
MinimumHealthyPercent:
Type: Number
Default: 75
Description: Lower limit on the number of tasks in a service that must remain in the RUNNING state during a deployment, as a percentage of the desired number of tasks
ConfigApp:
Type: String
Default: TwelveFactorApplication
Description: Name of the AppConfig Application
ConfigProfile:
Type: String
Default: ConfigProfile
Description: Name of the AppConfig Profile
ConfigClient:
Type: String
Default: TwelveFactorAppClient
Description: Name of the AppConfig Client
Conditions:
NeedsStaging: !Equals
- !Ref EnvironmentName
- Prod
Mappings:
SubnetCIDRBlocks:
VPC:
CIDR: "10.0.0.0/16"
PrivateSubnet1:
CIDR: "10.0.0.0/24"
PrivateSubnet2:
CIDR: "10.0.1.0/24"
PublicSubnet1:
CIDR: "10.0.2.0/24"
PublicSubnet2:
CIDR: "10.0.3.0/24"
Resources:
TwelveFactorAppVPC:
Type: AWS::EC2::VPC
Properties:
EnableDnsSupport: true
EnableDnsHostnames: true
CidrBlock: !FindInMap ["SubnetCIDRBlocks", "VPC", "CIDR"]
Tags:
- Key: Name
Value: TwelveFactorAppVPC
PrivateSubnet1:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone:
Fn::Select:
- 0
- Fn::GetAZs: { Ref: "AWS::Region" }
VpcId: !Ref TwelveFactorAppVPC
CidrBlock: !FindInMap ["SubnetCIDRBlocks", "PrivateSubnet1", "CIDR"]
MapPublicIpOnLaunch: false
Tags:
- Key: Name
Value: TwelveFactorAppPrivateSubnet1
PrivateSubnet2:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone:
Fn::Select:
- 1
- Fn::GetAZs: { Ref: "AWS::Region" }
VpcId: !Ref TwelveFactorAppVPC
CidrBlock: !FindInMap ["SubnetCIDRBlocks", "PrivateSubnet2", "CIDR"]
MapPublicIpOnLaunch: false
Tags:
- Key: Name
Value: TwelveFactorAppPrivateSubnet2
PublicSubnet1:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone:
Fn::Select:
- 0
- Fn::GetAZs: { Ref: "AWS::Region" }
VpcId: !Ref TwelveFactorAppVPC
CidrBlock: !FindInMap ["SubnetCIDRBlocks", "PublicSubnet1", "CIDR"]
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: TwelveFactorAppPublicSubnet1
PublicSubnet2:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone:
Fn::Select:
- 1
- Fn::GetAZs: { Ref: "AWS::Region" }
VpcId: !Ref TwelveFactorAppVPC
CidrBlock: !FindInMap ["SubnetCIDRBlocks", "PublicSubnet2", "CIDR"]
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: TwelveFactorAppPublicSubnet2
InternetGateway:
Type: AWS::EC2::InternetGateway
Properties:
Tags:
- Key: Name
Value: TwelveFactorAppIGW
IGWAttachment:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref TwelveFactorAppVPC
InternetGatewayId: !Ref InternetGateway
NAT1:
Type: AWS::EC2::NatGateway
Properties:
AllocationId:
Fn::GetAtt:
- NATEIP1
- AllocationId
SubnetId:
Ref: PublicSubnet1
Tags:
- Key: Name
Value: TwelveFactorAppNatGateway1
NATEIP1:
DependsOn: IGWAttachment
Type: AWS::EC2::EIP
Properties:
Domain: vpc
NATGWRoute1:
Type: AWS::EC2::Route
Properties:
RouteTableId:
Ref: PrivateRouteTable1
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId:
Ref: NAT1
NAT2:
Type: AWS::EC2::NatGateway
Properties:
AllocationId:
Fn::GetAtt:
- NATEIP2
- AllocationId
SubnetId:
Ref: PublicSubnet2
Tags:
- Key: Name
Value: TwelveFactorAppNatGateway2
NATEIP2:
DependsOn: IGWAttachment
Type: AWS::EC2::EIP
Properties:
Domain: vpc
NATGWRoute2:
Type: AWS::EC2::Route
Properties:
RouteTableId:
Ref: PrivateRouteTable2
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId:
Ref: NAT2
PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref TwelveFactorAppVPC
Tags:
- Key: Name
Value: TwelveFactorAppPublicRouteTable
PublicRoute:
Type: AWS::EC2::Route
DependsOn: IGWAttachment
Properties:
RouteTableId: !Ref PublicRouteTable
DestinationCidrBlock: "0.0.0.0/0"
GatewayId: !Ref InternetGateway
PublicSubnet1RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PublicSubnet1
RouteTableId: !Ref PublicRouteTable
PublicSubnet2RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PublicSubnet2
RouteTableId: !Ref PublicRouteTable
PrivateRouteTable1:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref TwelveFactorAppVPC
PrivateRouteTable2:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref TwelveFactorAppVPC
PrivateSubnet1RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PrivateSubnet1
RouteTableId: !Ref PrivateRouteTable1
PrivateSubnet2RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
SubnetId: !Ref PrivateSubnet2
RouteTableId: !Ref PrivateRouteTable2
ECRRepository:
Type: AWS::ECR::Repository
Properties:
RepositoryName: !Ref ECRRepositoryName
ECSCluster:
Type: AWS::ECS::Cluster
Properties:
ClusterName: !Sub ${ECSClusterName}-${EnvironmentName}
ContainerSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Container Security Group
VpcId: !Ref TwelveFactorAppVPC
ECSTaskRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: [ecs-tasks.amazonaws.com]
Action: ["sts:AssumeRole"]
Path: /
Policies:
- PolicyName: ecs-service
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "ec2:AttachNetworkInterface"
- "ec2:CreateNetworkInterface"
- "ec2:CreateNetworkInterfacePermission"
- "ec2:DeleteNetworkInterface"
- "ec2:DeleteNetworkInterfacePermission"
- "ec2:Describe*"
- "ec2:DetachNetworkInterface"
- "elasticloadbalancing:DeregisterInstancesFromLoadBalancer"
- "elasticloadbalancing:DeregisterTargets"
- "elasticloadbalancing:Describe*"
- "elasticloadbalancing:RegisterInstancesWithLoadBalancer"
- "elasticloadbalancing:RegisterTargets"
- "appconfig:GetEnvironment"
- "appconfig:GetHostedConfigurationVersion"
- "appconfig:GetConfiguration"
- "appconfig:GetApplication"
- "appconfig:GetConfigurationProfile"
- "dynamodb:DescribeTable"
- "dynamodb:Query"
- "dynamodb:Scan"
- "dynamodb:GetItem"
- "dynamodb:CreateBackup"
Resource: "*"
ECSTaskExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: [ecs-tasks.amazonaws.com]
Action: ["sts:AssumeRole"]
Path: /
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
EcsSecurityGroupIngressFromPublicALB:
Type: AWS::EC2::SecurityGroupIngress
Properties:
Description: Ingress from the public ALB
GroupId: !Ref ContainerSecurityGroup
IpProtocol: tcp
SourceSecurityGroupId: !Ref ECSPublicLoadBalancerSG
FromPort: 80
ToPort: 80
ECSPublicLoadBalancerSG:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Access to the public facing load balancer
VpcId: !Ref TwelveFactorAppVPC
SecurityGroupIngress:
- CidrIp: 0.0.0.0/0
IpProtocol: tcp
FromPort: 80
ToPort: 80
ECSPublicLoadBalancer:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Properties:
Scheme: internet-facing
LoadBalancerAttributes:
- Key: idle_timeout.timeout_seconds
Value: "30"
Subnets:
- !Ref PublicSubnet1
- !Ref PublicSubnet2
SecurityGroups: [!Ref ECSPublicLoadBalancerSG]
Tags:
- Key: "Name"
Value: !Sub ${ECSServiceName}:LB
DummyTargetGroupPublic:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
HealthCheckIntervalSeconds: 6
HealthCheckPath: /
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 5
HealthyThresholdCount: 2
Port: 80
Protocol: HTTP
UnhealthyThresholdCount: 2
VpcId: !Ref TwelveFactorAppVPC
ECSPublicLoadBalancerListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
DefaultActions:
- TargetGroupArn: !Ref DummyTargetGroupPublic
Type: "forward"
LoadBalancerArn: !Ref "ECSPublicLoadBalancer"
Port: 80
Protocol: HTTP
TwelveFactorAppCWLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub TwelveFactorApp-service-${ECSServiceName}
ECSTaskDefinition:
DependsOn: ECRRepository
Type: AWS::ECS::TaskDefinition
Properties:
Family: !Ref ECSServiceName
Cpu: !Ref ContainerCpu
Memory: !Ref ContainerMemory
NetworkMode: awsvpc
RequiresCompatibilities:
- FARGATE
ExecutionRoleArn: !GetAtt "ECSTaskExecutionRole.Arn"
TaskRoleArn: !GetAtt "ECSTaskRole.Arn"
ContainerDefinitions:
- Name: !Ref ECSServiceName
Cpu: !Ref ContainerCpu
Memory: !Ref ContainerMemory
Image: !Sub "${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${ECRRepositoryName}"
PortMappings:
- ContainerPort: !Ref ContainerPort
LogConfiguration:
LogDriver: "awslogs"
Options:
awslogs-group: !Sub TwelveFactorApp-service-${ECSServiceName}
awslogs-region: !Ref AWS::Region
awslogs-stream-prefix: !Ref ECSClusterName
Environment:
- Name: AWS_DEFAULT_REGION
Value: !Sub ${AWS::Region}
- Name: ConfigApp
Value: !Ref ConfigApp
- Name: ConfigEnv
Value: !Ref EnvironmentName
- Name: ConfigProfile
Value: !Ref ConfigProfile
- Name: ConfigClient
Value: !Ref ConfigClient
ECSService:
Type: AWS::ECS::Service
DependsOn: [LoadBalancerRule, CodeCommitRepo]
Properties:
ServiceName: !Ref "ECSServiceName"
Cluster: !Ref 'ECSCluster'
LaunchType: FARGATE
DeploymentConfiguration:
MaximumPercent: 200
MinimumHealthyPercent: 75
DesiredCount: 2
NetworkConfiguration:
AwsvpcConfiguration:
AssignPublicIp: ENABLED
SecurityGroups: [!Ref 'ContainerSecurityGroup']
Subnets:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
TaskDefinition: !Ref "ECSTaskDefinition"
LoadBalancers:
- ContainerName: !Ref "ECSServiceName"
ContainerPort: 80
TargetGroupArn: !Ref "ECSServiceTargetGroup"
ECSServiceTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
HealthCheckIntervalSeconds: 12
HealthCheckPath: !Ref HealthCheckPath
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 10
HealthyThresholdCount: 2
TargetType: ip
Name: !Ref "ECSServiceName"
Port: !Ref "ContainerPort"
Protocol: HTTP
UnhealthyThresholdCount: 2
VpcId: !Ref TwelveFactorAppVPC
LoadBalancerRule:
Type: AWS::ElasticLoadBalancingV2::ListenerRule
Properties:
Actions:
- TargetGroupArn: !Ref ECSServiceTargetGroup
Type: "forward"
Conditions:
- Field: path-pattern
Values: [!Ref Path]
ListenerArn: !Ref ECSPublicLoadBalancerListener
Priority: !Ref Priority
ECSClusterStaging:
Type: AWS::ECS::Cluster
Condition: NeedsStaging
Properties:
ClusterName: !Sub ${ECSClusterName}-Staging
ECSPublicLoadBalancerStaging:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Condition: NeedsStaging
Properties:
Scheme: internet-facing
LoadBalancerAttributes:
- Key: idle_timeout.timeout_seconds
Value: "30"
Subnets:
- !Ref PublicSubnet1
- !Ref PublicSubnet2
SecurityGroups: [!Ref ECSPublicLoadBalancerSG]
Tags:
- Key: "Name"
Value: !Sub ${ECSServiceName}-Staging:LB
DummyTargetGroupPublicStaging:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Condition: NeedsStaging
DependsOn: ECSPublicLoadBalancerStaging
Properties:
HealthCheckIntervalSeconds: 6
HealthCheckPath: /
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 5
HealthyThresholdCount: 2
Port: 80
Protocol: HTTP
UnhealthyThresholdCount: 2
VpcId: !Ref TwelveFactorAppVPC
ECSPublicLoadBalancerListenerStaging:
Type: AWS::ElasticLoadBalancingV2::Listener
Condition: NeedsStaging
Properties:
DefaultActions:
- TargetGroupArn: !Ref DummyTargetGroupPublicStaging
Type: "forward"
LoadBalancerArn: !Ref "ECSPublicLoadBalancerStaging"
Port: 80
Protocol: HTTP
ECSTaskDefinitionStaging:
DependsOn: ECRRepository
Condition: NeedsStaging
Type: AWS::ECS::TaskDefinition
Properties:
Family: !Sub ${ECSServiceName}-Staging
Cpu: !Ref ContainerCpu
Memory: !Ref ContainerMemory
NetworkMode: awsvpc
RequiresCompatibilities:
- FARGATE
ExecutionRoleArn: !GetAtt "ECSTaskExecutionRole.Arn"
TaskRoleArn: !GetAtt "ECSTaskRole.Arn"
ContainerDefinitions:
- Name: !Ref ECSServiceName
Cpu: !Ref ContainerCpu
Memory: !Ref ContainerMemory
Image: !Sub "${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${ECRRepositoryName}"
PortMappings:
- ContainerPort: !Ref ContainerPort
LogConfiguration:
LogDriver: "awslogs"
Options:
awslogs-group: !Sub TwelveFactorApp-service-${ECSServiceName}
awslogs-region: !Ref AWS::Region
awslogs-stream-prefix: !Sub ${ECSClusterName}-Staging
Environment:
- Name: AWS_DEFAULT_REGION
Value: !Sub ${AWS::Region}
- Name: ConfigApp
Value: !Ref ConfigApp
- Name: ConfigEnv
Value: !Ref EnvironmentName
- Name: ConfigProfile
Value: !Ref ConfigProfile
- Name: ConfigClient
Value: !Ref ConfigClient
ECSServiceStaging:
Type: AWS::ECS::Service
Condition: NeedsStaging
DependsOn: [StagingLoadBalancerRule, CodeCommitRepo]
Properties:
ServiceName: !Sub ${ECSServiceName}-Staging
Cluster: !Ref 'ECSClusterStaging'
LaunchType: FARGATE
DeploymentConfiguration:
MaximumPercent: 200
MinimumHealthyPercent: 75
DesiredCount: 2
NetworkConfiguration:
AwsvpcConfiguration:
AssignPublicIp: ENABLED
SecurityGroups: [!Ref 'ContainerSecurityGroup']
Subnets:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
TaskDefinition: !Ref "ECSTaskDefinitionStaging"
LoadBalancers:
- ContainerName: !Ref ECSServiceName
ContainerPort: 80
TargetGroupArn: !Ref "StagingECSServiceTargetGroup"
StagingECSServiceTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Condition: NeedsStaging
DependsOn: ECSPublicLoadBalancerStaging
Properties:
HealthCheckIntervalSeconds: 12
HealthCheckPath: !Ref HealthCheckPath
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 10
HealthyThresholdCount: 2
TargetType: ip
Name: !Sub ${ECSServiceName}-Stg
Port: !Ref "ContainerPort"
Protocol: HTTP
UnhealthyThresholdCount: 2
VpcId: !Ref TwelveFactorAppVPC
StagingLoadBalancerRule:
Type: AWS::ElasticLoadBalancingV2::ListenerRule
Condition: NeedsStaging
Properties:
Actions:
- TargetGroupArn: !Ref StagingECSServiceTargetGroup
Type: "forward"
Conditions:
- Field: path-pattern
Values: [!Ref Path]
ListenerArn: !Ref ECSPublicLoadBalancerListenerStaging
Priority: !Ref Priority
SourceCodeBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Join
- "-"
- - !Ref SourceCodeS3BucketPrefix
- !Select
- 0
- !Split
- "-"
- !Select
- 2
- !Split
- "/"
- !Ref "AWS::StackId"
S3InitLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: s3AccessRole
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- s3:*
Resource: !Sub arn:aws:s3:::${SourceCodeS3BucketPrefix}*/*
- Effect: Allow
Action:
- logs:*
Resource: "*"
S3InitFunction:
Type: AWS::Lambda::Function
DependsOn:
- S3InitLambdaRole
Properties:
Code:
ZipFile: >
const AWS = require("aws-sdk");
const cfnResponse = require("cfn-response");
const stream = require('stream');
const s3 = new AWS.S3();
exports.handler = function(event, context) {
var options = {
host: event.ResourceProperties.GitHubHost,
path: event.ResourceProperties.GitHubPath,
method: 'GET',
headers: {'user-agent': 'node.js'}
};
const https = require('https');
https.get(options, async function(response) {
const { writeStream, manager } = uploadStream({ Bucket: event.ResourceProperties.SourceCodeBucket, Key: event.ResourceProperties.SourceZipKey });
response.pipe(writeStream);
try{
const results = await manager.promise();
cfnResponse.send(event, context, "SUCCESS", {});
}catch(err){
console.log(err);
cfnResponse.send(event, context, "FAILED", {});
}
}).on('error', function(e) {
cfnResponse.send(event, context, "FAILED", {});
});
};
const uploadStream = ({ Bucket, Key }) => {
const s3 = new AWS.S3();
const pass = new stream.PassThrough();
return {
writeStream: pass,
manager: s3.upload({ Bucket, Key, Body: pass })
};
}
Handler: index.handler
Role:
Fn::GetAtt: [ S3InitLambdaRole , "Arn" ]
Runtime: nodejs12.x
Timeout: 60
InitializeS3Bucket:
Type: Custom::InitFunction
DependsOn: SourceCodeBucket
Properties:
ServiceToken:
Fn::GetAtt: [ S3InitFunction , "Arn" ]
SourceCodeBucket: !Ref SourceCodeBucket
GitHubHost: !Ref GitHubHost
GitHubPath: !Ref GitHubPath
SourceZipKey: !Ref SourceZipKey
CodeCommitRepo:
Type: AWS::CodeCommit::Repository
DependsOn: InitializeS3Bucket
Properties:
RepositoryName: !Ref RepositoryName
RepositoryDescription: This is a repository for my project with code from MySourceCodeBucket.
Code:
BranchName: !Ref BranchName
S3:
Bucket: !Ref SourceCodeBucket
Key: !Ref SourceZipKey
CodePipelineArtifactStoreBucket:
Type: 'AWS::S3::Bucket'
CodePipelineArtifactStoreBucketPolicy:
Type: 'AWS::S3::BucketPolicy'
Properties:
Bucket: !Ref CodePipelineArtifactStoreBucket
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: DenyUnEncryptedObjectUploads
Effect: Deny
Principal: '*'
Action: 's3:PutObject'
Resource: !Join
- ''
- - !GetAtt
- CodePipelineArtifactStoreBucket
- Arn
- /*
Condition:
StringNotEquals:
's3:x-amz-server-side-encryption': 'aws:kms'
- Sid: DenyInsecureConnections
Effect: Deny
Principal: '*'
Action: 's3:*'
Resource: !Join
- ''
- - !GetAtt
- CodePipelineArtifactStoreBucket
- Arn
- /*
Condition:
Bool:
'aws:SecureTransport': false
AppPipelineCloudWatchEventRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- events.amazonaws.com
Action: 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: cwe-pipeline-execution
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: 'codepipeline:StartPipelineExecution'
Resource: !Join
- ''
- - 'arn:aws:codepipeline:'
- !Ref 'AWS::Region'
- ':'
- !Ref 'AWS::AccountId'
- ':'
- !Ref AppPipeline
AppPipelineCloudWatchEventRule:
Type: 'AWS::Events::Rule'
DependsOn: ECSService
Properties:
EventPattern:
source:
- aws.codecommit
detail-type:
- CodeCommit Repository State Change
resources:
- !Join
- ''
- - 'arn:aws:codecommit:'
- !Ref 'AWS::Region'
- ':'
- !Ref 'AWS::AccountId'
- ':'
- !Ref RepositoryName
detail:
event:
- referenceCreated
- referenceUpdated
referenceType:
- branch
referenceName:
- main
Targets:
- Arn: !Join
- ''
- - 'arn:aws:codepipeline:'
- !Ref 'AWS::Region'
- ':'
- !Ref 'AWS::AccountId'
- ':'
- !Ref AppPipeline
RoleArn: !GetAtt
- AppPipelineCloudWatchEventRole
- Arn
Id: codepipeline-AppPipeline
AppPipeline:
Type: 'AWS::CodePipeline::Pipeline'
DependsOn: CodeCommitRepo
Properties:
Name: !Sub Twelve-Factor-App-Pipeline
RoleArn: !GetAtt
- CodePipelineServiceRole
- Arn
Stages:
- Name: Source
Actions:
- Name: SourceAction
ActionTypeId:
Category: Source
Owner: AWS
Version: 1
Provider: CodeCommit
OutputArtifacts:
- Name: SourceOutput
Configuration:
BranchName: !Ref BranchName
RepositoryName: !Ref RepositoryName
PollForSourceChanges: false
RunOrder: 1
- Name: Build
Actions:
- Name: Build
ActionTypeId:
Category: Build
Owner: AWS
Provider: CodeBuild
Version: 1
Configuration:
ProjectName: !Ref CodeBuildProject
InputArtifacts:
- Name: SourceOutput
OutputArtifacts:
- Name: BuildOutput
- !If
- NeedsStaging
- Name: Staging_Deploy
Actions:
- Name: Staging_Deploy
ActionTypeId:
Category: Deploy
Owner: AWS
Version: 1
Provider: ECS
Configuration:
ClusterName: !Sub ${ECSClusterName}-Staging
ServiceName: !Sub ${ECSServiceName}-Staging
FileName: images.json
InputArtifacts:
- Name: BuildOutput
RunOrder: 1
- !Ref "AWS::NoValue"
- !If
- NeedsStaging
- Name: Deployment_Approval
Actions:
- Name: Deployment_Approval
ActionTypeId:
Category: Approval
Owner: AWS
Provider: Manual
Version: '1'
InputArtifacts: []
RunOrder: 1
- !Ref "AWS::NoValue"
- Name: Deploy
Actions:
- Name: Deploy
ActionTypeId:
Category: Deploy
Owner: AWS
Version: 1
Provider: ECS
Configuration:
ClusterName: !Sub ${ECSClusterName}-${EnvironmentName}
ServiceName: !Ref ECSServiceName
FileName: images.json
InputArtifacts:
- Name: BuildOutput
RunOrder: 1
ArtifactStore:
Type: S3
Location: !Ref CodePipelineArtifactStoreBucket
CodePipelineServiceRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- codepipeline.amazonaws.com
Action: 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: AWS-CodePipeline-Service-3
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'codecommit:CancelUploadArchive'
- 'codecommit:GetBranch'
- 'codecommit:GetCommit'
- 'codecommit:GetUploadArchiveStatus'
- 'codecommit:UploadArchive'
Resource: '*'
- Effect: Allow
Action:
- 'codedeploy:CreateDeployment'
- 'codedeploy:GetApplicationRevision'
- 'codedeploy:GetDeployment'
- 'codedeploy:GetDeploymentConfig'
- 'codedeploy:RegisterApplicationRevision'
Resource: '*'
- Effect: Allow
Action:
- 'codebuild:BatchGetBuilds'
- 'codebuild:StartBuild'
Resource: '*'
- Effect: Allow
Action:
- 'devicefarm:ListProjects'
- 'devicefarm:ListDevicePools'
- 'devicefarm:GetRun'
- 'devicefarm:GetUpload'
- 'devicefarm:CreateUpload'
- 'devicefarm:ScheduleRun'
Resource: '*'
- Effect: Allow
Action:
- 'lambda:InvokeFunction'
- 'lambda:ListFunctions'
Resource: '*'
- Effect: Allow
Action:
- 'iam:PassRole'
Resource: '*'
- Effect: Allow
Action:
- 'elasticbeanstalk:*'
- 'ec2:*'
- 'elasticloadbalancing:*'
- 'autoscaling:*'
- 'cloudwatch:*'
- 's3:*'
- 'sns:*'
- 'cloudformation:*'
- 'rds:*'
- 'sqs:*'
- 'ecs:*'
Resource: '*'
CodeBuildProject:
Type: AWS::CodeBuild::Project
DependsOn: ECRRepository
Properties:
Name: !Sub ${ProjectName}-Build-Package
Source:
Type: CODEPIPELINE
BuildSpec: twelve-factor-app-ecs-blog-main/buildspec.yaml
Artifacts:
Type: CODEPIPELINE
Cache: