-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathsetup-das-cfn.yaml
More file actions
2713 lines (2514 loc) · 94.3 KB
/
Copy pathsetup-das-cfn.yaml
File metadata and controls
2713 lines (2514 loc) · 94.3 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
Description: This template deploys a VPC, with a pair of public and private subnets spread across three Availability Zones. In addition to the network components, the following will also be created (AWS Cloud9, Amazon ECR, Amazon EKS, Amazon OpenSearch Service and Reverse-Proxy Instance).
Parameters:
######## VPC Variables ########
EnvironmentName:
Description: An environment name that is prefixed to resource names
Type: String
Default: VPC-das-lambda-java-sam
VpcCIDR:
Description: Please enter the IP range (CIDR notation) for this VPC
Type: String
Default: 172.16.0.0/16
PublicSubnet1CIDR:
Description: Please enter the IP range (CIDR notation) for the public subnet in the first Availability Zone
Type: String
Default: 172.16.10.0/24
PublicSubnet2CIDR:
Description: Please enter the IP range (CIDR notation) for the public subnet in the second Availability Zone
Type: String
Default: 172.16.11.0/24
PublicSubnet3CIDR:
Description: Please enter the IP range (CIDR notation) for the public subnet in the second Availability Zone
Type: String
Default: 172.16.12.0/24
PrivateSubnet1CIDR:
Description: Please enter the IP range (CIDR notation) for the private subnet in the first Availability Zone
Type: String
Default: 172.16.20.0/24
PrivateSubnet2CIDR:
Description: Please enter the IP range (CIDR notation) for the private subnet in the second Availability Zone
Type: String
Default: 172.16.21.0/24
PrivateSubnet3CIDR:
Description: Please enter the IP range (CIDR notation) for the private subnet in the second Availability Zone
Type: String
Default: 172.16.22.0/24
NatGateway:
Description: Create NatGateway (Yes or No)?
Default: "Yes"
Type: String
AllowedValues:
- "Yes"
AuroraPostgresVersion:
Description: The Version of Aurora Postgres
Default: "15.14"
Type: String
AllowedValues:
- "11.21"
- "12.16"
- "13.12"
- "14.9"
- "15.6"
- "15.7"
- "15.8"
- "15.10"
- "15.12"
- "15.13"
- "15.14"
- "16.1"
- "16.2"
- "16.3"
- "16.4"
- "16.6"
######## Amazon OpenSearch Variables ########
DomainName:
Type: String
Default: "das-lambda-java-sam-os-dom"
EngineVersion:
Description: Amazon OpenSearch Service - Version
Type: String
Default: "OpenSearch_2.11"
InstanceType:
Description: Amazon OpenSearch Service - Instance Type
Type: String
Default: "r6g.large.search"
OpenSearchAdminUserName:
Description: Amazon OpenSearch Service - Username
Default: "aosadmin"
Type: String
######## Reverse Proxy Variables ########
ReverseProxyInstanceType:
Description: Reverse Proxy EC2 instance type
Type: String
Default: m5.large
LatestAmiId:
Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
Default: '/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64'
JavaVersion:
Type: String
Description: Choose the version of Java. Lambda currently supports Java 17 and 21 (Java 11 was removed because it is end-of-support in Lambda)
AllowedValues:
- java17
- java21
Default: java21
Python3Version:
Type: String
Description: Choose the version of Python 3 between 3.9 and 3.12. Note that in Amazon Linux 2023, 3.9 is installed by default and maximum allowed version is 3.12. Also Python 3.10 is not available to install on Amazon Linux 2023 so it is not being offered as an option
AllowedValues:
- python3.9
- python3.11
- python3.12
Default: python3.12
DASLambdaCodeGithubLocation:
Type: String
Description: >-
Public Git URL from which the EC2 UserData clones the project source.
Defaults to the upstream aws-samples repository. For local testing
against a fork, override this parameter (e.g., via the
DAS_GITHUB_LOCATION env var consumed by RunCloudformationStack.sh).
Default: https://github.com/aws-samples/serverless-samples/
DASLambdaCodeS3Uri:
Type: String
Description: >-
Optional S3 URI (s3://bucket/key.tgz) of a tar.gz of the project source
tree. When set, the EC2 UserData downloads and extracts this archive
INSTEAD of cloning from DASLambdaCodeGithubLocation. Used for local
development against unpublished code. Leave empty for production /
PCSR-time deployments. The archive must extract a top-level
"das-lambda-java-sam/" directory matching the upstream layout.
Default: ""
######## S3 Bucket, SQS and SNS parameters ########
SourceBucketPrefix:
Type: String
Description: A prefix where the Database Activity Logs will be sent to in the S3 bucket
Default: das
CloudFrontPrefixListId:
Type: String
Description: The CloudFront managed prefix list ID for the deployment region. Looked up automatically by RunCloudformationStack.sh
Default: ""
Conditions:
CreateNgwResource: !Equals [!Ref NatGateway, "Yes"]
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: "General Information"
Parameters:
- EnvironmentName
- Label:
default: "Network Configuration"
Parameters:
- VpcCIDR
- PublicSubnet1CIDR
- PublicSubnet2CIDR
- PublicSubnet3CIDR
- PrivateSubnet1CIDR
- PrivateSubnet2CIDR
- PrivateSubnet3CIDR
- NatGateway
- Label:
default: "OpenSearch Configuration"
Parameters:
- DomainName
- EngineVersion
- InstanceType
- OpenSearchAdminUserName
- Label:
default: "Reverse Proxy Configuration"
Parameters:
- ReverseProxyInstanceType
Resources:
######## Amazon VPC ########
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: !Ref VpcCIDR
EnableDnsSupport: true
EnableDnsHostnames: true
Tags:
- Key: Name
Value: !Ref EnvironmentName
- Key: IsUsedForDeploy
Value: "True"
InternetGateway:
Type: AWS::EC2::InternetGateway
Properties:
Tags:
- Key: Name
Value: !Ref EnvironmentName
InternetGatewayAttachment:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
InternetGatewayId: !Ref InternetGateway
VpcId: !Ref VPC
PublicSubnet1:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [0, !GetAZs ""]
CidrBlock: !Ref PublicSubnet1CIDR
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} Public Subnet (AZ1)
PublicSubnet2:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [1, !GetAZs ""]
CidrBlock: !Ref PublicSubnet2CIDR
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} Public Subnet (AZ2)
PublicSubnet3:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [2, !GetAZs ""]
CidrBlock: !Ref PublicSubnet3CIDR
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} Public Subnet (AZ3)
PrivateSubnet1:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [0, !GetAZs ""]
CidrBlock: !Ref PrivateSubnet1CIDR
MapPublicIpOnLaunch: false
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} Private Subnet (AZ1)
- Key: IsUsedForDeploy
Value: "True"
PrivateSubnet2:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [1, !GetAZs ""]
CidrBlock: !Ref PrivateSubnet2CIDR
MapPublicIpOnLaunch: false
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} Private Subnet (AZ2)
- Key: IsUsedForDeploy
Value: "True"
PrivateSubnet3:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
AvailabilityZone: !Select [2, !GetAZs ""]
CidrBlock: !Ref PrivateSubnet3CIDR
MapPublicIpOnLaunch: false
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} Private Subnet (AZ3)
- Key: IsUsedForDeploy
Value: "True"
NatGateway1EIP:
Type: AWS::EC2::EIP
Condition: CreateNgwResource
DependsOn: InternetGatewayAttachment
DeletionPolicy: Delete
Properties:
Domain: vpc
NatGateway2EIP:
Type: AWS::EC2::EIP
Condition: CreateNgwResource
DependsOn: InternetGatewayAttachment
DeletionPolicy: Delete
Properties:
Domain: vpc
NatGateway3EIP:
Type: AWS::EC2::EIP
Condition: CreateNgwResource
DependsOn: InternetGatewayAttachment
DeletionPolicy: Delete
Properties:
Domain: vpc
NatGateway1:
Type: AWS::EC2::NatGateway
Condition: CreateNgwResource
Properties:
AllocationId: !GetAtt NatGateway1EIP.AllocationId
SubnetId: !Ref PublicSubnet1
NatGateway2:
Type: AWS::EC2::NatGateway
Condition: CreateNgwResource
Properties:
AllocationId: !GetAtt NatGateway2EIP.AllocationId
SubnetId: !Ref PublicSubnet2
NatGateway3:
Type: AWS::EC2::NatGateway
Condition: CreateNgwResource
Properties:
AllocationId: !GetAtt NatGateway3EIP.AllocationId
SubnetId: !Ref PublicSubnet3
PublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} Public Routes
DefaultPublicRoute:
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
PublicSubnet3RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref PublicSubnet3
PrivateRouteTable1:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} Private Routes (AZ1)
DefaultPrivateRoute1:
Type: AWS::EC2::Route
Condition: CreateNgwResource
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 ${EnvironmentName} Private Routes (AZ2)
DefaultPrivateRoute2:
Type: AWS::EC2::Route
Condition: CreateNgwResource
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
PrivateRouteTable3:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: !Sub ${EnvironmentName} Private Routes (AZ3)
DefaultPrivateRoute3:
Type: AWS::EC2::Route
Condition: CreateNgwResource
Properties:
RouteTableId: !Ref PrivateRouteTable3
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId: !Ref NatGateway3
PrivateSubnet3RouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref PrivateRouteTable3
SubnetId: !Ref PrivateSubnet3
IngressSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "Security group for VPC endpoints - allows HTTPS and HTTP from VPC CIDR"
VpcId: !Ref VPC
SecurityGroupIngress:
- Description: "Allow HTTPS from VPC CIDR for VPC endpoint access"
FromPort: 443
IpProtocol: tcp
ToPort: 443
CidrIp: !Ref VpcCIDR
- Description: "Allow HTTP from VPC CIDR for VPC endpoint access"
FromPort: 80
IpProtocol: tcp
ToPort: 80
CidrIp: !Ref VpcCIDR
SecurityGroupEgress:
- Description: "Allow all outbound traffic"
IpProtocol: "-1"
CidrIp: 0.0.0.0/0
AOSSVPCESecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "Security group for OpenSearch Serverless VPC endpoint - allows traffic from VPC CIDR only"
VpcId: !Ref VPC
SecurityGroupIngress:
- Description: "Allow all traffic from VPC CIDR for OpenSearch Serverless access"
IpProtocol: -1
FromPort: -1
ToPort: -1
CidrIp: !Ref VpcCIDR
SecurityGroupEgress:
- Description: "Allow all outbound traffic to VPC CIDR"
IpProtocol: "-1"
CidrIp: !Ref VpcCIDR
CreateVpcEndpointEC2Messages:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcEndpointType: Interface
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
- !Ref PrivateSubnet3
SecurityGroupIds:
- !Ref IngressSecurityGroup
PrivateDnsEnabled: true
ServiceName: !Sub com.amazonaws.${AWS::Region}.ec2messages
VpcId: !Ref VPC
CreateVpcEndpointKMS:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcEndpointType: Interface
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
- !Ref PrivateSubnet3
SecurityGroupIds:
- !Ref IngressSecurityGroup
PrivateDnsEnabled: true
ServiceName: !Sub com.amazonaws.${AWS::Region}.kms
VpcId: !Ref VPC
# S3 Gateway Endpoint for Lambda VPC access
CreateVpcEndpointS3:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcEndpointType: Gateway
ServiceName: !Sub com.amazonaws.${AWS::Region}.s3
VpcId: !Ref VPC
RouteTableIds:
- !Ref PrivateRouteTable1
- !Ref PrivateRouteTable2
- !Ref PrivateRouteTable3
# Secrets Manager Interface Endpoint for Lambda VPC access
CreateVpcEndpointSecretsManager:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcEndpointType: Interface
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
- !Ref PrivateSubnet3
SecurityGroupIds:
- !Ref IngressSecurityGroup
PrivateDnsEnabled: true
ServiceName: !Sub com.amazonaws.${AWS::Region}.secretsmanager
VpcId: !Ref VPC
# SQS Interface Endpoint for Lambda VPC access (DLQ)
CreateVpcEndpointSQS:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcEndpointType: Interface
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
- !Ref PrivateSubnet3
SecurityGroupIds:
- !Ref IngressSecurityGroup
PrivateDnsEnabled: true
ServiceName: !Sub com.amazonaws.${AWS::Region}.sqs
VpcId: !Ref VPC
OpenSearchIngressSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "Security group for OpenSearch domain and OSI pipeline - allows HTTPS from VPC CIDR and access to VPC endpoints"
VpcId: !Ref VPC
SecurityGroupIngress:
- Description: "Allow HTTPS from VPC CIDR for internal access"
FromPort: "443"
IpProtocol: tcp
ToPort: "443"
CidrIp: !Ref VpcCIDR
SecurityGroupEgress:
- Description: "Allow all outbound traffic for OpenSearch inter-node communication and AWS service access"
IpProtocol: "-1"
CidrIp: 0.0.0.0/0
# Lambda Security Group for VPC-attached functions
LambdaSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: "Security group for Lambda functions in VPC - allows outbound HTTPS to VPC endpoints and internet via NAT Gateway"
VpcId: !Ref VPC
SecurityGroupEgress:
- Description: "Allow HTTPS to VPC endpoints for AWS service access"
IpProtocol: tcp
FromPort: 443
ToPort: 443
CidrIp: !Ref VpcCIDR
- Description: "Allow all outbound traffic via NAT Gateway for internet access (required for Lambda cold starts and external dependencies)"
IpProtocol: "-1"
CidrIp: 0.0.0.0/0
AOSSEncryptionPolicy:
Type: 'AWS::OpenSearchServerless::SecurityPolicy'
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
Name: das-lambda-aoss-security-policy
Type: encryption
Description: Encryption policy
Policy: >-
{"Rules":[{"ResourceType":"collection","Resource":["collection/das-lambda-*"]}],"AWSOwnedKey":true}
Collection:
Type: 'AWS::OpenSearchServerless::Collection'
DependsOn:
- AOSSVPCESecurityGroup
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
Name: das-lambda-os-collection
Type: TIMESERIES
Description: Collection to holds timeseries data
CreateVpcEndpointAOSS:
Type: AWS::OpenSearchServerless::VpcEndpoint
DependsOn:
- Collection
Properties:
Name: das-lambda-aoss-vpc-endpoint
SecurityGroupIds:
- !Ref AOSSVPCESecurityGroup
SubnetIds:
- !Ref PrivateSubnet1
VpcId: !Ref VPC
AOSSNetworkPolicy:
Type: AWS::OpenSearchServerless::SecurityPolicy
DependsOn:
- CreateVpcEndpointAOSS
Properties:
Description: DAS Lambda Network Policy
Name: das-lambda-aoss-network-policy
Type: network
# Note: Dashboard access uses VPC endpoint instead of public access to comply with SpringClean policies
Policy: !Join ['', ['[{"Description":"Private Access for Endpoint","Rules":[{"ResourceType":"collection","Resource":["collection/das-lambda*"]}],"AllowFromPublic":false,"SourceVPCEs":["', !Ref CreateVpcEndpointAOSS, '"]},{"Description":"VPC Access for Dashboards","AllowFromPublic":false,"SourceVPCEs":["', !Ref CreateVpcEndpointAOSS, '"],"Rules":[{"ResourceType":"collection","Resource":["collection/das-lambda*"]},{"ResourceType":"dashboard","Resource":["collection/das-lambda*"]}]}]']]
AOSSDataAccessPolicy:
Type: AWS::OpenSearchServerless::AccessPolicy
DependsOn:
- CreateVpcEndpointAOSS
Properties:
Description: DAS Lambda Data Access Policy
Name: das-lambda-data-access-policy
Type: data
Policy: !Sub >-
[{"Description":"Access for users Role","Rules":[{"ResourceType":"index","Resource":["index/*/*"],"Permission":["aoss:*"]},{"ResourceType":"collection","Resource":["collection/das-lambda*"],"Permission":["aoss:*"]}],"Principal":["arn:aws:iam::${AWS::AccountId}:role/Admin"]}]
################## GENERATE OPENSEARCH PASSWORD ###################
AOSAdminPasswordSecret:
Type: AWS::SecretsManager::Secret
Properties:
Description: This secret has a dynamically generated secret password.
KmsKeyId: !Ref SecretsManagerKMSKey
GenerateSecretString:
SecretStringTemplate:
!Join ["", ['{"username": "', !Ref OpenSearchAdminUserName, '"}']]
GenerateStringKey: "password"
PasswordLength: 10
ExcludeCharacters: "\" ' ( ) $ % & * + , - . / : ; < = > ! # ? [ \\ ] ^ _ ` ~ { | } ~"
# CloudWatch Log Groups for OpenSearch logging
OpenSearchAuditLogGroup:
Type: AWS::Logs::LogGroup
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
LogGroupName: !Sub '/aws/opensearch/${DomainName}/audit-logs'
RetentionInDays: 30
OpenSearchIndexSlowLogGroup:
Type: AWS::Logs::LogGroup
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
LogGroupName: !Sub '/aws/opensearch/${DomainName}/index-slow-logs'
RetentionInDays: 30
OpenSearchSearchSlowLogGroup:
Type: AWS::Logs::LogGroup
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
LogGroupName: !Sub '/aws/opensearch/${DomainName}/search-slow-logs'
RetentionInDays: 30
OpenSearchApplicationLogGroup:
Type: AWS::Logs::LogGroup
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
LogGroupName: !Sub '/aws/opensearch/${DomainName}/application-logs'
RetentionInDays: 30
# IAM Role for OpenSearch to write logs to CloudWatch
OpenSearchLogsRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: es.amazonaws.com
Action: 'sts:AssumeRole'
ManagedPolicyArns:
- arn:aws:iam::aws:policy/CloudWatchLogsFullAccess
# Resource policy for CloudWatch Logs to allow OpenSearch to write
OpenSearchLogsResourcePolicy:
Type: AWS::Logs::ResourcePolicy
Properties:
PolicyName: OpenSearchLogsPolicy
PolicyDocument: !Sub |
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "es.amazonaws.com"
},
"Action": [
"logs:PutLogEvents",
"logs:CreateLogStream"
],
"Resource": [
"arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/opensearch/${DomainName}/*"
]
}
]
}
OpenSearchServiceDomain:
Type: "AWS::OpenSearchService::Domain"
DependsOn:
- OpenSearchIngressSecurityGroup
- OpenSearchAuditLogGroup
- OpenSearchIndexSlowLogGroup
- OpenSearchSearchSlowLogGroup
- OpenSearchApplicationLogGroup
- OpenSearchLogsResourcePolicy
Properties:
DomainName:
Ref: DomainName
EngineVersion:
Ref: EngineVersion
ClusterConfig:
DedicatedMasterEnabled: true
DedicatedMasterType: 'm6g.large.search'
DedicatedMasterCount: '3'
InstanceCount: "3"
InstanceType:
Ref: InstanceType
ZoneAwarenessEnabled: true
ZoneAwarenessConfig:
AvailabilityZoneCount: 3
DomainEndpointOptions:
EnforceHTTPS: true
NodeToNodeEncryptionOptions:
Enabled: true
EncryptionAtRestOptions:
Enabled: true
EBSOptions:
EBSEnabled: true
Iops: "0"
VolumeSize: "100"
VolumeType: "gp2"
# PCSR suppression CKV_AWS_84 / CKV_AWS_317 (accepted): log publishing is enabled
# post-deployment via the EnableOpenSearchLogging custom resource.
# Enabling audit logging + FGAC during initial domain creation causes CloudFormation
# handler timeout (>60 min provisioning). Enabling via update after domain is active
# completes in ~10 min and avoids the timeout.
# Restrict access policy to specific principals and actions
# Note: OSI role access is granted through the OSIOpenSearchPolicy, not here to avoid circular dependency
# Anonymous access is required for the reverse proxy pattern - OpenSearch fine-grained access control
# (internal user database with username/password) handles authentication at the application layer.
# The domain is in a VPC with security groups restricting network access to only the reverse proxy.
AccessPolicies:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
AWS: '*'
Action:
- 'es:ESHttp*'
Resource: !Sub 'arn:aws:es:${AWS::Region}:${AWS::AccountId}:domain/${DomainName}/*'
- Effect: Allow
Principal:
Service: osis-pipelines.amazonaws.com
Action:
- 'es:ESHttpGet'
- 'es:ESHttpPut'
- 'es:ESHttpPost'
- 'es:ESHttpHead'
- 'es:DescribeDomain'
Resource: !Sub 'arn:aws:es:${AWS::Region}:${AWS::AccountId}:domain/${DomainName}/*'
Condition:
StringEquals:
'aws:SourceAccount': !Ref 'AWS::AccountId'
AdvancedOptions:
rest.action.multi.allow_explicit_index: 'true'
AdvancedSecurityOptions:
Enabled: true
InternalUserDatabaseEnabled: true
MasterUserOptions:
MasterUserName: !Ref OpenSearchAdminUserName
MasterUserPassword: !Join
- ""
- - "{{resolve:secretsmanager:"
- !Ref AOSAdminPasswordSecret
- ":SecretString:password}}"
VPCOptions:
SubnetIds:
- !Ref PrivateSubnet1
- !Ref PrivateSubnet2
- !Ref PrivateSubnet3
SecurityGroupIds:
- !Ref OpenSearchIngressSecurityGroup
UpdatePolicy:
EnableVersionUpgrade: true
######## Enable OpenSearch Logging Post-Creation ########
# Audit logging + FGAC during initial creation causes CloudFormation handler timeout.
# This custom resource enables logging after the domain is active.
EnableOpenSearchLoggingRole:
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: EnableOpenSearchLogging
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- 'es:UpdateDomainConfig'
- 'es:DescribeDomain'
Resource: !Sub 'arn:aws:es:${AWS::Region}:${AWS::AccountId}:domain/${DomainName}'
# PCSR suppression CKV_AWS_111 (accepted): logs:PutResourcePolicy /
# DescribeResourcePolicies and CreateLogGroup are account-level APIs that
# do not support resource-level constraints, so Resource '*' is required.
- Effect: Allow
Action:
- 'logs:CreateLogGroup'
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
- 'logs:PutResourcePolicy'
- 'logs:DescribeResourcePolicies'
Resource: '*'
- Effect: Allow
Action:
- 'sqs:SendMessage'
Resource: !GetAtt LambdaDLQ.Arn
- Effect: Allow
Action:
- 'kms:Decrypt'
- 'kms:GenerateDataKey'
Resource: !GetAtt LambdaDLQKMSKey.Arn
EnableOpenSearchLoggingFunction:
Type: AWS::Lambda::Function
DependsOn:
- OpenSearchServiceDomain
- OpenSearchAuditLogGroup
- OpenSearchIndexSlowLogGroup
- OpenSearchSearchSlowLogGroup
- OpenSearchApplicationLogGroup
- LambdaDLQ
Properties:
Handler: index.lambda_handler
Role: !GetAtt EnableOpenSearchLoggingRole.Arn
Runtime: python3.11
Timeout: 600
ReservedConcurrentExecutions: 1
DeadLetterConfig:
TargetArn: !GetAtt LambdaDLQ.Arn
Code:
ZipFile: |
import json
import boto3
import time
import cfnresponse
def lambda_handler(event, context):
print(f"Request Type: {event['RequestType']}")
if event['RequestType'] == 'Delete':
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
return
try:
props = event['ResourceProperties']
domain = props['DomainName']
region = props['Region']
audit_log_arn = props['AuditLogGroupArn']
index_slow_arn = props['IndexSlowLogGroupArn']
search_slow_arn = props['SearchSlowLogGroupArn']
app_log_arn = props['ApplicationLogGroupArn']
client = boto3.client('opensearch', region_name=region)
# Wait for domain to be active (not processing)
for i in range(30):
resp = client.describe_domain(DomainName=domain)
processing = resp['DomainStatus'].get('Processing', True)
if not processing:
print(f"Domain is active after {i*20}s")
break
print(f"Domain still processing, waiting... ({i*20}s)")
time.sleep(20)
# Enable log publishing
client.update_domain_config(
DomainName=domain,
LogPublishingOptions={
'AUDIT_LOGS': {
'CloudWatchLogsLogGroupArn': audit_log_arn,
'Enabled': True
},
'INDEX_SLOW_LOGS': {
'CloudWatchLogsLogGroupArn': index_slow_arn,
'Enabled': True
},
'SEARCH_SLOW_LOGS': {
'CloudWatchLogsLogGroupArn': search_slow_arn,
'Enabled': True
},
'ES_APPLICATION_LOGS': {
'CloudWatchLogsLogGroupArn': app_log_arn,
'Enabled': True
}
}
)
print("Log publishing enabled successfully")
cfnresponse.send(event, context, cfnresponse.SUCCESS, {"Status": "Logging enabled"})
except Exception as e:
print(f"Error: {e}")
cfnresponse.send(event, context, cfnresponse.FAILED, {"Error": str(e)})
Environment:
Variables:
REGION: !Ref AWS::Region
EnableOpenSearchLogging:
Type: Custom::EnableOpenSearchLogging
DependsOn:
- EnableOpenSearchLoggingFunction
- OpenSearchServiceDomain
Properties:
ServiceToken: !GetAtt EnableOpenSearchLoggingFunction.Arn
DomainName: !Ref DomainName
Region: !Ref AWS::Region
AuditLogGroupArn: !GetAtt OpenSearchAuditLogGroup.Arn
IndexSlowLogGroupArn: !GetAtt OpenSearchIndexSlowLogGroup.Arn
SearchSlowLogGroupArn: !GetAtt OpenSearchSearchSlowLogGroup.Arn
ApplicationLogGroupArn: !GetAtt OpenSearchApplicationLogGroup.Arn
######## Reverse Proxy Template ########
OSIOpenSearchPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- 'es:ESHttpGet'
- 'es:ESHttpPut'
- 'es:ESHttpPost'
- 'es:ESHttpHead'
- 'es:DescribeDomain'
Resource:
- !GetAtt OpenSearchServiceDomain.Arn
- !Sub '${OpenSearchServiceDomain.Arn}/*'
Sid: AllowOpenSearchAccess
OSIS3Policy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- 's3:GetObject'
- 's3:ListBucket'
- 's3:GetBucketLocation'
Resource:
- !Sub '${SourceBucket.Arn}/*'
- !GetAtt SourceBucket.Arn
Sid: AllowS3Read
OSISQSPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- 'sqs:ReceiveMessage'
- 'sqs:DeleteMessage'
- 'sqs:GetQueueAttributes'
Resource: !GetAtt StandardQueue.Arn
Sid: AllowSQSRead
OSIKMSPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow