-
Notifications
You must be signed in to change notification settings - Fork 1
/
service.yaml
975 lines (948 loc) · 31.8 KB
/
service.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
---
AWSTemplateFormatVersion: 2010-09-09
Description: >-
Blue/green ECS deployment for SATOSA
Metadata:
AWS::CloudFormation::Interface:
ParameterLabels:
CertificateArn:
default: ACM Certificate ARN
ClusterDesiredSize:
default: ECS Cluster - Desired Size
ClusterMaxSize:
default: ECS Cluster - Maximum Size
ClusterMinSize:
default: ECS Cluster - Minimum Size
DomainName:
default: Domain Name
EcrPrivateRepoArn:
default: ECR Private Repository ARN
EcsImageId:
default: ECS Image ID
HostedZoneId:
default: Route 53 Hosted Zone ID
Hostname:
default: Hostname
ImageUri:
default: Container Image URI
InstanceType:
default: EC2 Instance Type
LaunchType:
default: ECS Launch Type
PrivateSubnet1Cidr:
default: New VPC Private Subnet 1 IPv4 Address
PrivateSubnet1Id:
default: Existing VPC Private Subnet 1 ID
PrivateSubnet2Cidr:
default: New VPC Private Subnet 2 IPv4 Address
PrivateSubnet2Id:
default: Existing VPC Private Subnet 2 ID
PublicSubnet1Cidr:
default: New VPC Public Subnet 1 IPv4 Address
PublicSubnet1Id:
default: Existing VPC Public Subnet 1 ID
PublicSubnet2Cidr:
default: New VPC Public Subnet 2 IPv4 Address
PublicSubnet2Id:
default: Existing VPC Public Subnet 2 ID
RepositoryCredentialsSecretArn:
default: Image Repository Credentials Secret ARN
Saml2BackEndKeyPairSecretArn:
default: Service Provider Key-Pair Secret ARN
Saml2FrontEndKeyPairSecretArn:
default: Identity Provider Key-Pair Secret ARN
SecretsManagerEncryptionKeyArn:
default: Custom KMS Key ARN for Secrets Manager Encryption
VpcCidr:
default: New VPC IPv4 CIDR Block
VpcId:
default: Existing VPC ID
VpcType:
default: New or Existing VPC
ParameterGroups:
- Label:
default: Service Configuration
Parameters:
- Hostname
- DomainName
- HostedZoneId
- CertificateArn
- SecretsManagerEncryptionKeyArn
- Saml2BackEndKeyPairSecretArn
- Saml2FrontEndKeyPairSecretArn
- Label:
default: Service Networking
Parameters:
- VpcType
- VpcCidr
- PublicSubnet1Cidr
- PublicSubnet2Cidr
- PrivateSubnet1Cidr
- PrivateSubnet2Cidr
- VpcId
- PublicSubnet1Id
- PublicSubnet2Id
- PrivateSubnet1Id
- PrivateSubnet2Id
- Label:
default: Service Hosting
Parameters:
- LaunchType
- EcsImageId
- InstanceType
- ClusterMinSize
- ClusterMaxSize
- ClusterDesiredSize
- ImageUri
- EcrPrivateRepoArn
- RepositoryCredentialsSecretArn
Parameters:
CertificateArn:
Type: String
Description: >-
The service stack will use this certificate in AWS Certificate Manager (ACM).
ClusterDesiredSize:
Type: Number
Default: 2
Description: >-
When deploying ECS clusters on EC2, the stack will configure the Auto Scaling group to keep at least this many ECS container instances running at all times.
It must greater than or equal to the cluster's minimum size and less than or equal to the cluster's maximum size.
ClusterMaxSize:
Type: Number
Default: 2
Description: >-
When deploying ECS clusters on EC2, the stack will create the Auto Scaling group with no more than this many ECS container instances.
ClusterMinSize:
Type: Number
Default: 2
Description: >-
When deploying ECS clusters on EC2, the stack will create the Auto Scaling group with at least this many ECS container instances.
DomainName:
Type: String
Description: >-
The domain name of the service, e.g., for "aai.example.com", the domain name would be "example.com".
EcrPrivateRepoArn:
Type: String
Default: ''
Description: >-
(Optional) If specified, this stack will give the ECS task execution role read-only access to this ECR private repository.
If neither this parameter nor RepositoryCredentialsSecretArn is specified, ECS will download the container image anonymously.
EcsImageId:
Type: String
Default: ''
Description: >-
When deploying ECS clusters on EC2, the stack will create the Auto Scaling group with ECS container instances based on this Amazon Machine Image (AMI).
HostedZoneId:
Type: String
Default: ''
Description: >-
(Optional) If specified, the service stack will create resource records for SATOSA in this Route 53 hosted zone.
Note that the Route 53 hosted zone MUST exist in the same partition/account as this stack.
Hostname:
Type: String
Description: >-
The short name of the service, e.g., for "aai.example.com", the hostname would be "aai".
ImageUri:
Type: String
Default: satosa
Description: >-
The stack will deploy this Docker container image:tag.
InstanceType:
Type: String
Default: t3a.medium
Description: >-
When deploying ECS clusters on EC2, the stack will create the Auto Scaling group with ECS container instances based on this EC2 instance type.
LaunchType:
Type: String
Default: FARGATE
Description: >-
The stack will deploy ECS-managed containers using Fargate or EC2.
Selecting EC2 will create an Auto Scaling group of t3a.micro instances for the cluster.
For more information on launch types, refer to https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html.
AllowedValues:
- EC2
- FARGATE
PrivateSubnet1Cidr:
Type: String
Default: 192.168.128.0/18
Description: >-
When creating a new VPC, the stack will use this subnet of the VPC's IPv4 CIDR block for the first private subnet.
PrivateSubnet1Id:
Type: String
Default: ''
Description: >-
If using an existing VPC, the stack will use this subnet ID as the first private subnet.
PrivateSubnet2Cidr:
Type: String
Default: 192.168.192.0/18
Description: >-
When creating a new VPC, the stack will use this subnet of the VPC's IPv4 CIDR block for the second private subnet.
PrivateSubnet2Id:
Type: String
Default: ''
Description: >-
If using an existing VPC, the stack will use this subnet ID as the second private subnet.
PublicSubnet1Cidr:
Type: String
Default: 192.168.0.0/18
Description: >-
When creating a new VPC, the stack will use this subnet of the VPC's IPv4 CIDR block for the first public subnet.
PublicSubnet1Id:
Type: String
Default: ''
Description: >-
If using an existing VPC, the stack will use this subnet ID as the first public subnet.
PublicSubnet2Cidr:
Type: String
Default: 192.168.64.0/18
Description: >-
When creating a new VPC, the stack will use this subnet of the VPC's IPv4 CIDR block for the second public subnet.
PublicSubnet2Id:
Type: String
Default: ''
Description: >-
If using an existing VPC, the stack will use this subnet ID as the second public subnet.
RepositoryCredentialsSecretArn:
Type: String
Default: ''
Description: >-
(Optional) If specified, the ECS task execution role will use container image repository credentials stored in this AWS Secrets Manager secret.
For more information, refer to https://docs.aws.amazon.com/AmazonECS/latest/developerguide/private-auth.html.
If neither this parameter nor EcrPrivateRepoArn is specified, ECS will download the container image anonymously.
Saml2BackEndKeyPairSecretArn:
Type: String
Description: >-
SATOSA's service provier back end will use this key-pair, stored in Amazon Secrets Manager, for SAML 2.0 request signing and response decryption.
Saml2FrontEndKeyPairSecretArn:
Type: String
Description: >-
SATOSA's identity provider front end will use this key-pair, stored in Amazon Secrets Manager, for SAML 2.0 response signing.
SecretsManagerEncryptionKeyArn:
Type: String
Default: ''
Description: >-
(Optional) The stack will encrypt and decrypt Secrets Manager secrets with a KMS key identified by this ARN instead of the default.
VpcCidr:
Type: String
Default: 192.168.0.0/16
Description: >-
When creating a new VPC, the stack will use this IPv4 CIDR block.
VpcId:
Type: String
Default: ''
Description: >-
If using an existing VPC, the stack will create resources in the VPC with this identifier.
VpcType:
Type: String
Default: New
Description: >-
The stack will create a new VPC (the default) or deploy into an existing one.
AllowedValues:
- New
- Existing
Conditions:
WithEC2:
!Equals [ !Ref LaunchType, EC2 ]
WithEcrPrivateRepo:
!Not [ !Equals [ !Ref EcrPrivateRepoArn, '' ] ]
WithExistingVpc:
!Equals [ !Ref VpcType, Existing ]
WithFargate:
!Equals [ !Ref LaunchType, FARGATE ]
WithNewVpc:
!Equals [ !Ref VpcType, New ]
WithRepositoryCredentials:
!Not [ !Equals [ !Ref RepositoryCredentialsSecretArn, '' ] ]
WithRoute53:
!Not [ !Equals [ !Ref HostedZoneId, '' ] ]
WithSecretsManagerCustomKmsKey:
!Not [ !Equals [ !Ref SecretsManagerEncryptionKeyArn, '' ] ]
WithThirdPartyDns:
!Equals [ !Ref HostedZoneId, '' ]
Transform:
- AWS::CodeDeployBlueGreen
Hooks:
CodeDeployBlueGreenHook:
Type: AWS::CodeDeploy::BlueGreen
Properties:
TrafficRoutingConfig:
Type: TimeBasedCanary
TimeBasedCanary:
StepPercentage: 15
BakeTimeMins: 5
Applications:
- Target:
Type: AWS::ECS::Service
LogicalID: EcsService
ECSAttributes:
TaskDefinitions:
- BlueTaskDefinition
- GreenTaskDefinition
TaskSets:
- BlueTaskSet
- GreenTaskSet
TrafficRouting:
ProdTrafficRoute:
Type: AWS::ElasticLoadBalancingV2::Listener
LogicalID: AlbListenerHttps
TargetGroups:
- BlueAlbTargetGroup
- GreenAlbTargetGroup
Resources:
# conditionally deploy the service in a new VPC
VPC:
Type: AWS::EC2::VPC
Condition: WithNewVpc
Properties:
CidrBlock: !Ref VpcCidr
EnableDnsSupport: true
EnableDnsHostnames: true
Tags:
- Key: Name
Value: !Ref AWS::StackName
InternetGateway:
Type: AWS::EC2::InternetGateway
Condition: WithNewVpc
Properties:
Tags:
- Key: Name
Value: !Ref AWS::StackName
InternetGatewayAttachment:
Type: AWS::EC2::VPCGatewayAttachment
Condition: WithNewVpc
Properties:
InternetGatewayId: !Ref InternetGateway
VpcId: !Ref VPC
PublicSubnet1:
Type: AWS::EC2::Subnet
Condition: WithNewVpc
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [ 0, !GetAZs '' ]
CidrBlock: !Ref PublicSubnet1Cidr
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: !Sub ${AWS::StackName} Public Subnet (AZ1)
PublicSubnet2:
Type: AWS::EC2::Subnet
Condition: WithNewVpc
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [ 1, !GetAZs '' ]
CidrBlock: !Ref PublicSubnet2Cidr
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: !Sub ${AWS::StackName} Public Subnet (AZ2)
PrivateSubnet1:
Type: AWS::EC2::Subnet
Condition: WithNewVpc
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [ 0, !GetAZs '' ]
CidrBlock: !Ref PrivateSubnet1Cidr
MapPublicIpOnLaunch: false
Tags:
- Key: Name
Value: !Sub ${AWS::StackName} Private Subnet (AZ1)
PrivateSubnet2:
Type: AWS::EC2::Subnet
Condition: WithNewVpc
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [ 1, !GetAZs '' ]
CidrBlock: !Ref PrivateSubnet2Cidr
MapPublicIpOnLaunch: false
Tags:
- Key: Name
Value: !Sub ${AWS::StackName} Private Subnet (AZ2)
NatGateway1EIP:
Type: AWS::EC2::EIP
Condition: WithNewVpc
DependsOn: InternetGatewayAttachment
Properties:
Domain: vpc
NatGateway2EIP:
Type: AWS::EC2::EIP
Condition: WithNewVpc
DependsOn: InternetGatewayAttachment
Properties:
Domain: vpc
NatGateway1:
Type: AWS::EC2::NatGateway
Condition: WithNewVpc
Properties:
AllocationId: !GetAtt NatGateway1EIP.AllocationId
SubnetId: !Ref PublicSubnet1
NatGateway2:
Type: AWS::EC2::NatGateway
Condition: WithNewVpc
Properties:
AllocationId: !GetAtt NatGateway2EIP.AllocationId
SubnetId: !Ref PublicSubnet2
PublicRouteTable:
Type: AWS::EC2::RouteTable
Condition: WithNewVpc
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: !Sub ${AWS::StackName} Public Routes
DefaultPublicRoute:
Type: AWS::EC2::Route
Condition: WithNewVpc
DependsOn: InternetGatewayAttachment
Properties:
RouteTableId: !Ref PublicRouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
PublicSubnet1RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Condition: WithNewVpc
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref PublicSubnet1
PublicSubnet2RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Condition: WithNewVpc
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref PublicSubnet2
PrivateRouteTable1:
Type: AWS::EC2::RouteTable
Condition: WithNewVpc
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: !Sub ${AWS::StackName} Private Routes (AZ1)
DefaultPrivateRoute1:
Type: AWS::EC2::Route
Condition: WithNewVpc
Properties:
RouteTableId: !Ref PrivateRouteTable1
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId: !Ref NatGateway1
PrivateSubnet1RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Condition: WithNewVpc
Properties:
RouteTableId: !Ref PrivateRouteTable1
SubnetId: !Ref PrivateSubnet1
PrivateRouteTable2:
Type: AWS::EC2::RouteTable
Condition: WithNewVpc
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: !Sub ${AWS::StackName} Private Routes (AZ2)
DefaultPrivateRoute2:
Type: AWS::EC2::Route
Condition: WithNewVpc
Properties:
RouteTableId: !Ref PrivateRouteTable2
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId: !Ref NatGateway2
PrivateSubnet2RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Condition: WithNewVpc
Properties:
RouteTableId: !Ref PrivateRouteTable2
SubnetId: !Ref PrivateSubnet2
NewVpcWaitHandle:
Type: AWS::CloudFormation::WaitConditionHandle
Condition: WithNewVpc
DependsOn:
- VPC
- InternetGateway
- InternetGatewayAttachment
- PublicSubnet1
- PublicSubnet2
- PrivateSubnet1
- PrivateSubnet2
- NatGateway1EIP
- NatGateway2EIP
- NatGateway1
- NatGateway2
- PublicRouteTable
- DefaultPublicRoute
- PublicSubnet1RouteTableAssociation
- PublicSubnet2RouteTableAssociation
- PrivateRouteTable1
- DefaultPrivateRoute1
- PrivateSubnet1RouteTableAssociation
- PrivateRouteTable2
- DefaultPrivateRoute2
- PrivateSubnet2RouteTableAssociation
ExistingVpcWaitHandle: # no op
Type: AWS::CloudFormation::WaitConditionHandle
Condition: WithExistingVpc
WaitForVpcDeployment:
Type: AWS::CloudFormation::WaitCondition
Properties:
Handle: !If [ WithNewVpc, !Ref NewVpcWaitHandle, !Ref ExistingVpcWaitHandle ]
Timeout: 1
Count: 0
# put the service behind an application load balancer
AlbSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: !Sub ${AWS::StackName}-alb
VpcId: !If [ WithNewVpc, !Ref VPC, !Ref VpcId ]
SecurityGroupIngress:
- CidrIp: 0.0.0.0/0
IpProtocol: TCP
FromPort: 80
ToPort: 80
- CidrIp: 0.0.0.0/0
IpProtocol: TCP
FromPort: 443
ToPort: 443
BlueAlbTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
HealthCheckIntervalSeconds: 5
HealthCheckPath: /ping
HealthCheckPort: '8080'
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 2
HealthyThresholdCount: 2
Matcher:
HttpCode: '200'
Port: 8080
Protocol: HTTP
TargetGroupAttributes:
- Key: stickiness.enabled
Value: true
- Key: stickiness.type
Value: lb_cookie
- Key: stickiness.lb_cookie.duration_seconds
Value: 900
TargetType: !If [ WithFargate, ip, instance ]
UnhealthyThresholdCount: 4
VpcId: !If [ WithNewVpc, !Ref VPC, !Ref VpcId ]
GreenAlbTargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
HealthCheckIntervalSeconds: 5
HealthCheckPath: /ping
HealthCheckPort: '8080'
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 2
HealthyThresholdCount: 2
Matcher:
HttpCode: '200'
Port: 8080
Protocol: HTTP
TargetGroupAttributes:
- Key: stickiness.enabled
Value: true
- Key: stickiness.type
Value: lb_cookie
- Key: stickiness.lb_cookie.duration_seconds
Value: 900
TargetType: !If [ WithFargate, ip, instance ]
UnhealthyThresholdCount: 4
VpcId: !If [ WithNewVpc, !Ref VPC, !Ref VpcId ]
LoadBalancer:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
DependsOn: WaitForVpcDeployment
Properties:
Scheme: internet-facing
SecurityGroups:
- !Ref AlbSecurityGroup
Subnets:
- !If [ WithNewVpc, !Ref PublicSubnet1, !Ref PublicSubnet1Id ]
- !If [ WithNewVpc, !Ref PublicSubnet2, !Ref PublicSubnet2Id ]
Type: application
IpAddressType: ipv4
AlbListenerHttp:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
LoadBalancerArn: !Ref LoadBalancer
Protocol: HTTP
Port: 80
DefaultActions:
- Type: redirect
RedirectConfig:
Protocol: HTTPS
Port: 443
Host: "#{host}"
Path: "/#{path}"
Query: "#{query}"
StatusCode: HTTP_301
AlbListenerHttps:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
LoadBalancerArn: !Ref LoadBalancer
Protocol: HTTPS
Port: 443
Certificates:
- CertificateArn: !Ref CertificateArn
DefaultActions:
- Type: forward
ForwardConfig:
TargetGroups:
- TargetGroupArn: !Ref BlueAlbTargetGroup
Weight: 1
TargetGroupStickinessConfig:
Enabled: true
DurationSeconds: 900
# conditionally register the load balancer in DNS
DnsRecord:
Type: AWS::Route53::RecordSet
Condition: WithRoute53
Properties:
HostedZoneId: !Ref HostedZoneId
Name: !Sub ${Hostname}.${DomainName}
Type: A # TODO: create second record set for AAAA (IPv6)
AliasTarget:
DNSName: !GetAtt LoadBalancer.DNSName
HostedZoneId: !GetAtt LoadBalancer.CanonicalHostedZoneID
# generate and manage the SATOSA state encryption key
StateEncryptionKeySecret:
Type: AWS::SecretsManager::Secret
Properties:
GenerateSecretString:
ExcludePunctuation: true
KmsKeyId: !If [ WithSecretsManagerCustomKmsKey, !Ref SecretsManagerEncryptionKeyArn, !Ref AWS::NoValue ]
Description: >-
SATOSA uses cookies encrypted with this key to track the progress of an authentication flow.
# configure logging
EcsLogGroup:
Type: AWS::Logs::LogGroup
DeletionPolicy: Retain
Properties:
LogGroupName: !Sub /ecs/${AWS::StackName}
# deploy the ECS cluster
EcsCluster:
Type: AWS::ECS::Cluster
EcsSecurityGroup:
Type: AWS::EC2::SecurityGroup
DependsOn: AlbSecurityGroup
Properties:
GroupDescription: !Sub ${AWS::StackName}-ecs
VpcId: !If [ WithNewVpc, !Ref VPC, !Ref VpcId ]
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 8080
ToPort: 8080
SourceSecurityGroupId: !Ref AlbSecurityGroup
# conditionally host the ECS cluster on EC2
EcsRole:
Type: AWS::IAM::Role
Condition: WithEC2
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Action: sts:AssumeRole
Principal:
Service: !Sub ec2.${AWS::URLSuffix}
ManagedPolicyArns: # FIXME: least privileged access
- arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role
EcsInstanceProfile:
Type: AWS::IAM::InstanceProfile
Condition: WithEC2
Properties:
Roles:
- !Ref EcsRole
EcsLaunchConfiguration:
Type: AWS::AutoScaling::LaunchConfiguration
Condition: WithEC2
Metadata:
AWS::CloudFormation::Init:
config:
commands:
01_add_instance_to_cluster:
command: !Sub echo ECS_CLUSTER=${EcsCluster} > /etc/ecs/ecs.config
files:
# allows CloudFormation to make updates to running EC2
# instances via the UpdateStack API action, cf.,
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-hup.html
/etc/cfn/cfn-hup.conf:
mode: 00400
owner: root
group: root
content: !Sub |
[main]
stack=${AWS::StackId}
region=${AWS::Region}
# cf., https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-init.html
/etc/cfn/hooks.d/cfn-auto-reloader.conf:
content: !Sub |
[cfn-auto-reloader-hook]
triggers=post.update
path=Resources.EcsLaunchConfiguration.Metadata.AWS::CloudFormation::Init
action=/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource EcsLaunchConfiguration --region ${AWS::Region}
services:
sysvinit:
cfn-hup:
enabled: true
ensureRunning: true
files:
- /etc/cfn/cfn-hup.conf
- /etc/cfn/hooks.d/cfn-auto-reloader.conf
Properties:
ImageId: !Ref EcsImageId
InstanceType: !Ref InstanceType
IamInstanceProfile: !Ref EcsInstanceProfile
SecurityGroups:
- !Ref EcsSecurityGroup
UserData:
Fn::Base64: !Sub |
#!/bin/bash
yum install -y aws-cfn-bootstrap
/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource EcsLaunchConfiguration --region ${AWS::Region}
/opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource EcsAutoScalingGroup --region ${AWS::Region}
EcsAutoScalingGroup:
Type: AWS::AutoScaling::AutoScalingGroup
Condition: WithEC2
Properties:
MinSize: !Ref ClusterMinSize
MaxSize: !Ref ClusterMaxSize
DesiredCapacity: !Ref ClusterDesiredSize
LaunchConfigurationName: !Ref EcsLaunchConfiguration
VPCZoneIdentifier:
Fn::If:
- WithNewVpc
- [ !Ref PrivateSubnet1, !Ref PrivateSubnet2 ]
- [ !Ref PrivateSubnet1Id, !Ref PrivateSubnet2Id ]
CreationPolicy:
ResourceSignal:
Timeout: PT15M
UpdatePolicy:
AutoScalingRollingUpdate:
MinInstancesInService: 1
MaxBatchSize: 1
PauseTime: PT15M
WaitOnResourceSignals: true
# controls what the ECS agent can do,
# cf. https://blog.ruanbekker.com/blog/2021/07/31/difference-with-ecs-task-and-execution-iam-roles-on-aws/
TaskExecRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: sts:AssumeRole
Principal:
Service: !Sub ecs-tasks.${AWS::URLSuffix}
Policies:
- PolicyName: Logging
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- logs:CreateLogStream
- logs:PutLogEvents
Resource: !GetAtt EcsLogGroup.Arn
- PolicyName: ReadSecrets
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: secretsmanager:GetSecretValue
Resource:
- !Ref Saml2BackEndKeyPairSecretArn
- !Ref Saml2FrontEndKeyPairSecretArn
- !Ref StateEncryptionKeySecret
# either give the ECS agent read-only access to the ECR private
# repository that holds the container image to be deployed,...
EcrPrivateRepoPolicy:
Type: AWS::IAM::Policy
Condition: WithEcrPrivateRepo
Properties:
PolicyName: !Sub ${AWS::StackName}-EcrPrivateRepoPolicy
Roles:
- !Ref TaskExecRole
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: LogIntoRegistry
Effect: Allow
Action: ecr:GetAuthorizationToken
Resource: '*'
- Sid: PullImage
Effect: Allow
Action:
- ecr:BatchCheckLayerAvailability
- ecr:GetDownloadUrlForLayer
- ecr:BatchGetImage
Resource: !Ref EcrPrivateRepoArn
# ...or give the ECS agent read-only access to an AWS Secrets
# Manager secret that holds the username/password to the third-party
# container image repository that holds the container image to be
# deployed
RepositoryCredentialsPolicy:
Type: AWS::IAM::Policy
Condition: WithRepositoryCredentials
Properties:
PolicyName: !Sub ${AWS::StackName}-RepositoryCredentialsPolicy
Roles:
- !Ref TaskExecRole
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: secretsmanager:GetSecretValue
Resource: !Ref RepositoryCredentialsSecretArn
# give the ECS agent permission to decrypt secrets encrypted with a
# custom KMS key, if one was used
SecretsManagerCustomKmsKeyPolicy:
Type: AWS::IAM::Policy
Condition: WithSecretsManagerCustomKmsKey
Properties:
PolicyName: !Sub ${AWS::StackName}-SecretsManagerCustomKmsKeyPolicy
Roles:
- !Ref TaskExecRole
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: kms:Decrypt
Resource: !Ref SecretsManagerEncryptionKeyArn
EcsService:
Type: AWS::ECS::Service
Properties:
Cluster: !Ref EcsCluster
DesiredCount: 1
DeploymentController:
Type: EXTERNAL
BlueTaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: !Ref AWS::StackName
RequiresCompatibilities:
- !Ref LaunchType
NetworkMode: !If [ WithFargate, awsvpc, bridge ]
# Cpu and Memory must be string values, not integers, due to a
# bug in the AWS::CodeDeploy::BlueGreen hook
Cpu: '2048'
Memory: !If [ WithFargate, '4096', '3884' ]
# cf. https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_data_volumes.html
Volumes:
- Name: secrets # store secrets on local ephemeral storage
ExecutionRoleArn: !GetAtt TaskExecRole.Arn
ContainerDefinitions:
- Name: secrets-sidecar
Image: docker/ecs-secrets-sidecar:1.0
Essential: false
MountPoints:
- ContainerPath: /run/secrets/
SourceVolume: secrets
# copy secrets/parameters to the named environment variables
Secrets:
- Name: saml2_backend
ValueFrom: !Ref Saml2BackEndKeyPairSecretArn
- Name: saml2_frontend
ValueFrom: !Ref Saml2FrontEndKeyPairSecretArn
- Name: state_encryption_key
ValueFrom: !Ref StateEncryptionKeySecret
# if the secret/parameter is a string (i.e., Keys is null),
# create /run/secrets/<SECRET> containing the secret's
# value; if the secret is a JSON mapping, create
# /run/secrets/<SECRET>/<KEY> containing the value of each
# of the named keys in the secret
Command:
- >-
[
{
"Name": "saml2_backend",
"Keys": [
"certificate",
"key"
]
},
{
"Name": "saml2_frontend",
"Keys": [
"certificate",
"key"
]
},
{
"Name": "state_encryption_key",
"Keys": null
}
]
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-group: !Ref EcsLogGroup
awslogs-region: !Ref AWS::Region
awslogs-stream-prefix: task
- Name: satosa
RepositoryCredentials:
Fn::If:
- WithRepositoryCredentials
- CredentialsParameter: !Ref RepositoryCredentialsSecretArn
- !Ref AWS::NoValue
Image: !Ref ImageUri
Essential: true
MountPoints:
- ContainerPath: /run/secrets/
SourceVolume: secrets
PortMappings:
- HostPort: 8080
Protocol: tcp
ContainerPort: 8080
Environment:
- Name: BASE_URL
Value: !Sub https://${Hostname}.${DomainName}
- Name: STATE_ENCRYPTION_KEY_FILE
Value: /run/secrets/state_encryption_key
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-group: !Ref EcsLogGroup
awslogs-region: !Ref AWS::Region
awslogs-stream-prefix: task
BlueTaskSet:
Type: AWS::ECS::TaskSet
Properties:
LaunchType: !Ref LaunchType
Cluster: !Ref EcsCluster
Service: !Ref EcsService
TaskDefinition: !Ref BlueTaskDefinition
PlatformVersion: !If [ WithFargate, 1.4.0, !Ref AWS::NoValue ]
NetworkConfiguration:
AwsVpcConfiguration:
AssignPublicIp: !If [ WithFargate, ENABLED, DISABLED ]
SecurityGroups:
- !If [ WithFargate, !Ref EcsSecurityGroup, !Ref AWS::NoValue ]
Subnets:
- !If [ WithFargate, !If [ WithNewVpc, !Ref PrivateSubnet1, !Ref PrivateSubnet1Id ], !Ref AWS::NoValue ]
- !If [ WithFargate, !If [ WithNewVpc, !Ref PrivateSubnet2, !Ref PrivateSubnet2Id ], !Ref AWS::NoValue ]
LoadBalancers:
- ContainerName: satosa
ContainerPort: 8080
TargetGroupArn: !Ref BlueAlbTargetGroup
Scale:
Unit: PERCENT
Value: 100
PrimaryTaskSet:
Type: AWS::ECS::PrimaryTaskSet
Properties:
Cluster: !Ref EcsCluster
Service: !Ref EcsService
TaskSetId: !GetAtt BlueTaskSet.Id
Outputs:
EcsLogGroupName:
Value: !Ref EcsLogGroup
Description: >-
Use the name of the ECS cluster's log group to manage its retention policy, which is not controlled by this CloudFormation template.
LoadBalancerDnsName:
Condition: WithThirdPartyDns
Value: !GetAtt LoadBalancer.DNSName
Description: >-
Map the service's hostname to the load balancer's DNS name shown here.
LoadBalancerHostedZoneId:
Condition: WithThirdPartyDns
Value: !GetAtt LoadBalancer.CanonicalHostedZoneID
Description: >-
If creating an alias record set in Route 53 outside of this stack, use this value as the load balancer's canonical hosted zone ID.