forked from panyapoc/ItemStorePersonalize
-
Notifications
You must be signed in to change notification settings - Fork 6
/
template.yaml
1006 lines (982 loc) · 33.8 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'
Parameters:
ProjectName:
Description: Used as a prefix for project resources. Can be up to 12 characters, lowercase letters (a-z) only.
Type: String
Default: allstore
AllowedPattern: "^[a-z]{1,12}"
ConstraintDescription: The ProjectName can be up to 12 characters, lowercase letters (a-z) only.
ProductSource:
Description: S3 source for product data (.csv or .json, optionally compressed with .gz suffix)
Type: String
Default: s3://public-personalize-demo-assets-us-east-1/data/meta_Grocery_and_Gourmet_Food_5.01.json.gz
UserSource:
Description: S3 source for user data (.csv or .json, optionally compressed with .gz suffix)
Type: String
Default: s3://public-personalize-demo-assets-us-east-1/data/users_Grocery_and_Gourmet_Food.json
WebSource:
Description: S3 source for web UI assets
Type: String
Default: s3://public-personalize-demo-assets-us-east-1/webui.zip
InteractionSource:
Description: (Optional) S3 source for user-product interaction data (.csv or .json, optionally compressed with .gz suffix)
Type: String
Default: ''
ExistingBaseCampaignName:
Description: (Optional) Name of an existing Personalize recommendation campaign in your account to link to
Type: String
Default: ''
ExistingSearchCampaignName:
Description: (Optional) Name of an existing Personalize re-ranking campaign in your account to link to
Type: String
Default: ''
ExistingSimsCampaignName:
Description: (Optional) Name of an existing Personalize similar items campaign in your account to link to
Type: String
Default: ''
ExistingTrackingId:
Description: (Optional) Tracking ID for an existing Personalize event tracker in your account to link to
Type: String
Default: ''
Conditions:
IADRegion: !Equals [!Ref "AWS::Region", us-east-1]
UseInteractionSource: !Not [!Equals [!Ref InteractionSource, '']]
UseProductSource: !Not [!Equals [!Ref ProductSource, '']]
UseUserSource: !Not [!Equals [!Ref UserSource, '']]
UseExistingBaseCampaign: !Not [!Equals [!Ref ExistingBaseCampaignName, '']]
UseExistingSearchCampaign: !Not [!Equals [!Ref ExistingSearchCampaignName, '']]
UseExistingSimsCampaign: !Not [!Equals [!Ref ExistingSimsCampaignName, '']]
Globals:
Function:
Timeout: 180
Api:
EndpointConfiguration: REGIONAL
# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-api-corsconfiguration.html
Cors:
AllowMethods: "'*'"
AllowHeaders: "'*'"
AllowOrigin: "'*'"
# Domain:
# DomainName: www.my-domain.com
# CertificateArn: my-valid-cert-arn
# EndpointConfiguration: EDGE
# ---------- VPC - SUBNET - SECURITY GROUPS ---------
Resources:
ItemStoreVPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: '172.31.0.0/16'
Tags:
- Key: Name
Value: !Sub '${ProjectName}-VPC'
ItemStoreInternetGateway:
Type: AWS::EC2::InternetGateway
ItemStoreAttachGateway:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
InternetGatewayId: !Ref ItemStoreInternetGateway
VpcId: !Ref ItemStoreVPC
ItemStoreSubnet1:
Type: AWS::EC2::Subnet
Properties:
CidrBlock: !Select [0, !Cidr [!GetAtt ItemStoreVPC.CidrBlock, 3, 8]]
VpcId: !Ref ItemStoreVPC
# The following examples show valid patterns for using nested intrinsic functions using short form YAML
# ...You can't nest short form functions consecutively, so a pattern like !GetAZs !Ref is invalid.
AvailabilityZone: !Select [0, Fn::GetAZs: !Ref 'AWS::Region']
Tags:
- Key: Name
Value: !Sub '${ProjectName}-Subnet1'
ItemStoreSubnet2:
Type: AWS::EC2::Subnet
Properties:
CidrBlock: !Select [1, !Cidr [!GetAtt ItemStoreVPC.CidrBlock, 3, 8]]
VpcId: !Ref ItemStoreVPC
AvailabilityZone: !Select [1, Fn::GetAZs: !Ref 'AWS::Region']
Tags:
- Key: Name
Value: !Sub '${ProjectName}-Subnet2'
ItemStoreVPCRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref ItemStoreVPC
ItemStoreVPCPublicRouteTable:
Type: AWS::EC2::RouteTable
Properties:
VpcId: !Ref ItemStoreVPC
RouteToInternet:
Type: AWS::EC2::Route
Properties:
RouteTableId: !Ref ItemStoreVPCPublicRouteTable
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref ItemStoreInternetGateway
ItemStoreVPCRouteTableAssociation:
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref ItemStoreVPCRouteTable
SubnetId: !Ref ItemStoreSubnet1
ItemStoreVPCRouteTableAssociationTwo:
DependsOn: RouteToInternet
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref ItemStoreVPCPublicRouteTable
SubnetId: !Ref ItemStoreSubnet2
# ---------- ROLES FOR DYNAMODB ---------
DynamoDbRole:
Type: 'AWS::IAM::Role'
Properties:
RoleName: !Sub '${ProjectName}-DynamoDbLambda'
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'
- 'arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess'
Policies:
- PolicyName: DDBAccess
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'dynamodb:PutItem'
- 'dynamodb:Query'
- 'dynamodb:UpdateTable'
- 'dynamodb:UpdateItem'
- 'dynamodb:BatchWriteItem'
- 'dynamodb:GetItem'
- 'dynamodb:Scan'
- 'dynamodb:DeleteItem'
Resource:
- !GetAtt TableItems.Arn
- !Join ['', [!GetAtt TableItems.Arn, '/*']]
- !GetAtt TableUsers.Arn
- !Join ['', [!GetAtt TableUsers.Arn, '/*']]
- PolicyName: RekognitionAccess
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'rekognition:DetectLabels'
Resource: '*'
APIGateWayRole:
Type: 'AWS::IAM::Role'
Properties:
RoleName: !Sub '${ProjectName}-APIGateWayRole'
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- apigateway.amazonaws.com
Action:
- 'sts:AssumeRole'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs'
- 'arn:aws:iam::aws:policy/AmazonKinesisFullAccess'
# ---------- DYNAMODB TABLES DEFINITIONS ---------
TableItems:
Type: 'AWS::DynamoDB::Table'
Properties:
TableName: !Sub '${ProjectName}-Items'
AttributeDefinitions:
- AttributeName: asin
AttributeType: S
KeySchema:
- AttributeName: asin
KeyType: HASH
BillingMode: PAY_PER_REQUEST
StreamSpecification:
StreamViewType: NEW_AND_OLD_IMAGES
TableUsers:
Type: 'AWS::DynamoDB::Table'
Properties:
TableName: !Sub '${ProjectName}-Users'
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
BillingMode: PAY_PER_REQUEST
# ---------- ELASTICSEARCH ROLE - Domain -----------
LambdaAdminRole:
Type: 'AWS::IAM::Role'
Properties:
RoleName: !Sub '${ProjectName}-LambdaAdminRole'
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/AdministratorAccess'
ESSearchRole:
Type: 'AWS::IAM::Role'
Properties:
RoleName: !Sub '${ProjectName}-ESSearchRole'
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole'
Policies:
- PolicyName: !Sub '${ProjectName}-lambda-policy'
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'es:ESHttpPost'
- 'es:ESHttpGet'
# arn:aws:es:<REGION>:<ACCOUNTID>:domain/<ESDOMAIN>/*
Resource: !Join ['',['arn:aws:es:',!Ref 'AWS::Region',':',!Ref 'AWS::AccountId',':domain/',!Ref ElasticsearchDomain,'/*']]
- Effect: Allow
Action:
- 's3:ListBucket'
- 's3:GetObject'
Resource: '*'
- Effect: Allow
Action:
- 'dynamodb:DescribeStream'
- 'dynamodb:GetRecords'
- 'dynamodb:GetShardIterator'
- 'dynamodb:ListStreams'
Resource:
- !GetAtt TableItems.Arn
- !Join ['',[!GetAtt TableItems.Arn,'/stream/*']]
ElasticsearchDomain:
Type: 'AWS::Elasticsearch::Domain'
DependsOn:
- ItemStoreSubnet1
Properties:
DomainName: !Sub '${ProjectName}-domain'
ElasticsearchVersion: '7.1'
ElasticsearchClusterConfig:
DedicatedMasterEnabled: false
InstanceCount: 1
ZoneAwarenessEnabled: false
InstanceType: t2.small.elasticsearch
VPCOptions:
SubnetIds:
- !Ref ItemStoreSubnet1
EBSOptions:
EBSEnabled: true
Iops: 0
VolumeSize: 10
VolumeType: gp2
AccessPolicies:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
AWS: '*'
Action:
- 'es:*'
# arn:aws:es:<REGION>:<ACCOUNTID>:domain/<ESDOMAIN>/*
Resource: !Join ['',['arn:aws:es:',!Ref 'AWS::Region',':',!Ref 'AWS::AccountId',':domain/',!Sub '${ProjectName}-domain','/*']]
AdvancedOptions:
rest.action.multi.allow_explicit_index: 'true'
# ---------- LAMBDA STREAMING FUNCTIONS ---------
UpdateSearchCluster:
Type: AWS::Serverless::Function
DependsOn:
- TableItems
Properties:
FunctionName: !Sub '${ProjectName}-UpdateSearchCluster'
Description: 'Update Elasticsearch cluster as items are added'
Handler: index.handler
Role: !GetAtt ESSearchRole.Arn
Runtime: python3.8
Timeout: 60
VpcConfig:
SecurityGroupIds:
- !GetAtt ItemStoreVPC.DefaultSecurityGroup
SubnetIds:
- !Ref ItemStoreSubnet1
CodeUri: ./functions/streaming/UpdateSearchCluster/
Environment:
Variables:
ESENDPOINT: !GetAtt ElasticsearchDomain.DomainEndpoint
REGION: !Ref 'AWS::Region'
Events:
DynamoDB:
Type: DynamoDB
Properties:
Stream: !GetAtt TableItems.StreamArn
StartingPosition: TRIM_HORIZON
BatchSize: 1
Enabled: True
# ---------- API Function ------------
# when implecitly define api the logical name of AWS::ApiGateway::RestApi is ServerlessRestApi
FunctionGetItem:
Type: 'AWS::Serverless::Function'
Properties:
FunctionName: !Sub '${ProjectName}-GetItem'
Description: Get item by id
Handler: main.handler
MemorySize: 256
Runtime: nodejs12.x
Role: !GetAtt DynamoDbRole.Arn
Timeout: 120
Environment:
Variables:
TABLE_NAME: !Ref TableItems
CodeUri: ./functions/APIs/GetItem/
Events:
APIgateway:
Type: Api
Properties:
Path: /items/{id}
Method: get
FunctionGetItemDescription:
Type: 'AWS::Serverless::Function'
Properties:
FunctionName: !Sub '${ProjectName}-GetItemDescription'
Description: Get item description by id from Amazon
Handler: main.handler
MemorySize: 1344
Runtime: nodejs12.x
Role: !GetAtt LambdaAdminRole.Arn
Timeout: 60
Environment:
Variables:
# TODO: Still necessary?
CUSTOM_CHROME: 'true'
CodeUri: ./functions/APIs/GetItemDescription/
Events:
APIgateway:
Type: Api
Properties:
Path: /description
Method: get
FunctionListItems:
Type: 'AWS::Serverless::Function'
Properties:
FunctionName: !Sub '${ProjectName}-ListItems'
Description: Get list of items by category
Handler: main.handler
MemorySize: 256
Runtime: nodejs12.x
Role: !GetAtt DynamoDbRole.Arn
Timeout: 120
Environment:
Variables:
TABLE_NAME: !Ref TableItems
CodeUri: ./functions/APIs/ListItems/
Events:
APIgateway:
Type: Api
Properties:
Path: /items
Method: get
FunctionUploadItems:
Type: 'AWS::Serverless::Function'
DependsOn:
- WebBucket
Properties:
FunctionName: !Sub '${ProjectName}-UploadItems'
Description: Upload sample data for items
Handler: main.handler
Runtime: nodejs12.x
Role: !GetAtt LambdaAdminRole.Arn
Timeout: 900
MemorySize: 256
CodeUri: ./functions/setup/
FunctionGetRecommendations:
Type: 'AWS::Serverless::Function'
Properties:
FunctionName: !Sub '${ProjectName}-GetRecommendations'
CodeUri: ./functions/APIs/GetRecommendations/
Description: Get the product recommendations by user
Role: !GetAtt LambdaAdminRole.Arn
Environment:
Variables:
DDB_TABLE_NAME: !Ref TableItems
CAMPAIGN_ARN:
Fn::If:
- UseExistingBaseCampaign
- !Sub 'arn:aws:personalize:${AWS::Region}:${AWS::AccountId}:campaign/${ExistingBaseCampaignName}'
- ''
Handler: main.handler
MemorySize: 256
Runtime: python3.8
Timeout: 30
Events:
APIgateway:
Type: Api
Properties:
Path: /recommendations
Method: get
APIgatewayPath:
Type: Api
Properties:
Path: /recommendations/{userid}
Method: get
FunctionGetRecommendationsParam: # Expose the GetRecs function address to SageMaker notebooks:
Type: 'AWS::SSM::Parameter'
Properties:
Description: !Sub 'ARN of the GetRecommendations Lambda for "${AWS::StackName}" stack'
Name: !Sub '/${ProjectName}/GetRecommendationsLambdaArn'
Type: String
Value: !GetAtt FunctionGetRecommendations.Arn
FunctionGetRecommendationsByItem:
Type: 'AWS::Serverless::Function'
Properties:
FunctionName: !Sub '${ProjectName}-GetRecommendationsByItem'
CodeUri: ./functions/APIs/GetRecommendationsByItem
Description: Get the product recommendations by item
Role: !GetAtt LambdaAdminRole.Arn
Environment:
Variables:
DDB_TABLE_NAME: !Ref TableItems
CAMPAIGN_ARN:
Fn::If:
- UseExistingSimsCampaign
- !Sub 'arn:aws:personalize:${AWS::Region}:${AWS::AccountId}:campaign/${ExistingSimsCampaignName}'
- ''
Handler: main.handler
MemorySize: 256
Runtime: python3.8
Timeout: 30
Events:
APIgateway:
Type: Api
Properties:
Path: /recommendationsitem/{itemid}
Method: get
FunctionGetRecommendationsByItemParam: # Expose the GetRecsByItem function address to SageMaker notebooks:
Type: 'AWS::SSM::Parameter'
Properties:
Description: !Sub 'ARN of the GetRecommendationsByItem Lambda for "${AWS::StackName}" stack'
Name: !Sub '/${ProjectName}/GetRecommendationsByItemLambdaArn'
Type: String
Value: !GetAtt FunctionGetRecommendationsByItem.Arn
FunctionSession:
Type: 'AWS::Serverless::Function'
Properties:
FunctionName: !Sub '${ProjectName}-Session'
Description: Get session config
Handler: main.handler
MemorySize: 128
Runtime: nodejs12.x
Role: !GetAtt LambdaAdminRole.Arn
Timeout: 60
Environment:
Variables:
IDENTITY_POOL_ID: !Ref UserEventIdentityPool
KINESIS_STREAM_NAME: !Ref PostClickEventStream
USERS_TABLE_NAME: !Ref TableUsers
CodeUri: ./functions/APIs/Session/
Events:
APIgateway:
Type: Api
Properties:
Path: /session
Method: get
# ---------- LAMBDA FUNCTIONS for ELASTICSEARCH ---------
FunctionSearch:
Type: 'AWS::Serverless::Function'
DependsOn:
- TableItems
Properties:
FunctionName: !Sub '${ProjectName}-Search'
Description: Search for items across item names, authors, and categories
Handler: main.handler
MemorySize: 256
Role: !GetAtt ESSearchRole.Arn
Runtime: python3.8
Timeout: 60
VpcConfig:
SecurityGroupIds:
- !GetAtt ItemStoreVPC.DefaultSecurityGroup
SubnetIds:
- !Ref ItemStoreSubnet1
CodeUri: ./functions/APIs/Search/
Environment:
Variables:
ESENDPOINT: !GetAtt ElasticsearchDomain.DomainEndpoint
DDB_TABLE: !Ref TableItems
REGION: !Ref 'AWS::Region'
FunctionSearchRerank:
Type: 'AWS::Serverless::Function'
Properties:
FunctionName: !Sub '${ProjectName}-Rerank'
Description: Search then rerank
Handler: main.handler
MemorySize: 256
Role: !GetAtt LambdaAdminRole.Arn
Runtime: python3.8
Timeout: 60
CodeUri: ./functions/APIs/SearchRerank/
Environment:
Variables:
DDB_TABLE_NAME: !Ref TableItems
MAX_PROMOTED_RESULTS: 45
SEARCH_LAMBDA_ARN: !GetAtt FunctionSearch.Arn
CAMPAIGN_ARN:
Fn::If:
- UseExistingSearchCampaign
- !Sub 'arn:aws:personalize:${AWS::Region}:${AWS::AccountId}:campaign/${ExistingSearchCampaignName}'
- ''
Events:
APIgateway:
Type: Api
Properties:
Path: /search
Method: get
FunctionSearchRerankParam: # Expose the SearchRerank function address to SageMaker notebooks:
Type: 'AWS::SSM::Parameter'
Properties:
Description: !Sub 'ARN of the SearchRerank Lambda for "${AWS::StackName}" stack'
Name: !Sub '/${ProjectName}/SearchRerankLambdaArn'
Type: String
Value: !GetAtt FunctionSearchRerank.Arn
# ------- CLOUDFRONT DISTRIBUTION -------
WebsiteOriginAccessIdentity:
Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
Properties:
CloudFrontOriginAccessIdentityConfig:
Comment: !Sub "web-access-${WebBucket}"
WebBucket:
Type: AWS::S3::Bucket
Properties:
CorsConfiguration:
CorsRules:
- Id: AllowAll
AllowedMethods:
- GET
- HEAD
AllowedOrigins:
- "*"
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
WebsiteConfiguration:
IndexDocument: "index.html"
ErrorDocument: "index.html"
WebBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref WebBucket
PolicyDocument:
Statement:
- Action:
- "s3:GetObject"
Effect: Allow
Resource: !Join ['',['arn:aws:s3:::',!Ref WebBucket,'/*']]
Principal:
CanonicalUser: !GetAtt WebsiteOriginAccessIdentity.S3CanonicalUserId
WebCDN:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
CustomErrorResponses:
-
ErrorCachingMinTTL: 300
ErrorCode: 403
ResponseCode: 200
ResponsePagePath: /index.html
DefaultCacheBehavior: # S3 origin is default
AllowedMethods:
- GET
- HEAD
- OPTIONS
CachedMethods: # Cache get requests only
- GET
- HEAD
- OPTIONS
DefaultTTL: 60
MaxTTL: 60
ForwardedValues:
QueryString: true
TargetOriginId: webstatic
ViewerProtocolPolicy: redirect-to-https
CacheBehaviors: # Alternative behavior for the API gateway
- AllowedMethods:
- DELETE
- GET
- HEAD
- OPTIONS
- PATCH
- POST
- PUT
CachedMethods: # Cache get requests only
- GET
- HEAD
- OPTIONS
Compress: true
DefaultTTL: 60
MaxTTL: 60
ForwardedValues:
Cookies:
Forward: all
Headers: # Need to whitelist all headers that API gateway requires:
- Accept
- Referer
- Athorization
- Content-Type
QueryString: true
PathPattern: "/Prod/*"
TargetOriginId: api
ViewerProtocolPolicy: https-only
DefaultRootObject: index.html
Enabled: true
HttpVersion: http2
Origins:
-
# Note: DO NOT use !GetAtt WebBucket.DomainName for DomainName
# https://stackoverflow.com/q/38735306
#DomainName: !GetAtt WebBucket.DomainName
DomainName: !Sub ${WebBucket}.s3.amazonaws.com
Id: webstatic
S3OriginConfig:
OriginAccessIdentity: !Sub origin-access-identity/cloudfront/${WebsiteOriginAccessIdentity}
OriginPath: /web
-
DomainName: !Join ['',[!Ref ServerlessRestApi,'.execute-api.',!Ref 'AWS::Region','.amazonaws.com']]
Id: api
CustomOriginConfig:
OriginProtocolPolicy: https-only
# Note we don't map to a particular OriginPath - all API deployments eligible IF PathPattern matched
# Consider bumping up to PriceClass_All if South America or Australia are important to you:
PriceClass: PriceClass_200
# ========== AL/ML TEAM =================
StagingS3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub '${ProjectName}-staging'
StagingBucketParam: # Expose the Staging Bucket to SageMaker notebooks via SSM
Type: 'AWS::SSM::Parameter'
Properties:
Description: !Sub 'Name of the Staging Bucket for "${AWS::StackName}" stack'
Name: !Sub '/${ProjectName}/StagingBucket'
Type: String
Value: !Ref StagingS3Bucket
SageMakerExecutionPolicy:
Type: 'AWS::IAM::ManagedPolicy'
Properties:
Description: !Sub 'Permissions needed for a SageMaker execution role to run the setup notebooks on ${ProjectName}'
Path: !Sub '/${ProjectName}/'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: CloudWatchMetrics # As per AmazonPersonalizeFullAccess
Effect: Allow
Action:
- 'cloudwatch:PutMetricData'
- 'cloudwatch:ListMetrics'
Resource:
- '*'
- Sid: StackDynamoDB
Effect: Allow
Action:
- 'dynamodb:PutItem'
- 'dynamodb:Query'
- 'dynamodb:UpdateTable'
- 'dynamodb:UpdateItem'
- 'dynamodb:BatchWriteItem'
- 'dynamodb:GetItem'
- 'dynamodb:Scan'
- 'dynamodb:DeleteItem'
Resource:
- !GetAtt TableItems.Arn
- !Join ['', [!GetAtt TableItems.Arn, '/*']]
- !GetAtt TableUsers.Arn
- !Join ['', [!GetAtt TableUsers.Arn, '/*']]
- Sid: ManagePersonalizeRole # As per AmazonPersonalizeFullAccess
Effect: Allow
Action:
- 'iam:*'
Resource:
- !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/${ProjectName}-*'
- Sid: PassPersonalizeRole # As per AmazonPersonalizeFullAccess
Effect: Allow
Action:
- 'iam:PassRole'
Resource:
- '*'
Condition:
StringEquals:
iam:PassedToService: personalize.amazonaws.com
- Sid: UpdateLambdaConfigurations
Effect: Allow
Action:
- 'lambda:GetFunction'
- 'lambda:UpdateFunctionConfiguration'
Resource:
- !GetAtt FunctionGetRecommendations.Arn
- !GetAtt FunctionGetRecommendationsByItem.Arn
- !GetAtt FunctionSearchRerank.Arn
- !GetAtt PostClickEventFunction.Arn
- Sid: Personalize
Effect: Allow
Action:
- 'personalize:*'
Resource:
- '*' # TODO: Scope down to /${ProjectName}* where poss?
- Sid: SSMParams # To read stack config variables from SSM
Effect: Allow
Action:
- 'ssm:GetParameters'
Resource:
- !Sub 'arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${ProjectName}/*'
- Sid: S3PersonalizeAccess
Effect: Allow
Action:
- 's3:GetObject'
- 's3:PutObject'
- 's3:DeleteObject'
- 's3:ListBucket'
Resource:
- 'arn:aws:s3:::*Personalize*' # Per PersonalizeFullAccess
- 'arn:aws:s3:::*personalize*' # Per PersonalizeFullAccess
- Sid: S3ProjectAccess
Effect: Allow
Action:
- 's3:*'
Resource:
- !GetAtt StagingS3Bucket.Arn
- !Sub '${StagingS3Bucket.Arn}/*'
- Sid: RekognitionLabelling # For the extension exercise to label item categories via rek
Effect: Allow
Action:
- 'rekognition:DetectLabels'
Resource:
- '*'
# SageMaker Execution Role
SageMakerIamRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
-
Effect: Allow
Principal:
Service: sagemaker.amazonaws.com
Action: sts:AssumeRole
Path: '/'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/AmazonSageMakerFullAccess'
- !Ref SageMakerExecutionPolicy
# SageMaker notebook
NotebookConfig:
Type: 'AWS::SageMaker::NotebookInstanceLifecycleConfig'
Properties:
OnStart:
- Content:
# TODO: Remove the redundant env vars when notebooks transition to using SSM params instead
Fn::Base64: !Sub |
#!/bin/bash
set -e
# Install extension for ipywidgets interactivity:
sudo -u ec2-user -i <<'EOF'
source /home/ec2-user/anaconda3/bin/activate JupyterSystemEnv
jupyter labextension install @jupyter-widgets/jupyterlab-manager
source /home/ec2-user/anaconda3/bin/deactivate
EOF
# Set env vars
touch /etc/profile.d/jupyter-env.sh
cat << 'EOF' >> /etc/profile.d/jupyter-env.sh
export CF_STACK_NAME='${AWS::StackName}'
export LAMBDA_GETITEMRECS_ARN='${FunctionGetRecommendationsByItem.Arn}'
export LAMBDA_GETRECS_ARN='${FunctionGetRecommendations.Arn}'
export LAMBDA_RERANK_ARN='${FunctionSearchRerank.Arn}'
export LAMBDA_POSTCLICK_ARN='${PostClickEventFunction.Arn}'
export STAGING_BUCKET='${StagingS3Bucket}'
EOF
initctl restart jupyter-server --no-wait
NotebookInstance:
Type: AWS::SageMaker::NotebookInstance
Properties:
InstanceType: 'ml.t2.medium'
LifecycleConfigName: !GetAtt NotebookConfig.NotebookInstanceLifecycleConfigName
# Otherwise it gets some garbage name by default:
NotebookInstanceName: !Sub '${ProjectName}-Personalize-Notebook'
RoleArn: !GetAtt SageMakerIamRole.Arn
VolumeSizeInGB: 20
DefaultCodeRepository: https://github.com/apac-ml-tfc/personalize-demo
PostClickEventStream:
Type: AWS::Kinesis::Stream
Properties:
Name: !Sub '${ProjectName}-Clickstream'
RetentionPeriodHours: 24
ShardCount: 1
PostClickEventFunction:
Type: 'AWS::Serverless::Function'
Properties:
FunctionName: !Sub '${ProjectName}-PostClickEvent'
Description: PostClickEvent function
Handler: main.handler
MemorySize: 256
Runtime: python3.8
Role: !GetAtt LambdaAdminRole.Arn
Timeout: 69
Environment:
Variables:
TRACKING_ID: !Ref ExistingTrackingId
CodeUri: ./functions/APIs/PostClickEvent/
Events:
Clickstream:
Type: Kinesis
Properties:
Stream: !GetAtt PostClickEventStream.Arn
StartingPosition: TRIM_HORIZON
PostClickEventFunctionParam: # Expose the PostClickEvent function address to SageMaker notebooks:
Type: 'AWS::SSM::Parameter'
Properties:
Description: !Sub 'ARN of the PostClickEvent Lambda for "${AWS::StackName}" stack'
Name: !Sub '/${ProjectName}/PostClickEventLambdaArn'
Type: String
Value: !GetAtt PostClickEventFunction.Arn
UserEventIdentityPool:
Type: AWS::Cognito::IdentityPool
Properties:
AllowUnauthenticatedIdentities: True
# number letter underscore space only
IdentityPoolName: !Sub '${ProjectName}_UserEventIdentityPool'
UserEventIdentityPoolAttachment:
Type: AWS::Cognito::IdentityPoolRoleAttachment
Properties:
IdentityPoolId: !Ref UserEventIdentityPool
Roles:
authenticated: !GetAtt UserEventAuthRole.Arn
unauthenticated: !GetAtt UserEventAuthRole.Arn
UserEventAuthRole:
Type: 'AWS::IAM::Role'
Properties:
RoleName: !Sub '${ProjectName}-UserEventRole'
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Federated:
- 'cognito-identity.amazonaws.com'
Action:
- 'sts:AssumeRoleWithWebIdentity'
Condition:
StringEquals:
cognito-identity.amazonaws.com:aud: !Ref UserEventIdentityPool
ForAnyValue:StringLike:
cognito-identity.amazonaws.com:amr: "unauthenticated"
Policies:
- PolicyName: KinesisStreamPut
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'kinesis:PutRecord'
Resource:
- !GetAtt PostClickEventStream.Arn
- !Join ['', [!GetAtt PostClickEventStream.Arn, '/*']]
InitItemTable:
Condition: UseProductSource
DependsOn:
- TableItems
- UpdateSearchCluster
- ElasticsearchDomain
Type: Custom::ProductData
Version: "1.0"
Properties:
ServiceToken: !GetAtt FunctionUploadItems.Arn
Shards: 3
Source: !Ref ProductSource
TableName: !Ref TableItems
InitStagingBucket:
DependsOn:
- StagingS3Bucket
Type: Custom::S3Copy
Version: "1.0"
Properties:
ServiceToken: !GetAtt FunctionUploadItems.Arn
Items:
# Any items with empty To will be skipped:
- Name: Interactions
From: !Ref InteractionSource
To: !If [UseInteractionSource, !Sub 's3://${StagingS3Bucket}/raw/interactions', '']
- Name: Products
From: !Ref ProductSource
To: !If [UseProductSource, !Sub 's3://${StagingS3Bucket}/raw/items', '']
- Name: Users
From: !Ref UserSource
To: !If [UseUserSource, !Sub 's3://${StagingS3Bucket}/raw/users', '']
InitUserTable:
Condition: UseUserSource
DependsOn:
- TableUsers
Type: Custom::UserData
Version: "1.0"
Properties:
ServiceToken: !GetAtt FunctionUploadItems.Arn
Source: !Ref UserSource
TableName: !Ref TableUsers
InitWebAssets:
DependsOn:
- WebBucket
Type: Custom::WebAssets
Version: "1.0"
Properties:
ServiceToken: !GetAtt FunctionUploadItems.Arn
Source: !Ref WebSource
Target: !Sub 's3://${WebBucket}/web'
Outputs:
APIEndpoint:
Description: "API production endpoint"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"
AllStoreWebUI:
Description: "AllStore Website"
Value: !Sub 'https://${WebCDN.DomainName}/'
WebBucketName:
Value: !Ref WebBucket
Description: S3 Bucket for web asset storage
StagingS3Bucket:
Value: !Ref StagingS3Bucket
Description: S3 Bucket for Data Staging
RerankArn:
Description: "Rerank_arn"
Value: !GetAtt FunctionSearchRerank.Arn
GetRecommendationsByItemArn:
Description: "GetRecommendationsByItem_arn"
Value: !GetAtt FunctionGetRecommendationsByItem.Arn
GetRecommendationsArn:
Description: "GetRecommendations_arn"
Value: !GetAtt FunctionGetRecommendations.Arn
PostClickEventArn:
Description: "PostClickEvent_arn"
Value: !GetAtt PostClickEventFunction.Arn
SageMakerExecutionPolicy:
Description: IAM Policy defining permissions for SageMaker setup notebooks
Value: !Ref SageMakerExecutionPolicy