-
Notifications
You must be signed in to change notification settings - Fork 341
Expand file tree
/
Copy pathpersonalize_getting_started.yaml
More file actions
333 lines (311 loc) · 11.3 KB
/
personalize_getting_started.yaml
File metadata and controls
333 lines (311 loc) · 11.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
---
AWSTemplateFormatVersion: 2010-09-09
Description: Creates an S3 Bucket, IAM Roles & Policy, SSM Parameters, Lambda Function and SageMaker Notebook to work with Amazon Personalize.
Parameters:
BucketName:
Type: String
Default: personalizedemofirstnamelastname
Description: The name of the S3 Bucket to create, use only lowercase characters and numbers, no special characters or spaces.
NotebookName:
Type: String
Default: PersonalizeDemoLab
Description: Enter the name of the SageMaker notebook instance. Default is PersonalizeDemoLab.
VolumeSize:
Type: Number
Default: 10
MinValue: 5
MaxValue: 16384
ConstraintDescription: Must be an integer between 5 (GB) and 16384 (16 TB).
Description: Enter the size of the EBS volume in GB.
Metadata:
AWS::CloudFormation::Interface:
ParameterLabels:
BucketName:
default: Amazon S3 Bucket Name
NotebookName:
default: Amazon SageMaker Notebook Name
VolumeSize:
default: Size (in GB) of the Amazon SageMaker Notebook volume
Resources:
# Amazon S3 Bucket
# ---
S3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Ref BucketName
# Tagging Ressources to leverage SSM's Application Manager.
# ---
Tags:
- Key: AppManagerCFNStackKey
Value: !Ref 'AWS::StackId'
# AWS Cloudformation Custom Resource
# ---
# This custom resource calls AWS Lambda Function "BucketJanitor" before
# deleting the bucket as AWS Cloudformation doesn't allow to delete
# non-empty buckets.
EmptyS3BucketOnDelete:
Type: Custom::janitor
Properties:
ServiceToken:
Fn::GetAtt:
- "BucketJanitor"
- "Arn"
BucketName: !Ref S3Bucket
DependsOn: AmazonS3BucketAccessPolicy
# AWS Lambda function
# ---
# This function will empty the Amazon S3 Bucket "S3Bucket" upon stack
# deletion.
BucketJanitor:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile:
!Sub |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import boto3, logging
import cfnresponse
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info("event: {}".format(event))
try:
bucket = event['ResourceProperties']['BucketName']
logger.info("bucket: {}, event['RequestType']: {}".format(bucket,event['RequestType']))
# ---
# We only trigger the janitor if Cloudformation wants to
# delete the bucket (via a Custom Resource)
# ---
if event['RequestType'] == 'Delete':
s3 = boto3.resource('s3')
# ---
# convert bucket to string
# ---
bucket = str(bucket)
bucket_versioning_status = s3.BucketVersioning(bucket)
bucket = s3.Bucket(bucket)
# ---
# is versioning enabled ?
# ---
if bucket_versioning_status.status == 'Enabled':
print("### Bucket Versioning is enabled")
object_keys = []
# ---
# listing all object versions and adding them to an array.
# ---
for version in bucket.object_versions.all():
if version.object_key not in object_keys:
object_keys.append(version.object_key)
# ---
# deleting all the object versions in our array.
# ---
for key in object_keys:
print("deleting: " + key)
bucket.object_versions.filter(Prefix=key).delete()
else:
print("### Bucket Versioning is NOT enabled")
# ---
# delete all the objects
# ---
bucket.objects.all().delete()
# ---
# triger sendResponseCfn() to signal back to Cloudformation
# that all went well.
# ---
sendResponseCfn(event, context, cfnresponse.SUCCESS)
except Exception as e:
# ---
# triger sendResponseCfn() to signal back to Cloudformation
# that something went wrong and point to Cloudwatch Logs.
# ---
logger.info("Exception: {}".format(e))
sendResponseCfn(event, context, cfnresponse.FAILED)
def sendResponseCfn(event, context, responseStatus):
responseData = {}
responseData['Data'] = {}
cfnresponse.send(event, context, responseStatus, responseData, "CustomResourcePhysicalID")
Description: This function will empty the Amazon S3 Bucket "S3Bucket" upon stack deletion.
Handler: "index.lambda_handler"
Runtime: python3.12
MemorySize: 128
Timeout: 60
Role: !GetAtt BucketJanitorRole.Arn
# Tagging Ressources to leverage SSM's Application Manager.
# ---
Tags:
- Key: AppManagerCFNStackKey
Value: !Ref 'AWS::StackId'
# AWS Lambda Execution Role
# ---
BucketJanitorRole:
Type: AWS::IAM::Role
Properties:
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"
# Tagging Ressources to leverage SSM's Application Manager.
# ---
Tags:
- Key: AppManagerCFNStackKey
Value: !Ref 'AWS::StackId'
# Amazon 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: "/"
Policies:
- PolicyName: InlinePolicies
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- iam:CreateRole
- logs:PutLogEvents
Resource:
- !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/RetailDemoStorePersonalizePreCreateResources:log-stream:*'
- !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/RetailDemoStorePersonalizePreCreateResources'
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess"
- "arn:aws:iam::aws:policy/service-role/AmazonPersonalizeFullAccess"
- "arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess"
# Tagging Ressources to leverage SSM's Application Manager.
# ---
Tags:
- Key: AppManagerCFNStackKey
Value: !Ref 'AWS::StackId'
# Amazon Personalize Execution Role
# ---
PersonalizeIamRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
-
Effect: Allow
Principal:
Service: personalize.amazonaws.com
Action: sts:AssumeRole
Path: "/"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AmazonPersonalizeFullAccess"
- "arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess"
# Tagging Ressources to leverage SSM's Application Manager.
# ---
Tags:
- Key: AppManagerCFNStackKey
Value: !Ref 'AWS::StackId'
# AWS Identity and Access Management - S3 Custom Access Policy
# ---
# This policy allows Sagemaker and Personalize to perform any actions on the
# S3 bucket created by this template
AmazonS3BucketAccessPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: '2012-10-17'
Statement:
-
Effect: Allow
Action:
- "s3:*"
Resource:
- !Sub arn:aws:s3:::${S3Bucket}
- !Sub arn:aws:s3:::${S3Bucket}/*
Roles:
- !Ref SageMakerIamRole
- !Ref PersonalizeIamRole
- !Ref BucketJanitorRole
# Amazon S3 - S3 Bucket Policy
# ---
# This policy allows Personalize to perform any actions on the
# S3 bucket created by this template
PersonalizeBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref S3Bucket
PolicyDocument:
Version: '2012-10-17'
Id: 'PersonalizeS3BucketAccessPolicy'
Statement:
- Action:
- 's3:GetObject'
- 's3:PutObject'
- 's3:ListBucket'
Effect: Allow
Resource:
- !Sub arn:aws:s3:::${S3Bucket}
- !Sub arn:aws:s3:::${S3Bucket}/*
Principal:
Service: personalize.amazonaws.com
# SageMaker notebook
# ---
NotebookInstance:
Type: "AWS::SageMaker::NotebookInstance"
Properties:
# bumped ml.t2.medium to ml.t3.medium for newer regions compatibility
InstanceType: "ml.t3.medium"
NotebookInstanceName: !Ref NotebookName
RoleArn: !GetAtt SageMakerIamRole.Arn
VolumeSizeInGB: !Ref VolumeSize
DefaultCodeRepository: https://github.com/aws-samples/amazon-personalize-samples.git
Tags:
- Key: AppManagerCFNStackKey
Value: !Ref 'AWS::StackId'
# SSM Parameter with the s3 bucket for personalize
# ---
PersonalizeS3Bucket:
Type: AWS::SSM::Parameter
Properties:
Name: /cloudformation/personalize-s3-bucket
Type: String
Value: !Ref BucketName
Description: SSM Parameter containing the s3 bucket for Personalize Samples.
# Tagging Ressources to leverage SSM's Application Manager.
# ---
Tags:
Key: AppManagerCFNStackKey
Value: !Ref 'AWS::StackId'
# SSM Parameter with the IAM Role for personalize
# ---
PersonalizeIAMRole:
Type: AWS::SSM::Parameter
Properties:
Name: /cloudformation/personalize-iam-role-arn
Type: String
Value: !GetAtt PersonalizeIamRole.Arn
Description: SSM Parameter containing the iam role arn for Personalize.
# Tagging Ressources to leverage SSM's Application Manager.
# ---
Tags:
Key: AppManagerCFNStackKey
Value: !Ref 'AWS::StackId'
Outputs:
S3Bucket:
Value: !Ref BucketName
Description: S3 Bucket for object storage
NotebookInstance:
Value: !Ref NotebookInstance
Description: SageMaker Notebook Instance
AppManagerUrl:
Value: !Sub "https://console.aws.amazon.com/systems-manager/appmanager/application/AppManager-CFN-${AWS::StackName}"
Description: AWS Systems Manager Application Manager for this stack