-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtemplate.yml
437 lines (433 loc) · 16.4 KB
/
template.yml
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
AWSTemplateFormatVersion: 2010-09-09
Description: SageMaker Studio Module
Mappings:
RegionMap:
us-east-1:
datascience: 'arn:aws:sagemaker:us-east-1:081325390199:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:us-east-1:663277389841:image/sagemaker-data-wrangler-1.0
us-east-2:
datascience: 'arn:aws:sagemaker:us-east-2:429704687514:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:us-east-2:415577184552:image/sagemaker-data-wrangler-1.0
us-west-1:
datascience: 'arn:aws:sagemaker:us-west-1:742091327244:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:us-west-1:926135532090:image/sagemaker-data-wrangler-1.0
us-west-2:
datascience: 'arn:aws:sagemaker:us-west-2:236514542706:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:us-west-2:174368400705:image/sagemaker-data-wrangler-1.0
af-south-1:
datascience: 'arn:aws:sagemaker:af-south-1:559312083959:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:af-south-1:143210264188:image/sagemaker-data-wrangler-1.0
ap-east-1:
datascience: 'arn:aws:sagemaker:ap-east-1:493642496378:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:ap-east-1:707077482487:image/sagemaker-data-wrangler-1.0
ap-south-1:
datascience: 'arn:aws:sagemaker:ap-south-1:394103062818:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:ap-south-1:089933028263:image/sagemaker-data-wrangler-1.0
ap-northeast-2:
datascience: 'arn:aws:sagemaker:ap-northeast-2:806072073708:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:ap-northeast-2:131546521161:image/sagemaker-data-wrangler-1.0
ap-southeast-1:
datascience: 'arn:aws:sagemaker:ap-southeast-1:492261229750:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:ap-southeast-1:119527597002:image/sagemaker-data-wrangler-1.0
ap-southeast-2:
datascience: 'arn:aws:sagemaker:ap-southeast-2:452832661640:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:ap-southeast-2:422173101802:image/sagemaker-data-wrangler-1.0
ap-northeast-1:
datascience: 'arn:aws:sagemaker:ap-northeast-1:102112518831:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:ap-northeast-1:649008135260:image/sagemaker-data-wrangler-1.0
ca-central-1:
datascience: 'arn:aws:sagemaker:ca-central-1:310906938811:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:ca-central-1:557239378090:image/sagemaker-data-wrangler-1.0
eu-central-1:
datascience: 'arn:aws:sagemaker:eu-central-1:936697816551:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:eu-central-1:024640144536:image/sagemaker-data-wrangler-1.0
eu-west-1:
datascience: 'arn:aws:sagemaker:eu-west-1:470317259841:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:eu-west-1:245179582081:image/sagemaker-data-wrangler-1.0
eu-west-2:
datascience: 'arn:aws:sagemaker:eu-west-2:712779665605:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:eu-west-2:894491911112:image/sagemaker-data-wrangler-1.0
eu-west-3:
datascience: 'arn:aws:sagemaker:eu-west-3:615547856133:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:eu-west-3:807237891255:image/sagemaker-data-wrangler-1.0
eu-north-1:
datascience: 'arn:aws:sagemaker:eu-north-1:243637512696:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:eu-north-1:054986407534:image/sagemaker-data-wrangler-1.0
eu-south-1:
datascience: >-
arn:aws:sagemaker:eu-south-1:488287956546:image/sagemaker-data-wrangler-1.0
datawrangler: 'arn:aws:sagemaker:eu-south-1:592751261982:image/datascience-1.0'
sa-east-1:
datascience: 'arn:aws:sagemaker:sa-east-1:782484402741:image/datascience-1.0'
datawrangler: >-
arn:aws:sagemaker:sa-east-1:424196993095:image/sagemaker-data-wrangler-1.0
Parameters:
SageMakerDomainName:
Type: String
Description: SageMaker Studio domain id
Default: studio-domain
SecurityGroupId:
Type: String
Description: >-
List of security group ids separated by comma. Can be empty if it is
stored in SSM
Default: ''
SubnetId:
Type: String
Description: List of subnet ids separated by comma. Can be empty if it is stored in SSM
Default: ''
VpcId:
Type: String
Description: VPC ID used for the SageMaker domain. Can be empty if it is stored in SSM
Default: ''
Conditions:
SecurityGroupIdEmpty: !Equals
- !Ref SecurityGroupId
- ''
SubnetIdEmpty: !Equals
- !Ref SubnetId
- ''
VpcIdEmpty: !Equals
- !Ref VpcId
- ''
Resources:
S3BucketStudio:
Type: 'AWS::S3::Bucket'
Properties:
VersioningConfiguration:
Status: Enabled
PublicAccessBlockConfiguration:
BlockPublicAcls: true
IgnorePublicAcls: true
BlockPublicPolicy: true
RestrictPublicBuckets: true
DefaultPolicy:
Type: 'AWS::IAM::ManagedPolicy'
Properties:
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: SageMakerBasePolicy
Effect: Allow
Action:
- 'application-autoscaling:DeleteScalingPolicy'
- 'application-autoscaling:DeleteScheduledAction'
- 'application-autoscaling:DeregisterScalableTarget'
- 'application-autoscaling:DescribeScalableTargets'
- 'application-autoscaling:DescribeScalingActivities'
- 'application-autoscaling:DescribeScalingPolicies'
- 'application-autoscaling:DescribeScheduledActions'
- 'application-autoscaling:PutScalingPolicy'
- 'application-autoscaling:PutScheduledAction'
- 'application-autoscaling:RegisterScalableTarget'
- 'cloudwatch:DeleteAlarms'
- 'cloudwatch:DescribeAlarms'
- 'cloudwatch:GetMetricData'
- 'cloudwatch:GetMetricStatistics'
- 'cloudwatch:ListMetrics'
- 'cloudwatch:PutMetricAlarm'
- 'cloudwatch:PutMetricData'
- 'ec2:CreateNetworkInterface'
- 'ec2:CreateNetworkInterfacePermission'
- 'ec2:DeleteNetworkInterface'
- 'ec2:DeleteNetworkInterfacePermission'
- 'ec2:DescribeDhcpOptions'
- 'ec2:DescribeNetworkInterfaces'
- 'ec2:DescribeRouteTables'
- 'ec2:DescribeSecurityGroups'
- 'ec2:DescribeSubnets'
- 'ec2:DescribeVpcEndpoints'
- 'ec2:DescribeVpcs'
- 'elastic-inference:Connect'
- 'iam:GetRole'
- 'iam:ListRoles'
- 'iam:PassRole'
- 'lambda:InvokeFunction'
- 'lambda:ListFunctions'
- 'logs:CreateLogGroup'
- 'logs:CreateLogStream'
- 'logs:DescribeLogStreams'
- 'logs:GetLogEvents'
- 'logs:PutLogEvents'
- 'sts:AssumeRole'
Resource: '*'
KMSPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- "kms:CreateGrant"
- "kms:Decrypt"
- "kms:DescribeKey"
- "kms:Encrypt"
- "kms:ReEncrypt*"
- "kms:GenerateDataKey"
- "kms:ListKeys"
- "kms:ListAliases"
Resource:
- "*"
S3Policy:
Type: 'AWS::IAM::ManagedPolicy'
Properties:
PolicyDocument:
Version: 2012-10-17
Statement:
- Action:
- 's3:Create*'
Effect: Allow
Resource: '*'
- Effect: Allow
Action:
- 's3:AbortMultipartUpload'
- 's3:DeleteObject'
- 's3:Describe*'
- 's3:GetObject'
- 's3:PutBucket*'
- 's3:PutObject*'
- 's3:GetBucket*'
- 's3:ListBucket'
Resource:
- '*'
ServicesPolicy:
Type: 'AWS::IAM::ManagedPolicy'
Properties:
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'cloudformation:*'
- 'cloudwatch:*'
- 'codecommit:*'
- 'ecr:*'
- 'lambda:*'
- 'logs:*'
- 'sagemaker:*'
- 'servicecatalog:*'
- 'ssm:*'
- 'sts:GetCallerIdentity'
Resource: '*'
- Effect: Allow
Action:
- 'iam:PassRole'
Resource:
- !Sub 'arn:aws:iam::${AWS::AccountId}:role/*'
SageMakerExecutionRole:
Type: 'AWS::IAM::Role'
Properties:
RoleName: mlops-sagemaker-execution-role
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: 'sts:AssumeRole'
Principal:
Service:
- cloudformation.amazonaws.com
- lambda.amazonaws.com
- sagemaker.amazonaws.com
Path: /
ManagedPolicyArns:
- !Ref DefaultPolicy
- !Ref KMSPolicy
- !Ref S3Policy
- !Ref ServicesPolicy
- arn:aws:iam::aws:policy/ComprehendFullAccess
- arn:aws:iam::aws:policy/TranslateFullAccess
SageMakerStudioDomain:
Type: 'AWS::SageMaker::Domain'
Properties:
AppNetworkAccessType: VpcOnly
AuthMode: IAM
DefaultUserSettings:
ExecutionRole: !GetAtt
- SageMakerExecutionRole
- Arn
SecurityGroups: !If
- SecurityGroupIdEmpty
- - '{{resolve:ssm:/networking/sg}}'
- - !Ref SecurityGroupId
SharingSettings:
NotebookOutputOption: Allowed
S3OutputPath: !Sub 's3://${S3BucketStudio}/studio'
DomainName: !Ref SageMakerDomainName
SubnetIds: !If
- SubnetIdEmpty
- - '{{resolve:ssm:/networking/subnet/private}}'
- - !Ref SubnetId
VpcId: !If
- VpcIdEmpty
- '{{resolve:ssm:/networking/vpc}}'
- !Ref VpcId
EnableSageMakerProjects:
Type: 'Custom::ResourceForEnablingSageMakerProjects'
Properties:
ServiceToken: !GetAtt
- EnableSageMakerProjectsLambda
- Arn
ExecutionRole: !GetAtt
- SageMakerExecutionRole
- Arn
EnableSageMakerProjectsLambda:
Type: 'AWS::Lambda::Function'
DependsOn: SageMakerStudioDomain
Properties:
Code:
ZipFile: |
# Function: EnableSagemakerProjects
# Purpose: Enables Sagemaker Projects
import json
import boto3
import cfnresponse
from botocore.exceptions import ClientError
client = boto3.client("sagemaker")
sc_client = boto3.client("servicecatalog")
def lambda_handler(event, context):
try:
response_status = cfnresponse.SUCCESS
if "RequestType" in event and event["RequestType"] == "Create":
enable_sm_projects(event["ResourceProperties"]["ExecutionRole"])
cfnresponse.send(event, context, response_status, {}, "")
except ClientError as exception:
print(exception)
cfnresponse.send(event, context, cfnresponse.FAILED, {}, physicalResourceId=event.get("PhysicalResourceId"), reason=str(exception))
def enable_sm_projects(studio_role_arn):
# enable Project on account level (accepts portfolio share)
response = client.enable_sagemaker_servicecatalog_portfolio()
# associate studio role with portfolio
response = sc_client.list_accepted_portfolio_shares()
portfolio_id = ""
for portfolio in response["PortfolioDetails"]:
if portfolio["ProviderName"] == "Amazon SageMaker":
portfolio_id = portfolio["Id"]
response = sc_client.associate_principal_with_portfolio(
PortfolioId=portfolio_id,
PrincipalARN=studio_role_arn,
PrincipalType="IAM"
)
Description: Enable Sagemaker Projects
Handler: index.lambda_handler
MemorySize: 128
Role: !GetAtt
- SageMakerExecutionRole
- Arn
Runtime: python3.8
Timeout: 120
SageMakerStudioUserProfile:
Type: 'AWS::SageMaker::UserProfile'
Properties:
DomainId: !Ref SageMakerStudioDomain
UserProfileName: bpistone
JupyterApp:
Type: 'AWS::SageMaker::App'
DependsOn: SageMakerStudioUserProfile
Properties:
AppName: default
AppType: JupyterServer
DomainId: !Ref SageMakerStudioDomain
UserProfileName: bpistone
DataScienceApp:
Type: 'AWS::SageMaker::App'
DependsOn: SageMakerStudioUserProfile
Properties:
AppName: sm-mlops-datascience-ml-t3-medium
AppType: KernelGateway
DomainId: !Ref SageMakerStudioDomain
ResourceSpec:
InstanceType: ml.t3.medium
SageMakerImageArn: !FindInMap
- RegionMap
- !Ref 'AWS::Region'
- datascience
UserProfileName: bpistone
DeleteKernelGatewayAppsNoKGCondition:
Type: 'Custom::DeleteKernelGatewayApps'
DependsOn: SageMakerStudioUserProfile
Properties:
ServiceToken: !GetAtt
- DeleteKernelGatewayAppsLambda
- Arn
DomainId: !Ref SageMakerStudioDomain
DeleteKernelGatewayAppsKGCondition:
Type: 'Custom::DeleteKernelGatewayApps'
DependsOn:
- DataScienceApp
Properties:
ServiceToken: !GetAtt
- DeleteKernelGatewayAppsLambda
- Arn
DomainId: !Ref SageMakerStudioDomain
DeleteKernelGatewayAppsLambda:
Type: 'AWS::Lambda::Function'
Properties:
Code:
ZipFile: |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import time
import boto3
import logging
import cfnresponse
from botocore.exceptions import ClientError
sm_client = boto3.client('sagemaker')
logger = logging.getLogger(__name__)
def delete_apps(domain_id):
logging.info(f'Start deleting apps for domain id: {domain_id}')
try:
sm_client.describe_domain(DomainId=domain_id)
except:
logging.info(f'Cannot retrieve {domain_id}')
return
for p in sm_client.get_paginator('list_apps').paginate(DomainIdEquals=domain_id):
for a in p['Apps']:
if a['AppType'] == 'KernelGateway' and a['Status'] != 'Deleted':
sm_client.delete_app(DomainId=a['DomainId'], UserProfileName=a['UserProfileName'], AppType=a['AppType'], AppName=a['AppName'])
apps = 1
while apps:
apps = 0
for p in sm_client.get_paginator('list_apps').paginate(DomainIdEquals=domain_id):
apps += len([a['AppName'] for a in p['Apps'] if a['AppType'] == 'KernelGateway' and a['Status'] != 'Deleted'])
logging.info(f'Number of active KernelGateway apps: {str(apps)}')
time.sleep(5)
logger.info(f'KernelGateway apps for {domain_id} deleted')
return
def lambda_handler(event, context):
response_data = {}
physicalResourceId = event.get('PhysicalResourceId')
try:
if event['RequestType'] in ['Create', 'Update']:
physicalResourceId = event.get('ResourceProperties')['DomainId']
elif event['RequestType'] == 'Delete':
delete_apps(physicalResourceId)
cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data, physicalResourceId=physicalResourceId)
except ClientError as exception:
logging.error(exception)
cfnresponse.send(event, context, cfnresponse.FAILED, response_data, physicalResourceId=physicalResourceId, reason=str(exception))
Description: Delete KernelGateway apps to clean up
Handler: index.lambda_handler
MemorySize: 128
Role: !GetAtt
- SageMakerExecutionRole
- Arn
Runtime: python3.8
Timeout: 900