-
Notifications
You must be signed in to change notification settings - Fork 13
/
template.yaml
1418 lines (1337 loc) · 52.6 KB
/
template.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
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: (P13N-RT-APIS) - Real-time personalization APIs for recommendation systems
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: "Application name and environment parameters"
Parameters:
- ApplicationName
- EnvironmentName
- TimeZone
- Label:
default: "API configuration"
Parameters:
- AuthenticationScheme
- ApiEntryPointType
- CacheScheme
- CreateCognitoResources
- Label:
default: "Configuration and API testing support"
Parameters:
- GenerateConfigDatasetGroupNames
- CreateSwaggerUI
ParameterLabels:
ApplicationName:
default: "Application name"
EnvironmentName:
default: "Environment name"
TimeZone:
default: "Default time zone"
ApiEntryPointType:
default: "API entry point type"
AuthenticationScheme:
default: "Authentication scheme"
CacheScheme:
default: "Cache scheme"
CreateCognitoResources:
default: "Create Amazon Cognito resources?"
GenerateConfigDatasetGroupNames:
default: "Generate application configuration for Amazon Personalize dataset groups"
CreateSwaggerUI:
default: "Create Swagger UI?"
Parameters:
ApplicationName:
Type: String
Description: Application name used to name AWS AppConfig application.
EnvironmentName:
Type: String
Description: >
Application environment name (such as "dev", "staging", "prod", etc). Used as the stage in API Gateway and to organize
application configuration resources in AppConfig.
Default: prod
TimeZone:
Type: String
Description: >
Initialize the solution's time zone to match your default local time zone. This is used as the default time zone if the user's
time zone is not available when determining time-based automatic context.
Default: UTC
AuthenticationScheme:
Type: String
Description: >
Desired authentication scheme to protect API access. Note that "ApiKey" requires "API-Gateway-REST" for the API entry point type.
If you select "OAuth2-Cognito", be sure to deploy the edge authentication template as well (must be done separately, see repo documentation).
AllowedValues:
- 'OAuth2-Cognito'
- 'ApiKey'
- 'None'
Default: 'OAuth2-Cognito'
CreateCognitoResources:
Type: String
Description: >
Create Amazon Cognito user pool and client that can be used to create OAuth2 tokens for API authentication. Only applicable when
the authentication scheme is "OAuth2-Cognito". If you have an existing Cognito user pool, select "No".
AllowedValues:
- 'Yes'
- 'No'
Default: 'Yes'
ApiEntryPointType:
Type: String
Description: >
API entry point type for requests that access the personalization APIs. "API-Gateway-HTTP" is recommended when the authentication
scheme is "None" or "OAuth2-Cognito" for the best performance and lowest cost.
AllowedValues:
- 'API-Gateway-HTTP'
- 'API-Gateway-REST'
# FUTURE: - 'ALB'
Default: 'API-Gateway-HTTP'
CacheScheme:
Type: String
Description: >
Cache scheme to deploy with the API entry point type. Note that using "API-Gateway-REST" for the API entry point type includes a CloudFront
distribution that is transparently managed by API Gateway. However, the CloudFront distribution included with "API-Gateway-REST" does not
include caching so you should select "API-Gateway-Cache" with "API-Gateway-REST".
AllowedValues:
- 'CloudFront'
- 'API-Gateway-Cache'
- 'Both'
- 'None'
Default: 'CloudFront'
GenerateConfigDatasetGroupNames:
Type: String
Description: >
Comma separated list of Amazon Personalize dataset group names for which to generate an API configuration or 'all'
to generate a configuration for all dataset groups in the region and account where this solution is deployed. Leave this value
blank to skip generating an API configuration.
Default: ''
CreateSwaggerUI:
Type: String
Description: >
Create interactive public Swagger UI web interface to test and inspect APIs. If 'Yes', this option will create a CloudFront distribution for
the staging bucket that loads the auto-generated OpenAPI/Swagger specification. Note: this interface will be publicly accessible!
AllowedValues:
- 'Yes'
- 'No'
Default: 'Yes'
Conditions:
DeployApiGatewayHttp: !Equals [ !Ref ApiEntryPointType, 'API-Gateway-HTTP' ]
DeployApiGatewayRest: !Equals [ !Ref ApiEntryPointType, 'API-Gateway-REST' ]
DeployApiKey: !And
- !Condition DeployApiGatewayRest
- !Equals [ !Ref AuthenticationScheme, 'ApiKey' ]
DeployApiGatewayCache: !Or
- !Equals [ !Ref CacheScheme, 'API-Gateway-Cache' ]
- !Equals [ !Ref CacheScheme, 'Both' ]
DeployCloudFront: !Or
- !Equals [ !Ref CacheScheme, 'CloudFront' ]
- !Equals [ !Ref CacheScheme, 'Both' ]
DeployCognito: !Equals [ !Ref CreateCognitoResources, 'Yes' ]
DeploySwaggerUI: !Equals [ !Ref CreateSwaggerUI, 'Yes' ]
IADRegion: !Equals [!Ref 'AWS::Region', 'us-east-1' ]
Rules:
ApiKeyAuthTypeRule:
RuleCondition: !Equals [ !Ref AuthenticationScheme, 'ApiKey' ]
Assertions:
- Assert: !Equals [ !Ref ApiEntryPointType, 'API-Gateway-REST' ]
AssertDescription: 'For "ApiKey" authentication, "API-Gateway-REST" is required.'
CachingSchemeApiGatewayRule:
RuleCondition: !Equals [ !Ref ApiEntryPointType, 'API-Gateway-REST' ]
Assertions:
- Assert:
'Fn::Contains':
-
- 'API-Gateway-Cache'
- 'None'
- !Ref CacheScheme
AssertDescription: 'For "API-Gateway-REST" entry point type, only "API-Gateway-Cache" or "None" can be selected for cache scheme.'
Mappings:
RegionMap:
# AppConfig Lambda extension ARNs pulled from the following page and filtered by supported Personalize regions
# https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-integration-lambda-extensions.html#appconfig-integration-lambda-extensions-add
us-east-1:
AppConfigExtensionArn: "arn:aws:lambda:us-east-1:027255383542:layer:AWS-AppConfig-Extension:61"
us-east-2:
AppConfigExtensionArn: "arn:aws:lambda:us-east-2:728743619870:layer:AWS-AppConfig-Extension:47"
us-west-2:
AppConfigExtensionArn: "arn:aws:lambda:us-west-2:359756378197:layer:AWS-AppConfig-Extension:89"
ca-central-1:
AppConfigExtensionArn: "arn:aws:lambda:ca-central-1:039592058896:layer:AWS-AppConfig-Extension:47"
eu-central-1:
AppConfigExtensionArn: "arn:aws:lambda:eu-central-1:066940009817:layer:AWS-AppConfig-Extension:54"
eu-west-1:
AppConfigExtensionArn: "arn:aws:lambda:eu-west-1:434848589818:layer:AWS-AppConfig-Extension:59"
cn-north-1:
AppConfigExtensionArn: "arn:aws-cn:lambda:cn-north-1:615057806174:layer:AWS-AppConfig-Extension:43"
ap-northeast-1:
AppConfigExtensionArn: "arn:aws:lambda:ap-northeast-1:980059726660:layer:AWS-AppConfig-Extension:45"
ap-northeast-2:
AppConfigExtensionArn: "arn:aws:lambda:ap-northeast-2:826293736237:layer:AWS-AppConfig-Extension:54"
ap-southeast-1:
AppConfigExtensionArn: "arn:aws:lambda:ap-southeast-1:421114256042:layer:AWS-AppConfig-Extension:45"
ap-southeast-2:
AppConfigExtensionArn: "arn:aws:lambda:ap-southeast-2:080788657173:layer:AWS-AppConfig-Extension:54"
ap-south-1:
AppConfigExtensionArn: "arn:aws:lambda:ap-south-1:554480029851:layer:AWS-AppConfig-Extension:55"
DDB:
Parameters:
ItemsTableNamePrefix: 'PersonalizationApiItemMetadata_'
ItemsTablePrimaryKeyFieldName: 'id'
Globals:
Api:
TracingEnabled: true
HttpApi:
Tags:
CreatedBy: Personalization-APIs-Solution
Function:
Timeout: 5
Runtime: python3.11
Tracing: Active
Environment:
Variables:
LOG_LEVEL: INFO
POWERTOOLS_SERVICE_NAME: personalization_apis
POWERTOOLS_METRICS_NAMESPACE: !Sub 'Personalization-APIs-${AWS::StackName}'
POWERTOOLS_LOGGER_LOG_EVENT: true
POWERTOOLS_LOGGER_SAMPLE_RATE: 0
Tags:
CreatedBy: Personalization-APIs-Solution
Resources:
StagingBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub '${AWS::StackName}-${AWS::Region}-${AWS::AccountId}-staging'
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
CommonLayer:
Type: AWS::Serverless::LayerVersion
Properties:
ContentUri: src/layer
CompatibleRuntimes:
- python3.11
Metadata:
BuildMethod: python3.11
##########################################################################
# API Gateway Resources #
##########################################################################
RestApi:
Condition: DeployApiGatewayRest
Type: AWS::Serverless::Api
Properties:
Description: REST API for personalization API endpoints
StageName: !Ref EnvironmentName
CacheClusterEnabled: !If [ DeployApiGatewayCache, true, false ]
CacheClusterSize: "1.6"
MinimumCompressionSize: 2048
Auth:
ApiKeyRequired: !If [ DeployApiKey, true, false ]
AddDefaultAuthorizerToCorsPreflight: false
UsagePlan:
CreateUsagePlan: PER_API
Description: Usage plan for personalization REST APIs and API Key
EndpointConfiguration:
Type: EDGE
MethodSettings:
- ResourcePath: '/recommend-items/{namespace}/{recommender}/{userId}'
HttpMethod: 'OPTIONS'
CachingEnabled: false
- ResourcePath: '/recommend-items/{namespace}/{recommender}/{userId}'
HttpMethod: 'GET'
CachingEnabled: true
CacheTtlInSeconds: 10
- ResourcePath: '/related-items/{namespace}/{recommender}/{itemId}'
HttpMethod: 'OPTIONS'
CachingEnabled: false
- ResourcePath: '/related-items/{namespace}/{recommender}/{itemId}'
HttpMethod: 'GET'
CachingEnabled: true
CacheTtlInSeconds: 30
- ResourcePath: '/rerank-items/{namespace}/{recommender}/{userId}/{itemIds}'
HttpMethod: 'OPTIONS'
CachingEnabled: false
- ResourcePath: '/rerank-items/{namespace}/{recommender}/{userId}/{itemIds}'
HttpMethod: 'GET'
CachingEnabled: true
CacheTtlInSeconds: 10
- ResourcePath: '/rerank-items/{namespace}/{recommender}/{userId}'
HttpMethod: 'OPTIONS'
CachingEnabled: false
- ResourcePath: '/rerank-items/{namespace}/{recommender}/{userId}'
HttpMethod: 'POST'
CachingEnabled: false
- ResourcePath: '/events/{namespace}'
HttpMethod: 'OPTIONS'
CachingEnabled: false
- ResourcePath: '/events/{namespace}'
HttpMethod: 'POST'
CachingEnabled: false
ApiKey:
Condition: DeployApiKey
Type: AWS::ApiGateway::ApiKey
Properties:
Description: REST API Key to use when making API calls to personalization APIs
Enabled: true
StageKeys:
- RestApiId: !Ref RestApi
StageName: !Ref RestApi.Stage
ApiKeyUsagePlan:
Condition: DeployApiKey
Type: AWS::ApiGateway::UsagePlanKey
Properties:
KeyId: !Ref ApiKey
KeyType: API_KEY
UsagePlanId: !Ref RestApi.UsagePlan
HttpApi:
Condition: DeployApiGatewayHttp
Type: AWS::Serverless::HttpApi
Properties:
Description: HTTP API for personalization API endpoints
StageName: !Ref EnvironmentName
CorsConfiguration:
AllowMethods:
- GET
- HEAD
- OPTIONS
- POST
- PUT
AllowOrigins:
- '*'
AllowHeaders:
- Content-Type
- Authorization
- X-Amz-Date
MaxAge: 600
Tags:
CreatedBy: Personalization-APIs-Solution
##########################################################################
# Function Resources #
##########################################################################
PersonalizationHttpApiFunction:
Condition: DeployApiGatewayHttp
Type: AWS::Serverless::Function
Properties:
Description: Function that implements real-time personalization APIs
Timeout: 5
CodeUri: src/personalization_api_function
Handler: main.lambda_handler
MemorySize: 1024
Layers:
- !FindInMap [RegionMap, !Ref 'AWS::Region', AppConfigExtensionArn]
- !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:017000801446:layer:AWSLambdaPowertoolsPythonV2:68
- !Ref CommonLayer
Environment:
Variables:
AWS_APPCONFIG_EXTENSION_PREFETCH_LIST: !Sub '/applications/${ApplicationName}/environments/${EnvironmentName}/configurations/Personalization-API-Config'
TZ: !Ref TimeZone
ApiType: HTTP
StagingBucket: !Ref StagingBucket
ItemsTablePrimaryKeyFieldName: !FindInMap [DDB, Parameters, ItemsTablePrimaryKeyFieldName]
Role: !GetAtt PersonalizationApiExecutionRole.Arn
Events:
GetRecommendItems:
Type: HttpApi
Properties:
Path: /recommend-items/{namespace}/{recommender}/{userId}
Method: get
PayloadFormatVersion: "2.0"
ApiId: !Ref HttpApi
GetRelatedItems:
Type: HttpApi
Properties:
Path: /related-items/{namespace}/{recommender}/{itemId}
Method: get
PayloadFormatVersion: "2.0"
ApiId: !Ref HttpApi
GetRerankItems:
Type: HttpApi
Properties:
Path: /rerank-items/{namespace}/{recommender}/{userId}/{itemIds}
Method: get
PayloadFormatVersion: "2.0"
ApiId: !Ref HttpApi
PostRerankItems:
Type: HttpApi
Properties:
Path: /rerank-items/{namespace}/{recommender}/{userId}
Method: post
PayloadFormatVersion: "2.0"
ApiId: !Ref HttpApi
PostEvents:
Type: HttpApi
Properties:
Path: /events/{namespace}
Method: post
PayloadFormatVersion: "2.0"
ApiId: !Ref HttpApi
PersonalizationRestApiFunction:
Condition: DeployApiGatewayRest
Type: AWS::Serverless::Function
Properties:
Description: Function that implements real-time personalization APIs
Timeout: 5
CodeUri: src/personalization_api_function
Handler: main.lambda_handler
MemorySize: 1024
Layers:
- !FindInMap [RegionMap, !Ref 'AWS::Region', AppConfigExtensionArn]
- !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:017000801446:layer:AWSLambdaPowertoolsPythonV2:68
- !Ref CommonLayer
Environment:
Variables:
AWS_APPCONFIG_EXTENSION_PREFETCH_LIST: !Sub '/applications/${ApplicationName}/environments/${EnvironmentName}/configurations/Personalization-API-Config'
TZ: !Ref TimeZone
ApiType: REST
StagingBucket: !Ref StagingBucket
ItemsTablePrimaryKeyFieldName: !FindInMap [DDB, Parameters, ItemsTablePrimaryKeyFieldName]
Role: !GetAtt PersonalizationApiExecutionRole.Arn
Events:
OptionsRecommendItems:
Type: Api
Properties:
Path: /recommend-items/{namespace}/{recommender}/{userId}
Method: options
RestApiId: !Ref RestApi
RequestParameters:
- method.request.path.namespace:
Caching: true
Required: true
- method.request.path.recommender:
Caching: true
Required: true
- method.request.path.userId:
Caching: true
Required: true
GetRecommendItems:
Type: Api
Properties:
Path: /recommend-items/{namespace}/{recommender}/{userId}
Method: get
RestApiId: !Ref RestApi
RequestParameters:
- method.request.path.namespace:
Caching: true
Required: true
- method.request.path.recommender:
Caching: true
Required: true
- method.request.path.userId:
Caching: true
Required: true
- method.request.querystring.numResults:
Caching: true
Required: false
- method.request.querystring.filter:
Caching: true
Required: false
- method.request.querystring.filterValues:
Caching: true
Required: false
- method.request.querystring.context:
Caching: true
Required: false
- method.request.querystring.decorateItems:
Caching: true
Required: false
- method.request.querystring.syntheticUser:
Caching: true
Required: false
- method.request.querystring.feature:
Caching: true
Required: false
OptionsRelatedItems:
Type: Api
Properties:
Path: /related-items/{namespace}/{recommender}/{itemId}
Method: options
RestApiId: !Ref RestApi
RequestParameters:
- method.request.path.namespace:
Caching: true
Required: true
- method.request.path.recommender:
Caching: true
Required: true
- method.request.path.itemId:
Caching: true
Required: true
GetRelatedItems:
Type: Api
Properties:
Path: /related-items/{namespace}/{recommender}/{itemId}
Method: get
RestApiId: !Ref RestApi
RequestParameters:
- method.request.path.namespace:
Caching: true
Required: true
- method.request.path.recommender:
Caching: true
Required: true
- method.request.path.itemId:
Caching: true
Required: true
- method.request.querystring.numResults:
Caching: true
Required: false
- method.request.querystring.userId:
Caching: true
Required: false
- method.request.querystring.filter:
Caching: true
Required: false
- method.request.querystring.filterValues:
Caching: true
Required: false
- method.request.querystring.context:
Caching: true
Required: false
- method.request.querystring.decorateItems:
Caching: true
Required: false
- method.request.querystring.feature:
Caching: true
Required: false
OptionsRerankItems:
Type: Api
Properties:
Path: /rerank-items/{namespace}/{recommender}/{userId}/{itemIds}
Method: options
RestApiId: !Ref RestApi
RequestParameters:
- method.request.path.namespace:
Caching: true
Required: true
- method.request.path.recommender:
Caching: true
Required: true
- method.request.path.userId:
Caching: true
Required: true
- method.request.path.itemIds:
Caching: true
Required: false
GetRerankItems:
Type: Api
Properties:
Path: /rerank-items/{namespace}/{recommender}/{userId}/{itemIds}
Method: get
RestApiId: !Ref RestApi
RequestParameters:
- method.request.path.namespace:
Caching: true
Required: true
- method.request.path.recommender:
Caching: true
Required: true
- method.request.path.userId:
Caching: true
Required: true
- method.request.path.itemIds:
Caching: true
Required: true
- method.request.querystring.filter:
Caching: true
Required: false
- method.request.querystring.filterValues:
Caching: true
Required: false
- method.request.querystring.context:
Caching: true
Required: false
- method.request.querystring.decorateItems:
Caching: true
Required: false
- method.request.querystring.syntheticUser:
Caching: true
Required: false
- method.request.querystring.feature:
Caching: true
Required: false
PostRerankItems:
Type: Api
Properties:
Path: /rerank-items/{namespace}/{recommender}/{userId}
Method: post
RestApiId: !Ref RestApi
RequestParameters:
- method.request.path.namespace:
Caching: true
Required: true
- method.request.path.recommender:
Caching: true
Required: true
- method.request.path.userId:
Caching: true
Required: true
- method.request.querystring.filter:
Caching: true
Required: false
- method.request.querystring.filterValues:
Caching: true
Required: false
- method.request.querystring.context:
Caching: true
Required: false
- method.request.querystring.decorateItems:
Caching: true
Required: false
- method.request.querystring.syntheticUser:
Caching: true
Required: false
- method.request.querystring.feature:
Caching: true
Required: false
OptionsEvents:
Type: Api
Properties:
Path: /events/{namespace}
Method: options
RestApiId: !Ref RestApi
RequestParameters:
- method.request.path.namespace:
Caching: false
Required: true
PostEvents:
Type: Api
Properties:
Path: /events/{namespace}
Method: post
RestApiId: !Ref RestApi
RequestParameters:
- method.request.path.namespace:
Caching: false
Required: true
PersonalizationApiExecutionRole:
Type: AWS::IAM::Role
Properties:
Description: Execution role for the core API function. Attach additional policies to this role as needed in your configuration.
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
PersonalizationApiBasePolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
Description: Base policy for the personalization API function
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- appconfig:GetLatestConfiguration
- appconfig:StartConfigurationSession
Resource:
- !Sub 'arn:${AWS::Partition}:appconfig:${AWS::Region}:${AWS::AccountId}:application/${AppConfigApplication}/environment/${AppConfigEnvironment}/configuration/${AppConfigConfigurationProfile}'
- Effect: Allow
Action:
- personalize:GetRecommendations
- personalize:GetPersonalizedRanking
- personalize:PutEvents
Resource: '*'
- Effect: Allow
Action:
- dynamodb:BatchGetItem
Resource:
- !Sub
- 'arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${TablePrefix}*'
- { TablePrefix: !FindInMap [DDB, Parameters, ItemsTableNamePrefix] }
- Effect: Allow
Action:
- evidently:EvaluateFeature
- evidently:PutProjectEvents
Resource: '*'
- Effect: Allow
Action:
- s3:GetObject
Resource: !Sub 'arn:${AWS::Partition}:s3:::${StagingBucket}/localdbs/*'
Roles:
- Ref: PersonalizationApiExecutionRole
LoadItemMetadataFunction:
Type: AWS::Serverless::Function
Properties:
Description: Loads items from a file in S3 into the configured datastore type
Timeout: 900
CodeUri: src/load_item_metadata_function
Handler: main.lambda_handler
MemorySize: 1024
Layers:
- !FindInMap [RegionMap, !Ref 'AWS::Region', AppConfigExtensionArn]
- !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:017000801446:layer:AWSLambdaPowertoolsPythonV2:68
- !Ref CommonLayer
Policies:
- Statement:
- Effect: Allow
Action:
- appconfig:GetLatestConfiguration
- appconfig:StartConfigurationSession
Resource:
- !Sub 'arn:${AWS::Partition}:appconfig:${AWS::Region}:${AWS::AccountId}:application/${AppConfigApplication}/environment/${AppConfigEnvironment}/configuration/${AppConfigConfigurationProfile}'
- Effect: Allow
Action:
- dynamodb:BatchWriteItem
- dynamodb:DescribeTable
- dynamodb:Scan
Resource:
- !Sub
- 'arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${TablePrefix}*'
- { TablePrefix: !FindInMap [DDB, Parameters, ItemsTableNamePrefix] }
- Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
Resource: !Sub 'arn:${AWS::Partition}:s3:::${AWS::StackName}-${AWS::Region}-${AWS::AccountId}-staging*'
Environment:
Variables:
AWS_APPCONFIG_EXTENSION_PREFETCH_LIST: !Sub '/applications/${ApplicationName}/environments/${EnvironmentName}/configurations/Personalization-API-Config'
AWS_APPCONFIG_EXTENSION_POLL_INTERVAL_SECONDS: 10
ItemsTablePrimaryKeyFieldName: !FindInMap [DDB, Parameters, ItemsTablePrimaryKeyFieldName]
ItemsTableNamePrefix: !FindInMap [DDB, Parameters, ItemsTableNamePrefix]
Events:
BucketEvent:
Type: S3
Properties:
Bucket: !Ref StagingBucket
Events: 's3:ObjectCreated:*'
Filter:
S3Key:
Rules:
- Name: prefix
Value: 'import/'
ConfigValidatorFunction:
Type: AWS::Serverless::Function
Properties:
Description: Validates the configuration set in AppConfig and fires events to synchronize CloudFront policies and DynamoDB tables
Timeout: 15
CodeUri: src/config_validator_function
Handler: main.lambda_handler
MemorySize: 256
Layers:
- !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:017000801446:layer:AWSLambdaPowertoolsPythonV2:68
Environment:
Variables:
StagingBucket: !Sub '${AWS::StackName}-${AWS::Region}-${AWS::AccountId}-staging'
AuthenticationScheme: !Ref AuthenticationScheme
ApiGatewayHost: '' # Will be updated by ConfigValidatorEnvFunction
CloudFrontHost: '' # Will be updated by ConfigValidatorEnvFunction
Policies:
- Statement:
- Sid: EventBridgePolicy
Effect: Allow
Action:
- events:PutEvents
Resource: '*'
- Sid: StagingBucketAccess
Effect: Allow
Action:
- s3:PutObject
Resource: !Sub 'arn:${AWS::Partition}:s3:::${AWS::StackName}-${AWS::Region}-${AWS::AccountId}-staging/openapi/*'
ConfigValidatorPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt ConfigValidatorFunction.Arn
Principal: appconfig.amazonaws.com
SourceArn: !Sub 'arn:${AWS::Partition}:appconfig:${AWS::Region}:${AWS::AccountId}:*'
ConfigValidatorEnvFunction:
Type: AWS::Serverless::Function
Properties:
Description: Updates the config validator handler function environment
Timeout: 30
CodeUri: src/config_validator_env_function
Handler: main.lambda_handler
Policies:
- Statement:
- Effect: Allow
Action:
- lambda:GetFunctionConfiguration
- lambda:UpdateFunctionConfiguration
Resource: !GetAtt ConfigValidatorFunction.Arn
- Effect: Allow
Action:
- lambda:GetLayerVersion
Resource: !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:017000801446:layer:AWSLambdaPowertoolsPython:17
- Effect: Allow
Action:
- iam:PassRole
Resource:
- !Sub 'arn:aws:iam::${AWS::AccountId}:role/*'
Environment:
Variables:
ConfigValidatorFunctionArn: !GetAtt ConfigValidatorFunction.Arn
ApiGatewayHost:
!If
- DeployApiGatewayRest
- !Sub "https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/${EnvironmentName}/"
- !Sub "https://${HttpApi}.execute-api.${AWS::Region}.amazonaws.com/${EnvironmentName}/"
CloudFrontHost:
!If
- DeployCloudFront
- !Sub
- 'https://${Domain}'
- Domain: !GetAtt ApiCdn.DomainName
- ""
CustomConfigValidatorEnv:
Type: Custom::ConfigValidatorEnv
Properties:
ServiceToken: !GetAtt ConfigValidatorEnvFunction.Arn
##########################################################################
# Cognito Resources #
##########################################################################
CognitoUserPool:
Condition: DeployCognito
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: !Sub '${AWS::StackName}-${AWS::Region}-User-Pool'
AliasAttributes:
- email
AutoVerifiedAttributes:
- email
AdminCreateUserConfig:
AllowAdminCreateUserOnly: true
UnusedAccountValidityDays: 7
Policies:
PasswordPolicy:
MinimumLength: 8
RequireLowercase: true
RequireNumbers: true
RequireSymbols: false
RequireUppercase: true
Schema:
- AttributeDataType: String
Name: email
Required: true
CognitoUserPoolClient:
Condition: DeployCognito
Type: AWS::Cognito::UserPoolClient
Properties:
ClientName: !Sub '${AWS::StackName}-${AWS::Region}-Client'
GenerateSecret: false
ExplicitAuthFlows:
- ALLOW_USER_PASSWORD_AUTH
- ALLOW_USER_SRP_AUTH
- ALLOW_REFRESH_TOKEN_AUTH
RefreshTokenValidity: 30
SupportedIdentityProviders:
- COGNITO
UserPoolId: !Ref CognitoUserPool
##########################################################################
# Step Functions Resources #
##########################################################################
ConfigResourceSyncStateMachine:
Type: AWS::Serverless::StateMachine
Properties:
DefinitionUri: src/statemachine/sync_resources.asl.json
DefinitionSubstitutions:
SyncCacheSettingsFunctionArn: !GetAtt SyncCacheSettingsFunction.Arn
SyncDyanamoDbTableFunctionArn: !GetAtt SyncDynamoDbTableFunction.Arn
Policies:
- LambdaInvokePolicy:
FunctionName: !Ref SyncCacheSettingsFunction
- LambdaInvokePolicy:
FunctionName: !Ref SyncDynamoDbTableFunction
Events:
EBRule:
Type: EventBridgeRule
Properties:
Pattern:
source:
- personalization.apis
detail-type:
- PersonalizationApisConfigurationChange
Tracing:
Enabled: true
SyncCacheSettingsFunction:
Type: AWS::Serverless::Function
Properties:
Description: Synchronizes CloudFront policies or API Gateway cache settings with configuration in AppConfig
Timeout: 30
CodeUri: src/sync_cache_settings_function
Handler: main.lambda_handler
MemorySize: 256
Layers:
- !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:017000801446:layer:AWSLambdaPowertoolsPythonV2:68
Role: !GetAtt SyncCacheSettingsExecutionRole.Arn
Environment:
Variables:
RestApiId: !If [ DeployApiGatewayRest, !Ref RestApi, '' ]
RestApiStage: !If [ DeployApiGatewayRest, !Ref RestApi.Stage, '' ]
CloudFrontCachePolicyId: !If [ DeployCloudFront, !Ref ApiCdnCachePolicy, '' ]
CloudFrontOriginRequestPolicyId: !If [ DeployCloudFront, !Ref ApiCdnOriginRequestPolicy, '' ]
SyncCacheSettingsExecutionRole:
Type: AWS::IAM::Role
Properties:
Description: Execution role for the cache settings synchronization function.
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
SyncApiGatewayCachePolicy:
Condition: DeployApiGatewayRest
Type: AWS::IAM::Policy
Properties:
PolicyName: !Sub ${AWS::StackName}-${AWS::Region}-SyncApiGatewayCachePolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- apigateway:GET
- apigateway:PATCH
Resource:
- !Sub 'arn:${AWS::Partition}:apigateway:${AWS::Region}::/restapis/${RestApi}/stages/${RestApi.Stage}'
Roles:
- Ref: SyncCacheSettingsExecutionRole
SyncCloudFrontPoliciesPolicy:
Condition: DeployCloudFront
Type: AWS::IAM::Policy
Properties:
PolicyName: !Sub ${AWS::StackName}-${AWS::Region}-SyncCloudFrontPoliciesPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- cloudfront:GetCachePolicy
- cloudfront:UpdateCachePolicy
Resource: '*' # Mapping to resource does not seem to work
- Effect: Allow
Action:
- cloudfront:GetOriginRequestPolicy
- cloudfront:UpdateOriginRequestPolicy
Resource: '*' # Mapping to resource does not seem to work
Roles:
- Ref: SyncCacheSettingsExecutionRole
SyncDynamoDbTableFunction:
Type: AWS::Serverless::Function
Properties:
Description: Synchronizes DynamoDB tables with configuration in AppConfig
Timeout: 30
CodeUri: src/sync_dynamodb_tables_function
Handler: main.lambda_handler
MemorySize: 256
Layers:
- !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:017000801446:layer:AWSLambdaPowertoolsPythonV2:68
Policies:
- Statement:
- Effect: Allow
Action:
- dynamodb:CreateTable
- dynamodb:DescribeTable
- dynamodb:TagResource
- dynamodb:UpdateTable
Resource:
- !Sub
- 'arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${TablePrefix}*'
- { TablePrefix: !FindInMap [DDB, Parameters, ItemsTableNamePrefix] }
Environment:
Variables:
ItemsTablePrimaryKeyFieldName: !FindInMap [DDB, Parameters, ItemsTablePrimaryKeyFieldName]
ItemsTableNamePrefix: !FindInMap [DDB, Parameters, ItemsTableNamePrefix]
##########################################################################
# CloudFront Resources #
##########################################################################
ApiCdnCachePolicy:
Condition: DeployCloudFront
Type: AWS::CloudFront::CachePolicy
Properties:
CachePolicyConfig:
Comment: !Sub 'Personalization API (${ApiEntryPointType}/${CacheScheme}/${EnvironmentName}) cache policy (maintained by AppConfig validator)'
DefaultTTL: 10 # Managed by SyncCacheSettingsFunction when config is deployed
MaxTTL: 3600 # Managed by SyncCacheSettingsFunction when config is deployed
MinTTL: 2 # Managed by the SyncCacheSettingsFunction when config is deployed
Name: !Sub 'PersonalizationAPIs-${AWS::StackName}-${AWS::Region}'
ParametersInCacheKeyAndForwardedToOrigin:
EnableAcceptEncodingBrotli: 'true'
EnableAcceptEncodingGzip: 'true'
CookiesConfig: