forked from snyk/snyk-iac-cloudformation
-
Notifications
You must be signed in to change notification settings - Fork 3
/
fargate.yml
998 lines (910 loc) · 33.4 KB
/
fargate.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
---
AWSTemplateFormatVersion: 2010-09-09
# A CloudFormation template to create/configure an AWS Fargate Cluster, Application Load Balancer (ALB),
# Amazon Elastic Container Registry (ECR), AWS CodePipeline and Service based on parameters. Optionally,
# you can specify a domain name and/or an AWS Certificate Manager ARN can be passed if you want to
# enable TLS on the ALB. If you want to create the DNS alias to the ALB, your DNS must be hosted in
# Amazon Route 53.
#
# From the Startup Kit Templates, this template requires the name of an existing vpc.cfn.yml stack as
# a parameter.
#
# If you pass the optional database stack name, it pulls the values for the DB endpoint and username
# and sets them as environment variables in the container.
#
# The service creates CloudWatch Alarms to monitor CPU utilization in order to determine container
# counts (up and down), but other metrics may be more important in your system.
# See: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service_autoscaling_tutorial.html
#
# This template is released under Apache Version 2.0, and can be forked, copied, modified,
# customized, etc. to match your application/system requirements.
Description: Fargate
Parameters:
NetworkStackName:
Type: String
Description: Name of an active Startup Kit CloudFormation stack that contains networking resources
MinLength: 1
MaxLength: 255
AllowedPattern: "^[a-zA-Z][-a-zA-Z0-9]*$"
DatabaseStackName:
Type: String
Description: Name of an optional active Startup Kit CloudFormation stack that contains database resources
Default: ""
HostedZoneName:
Type: String
Description: The Amazon Route 53 Hosted Zone Name for the optional load balancer alias record - do not include a period at the end
Default: ""
AllowedPattern: "(^$|^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$)" # Allow for a blank or a domain name
ConstraintDescription: Please enter a valid Route 53 Hosted Zone Name
LoadBalancerDomainName:
Type: String
Description: Domain name to create an Amazon Route 53 alias record for the load balancer
Default: ""
AllowedPattern: "(^$|^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$)" # Allow for a blank or a domain name
ConstraintDescription: Please enter a valid domain name
AppProtocol:
Type: String
Description: The application server protocol
Default: HTTP
AllowedValues:
- HTTP
- HTTPS
ConstraintDescription: Specify either HTTTP or HTTPS
SSLCertificateArn:
Type: String
Description: The SSL/TLS certificate ARN
MinLength: 0
MaxLength: 2048
Default: ""
HealthCheckPath:
Type: String
Description: The path for the Application Load Balancer health check
Default: /
MinLength: 1
MaxLength: 255
ConstraintDescription: Value must be between 1 and 255 characters
GitSourceRepo:
Type: String
Description: CodeCommit or GitHub source repository - must contain a Dockerfile in the base
GitBranch:
Type: String
Default: master
Description: CodeCommit or GitHub git repository branch - change triggers a new build
GitHubToken:
Type: String
NoEcho: true
Description: "GitHub API token - see: https://github.com/blog/1509-personal-api-tokens"
GitHubUser:
Type: String
Description: GitHub username or organization - leave blank if using CodeCommit
CodeBuildDockerImage:
Type: String
Default: aws/codebuild/docker:17.09.0
SeedDockerImage:
Type: String
Default: registry.hub.docker.com/library/nginx:1.13
Description: Initial image before CodePipeline is executed. Existing application images in ECR should override this parameter
DefaultContainerCpu:
Type: Number
Description: "Amount of CPU for the container - options available: https://aws.amazon.com/fargate/pricing/"
Default: 256
MinValue: 256
MaxValue: 4096
ConstraintDescription: "Value must be between 256 and 4096 - see: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#task_size"
DefaultContainerMemory:
Type: Number
Description: "Amount of memory for the container - options available: https://aws.amazon.com/fargate/pricing/"
Default: 512
MinValue: 512
MaxValue: 30720
ConstraintDescription: "Value must be between 512 and 30720 - see: https://aws.amazon.com/fargate/pricing/"
# Scaling params
DefaultServiceScaleEvaluationPeriods:
Description: The number of periods over which data is compared to the specified threshold
Type: Number
Default: 2
MinValue: 2
DefaultServiceCpuScaleOutThreshold:
Type: Number
Description: Average CPU value to trigger auto scaling out
Default: 50
MinValue: 0
MaxValue: 100
ConstraintDescription: Value must be between 0 and 100
DefaultServiceCpuScaleInThreshold:
Type: Number
Description: Average CPU value to trigger auto scaling in
Default: 25
MinValue: 0
MaxValue: 100
ConstraintDescription: Value must be between 0 and 100
DefaultTaskMinContainerCount:
Type: Number
Description: Minimum number of containers to run for the service
Default: 1
MinValue: 1
ConstraintDescription: Value must be at least one
DefaultTaskMaxContainerCount:
Type: Number
Description: Maximum number of containers to run for the service when auto scaling out
Default: 2
MinValue: 1
ConstraintDescription: Value must be at least one
ContainerLogRetentionInDays:
Type: Number
Default: 7
MaxTaggedContainerImagesToRetain:
Type: Number
Description: The number of tagged container images to retain before expiring
MinValue: 1
MaxValue: 100
ConstraintDescription: Value must be between 1 and 100
Default: 20
DaysToRetainUntaggedContainerImages:
Type: Number
Description: The number days to retain untagged container images before expiring
MinValue: 1
MaxValue: 100
ConstraintDescription: Value must be between 1 and 100
Default: 7
EnvironmentName:
Type: String
Description: Environment name - dev or prod
Default: dev
AllowedValues:
- dev
- prod
ConstraintDescription: Specify either dev or prod
LoadBalancerAlarmEvaluationPeriods:
Description: The number of periods over which data is compared to the specified threshold
Type: Number
Default: 2
MinValue: 2
ConstraintDescription: Must be at least two
LoadBalancerAlarmEvaluationPeriodSeconds:
Description: The time over which the specified statistic is applied. Specify time in seconds, in multiples of 60.
Type: Number
Default: 300
MinValue: 60
ConstraintDescription: Must be at least 60 seconds
LoadBalancerLatencySeconds:
Description: LoadBalancer latency threshold, in seconds
Type: Number
Default: 2
MinValue: 1
ConstraintDescription: Must be at least one second
EnableLBAlarm:
Description: Set to true to enable load balancer latency alarm
Type: String
ConstraintDescription: Value must be true or false
Default: false
AllowedValues:
- true
- false
Conditions:
IsTlsEnabled: !Not [ !Equals [ !Ref SSLCertificateArn, "" ] ]
IsDbStackSet: !Not [ !Equals [ !Ref DatabaseStackName, "" ] ]
CreateRoute53Record: !And
- !Not [ !Equals [ !Ref LoadBalancerDomainName, "" ] ]
- !Not [ !Equals [ !Ref HostedZoneName, "" ] ]
IsGitHub: !And
- !Not [ !Equals [ !Ref GitHubToken, "" ] ]
- !Not [ !Equals [ !Ref GitHubUser, "" ] ]
IsCodeCommit: !Not [ Condition: IsGitHub ]
IsLBAlarmEnabled: !Equals [ !Ref EnableLBAlarm, true ]
Resources:
DefaultContainerBucket:
Type: AWS::S3::Bucket
CodePipelineArtifactBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Delete
CodeBuildServiceRole:
Type: AWS::IAM::Role
Properties:
Path: /
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: codebuild.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: root
PolicyDocument:
Version: 2012-10-17
Statement:
- Resource: "*"
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- ecr:GetAuthorizationToken
- Resource: "*"
Effect: Allow
Action:
- ec2:CreateNetworkInterface
- ec2:DescribeDhcpOptions
- ec2:DescribeNetworkInterfaces
- ec2:DeleteNetworkInterface
- ec2:DescribeSubnets
- ec2:DescribeSecurityGroups
- ec2:DescribeVpcs
- ec2:CreateNetworkInterfacePermission
- Resource: !Sub arn:aws:s3:::${CodePipelineArtifactBucket}/*
Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
- s3:GetObjectVersion
- Resource: !Sub arn:aws:ecr:${AWS::Region}:${AWS::AccountId}:repository/${EcrDockerRepository}
Effect: Allow
Action:
- ecr:GetDownloadUrlForLayer
- ecr:BatchGetImage
- ecr:BatchCheckLayerAvailability
- ecr:PutImage
- ecr:InitiateLayerUpload
- ecr:UploadLayerPart
- ecr:CompleteLayerUpload
# By default, the build specification is defined in this template, but you can also add buildspec.yml
# files in your repos to allow for customization.
# See:
# https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html
CodeBuildProject:
Type: AWS::CodeBuild::Project
Properties:
Artifacts:
Type: CODEPIPELINE
Source:
Type: CODEPIPELINE
BuildSpec: !Sub
- |
---
version: 0.2
phases:
install:
commands:
- apt-get update && apt-get -y install python-pip && pip install --upgrade python && pip install --upgrade awscli
pre_build:
commands:
- printenv
- TAG="$REPOSITORY_NAME.$REPOSITORY_BRANCH.$ENVIRONMENT_NAME.$(date +%Y-%m-%d.%H.%M.%S).$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | head -c 8)"
- $(aws ecr get-login --no-include-email)
build:
commands:
- docker build --tag $REPOSITORY_URI:$TAG .
post_build:
commands:
- docker push $REPOSITORY_URI:$TAG
- printf '[{"name":"${ServiceName}","imageUri":"%s"}]' $REPOSITORY_URI:$TAG > build.json
artifacts:
files: build.json
- ServiceName: !Ref GitSourceRepo
Environment:
ComputeType: BUILD_GENERAL1_SMALL
Type: LINUX_CONTAINER
Image: !Ref CodeBuildDockerImage
EnvironmentVariables:
- Name: REPOSITORY_URI
Value: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${EcrDockerRepository}
- Name: ENVIRONMENT_NAME
Value: !Ref EnvironmentName
- Name: REPOSITORY_NAME
Value: !Ref GitSourceRepo
- Name: REPOSITORY_BRANCH
Value: !Ref GitBranch
Name: !Ref AWS::StackName
ServiceRole: !Ref CodeBuildServiceRole
VpcConfig:
VpcId:
Fn::ImportValue: !Sub ${NetworkStackName}-VpcID
Subnets:
- Fn::ImportValue: !Sub ${NetworkStackName}-PrivateSubnet1ID
- Fn::ImportValue: !Sub ${NetworkStackName}-PrivateSubnet2ID
SecurityGroupIds:
- Fn::ImportValue: !Sub ${NetworkStackName}-AppSecurityGroupID
CodePipelineServiceRole:
Type: AWS::IAM::Role
Properties:
Path: /
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: codepipeline.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: codepipeline-access
PolicyDocument:
Version: 2012-10-17
Statement:
- Resource: "*"
Effect: Allow
Action:
- ecs:List*
- ecs:Describe*
- ecs:RegisterTaskDefinition
- ecs:UpdateService
- codebuild:StartBuild
- codebuild:BatchGetBuilds
- codecommit:GetBranch
- codecommit:GetCommit
- codecommit:UploadArchive
- codecommit:GetUploadArchiveStatus
- codecommit:CancelUploadArchive
- iam:PassRole
- Resource: !Sub arn:aws:s3:::${CodePipelineArtifactBucket}/*
Effect: Allow
Action:
- s3:PutObject
- s3:GetObject
- s3:GetObjectVersion
- s3:GetBucketVersioning
DependsOn:
- CodePipelineArtifactBucket
- FargateEcsCluster
# This CodePipeline is used for CodeCommit repos. It triggers on a commit to the Git branch passed,
# builds the Docker image and then deploys the container in the Fargate Cluster. CodePipeline can support N stages.
# For example, you may want to add a stage to test your build and/or container.
CodePipelineCodeCommit:
Type: AWS::CodePipeline::Pipeline
Condition: IsCodeCommit
Properties:
RoleArn: !GetAtt CodePipelineServiceRole.Arn
ArtifactStore:
Type: S3
Location: !Ref CodePipelineArtifactBucket
Stages:
- Name: Source
Actions:
- Name: App
ActionTypeId:
Category: Source
Owner: AWS
Version: 1
Provider: CodeCommit
Configuration:
RepositoryName: !Ref GitSourceRepo
BranchName: !Ref GitBranch
OutputArtifacts:
- Name: App
RunOrder: 1
- Name: Build
Actions:
- Name: Build
ActionTypeId:
Category: Build
Owner: AWS
Version: 1
Provider: CodeBuild
Configuration:
ProjectName: !Ref CodeBuildProject
InputArtifacts:
- Name: App
OutputArtifacts:
- Name: BuildOutput
RunOrder: 1
- Name: Deploy
Actions:
- Name: Deploy
ActionTypeId:
Category: Deploy
Owner: AWS
Version: 1
Provider: ECS
Configuration:
ClusterName: !Ref FargateEcsCluster
ServiceName: !GetAtt DefaultFargateService.Name
FileName: build.json
InputArtifacts:
- Name: BuildOutput
RunOrder: 1
DependsOn:
- CodePipelineArtifactBucket
- CodeBuildProject
- CodePipelineServiceRole
- DefaultFargateService
# This CodePipeline is used for GitHub based repos. It triggers on a commit to the Git branch passed,
# builds the Docker image and then deploys the container in the Fargate Cluster. CodePipeline can support N stages.
# For example, you may want to add a stage to test your build and/or container.
CodePipelineGitHub:
Type: AWS::CodePipeline::Pipeline
Condition: IsGitHub
Properties:
RoleArn: !GetAtt CodePipelineServiceRole.Arn
ArtifactStore:
Type: S3
Location: !Ref CodePipelineArtifactBucket
Stages:
- Name: Source
Actions:
- Name: App
ActionTypeId:
Category: Source
Owner: ThirdParty
Version: 1
Provider: GitHub
Configuration:
Owner: !Ref GitHubUser
Repo: !Ref GitSourceRepo
Branch: !Ref GitBranch
OAuthToken: !Ref GitHubToken
OutputArtifacts:
- Name: App
RunOrder: 1
- Name: Build
Actions:
- Name: Build
ActionTypeId:
Category: Build
Owner: AWS
Version: 1
Provider: CodeBuild
Configuration:
ProjectName: !Ref CodeBuildProject
InputArtifacts:
- Name: App
OutputArtifacts:
- Name: BuildOutput
RunOrder: 1
- Name: Deploy
Actions:
- Name: Deploy
ActionTypeId:
Category: Deploy
Owner: AWS
Version: 1
Provider: ECS
Configuration:
ClusterName: !Ref FargateEcsCluster
ServiceName: !GetAtt DefaultFargateService.Name
FileName: build.json
InputArtifacts:
- Name: BuildOutput
RunOrder: 1
DependsOn:
- CodePipelineArtifactBucket
- CodeBuildProject
- CodePipelineServiceRole
- DefaultFargateService
# Simple Amazon ECR Lifecycle Policies to try and reduce storage costs
# See: https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html
EcrDockerRepository:
Type: AWS::ECR::Repository
Properties:
LifecyclePolicy:
LifecyclePolicyText: !Sub
- |
{
"rules": [
{
"rulePriority": 1,
"description": "Only keep untagged images for ${DaysToRetainUntaggedContainerImages} days",
"selection": {
"tagStatus": "untagged",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": ${DaysToRetainUntaggedContainerImages}
},
"action": { "type": "expire" }
},
{
"rulePriority": 2,
"description": "Keep only ${MaxTaggedContainerImagesToRetain} tagged images, expire all others",
"selection": {
"tagStatus": "tagged",
"tagPrefixList": [ "${EnvironmentName}" ],
"countType": "imageCountMoreThan",
"countNumber": ${MaxTaggedContainerImagesToRetain}
},
"action": { "type": "expire" }
}
]
}
- DaysToRetainUntaggedContainerImages: !Ref DaysToRetainUntaggedContainerImages
MaxTaggedContainerImagesToRetain: !Ref MaxTaggedContainerImagesToRetain
EnvironmentName: !Ref EnvironmentName
FargateEcsCluster:
Type: AWS::ECS::Cluster
Properties:
ClusterName: !Ref AWS::StackName
# The ALB lives in two public subnets. See the existing vpc.cfn.yml stack
# for ELB/ALB and application security groups which define ingress ports.
ApplicationLoadBalancer:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Properties:
Subnets:
- Fn::ImportValue: !Sub ${NetworkStackName}-PublicSubnet1ID
- Fn::ImportValue: !Sub ${NetworkStackName}-PublicSubnet2ID
SecurityGroups:
- Fn::ImportValue: !Sub ${NetworkStackName}-ELBSecurityGroupID
Tags:
- Key: Stack
Value: !Ref AWS::StackName
- Key: Environment
Value: !Ref EnvironmentName
- Key: FargateCluster
Value: !Ref FargateEcsCluster
AlbRoute53Record:
Type: AWS::Route53::RecordSet
Condition: CreateRoute53Record
Properties:
Name: !Ref LoadBalancerDomainName
HostedZoneName: !Sub ${HostedZoneName}.
Type: A
AliasTarget:
HostedZoneId: !GetAtt ApplicationLoadBalancer.CanonicalHostedZoneID
DNSName: !GetAtt ApplicationLoadBalancer.DNSName
DependsOn: ApplicationLoadBalancer
# The health checks can be further tuned if your requirements differ
DefaultTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
VpcId:
Fn::ImportValue: !Sub ${NetworkStackName}-VpcID
Port:
Fn::ImportValue: !Sub ${NetworkStackName}-AppIngressPort
Protocol: !Ref AppProtocol
Matcher:
HttpCode: 200
HealthCheckIntervalSeconds: 10
HealthCheckPath: !Ref HealthCheckPath
HealthCheckProtocol: !Ref AppProtocol
HealthCheckTimeoutSeconds: 5
HealthyThresholdCount: 2
TargetGroupAttributes:
- Key: deregistration_delay.timeout_seconds
Value: 300
TargetType: ip
Tags:
- Key: Repository
Value: !Ref GitSourceRepo
- Key: Branch
Value: !Ref GitBranch
- Key: Stack
Value: !Ref AWS::StackName
- Key: Environment
Value: !Ref EnvironmentName
DependsOn: ApplicationLoadBalancer
# The namespace in Amazon CloudWatch Logs - see https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatchLogsConcepts.html
DefaultLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub /fargate/${AWS::StackName}/${GitSourceRepo}/${GitBranch}/${EnvironmentName}
RetentionInDays: !Ref ContainerLogRetentionInDays
DefaultTaskRole:
Type: AWS::IAM::Role
Properties:
Path: /
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: ecs-tasks.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyName: default-s3-bucket
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: s3:*
Resource: !GetAtt DefaultContainerBucket.Arn
DependsOn: DefaultContainerBucket
DefaultTaskExecutionRole:
Type: AWS::IAM::Role
Properties:
Path: /
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: ecs-tasks.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
DefaultFargateTaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: !Ref AWS::StackName
RequiresCompatibilities:
- FARGATE
Cpu: !Ref DefaultContainerCpu
Memory: !Ref DefaultContainerMemory
NetworkMode: awsvpc
TaskRoleArn: !GetAtt DefaultTaskRole.Arn
ExecutionRoleArn: !GetAtt DefaultTaskExecutionRole.Arn
ContainerDefinitions:
- Name: !Ref GitSourceRepo
Image: !Ref SeedDockerImage
Essential: true
PortMappings:
- ContainerPort:
Fn::ImportValue: !Sub ${NetworkStackName}-AppIngressPort
# Environment variables can be customized by adding parameters/values below. Secrets
# should be stored in AWS Systems Manager Parameter Store.
# See: https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html
Environment:
- Name: BUCKET_NAME
Value: !Ref DefaultContainerBucket
- Name: ENVIRONMENT_NAME
Value: !Ref EnvironmentName
- Name: DATABASE_ENDPOINT
Value: !If [ IsDbStackSet, "Fn::ImportValue": !Sub "${DatabaseStackName}-DatabaseURL", "" ]
- Name: DATABASE_USER
Value: !If [ IsDbStackSet, "Fn::ImportValue": !Sub "${DatabaseStackName}-DatabaseUser", "" ]
- Name: LOAD_BALANCER_DNS
Value: !If [ CreateRoute53Record, !Ref LoadBalancerDomainName, !GetAtt ApplicationLoadBalancer.DNSName ]
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-region: !Ref AWS::Region
awslogs-group: !Ref DefaultLogGroup
awslogs-stream-prefix: !Ref GitSourceRepo
DependsOn:
- DefaultContainerBucket
- DefaultLogGroup
- DefaultTaskExecutionRole
DefaultFargateService:
Type: AWS::ECS::Service
Properties:
Cluster: !Ref FargateEcsCluster
ServiceName: !Ref AWS::StackName
DesiredCount: !Ref DefaultTaskMinContainerCount
LaunchType: FARGATE
TaskDefinition: !Ref DefaultFargateTaskDefinition
LoadBalancers:
- ContainerName: !Ref GitSourceRepo
ContainerPort:
Fn::ImportValue: !Sub ${NetworkStackName}-AppIngressPort
TargetGroupArn: !Ref DefaultTargetGroup
NetworkConfiguration:
AwsvpcConfiguration:
AssignPublicIp: DISABLED
SecurityGroups:
- Fn::ImportValue: !Sub ${NetworkStackName}-AppSecurityGroupID
Subnets:
- Fn::ImportValue: !Sub ${NetworkStackName}-PrivateSubnet1ID
- Fn::ImportValue: !Sub ${NetworkStackName}-PrivateSubnet2ID
DependsOn:
- FargateEcsCluster
- DefaultFargateTaskDefinition
- LoadBalancerListener
ServiceAutoScalingRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: application-autoscaling.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
- PolicyName: service-autoscaling
PolicyDocument:
Statement:
- Effect: Allow
Action:
- application-autoscaling:*
- cloudwatch:DescribeAlarms
- cloudwatch:PutMetricAlarm
- ecs:DescribeServices
- ecs:UpdateService
Resource: '*'
DefaultServiceScalingTarget:
Type: AWS::ApplicationAutoScaling::ScalableTarget
Properties:
MinCapacity: !Ref DefaultTaskMinContainerCount
MaxCapacity: !Ref DefaultTaskMaxContainerCount
ResourceId: !Sub
- service/${EcsClusterName}/${EcsDefaultServiceName}
- EcsClusterName: !Ref FargateEcsCluster
EcsDefaultServiceName: !GetAtt DefaultFargateService.Name
RoleARN: !GetAtt ServiceAutoScalingRole.Arn
ScalableDimension: ecs:service:DesiredCount
ServiceNamespace: ecs
DependsOn:
- DefaultFargateService
- ServiceAutoScalingRole
DefaultServiceScaleOutPolicy:
Type: AWS::ApplicationAutoScaling::ScalingPolicy
Properties:
PolicyName: ScaleOutPolicy
PolicyType: StepScaling
ScalingTargetId: !Ref DefaultServiceScalingTarget
StepScalingPolicyConfiguration:
AdjustmentType: ChangeInCapacity
Cooldown: 60
MetricAggregationType: Average
StepAdjustments:
- ScalingAdjustment: 1
MetricIntervalLowerBound: 0
DependsOn: DefaultServiceScalingTarget
DefaultServiceScaleInPolicy:
Type: AWS::ApplicationAutoScaling::ScalingPolicy
Properties:
PolicyName: ScaleInPolicy
PolicyType: StepScaling
ScalingTargetId: !Ref DefaultServiceScalingTarget
StepScalingPolicyConfiguration:
AdjustmentType: ChangeInCapacity
Cooldown: 60
MetricAggregationType: Average
StepAdjustments:
- ScalingAdjustment: -1
MetricIntervalUpperBound: 0
DependsOn: DefaultServiceScalingTarget
DefaultServiceScaleOutAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
EvaluationPeriods: !Ref DefaultServiceScaleEvaluationPeriods
Statistic: Average
TreatMissingData: notBreaching
Threshold: !Ref DefaultServiceCpuScaleOutThreshold
AlarmDescription: Alarm to add capacity if CPU is high
Period: 60
AlarmActions:
- !Ref DefaultServiceScaleOutPolicy
Namespace: AWS/ECS
Dimensions:
- Name: ClusterName
Value: !Ref FargateEcsCluster
- Name: ServiceName
Value: !GetAtt DefaultFargateService.Name
ComparisonOperator: GreaterThanThreshold
MetricName: CPUUtilization
DependsOn:
- DefaultFargateService
- DefaultServiceScaleOutPolicy
DefaultServiceScaleInAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
EvaluationPeriods: !Ref DefaultServiceScaleEvaluationPeriods
Statistic: Average
TreatMissingData: notBreaching
Threshold: !Ref DefaultServiceCpuScaleInThreshold
AlarmDescription: Alarm to reduce capacity if container CPU is low
Period: 300
AlarmActions:
- !Ref DefaultServiceScaleInPolicy
Namespace: AWS/ECS
Dimensions:
- Name: ClusterName
Value: !Ref FargateEcsCluster
- Name: ServiceName
Value: !GetAtt DefaultFargateService.Name
ComparisonOperator: LessThanThreshold
MetricName: CPUUtilization
DependsOn:
- DefaultFargateService
- DefaultServiceScaleInPolicy
LoadBalancerListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
LoadBalancerArn: !Ref ApplicationLoadBalancer
Port:
Fn::ImportValue: !Sub ${NetworkStackName}-ELBIngressPort
Protocol: !If [ IsTlsEnabled, HTTPS, HTTP ]
Certificates:
- CertificateArn: !If [ IsTlsEnabled, !Ref SSLCertificateArn, !Ref "AWS::NoValue" ]
DefaultActions:
- Type: forward
TargetGroupArn: !Ref DefaultTargetGroup
DependsOn:
- DefaultTargetGroup
- ApplicationLoadBalancer
LBLatency:
Type: AWS::CloudWatch::Alarm
Condition: IsLBAlarmEnabled
Properties:
AlarmDescription: !Sub LB latency is over ${LoadBalancerLatencySeconds} second(s) for ${LoadBalancerAlarmEvaluationPeriods} period(s) of ${LoadBalancerAlarmEvaluationPeriodSeconds} seconds
TreatMissingData: notBreaching
AlarmActions:
- !Ref LoadBalancerAlarmTopic
Namespace: AWS/ApplicationELB
MetricName: TargetResponseTime
ComparisonOperator: GreaterThanOrEqualToThreshold
Unit: Seconds
Statistic: Average
EvaluationPeriods: !Ref LoadBalancerAlarmEvaluationPeriods
Period: !Ref LoadBalancerAlarmEvaluationPeriodSeconds
Threshold: !Ref LoadBalancerLatencySeconds
Dimensions:
- Name: LoadBalancer
Value: !GetAtt ApplicationLoadBalancer.LoadBalancerFullName
DependsOn: ApplicationLoadBalancer
LoadBalancerAlarmTopic:
Type: AWS::SNS::Topic
Condition: IsLBAlarmEnabled
Properties:
DisplayName: LoadBalancer Alarm Topic
Outputs:
Name:
Description: Fargate Stack Name
Value: !Ref AWS::StackName
Export:
Name: !Sub ${AWS::StackName}-Name
EnvironmentName:
Description: Environment Name
Value: !Ref EnvironmentName
Export:
Name: !Sub ${AWS::StackName}-EnvironmentName
EcrDockerRepositoryName:
Value: !Ref EcrDockerRepository
Export:
Name: !Sub ${AWS::StackName}-EcrDockerRepositoryName
EcrDockerRepositoryArn:
Value: !Sub arn:aws:ecr:${AWS::Region}:${AWS::AccountId}:repository/${EcrDockerRepository}
Export:
Name: !Sub ${AWS::StackName}-EcrDockerRepositoryArn
EcrDockerRepositoryUri:
Value: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${EcrDockerRepository}
Export:
Name: !Sub ${AWS::StackName}-EcrDockerRepositoryUri
FargateEcsClusterName:
Value: !Ref FargateEcsCluster
Export:
Name: !Sub ${AWS::StackName}-FargateEcsClusterName
FargateEcsClusterArn:
Value: !GetAtt FargateEcsCluster.Arn
Export:
Name: !Sub ${AWS::StackName}-FargateEcsClusterArn
DefaultFargateServiceArn:
Value: !Ref DefaultFargateService
Export:
Name: !Sub ${AWS::StackName}-DefaultFargateServiceArn
DefaultFargateServiceName:
Value: !GetAtt DefaultFargateService.Name
Export:
Name: !Sub ${AWS::StackName}-DefaultFargateServiceName
ApplicationLoadBalancerArn:
Value: !Ref ApplicationLoadBalancer
Export:
Name: !Sub ${AWS::StackName}-ApplicationLoadBalancerArn
ApplicationLoadBalancerDnsName:
Value: !If [ CreateRoute53Record, !Ref LoadBalancerDomainName, !GetAtt ApplicationLoadBalancer.DNSName ]
Export:
Name: !Sub ${AWS::StackName}-ApplicationLoadBalancerDnsName
ApplicationLoadBalancerBaseDnsName:
Value: !GetAtt ApplicationLoadBalancer.DNSName
Export:
Name: !Sub ${AWS::StackName}-ApplicationLoadBalancerBaseDnsName
ApplicationLoadBalancerCanonicalHostedZoneId:
Value: !GetAtt ApplicationLoadBalancer.CanonicalHostedZoneID
Export:
Name: !Sub ${AWS::StackName}-ApplicationLoadBalancerCanonicalHostedZoneId
ApplicationLoadBalancerName:
Value: !GetAtt ApplicationLoadBalancer.LoadBalancerName
Export:
Name: !Sub ${AWS::StackName}-ApplicationLoadBalancerName
ApplicationLoadBalancerListenerArn:
Value: !Ref LoadBalancerListener
Export:
Name: !Sub ${AWS::StackName}-ApplicationLoadBalancerListenerArn
LoadBalancerAlarmTopicArn:
Description: LoadBalancer Alarm Topic ARN
Value: !Ref LoadBalancerAlarmTopic
Condition: IsLBAlarmEnabled
Export:
Name: !Sub ${AWS::StackName}-LoadBalancerAlarmTopicArn
LoadBalancerAlarmTopicName:
Description: LoadBalancer Alarm Topic Name
Value: !GetAtt LoadBalancerAlarmTopic.TopicName
Condition: IsLBAlarmEnabled
Export:
Name: !Sub ${AWS::StackName}-LoadBalancerAlarmTopicName
CodePipelineArtifactBucketName:
Value: !Ref CodePipelineArtifactBucket
Export:
Name: !Sub ${AWS::StackName}-CodePipelineArtifactBucket
CodePipelineArtifactBucketArn:
Value: !GetAtt CodePipelineArtifactBucket.Arn
Export:
Name: !Sub ${AWS::StackName}-CodePipelineArtifactBucketArn