-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.yaml
More file actions
3768 lines (3341 loc) · 143 KB
/
Copy pathtemplate.yaml
File metadata and controls
3768 lines (3341 loc) · 143 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: "Tolling Vision ANPR/MMR Infrastructure - Complete deployment with Lambda custom resources for SAR compatibility"
Metadata:
AWS::ServerlessRepo::Application:
Name: tolling-vision
Description: "Complete Tolling Vision ANPR/MMR infrastructure. Deploys secure, scalable computer vision processing with optional WAF/JWT protection."
Author: "Smart Cloud Solutions Inc."
SpdxLicenseId: MIT
LicenseUrl: LICENSE
ReadmeUrl: README.md
Labels:
- "tolling"
- "image-review"
- "anpr"
- "mmr"
- "computer-vision"
- "infrastructure"
- "security"
HomePageUrl: https://tollingvision.com
SemanticVersion: 1.0.0
SourceCodeUrl: https://github.com/tollingvision/sar-cluster
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: "Required Configuration"
Parameters:
- LicenseKey
- MaxSize
- Label:
default: "Docker Container Configuration"
Parameters:
- ProcessCount
- ImageArchitecture
- ImageTag
- ConcurrentRequestCount
- MaxRequestSize
- Backlog
- BacklogTimeout
- RequestTimeout
- Label:
default: "Auto Scaling Configuration"
Parameters:
- DesiredCapacity
- MinSize
- OnDemandPercentage
- KeyPairName
- EnableDetailedMonitoring
- Label:
default: "Domain and SSL Configuration"
Parameters:
- DomainName
- CertificateArn
- EnableDNS
- Label:
default: "JWT Authentication (Container-based)"
Parameters:
- CognitoUserPoolId
- CognitoRegion
- CognitoAppClientId
- CognitoRequiredScope
- Label:
default: "Security (WAF Protection)"
Parameters:
- EnableWAF
- AllowedIpCidrs
- EnableAWSManagedRules
- Label:
default: "Network Configuration"
Parameters:
- VpcCidr
- PrivateSubnet1Cidr
- PrivateSubnet2Cidr
- PublicSubnet1Cidr
- PublicSubnet2Cidr
- Label:
default: "Observability & Logging"
Parameters:
- CloudWatchLogRetentionDays
- EnableSNSNotifications
- SNSNotificationEmail
- EnableCustomMetrics
- EnableALBAccessLogs
- ALBAccessLogsBucketName
ParameterLabels:
# Required Configuration
LicenseKey:
default: "Tolling Vision License Key *"
MaxSize:
default: "Maximum Instance Count *"
# Docker Container Configuration
ProcessCount:
default: "Processing Thread Count"
ImageArchitecture:
default: "Container Architecture"
ImageTag:
default: "Container Image Tag"
ConcurrentRequestCount:
default: "Concurrent Requests per Process"
MaxRequestSize:
default: "Maximum Request Size (bytes)"
Backlog:
default: "Request Queue Size"
BacklogTimeout:
default: "Queue Timeout (seconds)"
RequestTimeout:
default: "Request Timeout (seconds)"
# Auto Scaling Configuration
DesiredCapacity:
default: "Desired Instance Count"
MinSize:
default: "Minimum Instance Count"
OnDemandPercentage:
default: "On-Demand Instance Percentage"
KeyPairName:
default: "EC2 Key Pair (optional)"
EnableDetailedMonitoring:
default: "Enable Detailed CloudWatch Monitoring"
# API Gateway Configuration
# Domain and SSL Configuration
DomainName:
default: "Custom Domain Name (optional)"
CertificateArn:
default: "ACM Certificate ARN (optional)"
EnableDNS:
default: "Create Route53 DNS Records (Auto-Discovery)"
# JWT Authentication (Container-based)
CognitoUserPoolId:
default: "Cognito User Pool ID (optional)"
CognitoRegion:
default: "Cognito Region (optional)"
CognitoAppClientId:
default: "Cognito App Client ID (optional)"
CognitoRequiredScope:
default: "Required JWT Scope (optional)"
# Security Configuration
EnableWAF:
default: "Enable WAF Protection"
AllowedIpCidrs:
default: "IP CIDR Ranges for Allow/Deny List"
EnableAWSManagedRules:
default: "Enable AWS Managed Rule Groups"
# Network Configuration
VpcCidr:
default: "VPC CIDR Block"
PrivateSubnet1Cidr:
default: "Private Subnet 1 CIDR"
PrivateSubnet2Cidr:
default: "Private Subnet 2 CIDR"
PublicSubnet1Cidr:
default: "Public Subnet 1 CIDR"
PublicSubnet2Cidr:
default: "Public Subnet 2 CIDR"
# Observability Configuration
EnableALBAccessLogs:
default: "Enable ALB Access Logs"
ALBAccessLogsBucketName:
default: "ALB Logs S3 Bucket (optional)"
CloudWatchLogRetentionDays:
default: "CloudWatch Log Retention (days)"
EnableSNSNotifications:
default: "Enable SNS Notifications"
SNSNotificationEmail:
default: "Notification Email Address"
EnableCustomMetrics:
default: "Enable Custom Application Metrics"
Parameters:
# ========================================
# Docker Image Configuration Parameters
# ========================================
LicenseKey:
Type: String
Description: "Tolling Vision license key for container activation and tollingvision.com validation"
NoEcho: true
MinLength: 10
MaxLength: 256
AllowedPattern: "^[A-Za-z0-9+/=_-]+$"
ConstraintDescription: "Must be a valid Tolling Vision license key (10-256 characters, alphanumeric and special chars)"
ProcessCount:
Type: Number
Default: 1
MinValue: 1
MaxValue: 64
Description: "Number of processing threads (affects memory requirements: 3GB + 1GB per additional process)"
ConstraintDescription: "Must be between 1 and 64 processes"
ConcurrentRequestCount:
Type: Number
Default: 1
MinValue: 1
MaxValue: 100
Description: "Maximum number of concurrent requests per process"
ConstraintDescription: "Must be between 1 and 100 concurrent requests"
MaxRequestSize:
Type: Number
Default: 6291456
MinValue: 1048576
MaxValue: 104857600
Description: "Maximum request size in bytes (default 6MB, max 100MB)"
ConstraintDescription: "Must be between 1MB (1048576) and 100MB (104857600) bytes"
Backlog:
Type: Number
Default: 10
MinValue: 1
MaxValue: 1000
Description: "Request backlog queue size"
ConstraintDescription: "Must be between 1 and 1000"
BacklogTimeout:
Type: Number
Default: 60
MinValue: 1
MaxValue: 300
Description: "Backlog timeout in seconds"
ConstraintDescription: "Must be between 1 and 300 seconds"
RequestTimeout:
Type: Number
Default: 30
MinValue: 1
MaxValue: 300
Description: "Individual request timeout in seconds"
ConstraintDescription: "Must be between 1 and 300 seconds"
ImageArchitecture:
Type: String
Default: "arm64"
AllowedValues: ["arm64", "x86-64"]
Description: "Container image architecture (affects instance type selection and performance)"
ImageTag:
Type: String
Default: "arm64"
MinLength: 1
MaxLength: 128
AllowedPattern: "^[a-zA-Z0-9._-]+$"
Description: "Container image tag (should match ImageArchitecture unless using specific version)"
ConstraintDescription: "Must be a valid Docker tag (alphanumeric, dots, hyphens, underscores)"
# ========================================
# EC2 and Auto Scaling Configuration
# ========================================
DesiredCapacity:
Type: Number
Default: 0
MinValue: 0
MaxValue: 100
Description: "Desired number of EC2 instances in Auto Scaling Group (0 for cost optimization)"
ConstraintDescription: "Must be between 0 and 100 instances"
MinSize:
Type: Number
Default: 0
MinValue: 0
MaxValue: 100
Description: "Minimum number of EC2 instances in Auto Scaling Group"
ConstraintDescription: "Must be between 0 and 100 instances"
MaxSize:
Type: Number
MinValue: 1
MaxValue: 100
Description: "Maximum number of EC2 instances in Auto Scaling Group (required)"
ConstraintDescription: "Must be between 1 and 100 instances"
OnDemandPercentage:
Type: Number
Default: 100
MinValue: 0
MaxValue: 100
Description: "Percentage of On-Demand instances (remainder will be Spot instances for cost savings)"
ConstraintDescription: "Must be between 0 and 100 percent"
KeyPairName:
Type: String
Default: ""
Description: "Optional EC2 Key Pair name for SSH access (leave empty for no SSH access - recommended for security)"
AllowedPattern: "^$|^[a-zA-Z0-9_-]+$"
ConstraintDescription: "Must be empty or a valid EC2 Key Pair name"
EnableDetailedMonitoring:
Type: String
Default: "false"
AllowedValues: ["true", "false"]
Description: "Enable detailed CloudWatch monitoring for EC2 instances (additional cost)"
# ========================================
# API Gateway and Domain Configuration
# ========================================
DomainName:
Type: String
Default: ""
MinLength: 0
MaxLength: 253
AllowedPattern: '^$|^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
Description: "Optional custom domain name for ALB (e.g., api.example.com). Leave empty to use ALB DNS name."
ConstraintDescription: "Must be empty or a valid domain name (e.g., api.example.com)"
CertificateArn:
Type: String
Default: ""
AllowedPattern: "^$|^arn:aws:acm:[a-z0-9-]+:[0-9]{12}:certificate/[a-f0-9-]+$"
Description: "Optional ARN of the SSL certificate in ACM for HTTPS/TLS termination. Required if DomainName is specified."
ConstraintDescription: "Must be empty or a valid ACM certificate ARN"
EnableDNS:
Type: String
Default: "false"
AllowedValues: ["true", "false"]
Description: "Create Route53 DNS records pointing to the ALB. Requires DomainName. Hosted zone will be auto-discovered."
# ========================================
# JWT Authentication Configuration (Container-based)
# ========================================
CognitoUserPoolId:
Type: String
Default: ""
AllowedPattern: "^$|^[a-zA-Z0-9-]+_[a-zA-Z0-9]+$"
Description: "Existing Cognito User Pool ID for JWT validation (leave empty to disable authentication)"
ConstraintDescription: "Must be empty or a valid Cognito User Pool ID format (e.g., us-east-1_XXXXXXXXX)"
CognitoRegion:
Type: String
Default: ""
AllowedPattern: "^$|^[a-z0-9-]+$"
Description: "AWS region for Cognito User Pool. Defaults to current stack region if empty."
ConstraintDescription: "Must be empty or a valid AWS region (e.g., us-east-1)"
CognitoAppClientId:
Type: String
Default: ""
AllowedPattern: "^$|^[a-zA-Z0-9]+$"
Description: "Cognito App Client ID for JWT validation (leave empty to disable authentication)"
ConstraintDescription: "Must be empty or a valid Cognito App Client ID"
CognitoRequiredScope:
Type: String
Default: ""
AllowedPattern: "^$|^[a-zA-Z0-9_/-]+$"
Description: "Required JWT scope for API access (leave empty to disable authentication)"
ConstraintDescription: "Must be empty or a valid scope format (e.g., api/m2m)"
# ALB Access Logging
EnableALBAccessLogs:
Type: String
Default: "false"
AllowedValues: ["true", "false"]
Description: "Enable ALB access logs to S3 bucket (creates S3 bucket automatically)"
ALBAccessLogsBucketName:
Type: String
Default: ""
AllowedPattern: "^$|^[a-z0-9][a-z0-9-]*[a-z0-9]$"
ConstraintDescription: "Must be empty or a valid S3 bucket name (lowercase, alphanumeric, hyphens)"
Description: "S3 bucket name for ALB access logs (leave empty for auto-generated name)"
# ========================================
# Security Configuration (WAF)
# ========================================
EnableWAF:
Type: String
Default: "false"
AllowedValues: ["true", "false"]
Description: "Enable WAF protection with IP allowlisting (recommended for production)"
AllowedIpCidrs:
Type: CommaDelimitedList
Default: ""
Description: "Comma-separated list of IP CIDR ranges for allow/deny list (e.g., 10.0.0.0/8,192.168.1.0/24). Used when EnableWAF is true."
EnableAWSManagedRules:
Type: String
Default: "true"
AllowedValues: ["true", "false"]
Description: "Enable free AWS Managed Rule Groups (Common, Known Bad Inputs, Linux, IP Reputation)"
# ========================================
# Network Configuration
# ========================================
VpcCidr:
Type: String
Default: "10.0.0.0/16"
AllowedPattern: '^(10\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(1[6-9]|2[0-8]))$'
Description: "CIDR block for the VPC (must be /16 to /28 in 10.x.x.x range)"
ConstraintDescription: "Must be a valid private CIDR block in 10.x.x.x range with /16 to /28 prefix"
PrivateSubnet1Cidr:
Type: String
Default: "10.0.1.0/24"
AllowedPattern: '^(10\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(1[6-9]|2[0-8]))$'
Description: "CIDR block for private subnet 1 (must be within VPC CIDR)"
ConstraintDescription: "Must be a valid CIDR block within the VPC range"
PrivateSubnet2Cidr:
Type: String
Default: "10.0.2.0/24"
AllowedPattern: '^(10\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(1[6-9]|2[0-8]))$'
Description: "CIDR block for private subnet 2 (must be within VPC CIDR)"
ConstraintDescription: "Must be a valid CIDR block within the VPC range"
PublicSubnet1Cidr:
Type: String
Default: "10.0.101.0/24"
AllowedPattern: '^(10\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(1[6-9]|2[0-8]))$'
Description: "CIDR block for public subnet 1 (for NAT Gateway)"
ConstraintDescription: "Must be a valid CIDR block within the VPC range"
PublicSubnet2Cidr:
Type: String
Default: "10.0.102.0/24"
AllowedPattern: '^(10\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.(0|[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(1[6-9]|2[0-8]))$'
Description: "CIDR block for public subnet 2 (for NAT Gateway)"
ConstraintDescription: "Must be a valid CIDR block within the VPC range"
# ========================================
# Observability Configuration
# ========================================
CloudWatchLogRetentionDays:
Type: Number
Default: 7
AllowedValues:
[
1,
3,
5,
7,
14,
30,
60,
90,
120,
150,
180,
365,
400,
545,
731,
1827,
3653,
]
Description: "CloudWatch Logs retention period in days"
ConstraintDescription: "Must be a valid CloudWatch Logs retention period"
EnableSNSNotifications:
Type: String
Default: "false"
AllowedValues: ["true", "false"]
Description: "Enable SNS notifications for critical alerts and alarms"
SNSNotificationEmail:
Type: String
Default: ""
Description: "Email address for SNS notifications (required when EnableSNSNotifications is true)"
AllowedPattern: '^$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
ConstraintDescription: "Must be empty or a valid email address"
EnableCustomMetrics:
Type: String
Default: "true"
AllowedValues: ["true", "false"]
Description: "Enable custom application metrics for enhanced monitoring"
Conditions:
# ========================================
# Domain and DNS Conditions
# ========================================
HasCertificate: !Not [!Equals [!Ref CertificateArn, ""]]
NoCertificate: !Equals [!Ref CertificateArn, ""]
EnableDNS: !Equals [!Ref EnableDNS, "true"]
EnableDNSManagement: !Condition EnableDNS
# ========================================
# JWT Authentication Conditions (Container-based)
# ========================================
EnableContainerJWT: !And
- !Not [!Equals [!Ref CognitoUserPoolId, ""]]
- !Not [!Equals [!Ref CognitoAppClientId, ""]]
# ========================================
# Security Conditions (WAF)
# ========================================
EnableWAFProtection: !Equals [!Ref EnableWAF, "true"]
HasAllowedIPs: !Not [!Equals [!Join ["", !Ref AllowedIpCidrs], ""]]
# WAF with IP set requires both WAF enabled and IP CIDRs provided
EnableWAFWithIPSet: !And
- !Condition EnableWAFProtection
- !Condition HasAllowedIPs
# ========================================
# EC2 and Infrastructure Conditions
# ========================================
HasKeyPair: !Not [!Equals [!Ref KeyPairName, ""]]
# ========================================
# ALB Access Logs Conditions
# ========================================
EnableALBLogs: !Equals [!Ref EnableALBAccessLogs, "true"]
NoALBLogs: !Equals [!Ref EnableALBAccessLogs, "false"]
# ========================================
# Observability Conditions
# ========================================
HasCustomALBLogsBucket: !Not [!Equals [!Ref ALBAccessLogsBucketName, ""]]
# SNS notification conditions
EnableSNSNotificationsCondition: !Equals [!Ref EnableSNSNotifications, "true"]
# Custom metrics conditions
EnableCustomMetricsCondition: !Equals [!Ref EnableCustomMetrics, "true"]
# ========================================
# Custom Resource Creation Conditions
# ========================================
# Conditions for when to create custom resources
CreateAutoScalingResource: !Not [!Equals [!Ref MaxSize, 0]] # Create ASG when MaxSize > 0
Resources:
# ========================================
# VPC and Networking Resources
# ========================================
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: !Ref VpcCidr
EnableDnsHostnames: true
EnableDnsSupport: true
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-vpc"
InternetGateway:
Type: AWS::EC2::InternetGateway
Properties:
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-igw"
InternetGatewayAttachment:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
InternetGatewayId: !Ref InternetGateway
VpcId: !Ref VPC
# Private Subnets
PrivateSubnet1:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [0, !GetAZs ""]
CidrBlock: !Ref PrivateSubnet1Cidr
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-private-subnet-1"
PrivateSubnet2:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [1, !GetAZs ""]
CidrBlock: !Ref PrivateSubnet2Cidr
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-private-subnet-2"
# Public Subnets (for NAT Gateways)
PublicSubnet1:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [0, !GetAZs ""]
CidrBlock: !Ref PublicSubnet1Cidr
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-public-subnet-1"
PublicSubnet2:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [1, !GetAZs ""]
CidrBlock: !Ref PublicSubnet2Cidr
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-public-subnet-2"
# Elastic IPs for NAT Gateways
NATGateway1EIP:
Type: AWS::EC2::EIP
DependsOn: InternetGatewayAttachment
Properties:
Domain: vpc
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-nat-gateway-1-eip"
NATGateway2EIP:
Type: AWS::EC2::EIP
DependsOn: InternetGatewayAttachment
Properties:
Domain: vpc
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-nat-gateway-2-eip"
# NAT Gateways
NATGateway1:
Type: AWS::EC2::NatGateway
Properties:
AllocationId: !GetAtt NATGateway1EIP.AllocationId
SubnetId: !Ref PublicSubnet1
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-nat-gateway-1"
NATGateway2:
Type: AWS::EC2::NatGateway
Properties:
AllocationId: !GetAtt NATGateway2EIP.AllocationId
SubnetId: !Ref PublicSubnet2
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-nat-gateway-2"
# Route Tables
PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-public-rt"
PublicRoute:
Type: AWS::EC2::Route
DependsOn: InternetGatewayAttachment
Properties:
RouteTableId: !Ref PublicRouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
PublicSubnet1RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref PublicSubnet1
PublicSubnet2RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref PublicSubnet2
PrivateRouteTable1:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-private-rt-1"
PrivateRoute1:
Type: AWS::EC2::Route
Properties:
RouteTableId: !Ref PrivateRouteTable1
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId: !Ref NATGateway1
PrivateSubnet1RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PrivateRouteTable1
SubnetId: !Ref PrivateSubnet1
PrivateRouteTable2:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-private-rt-2"
PrivateRoute2:
Type: AWS::EC2::Route
Properties:
RouteTableId: !Ref PrivateRouteTable2
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId: !Ref NATGateway2
PrivateSubnet2RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PrivateRouteTable2
SubnetId: !Ref PrivateSubnet2
# Security Groups
ALBSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "Security group for public Application Load Balancer"
VpcId: !Ref VPC
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
Description: "HTTP traffic from internet"
- IpProtocol: tcp
FromPort: 443
ToPort: 443
CidrIp: 0.0.0.0/0
Description: "HTTPS traffic from internet"
- IpProtocol: tcp
FromPort: 8443
ToPort: 8443
CidrIp: 0.0.0.0/0
Description: "gRPC over TLS traffic from internet"
EC2SecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "Security group for EC2 instances"
VpcId: !Ref VPC
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
SourceSecurityGroupId: !Ref ALBSecurityGroup
SecurityGroupEgress:
- IpProtocol: tcp
FromPort: 0
ToPort: 65535
CidrIp: 0.0.0.0/0
# ========================================
# S3 Bucket for ALB Access Logs (Optional)
# ========================================
ALBAccessLogsBucket:
Type: AWS::S3::Bucket
Condition: EnableALBLogs
Properties:
OwnershipControls:
Rules:
- ObjectOwnership: BucketOwnerEnforced
BucketName: !If
- HasCustomALBLogsBucket
- !Ref ALBAccessLogsBucketName
- !Sub "${AWS::StackName}-${AWS::AccountId}-logs"
LifecycleConfiguration:
Rules:
- Id: DeleteOldLogs
Status: Enabled
ExpirationInDays: 90
NoncurrentVersionExpirationInDays: 30
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
Tags:
- Key: Name
Value: !Sub "${AWS::StackName}-${AWS::AccountId}-logs"
- Key: Purpose
Value: "Logs Storage"
ALBAccessLogsBucketPolicy:
Type: AWS::S3::BucketPolicy
Condition: EnableALBLogs
Properties:
Bucket: !Ref ALBAccessLogsBucket
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AWSLogDeliveryWrite
Effect: Allow
Principal:
Service: logdelivery.elasticloadbalancing.amazonaws.com
Action: s3:PutObject
Resource: !Sub "arn:${AWS::Partition}:s3:::${ALBAccessLogsBucket}/AWSLogs/${AWS::AccountId}/*"
Condition:
StringEquals:
aws:SourceAccount: !Sub "${AWS::AccountId}"
ArnLike:
aws:SourceArn: !Sub "arn:${AWS::Partition}:elasticloadbalancing:${AWS::Region}:${AWS::AccountId}:loadbalancer/app/*"
- Sid: AWSLogDeliveryListBucket
Effect: Allow
Principal:
Service: logdelivery.elasticloadbalancing.amazonaws.com
Action:
- s3:GetBucketAcl
- s3:ListBucket
Resource: !Sub "arn:${AWS::Partition}:s3:::${ALBAccessLogsBucket}"
# ========================================
# IAM Roles
# ========================================
EC2InstanceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: ec2.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy
Policies:
- PolicyName: ECRAccess
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- ecr-public:GetAuthorizationToken
- ecr-public:BatchCheckLayerAvailability
- ecr-public:GetDownloadUrlForLayer
- ecr-public:BatchGetImage
Resource: "*"
- PolicyName: CloudWatchLogsAccess
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- logs:DescribeLogStreams
- logs:DescribeLogGroups
Resource:
- !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/ec2/tolling-vision/${AWS::StackName}:*"
- Effect: Allow
Action:
- cloudwatch:PutMetricData
- ec2:DescribeVolumes
- ec2:DescribeTags
Resource: "*"
EC2InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles:
- !Ref EC2InstanceRole
LambdaCustomResourceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: CustomResourcePermissions
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- autoscaling:CreateAutoScalingGroup
- autoscaling:DescribeAutoScalingGroups
Resource: "*"
- Effect: Allow
Action:
- autoscaling:AttachLoadBalancerTargetGroups
- autoscaling:DeleteAutoScalingGroup
- autoscaling:DetachLoadBalancerTargetGroups
- autoscaling:UpdateAutoScalingGroup
Resource: !Sub "arn:${AWS::Partition}:autoscaling:${AWS::Region}:${AWS::AccountId}:autoScalingGroup:*:autoScalingGroupName/${AWS::StackName}-asg"
- Effect: Allow
Action:
- ec2:CreateLaunchTemplate
- ec2:DeleteLaunchTemplate
- ec2:DescribeImages
Resource: "*"
- Effect: Allow
Action:
- ssm:GetParameter
Resource:
- !Sub "arn:${AWS::Partition}:ssm:${AWS::Region}::parameter/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64"
- !Sub "arn:${AWS::Partition}:ssm:${AWS::Region}::parameter/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
- Effect: Allow
Action:
- wafv2:CreateIPSet
- wafv2:CreateWebACL
- wafv2:DeleteIPSet
- wafv2:DeleteWebACL
- wafv2:GetIPSet
- wafv2:GetWebACL
- wafv2:ListIPSets
- wafv2:ListWebACLs
Resource: "*"
- Effect: Allow
Action:
- route53:ChangeResourceRecordSets
Resource: !Sub "arn:${AWS::Partition}:route53:::hostedzone/*"
- Effect: Allow
Action:
- route53:GetChange
Resource: !Sub "arn:${AWS::Partition}:route53:::change/*"
- Effect: Allow
Action:
- route53:ListHostedZonesByName
- sts:GetCallerIdentity
Resource: "*"
- !If
- EnableALBLogs
- Effect: Allow
Action:
- s3:DeleteBucket
- s3:ListBucket
- s3:ListBucketVersions
- s3:DeleteObject
- s3:DeleteObjectVersion
Resource:
- !Sub arn:${AWS::Partition}:s3:::${ALBAccessLogsBucket}
- !Sub arn:${AWS::Partition}:s3:::${ALBAccessLogsBucket}/*
- !Ref AWS::NoValue
# ========================================
# Lambda Custom Resource Handler
# ========================================
TollingVisionCustomResourceHandler:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Sub "${AWS::StackName}-custom-resource-handler"
Runtime: python3.13
Handler: index.lambda_handler
Role: !GetAtt LambdaCustomResourceRole.Arn
Timeout: 870
MemorySize: 512
Environment:
Variables:
REGION: !Ref "AWS::Region"
Code:
ZipFile: |
import json,boto3,urllib.request,logging,time,os,traceback
from botocore.exceptions import ClientError,BotoCoreError
# Enhanced logging configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def lambda_handler(e,c):
"""Enhanced Lambda handler with comprehensive error handling and logging"""
request_id = e.get('RequestId', 'unknown')
logical_resource_id = e.get('LogicalResourceId', 'unknown')