-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.py
executable file
·1590 lines (1457 loc) · 52.8 KB
/
template.py
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
#!/usr/bin/env python
import argparse
from troposphere import Template, Parameter, Output, Tag, Ref, GetAZs, GetAtt
from troposphere import Sub, Select, Base64, Join, FindInMap
from troposphere import AWSHelperFn, If, Not, Equals
from troposphere import NoValue, AccountId, StackName, Region
import troposphere.ec2 as ec2
import troposphere.logs as logs
import troposphere.autoscaling as autoscaling
import troposphere.elasticloadbalancingv2 as loadbalancing
import troposphere.ecs as ecs
import troposphere.iam as iam
import troposphere.policies as policies
import troposphere.applicationautoscaling as applicationautoscaling
import troposphere.cloudwatch as cloudwatch
import troposphere.cloudfront as cloudfront
import troposphere.awslambda as aws_lambda
import troposphere.cloudformation as cloudformation
import awacs.aws as aws
import awacs.sts as actions_sts
import awacs.s3 as actions_s3
import awacs.cloudformation as actions_cloudformation
import awacs.logs as actions_logs
import awacs.cloudwatch as actions_cloudwatch
import awacs.ssm as actions_ssm
import awacs.kms as actions_kms
import awacs.autoscaling as actions_autoscaling
import awacs.aws_marketplace as actions_marketplace
cli_parser = argparse.ArgumentParser(description="imgproxy CloudFormation template generator")
cli_parser.add_argument("-f", "--format",
choices=["yaml", "json"],
default="yaml",
help="Output format. Default: yaml")
cli_parser.add_argument("-o", "--output",
type=str,
help=("Output file name."
" When not set, the template will be printed to stdout"))
cli_parser.add_argument("-t", "--launch-type",
choices=["fargate", "ec2"],
default="fargate",
help="ESC Launch type. Default: fargate")
cli_parser.add_argument("-s", "--subnets-number",
type=int,
default=3,
help="Number of subnets to create. Default: 3")
cli_parser.add_argument("-N", "--no-network",
action="store_true",
help="Don't create network resources (VPC, subnets, load balancer, etc)")
cli_parser.add_argument("-C", "--no-cluster",
action="store_true",
help="Don't create ECS cluster")
args = cli_parser.parse_args()
if args.no_cluster and args.launch_type == "ec2" and not args.no_network:
cli_parser.error("--no-cluster combined with --launch-type=ec2 requires --no-network")
template = Template()
template.set_version("2010-09-09")
template.set_description("imgproxy running in ECS")
yes_no = ["Yes", "No"]
def IfYes(param): return Equals(Ref(param), "Yes")
class Contains(AWSHelperFn):
def __init__(self, value_one: object, value_two: object) -> None:
self.data = {"Fn::Contains": [value_one, value_two]}
arm64_instance_types = [
"c8g.medium",
"c8g.large",
"c8g.xlarge",
"c8g.2xlarge",
"c8g.4xlarge",
"c8g.8xlarge",
"c8g.12xlarge",
"c8g.16xlarge",
"c8g.24xlarge",
"c8g.48xlarge",
"c7g.medium",
"c7g.large",
"c7g.xlarge",
"c7g.2xlarge",
"c7g.4xlarge",
"c7g.8xlarge",
"c7g.12xlarge",
"c7g.16xlarge",
"t4g.small",
"t4g.medium",
"t4g.large",
"t4g.xlarge",
"t4g.2xlarge",
]
amd64_instance_types = [
"c7i.large",
"c7i.xlarge",
"c7i.2xlarge",
"c7i.4xlarge",
"c7i.8xlarge",
"c7i.12xlarge",
"c7i.16xlarge",
"c7a.large",
"c7a.xlarge",
"c7a.2xlarge",
"c7a.4xlarge",
"c7a.8xlarge",
"c7a.12xlarge",
"c7a.16xlarge",
"c6i.large",
"c6i.xlarge",
"c6i.2xlarge",
"c6i.4xlarge",
"c6i.8xlarge",
"c6i.12xlarge",
"c6i.16xlarge",
"c6a.large",
"c6a.xlarge",
"c6a.2xlarge",
"c6a.4xlarge",
"c6a.8xlarge",
"c6a.12xlarge",
"c6a.16xlarge",
"t3.small",
"t3.medium",
"t3.large",
"t3.xlarge",
"t3.2xlarge",
]
# ==============================================================================
# PARAMETERS
# ==============================================================================
network_params_group = "Network"
cluster_params_group = "Cluster"
service_params_group = "Service"
configuration_params_group = "imgproxy Configuration"
s3_params_group = "S3 integration"
endpoint_params_group = "Endpoint"
# Network ----------------------------------------------------------------------
if args.no_network:
vpc = template.add_parameter(Parameter(
"VpcId",
Type="AWS::EC2::VPC::Id",
Description="ID of VPC to deploy imgproxy into",
))
template.add_parameter_to_group(vpc, network_params_group)
template.set_parameter_label(vpc, "VPC ID")
if not args.no_cluster or args.launch_type == "fargate":
subnets = template.add_parameter(Parameter(
"SubnetIds",
Type="List<AWS::EC2::Subnet::Id>",
Description="IDs of Subnets to deploy imgproxy into",
))
template.add_parameter_to_group(subnets, network_params_group)
template.set_parameter_label(subnets, "Subnet IDs")
ecs_host_security_group = template.add_parameter(Parameter(
"ECSHostSecurityGroupId",
Type="AWS::EC2::SecurityGroup::Id",
Description=("ID of security group to use for ECS hosts."
" Should allow access from the load balancer"),
))
template.add_parameter_to_group(ecs_host_security_group, network_params_group)
template.set_parameter_label(ecs_host_security_group, "ECS host security group ID")
load_balancer_listener = template.add_parameter(Parameter(
"LoadBalancerListenerArn",
Type="String",
Description="ARN of the load balancer listener to use for imgproxy",
AllowedPattern=("arn:aws:elasticloadbalancing:[a-z0-9-]+:[0-9]+:"
"listener/app/[a-z0-9-]+/[a-z0-9-]+/[a-z0-9]+"),
ConstraintDescription="Must be a valid load balancer listener ARN",
))
template.add_parameter_to_group(load_balancer_listener, network_params_group)
template.set_parameter_label(load_balancer_listener, "Load balancer listener ARN")
# Cluster ----------------------------------------------------------------------
if args.launch_type == "ec2" and not args.no_cluster:
cluster_instance_type = template.add_parameter(Parameter(
"ClusterInstanceType",
Type="String",
Description="EC2 instance type to use in your ECS cluster",
Default="c8g.medium",
AllowedValues=arm64_instance_types + amd64_instance_types,
))
template.add_parameter_to_group(cluster_instance_type, cluster_params_group)
template.set_parameter_label(cluster_instance_type, "EC2 instance type")
cluster_deised_size = template.add_parameter(Parameter(
"ClusterDeisedSize",
Type="Number",
Description="Number of EC2 instances to initially launch in your ECS cluster",
Default=2,
MinValue=1,
))
template.add_parameter_to_group(cluster_deised_size, cluster_params_group)
template.set_parameter_label(cluster_deised_size, "Desired number of instances")
cluster_min_size = template.add_parameter(Parameter(
"ClusterMinSize",
Type="Number",
Description="The minimum number of EC2 instances to launch in your ECS cluster",
Default=1,
MinValue=1,
))
template.add_parameter_to_group(cluster_min_size, cluster_params_group)
template.set_parameter_label(cluster_min_size, "Minimum number of instances")
cluster_max_size = template.add_parameter(Parameter(
"ClusterMaxSize",
Type="Number",
Description="The maximum number of EC2 instances to launch in your ECS cluster",
Default=5,
MinValue=1,
))
template.add_parameter_to_group(cluster_max_size, cluster_params_group)
template.set_parameter_label(cluster_max_size, "Maximum number of instances")
cluster_target_capacity_utilization = template.add_parameter(Parameter(
"ClusterTargetCapacityUtilization",
Type="Number",
Description=("The target capacity utilization as a percentage for the EC2 Auto Scaling group."
" For example, if you want the Auto Scaling group to maintain 10% spare capacity,"
" then that means the utilization is 90%, so use a value of 90. The value of 100"
" percent results in the Amazon EC2 instances in your Auto Scaling group being"
" completely used"),
Default=100,
MinValue=1,
MaxValue=100,
))
template.add_parameter_to_group(cluster_target_capacity_utilization, cluster_params_group)
template.set_parameter_label(cluster_target_capacity_utilization, "Target capacity utilization")
cluster_on_demand_percentage = template.add_parameter(Parameter(
"ClusterOnDemandPercentage",
Type="Number",
Description=("Controls the percentages of On-Demand Instances and Spot Instances in the EC2"
" Auto Scaling group. If set to 100, only On-Demand Instances are used"),
Default=100,
MinValue=1,
MaxValue=100,
))
template.add_parameter_to_group(cluster_on_demand_percentage, cluster_params_group)
template.set_parameter_label(cluster_on_demand_percentage, "On-Demand instances percentage")
cluster_add_warm_pool = template.add_parameter(Parameter(
"ClusterAddWramPool",
Type="String",
Description=("Create a pool of pre-initialized EC2 instances that sits alongside the EC2 Auto"
" Scaling group. Whenever your application needs to scale out, the Auto Scaling"
" group can draw on the warm pool to meet its new desired capacity. Can not be"
" used if ClusterOnDemandPercentage is below 100"),
Default="Yes",
AllowedValues=yes_no,
))
template.add_parameter_to_group(cluster_add_warm_pool, cluster_params_group)
template.set_parameter_label(cluster_add_warm_pool, "Add warm pool")
# Service ----------------------------------------------------------------------
if args.no_cluster:
ecs_cluster = template.add_parameter(Parameter(
"ClusterName",
Type="String",
Description="Name (not ARN!) of ECS cluster to deploy imgproxy into",
AllowedPattern="[a-zA-Z0-9-_]+",
ConstraintDescription="Must be a valid ECS cluster name",
))
template.add_parameter_to_group(ecs_cluster, service_params_group)
template.set_parameter_label(ecs_cluster, "ECS cluster name")
cpu_arch = template.add_parameter(Parameter(
"CpuArchitecture",
Type="String",
Description="CPU architecture of the Docker image. ARM64 is highly recommended",
Default="ARM64",
AllowedValues=[
"ARM64",
"AMD64"
],
))
template.add_parameter_to_group(cpu_arch, service_params_group)
template.set_parameter_label(cpu_arch, "CPU architecture")
docker_image = template.add_parameter(Parameter(
"DockerImage",
Type="String",
Description=("The imgproxy or imgproxy Pro Docker image name stored in a public registry or your"
" ECR registry"),
Default="darthsim/imgproxy:v3",
))
template.add_parameter_to_group(docker_image, service_params_group)
template.set_parameter_label(docker_image, "Docker image")
container_cpu = template.add_parameter(Parameter(
"ContainerCpu",
Type="Number",
Description="Amount of CPU to give to the container. 1024 is 1 CPU",
Default=1024,
MinValue=1024,
))
template.add_parameter_to_group(container_cpu, service_params_group)
template.set_parameter_label(container_cpu, "CPU per task")
container_memory = template.add_parameter(Parameter(
"ContainerMemory",
Type="Number",
Description="Amount of memory in megabytes to give to the container",
Default=2048 if args.launch_type == "fargate" else 1536,
MinValue=2048 if args.launch_type == "fargate" else 512,
))
template.add_parameter_to_group(container_memory, service_params_group)
template.set_parameter_label(container_memory, "Memory per task")
task_desired_count = template.add_parameter(Parameter(
"TaskDesiredCount",
Type="Number",
Description="Number of imgproxy instances to initially launch in your service",
Default=2,
MinValue=1,
))
template.add_parameter_to_group(task_desired_count, service_params_group)
template.set_parameter_label(task_desired_count, "Desired number of tasks")
task_min_count = template.add_parameter(Parameter(
"TaskMinCount",
Type="Number",
Description="Mainimum number of imgproxy instances we can launch in your service",
Default=2,
))
template.add_parameter_to_group(task_min_count, service_params_group)
template.set_parameter_label(task_min_count, "Minimum number of tasks")
task_max_count = template.add_parameter(Parameter(
"TaskMaxCount",
Type="Number",
Description="Maximum number of imgproxy instances we can launch in your service",
Default=8,
))
template.add_parameter_to_group(task_max_count, service_params_group)
template.set_parameter_label(task_max_count, "Maximum number of tasks")
# Configuration ----------------------------------------------------------------
environment_systems_manager_parameters_path = template.add_parameter(Parameter(
"EnvironmentSystemsManagerParametersPath",
Type="String",
Description=("A path of AWS Systems Manager Parameter Store parameters that should be loaded as"
" environment variables. The path should start with a slash (/) but should not have"
" a slash (/) at the end. For example, if you want to load the IMGPROXY_KEY variable"
" from the /imgproxy/prod/IMGPROXY_KEY parameter, the value should be"
" /imgproxy/prod. If not set, imgproxy will load environment variables from the"
" /${StackName} path."),
Default="",
))
template.add_parameter_to_group(environment_systems_manager_parameters_path,
configuration_params_group)
template.set_parameter_label(environment_systems_manager_parameters_path,
"Systems Manager Parameter Store parameters path (optional)")
# S3 ---------------------------------------------------------------------------
s3_objects = template.add_parameter(Parameter(
"S3Objects",
Type="CommaDelimitedList",
Description=("ARNs of S3 objects (comma delimited) that imgproxy should have access to. You can"
" grant access to multiple objects with a single ARN by using wildcards. Example:"
" arn:aws:s3:::my-images-bucket/*,arn:aws:s3:::my-assets-bucket/images/*"),
Default="",
))
template.add_parameter_to_group(s3_objects, s3_params_group)
template.set_parameter_label(s3_objects, "S3 objects (optional)")
s3_assume_role_arn = template.add_parameter(Parameter(
"S3AssumeRoleARN",
Type="String",
Description=("ARN of IAM Role that S3 client should assume. This allows you to provide imgproxy"
" access to third-party S3 buckets that the assummed IAM Role has access to"),
Default="",
))
template.add_parameter_to_group(s3_assume_role_arn, s3_params_group)
template.set_parameter_label(s3_assume_role_arn, "IAM Role ARN to assume (optional)")
s3_multi_region = template.add_parameter(Parameter(
"S3MultiRegion",
Type="String",
Description=("Should imgproxy be able to access S3 buckets in other regions? By default, imgproxy"
" can access only S3 buckets locates in the same region as imgproxy"),
Default="No",
AllowedValues=yes_no,
))
template.add_parameter_to_group(s3_multi_region, s3_params_group)
template.set_parameter_label(s3_multi_region, "Enable multi-region mode")
s3_client_side_decryption = template.add_parameter(Parameter(
"S3ClientSideDecryption",
Type="String",
Description=("Should imgproxy use S3 decryption client? The decription client will be used for"
"all objects in all S3 buckets, so unecrypted objects won't be accessable"),
Default="No",
AllowedValues=yes_no,
))
template.add_parameter_to_group(s3_client_side_decryption, s3_params_group)
template.set_parameter_label(s3_client_side_decryption, "Enable client-side decryption")
# Endpoint ---------------------------------------------------------------------
path_prefix = template.add_parameter(Parameter(
"PathPrefix",
Type="String",
Description=("Path prefix, beginning with a slash (/)."
"Do not add a slash (/) at the end of the path"),
Default="",
))
template.add_parameter_to_group(path_prefix, endpoint_params_group)
template.set_parameter_label(path_prefix, "Path prefix (optional)")
if not args.no_network:
create_cloudfront_distribution = template.add_parameter(Parameter(
"CreateCloudFrontDistribution",
Type="String",
Description=("Should caching CloudFront distribution be created? This CloudFront distribution"
" will automatically add the path prefix when requesting the origin. Also, it"
" will automatically add X-Imgproxy-Auth header with the provided authorization"
" token"),
Default="Yes",
AllowedValues=yes_no,
))
template.add_parameter_to_group(create_cloudfront_distribution, endpoint_params_group)
template.set_parameter_label(create_cloudfront_distribution, "Create CloudForont distribution?")
authorization_token = template.add_parameter(Parameter(
"AuthorizationToken",
Type="String",
Description=("The authorization token token that should be provided via the X-Imgproxy-Auth"
" header to get access to imgproxy. Allows to prevent access to imgproxy bypassing"
" CDN. The X-Imgproxy-Auth header will be checked by the load balancer listener"
" rule"),
Default="",
))
template.add_parameter_to_group(authorization_token, endpoint_params_group)
template.set_parameter_label(authorization_token, "Authorization token (optional)")
# ==============================================================================
# CONDITIONS
# ==============================================================================
if args.launch_type == "ec2" and not args.no_cluster:
cluster_use_spot = template.add_condition(
"ClusterUseSpot",
Not(Equals(Ref(cluster_on_demand_percentage), 100)),
)
cluster_should_add_warm_pool = template.add_condition(
"ClusterShouldAddWramPool",
IfYes(cluster_add_warm_pool),
)
have_environment_systems_manager_parameters_path = template.add_condition(
"HaveEnvironmentSystemsManagerParametersPath",
Not(Equals(Ref(environment_systems_manager_parameters_path), "")),
)
have_s3_objects = template.add_condition(
"HaveS3Objects",
Not(Equals(Join("", Ref(s3_objects)), "")),
)
have_s3_assume_role_arn = template.add_condition(
"HaveS3AssumeRole",
Not(Equals(Ref(s3_assume_role_arn), "")),
)
enable_s3_multi_region = template.add_condition(
"EnableS3MultiRegion",
IfYes(s3_multi_region),
)
enable_s3_client_side_decryption = template.add_condition(
"EnableS3ClientSideDecryption",
IfYes(s3_client_side_decryption),
)
have_path_prefix = template.add_condition(
"HavePathPrefix",
Not(Equals(Ref(path_prefix), "")),
)
if not args.no_network:
deploy_cloudfront = template.add_condition(
"DeployCloudFront",
IfYes(create_cloudfront_distribution),
)
have_authorization_token = template.add_condition(
"HaveAuthorizationToken",
Not(Equals(Ref(authorization_token), "")),
)
# ==============================================================================
# RULES
# ==============================================================================
if args.launch_type == "ec2" and not args.no_cluster:
template.add_rule(
"testWarmPoolAndNoSpot",
{
"RuleCondition": Not(Equals(Ref(cluster_on_demand_percentage), "100")),
"Assertions": [
{
"Assert": Not(IfYes(cluster_add_warm_pool)),
"AssertDescription": "Can't use a warm pool if ClusterOnDemandPercentage is below 100"
}
]
}
)
template.add_rule(
"testArm64InstanceType",
{
"RuleCondition": Equals(Ref(cpu_arch), "ARM64"),
"Assertions": [
{
"Assert": Contains(arm64_instance_types, Ref(cluster_instance_type)),
"AssertDescription": "ARM64 service requires ARM64-compatible instance type"
}
]
}
)
template.add_rule(
"testAmd64InstanceType",
{
"RuleCondition": Equals(Ref(cpu_arch), "AMD64"),
"Assertions": [
{
"Assert": Contains(amd64_instance_types, Ref(cluster_instance_type)),
"AssertDescription": "AMD64 service requires AMD64-compatible instance type"
}
]
}
)
# ==============================================================================
# MAPPINGS
# ==============================================================================
template.add_mapping("Architectures", {
"ARM64": {
"Arch": "ARM64",
"ImageId": "{{resolve:ssm:/aws/service/bottlerocket/aws-ecs-2/arm64/latest/image_id}}",
},
"AMD64": {
"Arch": "X86_64",
"ImageId": "{{resolve:ssm:/aws/service/bottlerocket/aws-ecs-2/x86_64/latest/image_id}}",
},
})
if not args.no_network:
template.add_mapping("OriginShieldRegionMap", {
# Regions with origin shield
"us-east-2": {"Region": "us-east-2"},
"us-east-1": {"Region": "us-east-1"},
"us-west-2": {"Region": "us-west-2"},
"ap-south-1": {"Region": "ap-south-1"},
"ap-northeast-2": {"Region": "ap-northeast-2"},
"ap-southeast-1": {"Region": "ap-southeast-1"},
"ap-southeast-2": {"Region": "ap-southeast-2"},
"ap-northeast-1": {"Region": "ap-northeast-1"},
"eu-central-1": {"Region": "eu-central-1"},
"eu-west-1": {"Region": "eu-west-1"},
"eu-west-2": {"Region": "eu-west-2"},
"sa-east-1": {"Region": "sa-east-1"},
# Regions without origin shield
"us-west-1": {"Region": "us-west-2"},
"af-south-1": {"Region": "eu-west-1"},
"ap-east-1": {"Region": "ap-southeast-1"},
"ca-central-1": {"Region": "us-east-1"},
"eu-south-1": {"Region": "eu-central-1"},
"eu-west-3": {"Region": "eu-west-2"},
"eu-north-1": {"Region": "eu-west-2"},
"me-south-1": {"Region": "ap-south-1"},
})
# ==============================================================================
# CLOUDWATCH LOGS
# ==============================================================================
log_group = template.add_resource(logs.LogGroup(
"CloudWatchLogGroup",
LogGroupName=StackName,
RetentionInDays=365,
))
# ==============================================================================
# NETWORK
# ==============================================================================
gateway_attachement = None
if not args.no_network:
vpc = template.add_resource(ec2.VPC(
"VPC",
EnableDnsSupport=True,
EnableDnsHostnames=True,
CidrBlock="10.0.0.0/16",
Tags=[
Tag("Name", Join("-", [StackName, "VPC"])),
],
))
internet_gateway = template.add_resource(ec2.InternetGateway(
"InternetGateway",
Tags=[
Tag("Name", Join("-", [StackName, "Internet-Gateway"])),
],
))
gateway_attachement = template.add_resource(ec2.VPCGatewayAttachment(
"GatewayAttachement",
VpcId=Ref(vpc),
InternetGatewayId=Ref(internet_gateway),
))
route_table = template.add_resource(ec2.RouteTable(
"PublicRouteTable",
VpcId=Ref(vpc),
Tags=[
Tag("Name", Join("-", [StackName, "Routes"])),
],
))
template.add_resource(ec2.Route(
"PublicRoute",
DependsOn=gateway_attachement,
RouteTableId=Ref(route_table),
DestinationCidrBlock="0.0.0.0/0",
GatewayId=Ref(internet_gateway),
))
subnet_refs = []
for n in range(args.subnets_number):
subnet = template.add_resource(ec2.Subnet(
"PublicSubnet{0}".format(n),
AvailabilityZone=Select(n, GetAZs()),
VpcId=Ref(vpc),
CidrBlock="10.0.{0}.0/20".format(n * 16),
MapPublicIpOnLaunch=True,
Tags=[
Tag("Name", Join("-", [StackName, "Subnet", str(n)]))
],
))
template.add_resource(ec2.SubnetRouteTableAssociation(
"PublicSubnet{0}RouteTableAssociation".format(n),
SubnetId=Ref(subnet),
RouteTableId=Ref(route_table),
))
subnet_refs.append(Ref(subnet))
# This security group defines who/where is allowed to access the Application Load Balancer.
# By default, we've opened this up to the public internet (0.0.0.0/0) but can you restrict
# it further if you want.
load_balancer_security_group = template.add_resource(ec2.SecurityGroup(
"LoadBalancerSecurityGroup",
VpcId=Ref(vpc),
GroupDescription="Access to the load balancer that sits in front of ECS",
SecurityGroupIngress=[
# Allow access from anywhere to our ECS services
{"CidrIp": "0.0.0.0/0", "IpProtocol": -1},
],
Tags=[
Tag("Name", Join("-", [StackName, "SG-LoadBalancers"])),
],
))
# This security group defines who/where is allowed to access the ECS hosts directly.
# By default we're just allowing access from the load balancer. If you want to SSH
# into the hosts, or expose non-load balanced services you can open their ports here.
ecs_host_security_group = template.add_resource(ec2.SecurityGroup(
"ECSHostSecurityGroup",
VpcId=Ref(vpc),
GroupDescription="Access to the ECS hosts and the tasks/containers that run on them",
SecurityGroupIngress=[
# Only allow inbound access to ECS from the ELB
{"SourceSecurityGroupId": Ref(load_balancer_security_group), "IpProtocol": -1},
],
Tags=[
Tag("Name", Join("-", [StackName, "SG-ECS-Hosts"])),
],
))
elif not args.no_cluster or args.launch_type == "fargate":
subnet_refs = Ref(subnets)
# ==============================================================================
# ECS CLUSTER
# ==============================================================================
if not args.no_cluster:
ecs_cluster = template.add_resource(ecs.Cluster(
"ECSCluster",
ClusterName=Join("-", [StackName, "Cluster"]),
))
# ==============================================================================
# ECS CAPACITY PROVIDER
# ==============================================================================
ecs_capacity_provider_associations = None
if not args.no_cluster:
if args.launch_type == "ec2":
ec2_instance_role = template.add_resource(iam.Role(
"EC2InstanceRole",
RoleName=Join("-", [StackName, "ec2-instance"]),
Path="/",
AssumeRolePolicyDocument=aws.PolicyDocument(
Version="2012-10-17",
Statement=[aws.Statement(
Effect=aws.Allow,
Action=[actions_sts.AssumeRole],
Principal=aws.Principal("Service", ["ec2.amazonaws.com"]),
)],
),
ManagedPolicyArns=[
"arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role",
],
Policies=[iam.Policy(
PolicyName="cloudformation-signal",
PolicyDocument=aws.PolicyDocument(
Version="2012-10-17",
Statement=[aws.Statement(
Effect=aws.Allow,
Action=[
actions_cloudformation.DescribeStackResource,
actions_cloudformation.SignalResource,
],
Resource=[
Join("",
["arn:aws:cloudformation:", Region, ":", AccountId, ":stack/", StackName, "/*"])
],
)],
),
)],
))
ec2_instance_profile = template.add_resource(iam.InstanceProfile(
"EC2InstanceProfile",
Path="/",
Roles=[Ref(ec2_instance_role)],
))
ec2_autoscaling_group_title = "EC2AutoScalingGroup"
ec2_launch_template = template.add_resource(ec2.LaunchTemplate(
"EC2LaunchTemplate",
LaunchTemplateName=Join("-", [StackName, "Launch-Template"]),
LaunchTemplateData=ec2.LaunchTemplateData(
ImageId=FindInMap("Architectures", Ref(cpu_arch), "ImageId"),
SecurityGroupIds=[Ref(ecs_host_security_group)],
InstanceType=Ref(cluster_instance_type),
IamInstanceProfile=ec2.IamInstanceProfile(Name=Ref(ec2_instance_profile)),
UserData=Base64(Sub("""
[settings.ecs]
cluster = "${{{cluster}}}"
[settings.autoscaling]
should-wait = true
[settings.cloudformation]
should-signal = true
stack-name = "${{AWS::StackName}}"
logical-resource-id = "{autoscaling_group}"
""".strip().format(cluster=ecs_cluster.title,
autoscaling_group=ec2_autoscaling_group_title))),
),
))
ec2_autoscaling_group = template.add_resource(autoscaling.AutoScalingGroup(
ec2_autoscaling_group_title,
VPCZoneIdentifier=subnet_refs,
MixedInstancesPolicy=If(
cluster_use_spot,
autoscaling.MixedInstancesPolicy(
LaunchTemplate=autoscaling.LaunchTemplate(
LaunchTemplateSpecification=autoscaling.LaunchTemplateSpecification(
LaunchTemplateId=Ref(ec2_launch_template),
Version=GetAtt(ec2_launch_template, "LatestVersionNumber"),
),
),
InstancesDistribution=autoscaling.InstancesDistribution(
OnDemandBaseCapacity=1,
OnDemandPercentageAboveBaseCapacity=Ref(cluster_on_demand_percentage),
SpotAllocationStrategy="price-capacity-optimized",
),
),
NoValue,
),
LaunchTemplate=If(
cluster_use_spot,
NoValue,
autoscaling.LaunchTemplateSpecification(
LaunchTemplateId=Ref(ec2_launch_template),
Version=GetAtt(ec2_launch_template, "LatestVersionNumber"),
),
),
MinSize=Ref(cluster_min_size),
MaxSize=Ref(cluster_max_size),
DesiredCapacity=Ref(cluster_deised_size),
Tags=[
autoscaling.Tag("Name", Join("-", [StackName, "ECS-ASG"]), True),
],
CreationPolicy=policies.CreationPolicy(
ResourceSignal=policies.ResourceSignal(
Timeout="PT15M",
),
),
UpdatePolicy=policies.UpdatePolicy(
AutoScalingRollingUpdate=If(
cluster_should_add_warm_pool,
NoValue,
policies.AutoScalingRollingUpdate(
MinInstancesInService=1,
MaxBatchSize=1,
PauseTime="PT15M",
SuspendProcesses=[
"HealthCheck",
"ReplaceUnhealthy",
"AZRebalance",
"AlarmNotification",
"ScheduledActions",
],
WaitOnResourceSignals=True,
),
),
),
))
template.add_resource(autoscaling.WarmPool(
"EC2AutoScalingGroupWarmPool",
Condition=cluster_should_add_warm_pool,
AutoScalingGroupName=Ref(ec2_autoscaling_group),
# ReuseOnScaleIn should be disabled.
# If an instance is returned to the warm pool and then reused, its status
# will still be "Draining" in ECS and it will not be able to accept new tasks.
# See https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using-warm-pool.html
InstanceReusePolicy=autoscaling.InstanceReusePolicy(
ReuseOnScaleIn=False,
),
))
ecs_capacity_provider = template.add_resource(ecs.CapacityProvider(
"ECSCapacityProvider",
AutoScalingGroupProvider=ecs.AutoScalingGroupProvider(
AutoScalingGroupArn=Ref(ec2_autoscaling_group),
ManagedScaling=ecs.ManagedScaling(
MaximumScalingStepSize=4,
MinimumScalingStepSize=1,
Status="ENABLED",
TargetCapacity=Ref(cluster_target_capacity_utilization),
),
),
))
ecs_capacity_provider_associations = \
template.add_resource(ecs.ClusterCapacityProviderAssociations(
"ECSClusterCapacityProviderAssociations",
Cluster=Ref(ecs_cluster),
CapacityProviders=[Ref(ecs_capacity_provider)],
DefaultCapacityProviderStrategy=[ecs.CapacityProviderStrategy(
Base=1,
Weight=10,
CapacityProvider=Ref(ecs_capacity_provider),
)],
))
else: # if args.launch_type == "ec2"
ecs_capacity_provider_associations = \
template.add_resource(ecs.ClusterCapacityProviderAssociations(
"ECSClusterCapacityProviderAssociations",
Cluster=Ref(ecs_cluster),
CapacityProviders=["FARGATE"],
DefaultCapacityProviderStrategy=[
ecs.CapacityProviderStrategy(
Base=1,
Weight=10,
CapacityProvider="FARGATE",
),
],
))
# ==============================================================================
# EC2 AUTOSCALING GROUP INSTANCE REFRESHER
# ==============================================================================
if not args.no_cluster and args.launch_type == "ec2":
instance_refresher_role = template.add_resource(iam.Role(
"InstanceRefresherLambdaRole",
Condition=cluster_should_add_warm_pool,
RoleName=Join("-", [StackName, "instance-refresher"]),
Path="/",
AssumeRolePolicyDocument=aws.PolicyDocument(
Version="2012-10-17",
Statement=[aws.Statement(
Effect=aws.Allow,
Action=[actions_sts.AssumeRole],
Principal=aws.Principal("Service", ["lambda.amazonaws.com"]),
)],
),
ManagedPolicyArns=[
"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
],
Policies=[
iam.Policy(
PolicyName="autoscaling-start-instance-refresh",
PolicyDocument=aws.PolicyDocument(
Version="2012-10-17",
Statement=[aws.Statement(
Effect=aws.Allow,
Action=[
actions_autoscaling.StartInstanceRefresh,
],
Resource=["*"],
)],
),
),
],
))
instance_refresher_lambda = template.add_resource(aws_lambda.Function(
"InstanceRefresherLambda",
Condition=cluster_should_add_warm_pool,
FunctionName=Join("-", [StackName, "instance-refresher"]),
Runtime="python3.12",
Handler="index.handler",
Role=GetAtt(instance_refresher_role, "Arn"),
Timeout=30,
Code=aws_lambda.Code(
ZipFile="""
import cfnresponse
import json
import boto3
client = boto3.client('autoscaling')
def handler(event, context):
response_data = {}
try:
if event['RequestType'] != 'Create' and event['RequestType'] != 'Update':
cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data, 'InstanceRefresher')
return
response = client.start_instance_refresh(
AutoScalingGroupName=event['ResourceProperties']['AutoScalingGroupName'],
Preferences={
'MinHealthyPercentage': 100,
'MaxHealthyPercentage': 200,
'SkipMatching': True,
'ScaleInProtectedInstances': 'Ignore',
'StandbyInstances': 'Ignore'
}
)
response_data['InstanceRefreshId'] = response['InstanceRefreshId']
cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data, 'InstanceRefresher')
except Exception as e:
response_data['exception'] = e.__str__()
cfnresponse.send(event, context, cfnresponse.FAILED, response_data, 'InstanceRefresher')
""".strip(),
),
))
class CustomPlacementGroup(cloudformation.AWSCustomObject):
resource_type = "Custom::InstanceRefresher"
props = {
"ServiceToken": (str, True),
"ServiceTimeout": (str, True),
"AutoScalingGroupName": (str, True),
"LaunchTemplate": (str, True),
"LaunchTemplateVersion": (str, True),
}
template.add_resource(CustomPlacementGroup(
"EC2InstanceRefresher",
Condition=cluster_should_add_warm_pool,