-
Notifications
You must be signed in to change notification settings - Fork 2
/
sagemaker-domain.yaml
843 lines (797 loc) · 32 KB
/
sagemaker-domain.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
AWSTemplateFormatVersion: '2010-09-09'
Description: >
This CFN template creates a SageMaker domain, a user profile, a Jupyter App Space
Parameters:
UserProfileNamePrefix:
Type: String
Description: The user profile name prefix for the SageMaker workshop
Default: 'studio-user-ts'
DomainNamePrefix:
Type: String
Description: The domain name prefix of the Sagemaker domain
Default: 'timeseries-domain'
JupyterLabAppInstance:
Type: String
Description: Name of an ML instance to run JupyterLab App space
Default: 'ml.g5.4xlarge'
OwnerID:
Type: String
Description: Owner identification to be written as a resource tag
Default: 'not-set'
CreateMLflowServer:
Type: String
Description: Create an MLflow trackings server as part of the domain
Default: 'NO'
AllowedValues:
- 'YES'
- 'NO'
Conditions:
CreateMLflowServerCondition: !Equals [ !Ref CreateMLflowServer, 'YES' ]
OwnerIDCondition: !Equals [ !Ref OwnerID, 'not-set' ]
Resources:
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
Policies:
- PolicyName: SetupLambdaPermissions
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: CloudWatchLogsPermissions
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: !Sub "arn:${AWS::Partition}:logs:*:*:*"
- Sid: SageMakerDomainPermission
Effect: Allow
Action:
- sagemaker:ListDomains
- sagemaker:CreateDomain
- sagemaker:DescribeDomain
- sagemaker:DeleteDomain
- sagemaker:UpdateDomain
- sagemaker:ListUserProfiles
- sagemaker:CreateUserProfile
- sagemaker:UpdateUserProfile
- sagemaker:DeleteUserProfile
- sagemaker:DescribeUserProfile
- sagemaker:ListApps
- sagemaker:CreateApp
- sagemaker:DescribeApp
- sagemaker:DeleteApp
- sagemaker:UpdateApp
Resource:
- !Sub "arn:${AWS::Partition}:sagemaker:*:*:domain/*"
- !Sub "arn:${AWS::Partition}:sagemaker:*:*:user-profile/*"
- !Sub "arn:${AWS::Partition}:sagemaker:*:*:app/*"
- Sid: SageMakerProjectsPermission
Effect: Allow
Action:
- servicecatalog:AcceptPortfolioShare
- sagemaker:EnableSagemakerServicecatalogPortfolio
- sagemaker:DisableSagemakerServicecatalogPortfolio
Resource: '*'
- Sid: ServiceCatalogPermission
Effect: Allow
Action:
- servicecatalog:ListAcceptedPortfolioShares
- servicecatalog:AssociatePrincipalWithPortfolio
Resource: '*'
- Sid: SageMakerExecPassRole
Effect: Allow
Action:
- iam:PassRole
Resource: !GetAtt SageMakerExecutionRole.Arn
- Sid: S3BucketCORSPermission
Effect: Allow
Action:
- s3:GetBucketCORS
- s3:PutBucketCORS
- s3:CreateBucket
- s3:ListBucket
- s3:HeadBucket
Resource: !Sub "arn:${AWS::Partition}:s3:::${StudioS3Bucket}"
- Sid: S3BucketDeletePermission
Effect: Allow
Action:
- s3:ListBucket
- s3:ListBucketVersions
- s3:DeleteBucket
- s3:DeleteObject
- s3:DeleteObjectVersion
Resource:
- !Sub "arn:${AWS::Partition}:s3:::${StudioS3Bucket}"
- !Sub "arn:${AWS::Partition}:s3:::${StudioS3Bucket}/*"
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- "sts:AssumeRole"
Path: /
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess'
- 'arn:aws:iam::aws:policy/IAMReadOnlyAccess'
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
SageMakerExecutionRole:
Type: AWS::IAM::Role
Properties:
Policies:
- PolicyName: logs
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- logs:FilterLogEvents
Resource: !Sub "arn:${AWS::Partition}:logs:*:${AWS::AccountId}:*"
- PolicyName: iam-access
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- iam:GetRole
- iam:GetRolePolicy
Resource: '*'
- PolicyName: pass-role
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- iam:PassRole
Resource: 'arn:aws:iam::*:role/*'
Condition:
StringLike:
iam:PassedToService:
- sagemaker.amazonaws.com
- events.amazonaws.com
- PolicyName: kms-access
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- kms:CreateKey
- kms:Get*
- kms:List*
Resource: '*'
- PolicyName: list-tags
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- sagemaker:ListTags
Resource: '*'
- PolicyName: get-service-quotas
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- servicequotas:GetServiceQuota
Resource: !Sub 'arn:${AWS::Partition}:servicequotas:${AWS::Region}:${AWS::AccountId}:sagemaker/*'
- PolicyName: mlflow-permissions
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- sagemaker-mlflow:*
- sagemaker:CreateMlflowTrackingServer
- sagemaker:UpdateMlflowTrackingServer
- sagemaker:DeleteMlflowTrackingServer
- sagemaker:StartMlflowTrackingServer
- sagemaker:StopMlflowTrackingServer
- sagemaker:CreatePresignedMlflowTrackingServerUrl
Resource: "*"
- PolicyName: q-developer-access
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- q:SendMessage
Resource: '*'
- PolicyName: bedrock-models-access
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- bedrock:GetFoundationModelAvailability
- bedrock:InvokeModel
- bedrock:InvokeModelWithResponseStream
Resource:
- 'arn:aws:bedrock:*::foundation-model/*'
- PolicyName: headless-execution-permissions
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- events:TagResource
- events:DeleteRule
- events:PutTargets
- events:DescribeRule
- events:PutRule
- events:RemoveTargets
- events:DisableRule
- events:EnableRule
Resource: '*'
Condition:
StringEquals:
'aws:ResourceTag/sagemaker:is-scheduling-notebook-job': 'true'
-
Effect: Allow
Action:
- s3:CreateBucket
- s3:PutBucketVersioning
- s3:PutEncryptionConfiguration
Resource: 'arn:aws:s3:::sagemaker-automated-execution-*'
-
Effect: Allow
Action:
- sagemaker:AddTags
Resource:
- 'arn:aws:sagemaker:*:*:training-job/*'
- 'arn:aws:sagemaker:*:*:pipeline/*'
-
Effect: Allow
Action:
- ec2:CreateNetworkInterface
- ec2:CreateNetworkInterfacePermission
- ec2:CreateVpcEndpoint
- ec2:DeleteNetworkInterface
- ec2:DeleteNetworkInterfacePermission
- ec2:DescribeDhcpOptions
- ec2:DescribeNetworkInterfaces
- ec2:DescribeRouteTables
- ec2:DescribeSecurityGroups
- ec2:DescribeSubnets
- ec2:DescribeVpcEndpoints
- ec2:DescribeVpcs
- ecr:BatchCheckLayerAvailability
- ecr:BatchGetImage
- ecr:GetDownloadUrlForLayer
- ecr:GetAuthorizationToken
- s3:ListBucket
- s3:GetBucketLocation
- s3:GetEncryptionConfiguration
- s3:PutObject
- s3:DeleteObject
- s3:GetObject
- s3:PutObjectTagging
- sagemaker:DescribeDomain
- sagemaker:DescribeUserProfile
- sagemaker:DescribeSpace
- sagemaker:DescribeStudioLifecycleConfig
- sagemaker:DescribeImageVersion
- sagemaker:DescribeAppImageConfig
- sagemaker:CreateTrainingJob
- sagemaker:DescribeTrainingJob
- sagemaker:StopTrainingJob
- sagemaker:Search
- sagemaker:CreatePipeline
- sagemaker:DescribePipeline
- sagemaker:DeletePipeline
- sagemaker:StartPipelineExecution
- glue:GetConnections
Resource: "*"
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Principal:
Service:
- sagemaker.amazonaws.com
- events.amazonaws.com
- forecast.amazonaws.com
- lambda.amazonaws.com
- bedrock.amazonaws.com
- redshift.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonSageMakerFullAccess
- arn:aws:iam::aws:policy/AWSCloudFormationFullAccess
- arn:aws:iam::aws:policy/AmazonSageMakerCanvasFullAccess
- arn:aws:iam::aws:policy/AmazonSageMakerCanvasDataPrepFullAccess
- arn:aws:iam::aws:policy/service-role/AmazonSageMakerCanvasDirectDeployAccess
- arn:aws:iam::aws:policy/AmazonSageMakerCanvasAIServicesAccess
- arn:aws:iam::aws:policy/AmazonSageMakerCanvasBedrockAccess
- arn:aws:iam::aws:policy/AWSPriceListServiceFullAccess
- !Sub "arn:${AWS::Partition}:iam::aws:policy/AmazonSageMakerPipelinesIntegrations"
EnableCanvasSettingsLambda:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
# Function: CFEnableSagemakerCanvasSettings
# Purpose: Enables Sagemaker Canvas Settings
import json
import boto3
import cfnresponse
client = boto3.client('sagemaker')
def lambda_handler(event, context):
response_status = cfnresponse.SUCCESS
sagemaker_domain_id = event['ResourceProperties']['SageMakerDomainId']
sagemaker_execution_role = event['ResourceProperties']['SageMakerExecutionRoleArn']
canvas_bucket_artifacts = event['ResourceProperties']['CanvasBucketName']
try:
if 'RequestType' in event and event['RequestType'] == 'Create':
client.update_domain(
DomainId=sagemaker_domain_id,
DefaultUserSettings={
'CanvasAppSettings': {
'WorkspaceSettings': {'S3ArtifactPath': f's3://{canvas_bucket_artifacts}/'},
'TimeSeriesForecastingSettings': {'Status': 'ENABLED'},
'ModelRegisterSettings': {'Status': 'ENABLED'},
'DirectDeploySettings': {'Status': 'ENABLED'},
'KendraSettings': {'Status': 'DISABLED'}, # Change to ENABLED when you want to use Kendra for RAG
'GenerativeAiSettings': {'AmazonBedrockRoleArn':sagemaker_execution_role},
# Uncomment and modify the below if you need to add OAuth for Salesforce or Snowflake
# 'IdentityProviderOAuthSettings': [
# {
# 'DataSourceName': 'SalesforceGenie'|'Snowflake',
# 'Status': 'ENABLED'|'DISABLED',
# 'SecretArn': 'string'
# },
# ],
}
}
)
cfnresponse.send(event, context, response_status, {}, '')
except Exception as e:
cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': str(e)}, context.log_stream_name)
Description: Enable SageMaker Canvas Settings
Handler: index.lambda_handler
MemorySize: 128
Role: !GetAtt LambdaExecutionRole.Arn
Runtime: python3.12
Timeout: 30
Tags:
- Key: owner
Value: !If [ OwnerIDCondition, !Ref 'AWS::StackId', !Ref OwnerID ]
EnableCanvasSettings:
Type: Custom::EnableCanvasSettings
Properties:
ServiceToken: !GetAtt EnableCanvasSettingsLambda.Arn
SageMakerDomainId: !GetAtt StudioDomain.DomainId
SageMakerExecutionRoleArn: !GetAtt SageMakerExecutionRole.Arn
CanvasBucketName: !Ref StudioS3Bucket
SetS3BucketCORSPolicyLambda:
Type: AWS::Lambda::Function
Properties:
Role: !GetAtt LambdaExecutionRole.Arn
Handler: index.handler
Runtime: python3.12
Timeout: 30
MemorySize: 128
Code:
ZipFile: |
import json
import boto3
import botocore
import cfnresponse
import os
s3 = boto3.client('s3')
def handler(event, context):
bucket_name = event['ResourceProperties']['BucketName']
cors_configuration = {
'CORSRules': [{
'AllowedHeaders': ['*'],
'AllowedMethods': ['POST', 'PUT', 'GET', 'HEAD', 'DELETE'],
'AllowedOrigins': ['https://*.sagemaker.aws'],
'ExposeHeaders': [
'ETag', 'x-amz-delete-marker', 'x-amz-id-2',
'x-amz-request-id', 'x-amz-server-side-encryption',
'x-amz-version-id'
]
}]
}
response_status = cfnresponse.SUCCESS
if 'RequestType' in event and event['RequestType'] != 'Create':
cfnresponse.send(event, context, response_status, {}, '')
try:
# Check if the bucket exists
s3.head_bucket(Bucket=bucket_name)
s3.put_bucket_cors(Bucket=bucket_name, CORSConfiguration=cors_configuration)
except botocore.exceptions.ClientError as e:
# If a 404 error occurs, then the bucket does not exist
if e.response['Error']['Code'] == '404':
try:
# Create the bucket
s3.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={'LocationConstraint': os.getenv("AWS_REGION")}
)
# Set the CORS configuration
s3.put_bucket_cors(Bucket=bucket_name, CORSConfiguration=cors_configuration)
except botocore.exceptions.ClientError as e:
# If an error occurs during bucket creation or CORS setting, return an error
print(f"Error creating or setting CORS for bucket {bucket_name}: {e}")
cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': str(e)}, bucket_name)
return
else:
# If any other error occurs, return an error
print(f"Error accessing bucket {bucket_name}: {e}")
cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': str(e)}, bucket_name)
return
except Exception as e:
# If any other unexpected error occurs, return an error
print(f"Unexpected error: {e}")
cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': str(e)}, bucket_name)
return
cfnresponse.send(event, context, cfnresponse.SUCCESS, {'BucketName': bucket_name}, bucket_name)
Tags:
- Key: owner
Value: !If [ OwnerIDCondition, !Ref 'AWS::StackId', !Ref OwnerID ]
SetS3BucketCORSPolicy:
Type: Custom::SetS3BucketCORSPolicy
Properties:
ServiceToken: !GetAtt SetS3BucketCORSPolicyLambda.Arn
BucketName: !Ref StudioS3Bucket
DefaultVpcLambda:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import json
import boto3
import cfnresponse
import logging
import traceback
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
try:
if 'RequestType' in event and event['RequestType'] == 'Create':
vpc_id = get_default_vpc_id()
subnets = get_subnets_for_vpc(vpc_id)
cfnresponse.send(event, context, cfnresponse.SUCCESS, {'VpcId': vpc_id , "Subnets" : subnets}, '')
else:
cfnresponse.send(event, context, cfnresponse.SUCCESS, {},'')
except:
logger.exception(f"CFGetDefaultVpcIdTut:failed :{traceback.format_exc()}")
cfnresponse.send(event, context, cfnresponse.FAILED, {})
def get_default_vpc_id():
vpcs = ec2.describe_vpcs(Filters=[{'Name': 'is-default', 'Values': ['true']}])
vpcs = vpcs['Vpcs']
vpc_id = vpcs[0]['VpcId']
return vpc_id
def get_subnets_for_vpc(vpcId):
response = ec2.describe_subnets(
Filters=[
{
'Name': 'vpc-id',
'Values': [vpcId]
}
]
)
subnet_ids = []
for subnet in response['Subnets']:
subnet_ids.append(subnet['SubnetId'])
return subnet_ids
Description: Return default VPC ID and Subnets
Handler: index.lambda_handler
MemorySize: 128
Role: !GetAtt LambdaExecutionRole.Arn
Runtime: python3.10
Timeout: 60
Tags:
- Key: owner
Value: !If [ OwnerIDCondition, !Ref 'AWS::StackId', !Ref OwnerID ]
DefaultVpcFinder:
Type: Custom::ResourceForFindingDefaultVpc
Properties:
ServiceToken: !GetAtt DefaultVpcLambda.Arn
DeleteS3BucketContentLambda:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import json, boto3
import cfnresponse
import logging
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']))
if event['RequestType'] == 'Delete':
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket)
for obj in bucket.objects.filter():
logger.info("delete obj: {}".format(obj))
s3.Object(bucket.name, obj.key).delete()
sendResponseCfn(event, context, cfnresponse.SUCCESS)
except Exception as e:
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")
Handler: index.lambda_handler
Description: "Delete all objects in S3 bucket"
Role: !GetAtt LambdaExecutionRole.Arn
Runtime: python3.10
Timeout: 60
Tags:
- Key: owner
Value: !If [ OwnerIDCondition, !Ref 'AWS::StackId', !Ref OwnerID ]
DeleteS3BucketContentOnDelete:
Type: Custom::DeleteS3BucketContent
Properties:
ServiceToken: !GetAtt DeleteS3BucketContentLambda.Arn
BucketName: !Ref StudioS3Bucket
DelayLambda:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt LambdaExecutionRole.Arn
Runtime: python3.10
Timeout: 900
Code:
ZipFile: |
import time
import cfnresponse
def lambda_handler(event, context):
try:
delay_sec = int(event.get('ResourceProperties', {}).get('DelayInSec', 60))
time.sleep(delay_sec)
cfnresponse.send(event, context, cfnresponse.SUCCESS, {
'Data': f'Delayed for {delay_sec} seconds'
}, event.get('PhysicalResourceId', 'DelayCustomResource'))
except Exception as e:
cfnresponse.send(event, context, cfnresponse.FAILED, {
'Error': str(e)
}, event.get('PhysicalResourceId', 'DelayCustomResource'))
Tags:
- Key: owner
Value: !If [ OwnerIDCondition, !Ref 'AWS::StackId', !Ref OwnerID ]
Delay:
DependsOn:
- StudioDomain
Type: Custom::DelayLambda
Properties:
ServiceToken: !GetAtt DelayLambda.Arn
DelayInSec: 60
StudioDomain:
Type: AWS::SageMaker::Domain
Properties:
AppNetworkAccessType: PublicInternetOnly
AuthMode: IAM
DomainSettings:
DockerSettings:
EnableDockerAccess: ENABLED
DefaultUserSettings:
ExecutionRole: !GetAtt SageMakerExecutionRole.Arn
StudioWebPortal: ENABLED
DefaultLandingUri: 'studio::'
DomainName: !Join ["-", [!Ref DomainNamePrefix, !Select [0, !Split [ "-", !Select [2, !Split ["/", !Ref AWS::StackId]]]]]]
SubnetIds: !GetAtt DefaultVpcFinder.Subnets
VpcId: !GetAtt DefaultVpcFinder.VpcId
Tags:
- Key: owner
Value: !If [ OwnerIDCondition, !Ref 'AWS::StackId', !Ref OwnerID ]
StudioUserProfile:
DependsOn:
- Delay
Type: AWS::SageMaker::UserProfile
Properties:
DomainId: !GetAtt StudioDomain.DomainId
UserProfileName: !Join ["-", [!Ref UserProfileNamePrefix, !Select [0, !Split [ "-", !Select [2, !Split ["/", !Ref AWS::StackId]]]]]]
UserSettings:
DefaultLandingUri: 'studio::'
ExecutionRole: !GetAtt SageMakerExecutionRole.Arn
Tags:
- Key: domain-id
Value: !Ref StudioDomain
- Key: owner
Value: !If [ OwnerIDCondition, !Ref 'AWS::StackId', !Ref OwnerID ]
### S3 Bucket similar to the one created by the create domain action in the UI
StudioS3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Join
- "-"
- - "sagemaker-studio"
- !Ref AWS::AccountId
- !Select [0, !Split [ "-", !Select [2, !Split ["/", !Ref AWS::StackId]]]]
Tags:
- Key: owner
Value: !If [ OwnerIDCondition, !Ref 'AWS::StackId', !Ref OwnerID ]
LifeCycleConfigLambdaRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: !Sub 'LifeCycleConfigLambdaPolicy-${AWS::StackName}'
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'sagemaker:CreateStudioLifecycleConfig'
- 'sagemaker:DeleteStudioLifecycleConfig'
Resource: !Sub 'arn:aws:sagemaker:${AWS::Region}:${AWS::AccountId}:studio-lifecycle-config/*'
- Effect: Allow
Action:
- 'sagemaker:UpdateUserProfile'
- 'sagemaker:DeleteUserProfile'
Resource: !Sub 'arn:aws:sagemaker:${AWS::Region}:${AWS::AccountId}:user-profile/*'
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
LifeCycleConfigLambda:
DependsOn:
- StudioUserProfile
Type: 'AWS::Lambda::Function'
Properties:
Description: Add LifeCycle Configuration to copy workshop files to Studio
Handler: index.lambda_handler
Role: !GetAtt LifeCycleConfigLambdaRole.Arn
Runtime: python3.10
Timeout: 60
Code:
ZipFile: !Join
- |+
- - 'import boto3'
- 'import base64'
- 'import cfnresponse'
- ''
- 'client = boto3.client(''sagemaker'')'
- 'lcc_up1 = ''\n''.join(('
- ' ''#!/bin/bash'','
- ' '''','
- ' ''set -ex'','
- ' '''','
- ' ''if [ ! -z "${SM_JOB_DEF_VERSION}" ]'','
- ' ''then'','
- ' '' echo "Running in job mode, skip lcc"'','
- ' ''else'','
- ' '' git clone https://github.com/aws-samples/modern-time-series-forecasting-on-aws.git || { echo "Error: Failed to clone repository"; exit 0; }'','
- ' '' echo "Files cloned from GitHub repo"'','
- ' ''fi'','
- ' '''','
- '))'
- ''
- !Sub 'lcc_name_up1 = "${AWS::StackName}-clone-repo"'
- !Sub 'up1 = "${StudioUserProfile}"'
- ''
- 'def get_lcc_base64_string(lcc_string):'
- ' lcc_bytes = lcc_string.encode("ascii")'
- ' base64_lcc_bytes = base64.b64encode(lcc_bytes)'
- ' base64_lcc_string = base64_lcc_bytes.decode("ascii")'
- ' return base64_lcc_string'
- ''
- ''
- 'def apply_lcc_to_user_profile(base64_lcc_string, lcc_config_name, profile):'
- ' response = client.create_studio_lifecycle_config('
- ' StudioLifecycleConfigName=lcc_config_name,'
- ' StudioLifecycleConfigContent=base64_lcc_string,'
- ' StudioLifecycleConfigAppType="JupyterLab",'
- ' )'
- ''
- ' lcc_arn = response["StudioLifecycleConfigArn"]'
- ' update_up = client.update_user_profile('
- ' DomainId=profile.split("|")[1],'
- ' UserProfileName=profile.split("|")[0],'
- ' UserSettings={'
- ' "JupyterLabAppSettings": {'
- ' "DefaultResourceSpec": {"LifecycleConfigArn": lcc_arn},'
- ' "LifecycleConfigArns": [lcc_arn]'
- ' }'
- ' }'
- ' )'
- ' return update_up'
- ''
- ''
- 'def lambda_handler(event, context):'
- ' print(event)'
- ' try:'
- ' base64_lcc_up1_string = get_lcc_base64_string(lcc_up1)'
- ' updated_up1 = apply_lcc_to_user_profile('
- ' base64_lcc_up1_string,'
- ' lcc_name_up1,'
- ' up1'
- ' )'
- ' print("Response User Profile LCC update for UP1")'
- ' print(updated_up1)'
- ''
- ' response_value = 120'
- ' response_data = {"Data": response_value}'
- ' cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)'
- ' except Exception as e:'
- ' if "RequestType" in event:'
- ' if event["RequestType"] == "Delete":'
- ' try:'
- ' response1 = client.delete_studio_lifecycle_config('
- ' StudioLifecycleConfigName=lcc_name_up1'
- ' )'
- ' print(response1)'
- ' response_data = {}'
- ' cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)'
- ' return'
- ' except Exception as e2:'
- ' print(e2)'
- ' response_data = e2'
- ' cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)'
- ' return'
- ' print(e)'
- ' response_data = {"Data": str(e)}'
- ' cfnresponse.send(event, context, cfnresponse.FAILED, response_data)'
Tags:
- Key: owner
Value: !If [ OwnerIDCondition, !Ref 'AWS::StackId', !Ref OwnerID ]
LifeCycleConfigLambdaInvoke:
Type: AWS::CloudFormation::CustomResource
Version: "1.0"
Properties:
ServiceToken: !GetAtt LifeCycleConfigLambda.Arn
JupyterAppSpace:
Type: AWS::SageMaker::Space
Properties:
DomainId: !GetAtt StudioDomain.DomainId
OwnershipSettings:
OwnerUserProfileName: !Select [2, !Split ["/", !GetAtt StudioUserProfile.UserProfileArn ]]
SpaceDisplayName: ts-space
SpaceName: ts-space
SpaceSettings:
AppType: JupyterLab
JupyterLabAppSettings:
CodeRepositories:
- RepositoryUrl: https://github.com/aws-samples/modern-time-series-forecasting-on-aws.git
DefaultResourceSpec:
InstanceType: !Ref JupyterLabAppInstance
SpaceStorageSettings:
EbsStorageSettings:
EbsVolumeSizeInGb: 100
SpaceSharingSettings:
SharingType: Private
# MLflow tracking server
MlFlowServer:
Type: AWS::SageMaker::MlflowTrackingServer
Condition: CreateMLflowServerCondition
Properties:
ArtifactStoreUri: !Sub 's3://${StudioS3Bucket}/mlflow/${StudioDomain.DomainId}'
AutomaticModelRegistration: True
RoleArn: !GetAtt SageMakerExecutionRole.Arn
TrackingServerName: !Sub 'mlflow-${StudioDomain.DomainId}'
TrackingServerSize: Small
Tags:
- Key: domain-id
Value: !Ref StudioDomain
- Key: owner
Value: !If [ OwnerIDCondition, !Ref 'AWS::StackId', !Ref OwnerID ]