forked from data-science-on-aws/data-science-on-aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lab.template
1294 lines (1251 loc) · 49.1 KB
/
lab.template
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"
Description: >
Creates the SageMaker Studio Domain, default user and default app
Parameters:
UserProfileName:
Description: Name of studio user
Type: String
Default: DefaultUser
Resources:
####
# Setup VPC, Subnet, IG and Routing Table ready for Studio
####
VPC:
Type: 'AWS::EC2::VPC'
Properties:
CidrBlock: 10.0.0.0/16
EnableDnsHostnames: true
Tags:
- Key: VPC
Value: VPC
- Key: Name
Value: VPC
InternetGateway1:
Type: 'AWS::EC2::InternetGateway'
DependsOn: VPC
AttachGateway:
Type: 'AWS::EC2::VPCGatewayAttachment'
Properties:
VpcId: !Ref VPC
InternetGatewayId: !Ref InternetGateway1
PublicSubnet:
Type: 'AWS::EC2::Subnet'
Properties:
VpcId: !Ref VPC
CidrBlock: 10.0.0.0/24
AvailabilityZone: !Select
- 0
- !GetAZs
Ref: AWS::Region
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: Public Subnet
PublicRouteTable1:
Type: 'AWS::EC2::RouteTable'
DependsOn:
- AttachGateway
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: Public Route Table
PublicRoute1:
Type: 'AWS::EC2::Route'
DependsOn:
- VPC
- AttachGateway
Properties:
RouteTableId: !Ref PublicRouteTable1
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway1
PublicSubnet1RouteTableAssociation:
Type: 'AWS::EC2::SubnetRouteTableAssociation'
Properties:
SubnetId: !Ref PublicSubnet
RouteTableId: !Ref PublicRouteTable1
####
# Private Subet
####
PrivateSubnet:
Type: 'AWS::EC2::Subnet'
Properties:
VpcId: !Ref VPC
CidrBlock: 10.0.1.0/24
AvailabilityZone: !Select
- 0
- !GetAZs
Ref: AWS::Region
MapPublicIpOnLaunch: false
Tags:
- Key: Name
Value: Private Subnet
PrivateRouteTable:
Type: 'AWS::EC2::RouteTable'
Properties:
VpcId: !Ref VPC
Tags:
- Key: Name
Value: Private Route Table
NAT:
Type: AWS::EC2::NatGateway
Properties:
AllocationId:
Fn::GetAtt:
- EIP
- AllocationId
SubnetId:
Ref: PublicSubnet
EIP:
Type: AWS::EC2::EIP
Properties:
Domain: vpc
Route:
Type: AWS::EC2::Route
Properties:
RouteTableId:
Ref: PrivateRouteTable
DestinationCidrBlock: 0.0.0.0/0
NatGatewayId:
Ref: NAT
PrivateSubnetRouteTableAssociation:
Type: 'AWS::EC2::SubnetRouteTableAssociation'
Properties:
SubnetId: !Ref PrivateSubnet
RouteTableId: !Ref PrivateRouteTable
### Roles for Sagemaker projects
AmazonSageMakerServiceCatalogProductsLaunchRole:
Type: "AWS::IAM::Role"
Properties:
RoleName: AmazonSageMakerServiceCatalogProductsLaunchRole
Description: "SageMaker role created from the SageMaker AWS Management Console. This role has the permissions required to launch the Amazon SageMaker portfolio of products from AWS ServiceCatalog."
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service: "servicecatalog.amazonaws.com"
Action: "sts:AssumeRole"
Path: "/service-role/"
MaxSessionDuration: 3600
Policies:
- PolicyName: AmazonSageMakerAdmin-ServiceCatalogProductsServiceRolePolicy
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- 'apigateway:GET'
- 'apigateway:POST'
- 'apigateway:PUT'
- 'apigateway:PATCH'
- 'apigateway:DELETE'
Resource: '*'
Condition:
StringLike:
'aws:ResourceTag/sagemaker:launch-source': '*'
- Effect: Allow
Action:
- 'apigateway:POST'
Resource: '*'
Condition:
'ForAnyValue:StringLike':
'aws:TagKeys':
- 'sagemaker:launch-source'
- Effect: Allow
Action:
- 'apigateway:PATCH'
Resource:
- 'arn:aws:apigateway:*::/account'
- Effect: Allow
Action:
- 'cloudformation:CreateStack'
- 'cloudformation:UpdateStack'
- 'cloudformation:DeleteStack'
Resource: 'arn:aws:cloudformation:*:*:stack/SC-*'
Condition:
ArnLikeIfExists:
'cloudformation:RoleArn':
- 'arn:aws:sts::*:assumed-role/AmazonSageMakerServiceCatalog*'
- Effect: Allow
Action:
- 'cloudformation:DescribeStackEvents'
- 'cloudformation:DescribeStacks'
Resource: 'arn:aws:cloudformation:*:*:stack/SC-*'
- Effect: Allow
Action:
- 'cloudformation:GetTemplateSummary'
- 'cloudformation:ValidateTemplate'
Resource: '*'
- Effect: Allow
Action:
- 'codebuild:CreateProject'
- 'codebuild:DeleteProject'
- 'codebuild:UpdateProject'
Resource:
- 'arn:aws:codebuild:*:*:project/sagemaker-*'
- Effect: Allow
Action:
- 'codecommit:CreateCommit'
- 'codecommit:CreateRepository'
- 'codecommit:DeleteRepository'
- 'codecommit:GetRepository'
- 'codecommit:TagResource'
Resource:
- 'arn:aws:codecommit:*:*:sagemaker-*'
- Effect: Allow
Action:
- 'codecommit:ListRepositories'
Resource: '*'
- Effect: Allow
Action:
- 'codepipeline:CreatePipeline'
- 'codepipeline:DeletePipeline'
- 'codepipeline:GetPipeline'
- 'codepipeline:GetPipelineState'
- 'codepipeline:StartPipelineExecution'
- 'codepipeline:TagResource'
- 'codepipeline:UpdatePipeline'
Resource:
- 'arn:aws:codepipeline:*:*:sagemaker-*'
- Effect: Allow
Action:
- 'cognito-idp:CreateUserPool'
Resource: '*'
Condition:
'ForAnyValue:StringLike':
'aws:TagKeys':
- 'sagemaker:launch-source'
- Effect: Allow
Action:
- 'cognito-idp:CreateGroup'
- 'cognito-idp:CreateUserPoolDomain'
- 'cognito-idp:CreateUserPoolClient'
- 'cognito-idp:DeleteGroup'
- 'cognito-idp:DeleteUserPool'
- 'cognito-idp:DeleteUserPoolClient'
- 'cognito-idp:DeleteUserPoolDomain'
- 'cognito-idp:DescribeUserPool'
- 'cognito-idp:DescribeUserPoolClient'
- 'cognito-idp:UpdateUserPool'
- 'cognito-idp:UpdateUserPoolClient'
Resource: '*'
Condition:
StringLike:
'aws:ResourceTag/sagemaker:launch-source': '*'
- Action:
- 'ecr:CreateRepository'
- 'ecr:DeleteRepository'
Resource:
- 'arn:aws:ecr:*:*:repository/sagemaker-*'
Effect: Allow
- Effect: Allow
Action:
- 'events:DescribeRule'
- 'events:DeleteRule'
- 'events:DisableRule'
- 'events:EnableRule'
- 'events:PutRule'
- 'events:PutTargets'
- 'events:RemoveTargets'
Resource:
- 'arn:aws:events:*:*:rule/sagemaker-*'
- Effect: Allow
Action:
- 'firehose:CreateDeliveryStream'
- 'firehose:DeleteDeliveryStream'
- 'firehose:DescribeDeliveryStream'
- 'firehose:StartDeliveryStreamEncryption'
- 'firehose:StopDeliveryStreamEncryption'
- 'firehose:UpdateDestination'
Resource: 'arn:aws:firehose:*:*:deliverystream/sagemaker-*'
- Action:
- 'glue:CreateDatabase'
- 'glue:DeleteDatabase'
Resource:
- 'arn:aws:glue:*:*:catalog'
- 'arn:aws:glue:*:*:database/sagemaker-*'
- 'arn:aws:glue:*:*:table/sagemaker-*'
- 'arn:aws:glue:*:*:userDefinedFunction/sagemaker-*'
Effect: Allow
- Action:
- 'glue:CreateClassifier'
- 'glue:DeleteClassifier'
- 'glue:DeleteCrawler'
- 'glue:DeleteJob'
- 'glue:DeleteTrigger'
- 'glue:DeleteWorkflow'
- 'glue:StopCrawler'
Resource:
- '*'
Effect: Allow
- Action:
- 'glue:CreateWorkflow'
Resource:
- 'arn:aws:glue:*:*:workflow/sagemaker-*'
Effect: Allow
- Action:
- 'glue:CreateJob'
Resource:
- 'arn:aws:glue:*:*:job/sagemaker-*'
Effect: Allow
- Action:
- 'glue:CreateCrawler'
- 'glue:GetCrawler'
Resource:
- 'arn:aws:glue:*:*:crawler/sagemaker-*'
Effect: Allow
- Action:
- 'glue:CreateTrigger'
- 'glue:GetTrigger'
Resource:
- 'arn:aws:glue:*:*:trigger/sagemaker-*'
Effect: Allow
- Effect: Allow
Action:
- 'iam:PassRole'
Resource:
- 'arn:aws:iam::*:role/service-role/AmazonSageMakerServiceCatalog*'
- Effect: Allow
Action:
- 'lambda:AddPermission'
- 'lambda:CreateFunction'
- 'lambda:DeleteFunction'
- 'lambda:GetFunction'
- 'lambda:GetFunctionConfiguration'
- 'lambda:InvokeFunction'
- 'lambda:RemovePermission'
Resource:
- 'arn:aws:lambda:*:*:function:sagemaker-*'
- Effect: Allow
Action:
- 'logs:CreateLogGroup'
- 'logs:CreateLogStream'
- 'logs:DeleteLogGroup'
- 'logs:DeleteLogStream'
- 'logs:DescribeLogGroups'
- 'logs:DescribeLogStreams'
- 'logs:PutRetentionPolicy'
Resource:
- 'arn:aws:logs:*:*:log-group:/aws/apigateway/AccessLogs/*'
- 'arn:aws:logs:*:*:log-group::log-stream:*'
- Effect: Allow
Action: 's3:GetObject'
Resource: '*'
Condition:
StringEquals:
's3:ExistingObjectTag/servicecatalog:provisioning': 'true'
- Effect: Allow
Action: 's3:GetObject'
Resource:
- 'arn:aws:s3:::sagemaker-*'
- Effect: Allow
Action:
- 's3:CreateBucket'
- 's3:DeleteBucket'
- 's3:DeleteBucketPolicy'
- 's3:GetBucketPolicy'
- 's3:PutBucketAcl'
- 's3:PutBucketNotification'
- 's3:PutBucketPolicy'
- 's3:PutBucketPublicAccessBlock'
- 's3:PutBucketLogging'
- 's3:PutEncryptionConfiguration'
Resource: 'arn:aws:s3:::sagemaker-*'
- Action:
- 'sagemaker:CreateEndpoint'
- 'sagemaker:CreateEndpointConfig'
- 'sagemaker:CreateModel'
- 'sagemaker:CreateWorkteam'
- 'sagemaker:DeleteEndpoint'
- 'sagemaker:DeleteEndpointConfig'
- 'sagemaker:DeleteModel'
- 'sagemaker:DeleteWorkteam'
- 'sagemaker:DescribeModel'
- 'sagemaker:DescribeEndpointConfig'
- 'sagemaker:DescribeEndpoint'
- 'sagemaker:DescribeWorkteam'
Resource:
- 'arn:aws:sagemaker:*:*:*'
Effect: Allow
- Action:
- 'states:CreateStateMachine'
- 'states:DeleteStateMachine'
- 'states:UpdateStateMachine'
Resource:
- 'arn:aws:states:*:*:stateMachine:sagemaker-*'
Effect: Allow
AmazonSageMakerServiceCatalogProductsUseRole:
Type: "AWS::IAM::Role"
Properties:
RoleName: AmazonSageMakerServiceCatalogProductsUseRole
Description: "SageMaker role created from the SageMaker AWS Management Console. This role has the permissions required to use the Amazon SageMaker portfolio of products from AWS ServiceCatalog."
Path: "/service-role/"
MaxSessionDuration: 3600
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service:
- "cloudformation.amazonaws.com"
- "apigateway.amazonaws.com"
- "lambda.amazonaws.com"
- "codebuild.amazonaws.com"
- "sagemaker.amazonaws.com"
- "glue.amazonaws.com"
- "events.amazonaws.com"
- "states.amazonaws.com"
- "codepipeline.amazonaws.com"
- "firehose.amazonaws.com"
Action: "sts:AssumeRole"
Policies:
- PolicyName: AmazonSageMakerServiceCatalogProductsUseRole-20210122T152377
PolicyDocument:
Version: 2012-10-17
Statement:
-
Action:
- cloudformation:CreateChangeSet
- cloudformation:CreateStack
- cloudformation:DescribeChangeSet
- cloudformation:DeleteChangeSet
- cloudformation:DeleteStack
- cloudformation:DescribeStacks
- cloudformation:ExecuteChangeSet
- cloudformation:SetStackPolicy
- cloudformation:UpdateStack
Resource: arn:aws:cloudformation:*:*:stack/sagemaker-*
Effect: Allow
-
Action:
- cloudwatch:PutMetricData
Resource: "*"
Effect: Allow
-
Action:
- codebuild:BatchGetBuilds
- codebuild:StartBuild
Resource:
- arn:aws:codebuild:*:*:project/sagemaker-*
- arn:aws:codebuild:*:*:build/sagemaker-*
Effect: Allow
-
Action:
- codecommit:CancelUploadArchive
- codecommit:GetBranch
- codecommit:GetCommit
- codecommit:GetUploadArchiveStatus
- codecommit:UploadArchive
Resource: arn:aws:codecommit:*:*:sagemaker-*
Effect: Allow
-
Action:
- codepipeline:StartPipelineExecution
Resource: arn:aws:codepipeline:*:*:sagemaker-*
Effect: Allow
-
Action:
- ec2:DescribeRouteTables
Resource: "*"
Effect: Allow
-
Action:
- ecr:BatchCheckLayerAvailability
- ecr:BatchGetImage
- ecr:Describe*
- ecr:GetAuthorizationToken
- ecr:GetDownloadUrlForLayer
Resource: "*"
Effect: Allow
-
Effect: Allow
Action:
- ecr:BatchDeleteImage
- ecr:CompleteLayerUpload
- ecr:CreateRepository
- ecr:DeleteRepository
- ecr:InitiateLayerUpload
- ecr:PutImage
- ecr:UploadLayerPart
Resource:
- arn:aws:ecr:*:*:repository/sagemaker-*
-
Action:
- events:DeleteRule
- events:DescribeRule
- events:PutRule
- events:PutTargets
- events:RemoveTargets
Resource:
- arn:aws:events:*:*:rule/sagemaker-*
Effect: Allow
-
Action:
- firehose:PutRecord
- firehose:PutRecordBatch
Resource: arn:aws:firehose:*:*:deliverystream/sagemaker-*
Effect: Allow
-
Action:
- glue:BatchCreatePartition
- glue:BatchDeletePartition
- glue:BatchDeleteTable
- glue:BatchDeleteTableVersion
- glue:BatchGetPartition
- glue:CreateDatabase
- glue:CreatePartition
- glue:CreateTable
- glue:DeletePartition
- glue:DeleteTable
- glue:DeleteTableVersion
- glue:GetDatabase
- glue:GetPartition
- glue:GetPartitions
- glue:GetTable
- glue:GetTables
- glue:GetTableVersion
- glue:GetTableVersions
- glue:SearchTables
- glue:UpdatePartition
- glue:UpdateTable
Resource:
- arn:aws:glue:*:*:catalog
- arn:aws:glue:*:*:database/default
- arn:aws:glue:*:*:database/global_temp
- arn:aws:glue:*:*:database/sagemaker-*
- arn:aws:glue:*:*:table/sagemaker-*
- arn:aws:glue:*:*:tableVersion/sagemaker-*
Effect: Allow
-
Action:
- iam:PassRole
Resource:
- arn:aws:iam::*:role/service-role/AmazonSageMakerServiceCatalogProductsUse*
Effect: Allow
-
Effect: Allow
Action:
- lambda:InvokeFunction
Resource:
- arn:aws:lambda:*:*:function:sagemaker-*
-
Action:
- logs:CreateLogDelivery
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:DeleteLogDelivery
- logs:Describe*
- logs:GetLogDelivery
- logs:GetLogEvents
- logs:ListLogDeliveries
- logs:PutLogEvents
- logs:PutResourcePolicy
- logs:UpdateLogDelivery
Resource: "*"
Effect: Allow
-
Effect: Allow
Action:
- s3:CreateBucket
- s3:DeleteBucket
- s3:GetBucketAcl
- s3:GetBucketCors
- s3:GetBucketLocation
- s3:ListAllMyBuckets
- s3:ListBucket
- s3:ListBucketMultipartUploads
- s3:PutBucketCors
Resource:
- arn:aws:s3:::aws-glue-*
- arn:aws:s3:::sagemaker-*
-
Effect: Allow
Action:
- s3:AbortMultipartUpload
- s3:DeleteObject
- s3:GetObject
- s3:GetObjectVersion
- s3:PutObject
Resource:
- arn:aws:s3:::aws-glue-*
- arn:aws:s3:::sagemaker-*
-
Effect: Allow
Action:
- sagemaker:*
NotResource:
- arn:aws:sagemaker:*:*:domain/*
- arn:aws:sagemaker:*:*:user-profile/*
- arn:aws:sagemaker:*:*:app/*
- arn:aws:sagemaker:*:*:flow-definition/*
-
Action:
- states:DescribeExecution
- states:DescribeStateMachine
- states:DescribeStateMachineForExecution
- states:GetExecutionHistory
- states:ListExecutions
- states:ListTagsForResource
- states:StartExecution
- states:StopExecution
- states:TagResource
- states:UntagResource
- states:UpdateStateMachine
Resource:
- arn:aws:states:*:*:stateMachine:sagemaker-*
- arn:aws:states:*:*:execution:sagemaker-*:*
Effect: Allow
-
Action:
- states:ListStateMachines
Resource: "*"
Effect: Allow
#########
# Create custom resource to create studio domain
#########
LambdaExecutionRole:
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/AmazonSageMakerFullAccess
- arn:aws:iam::aws:policy/AdministratorAccess
- arn:aws:iam::aws:policy/AmazonS3FullAccess
LambdaExecutionPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
Path: /
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: CreateServiceLinkedRole
Effect: Allow
Action:
- iam:CreateServiceLinkedRole
Resource: '*'
- Sid: S3Permissions
Effect: Allow
Action:
- s3:Get*
- s3:List*
Resource: '*'
- Sid: NetworkPermissions
Effect: Allow
Action:
- ec2:CreateNetworkInterface
- ec2:AttachNetworkInterface
- ec2:DescribeNetworkInterfaces
- ec2:DeleteNetworkInterface
- ec2:DetachNetworkInterface
- ec2:DescribeNetworkInterfaceAttribute
- ec2:DescribeSecurityGroups
- ec2:DescribeSubnets
- ec2:DescribeVpcs
Resource: '*'
- Sid: EFSPermissions
Effect: Allow
Action:
- elasticfilesystem:DescribeMountTargets
- elasticfilesystem:DescribeMountTargetSecurityGroups
- elasticfilesystem:ClientMount
- elasticfilesystem:ClientWrite
Resource: '*'
- Sid: CloudWatchLogsPermissions
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: !Sub "arn:${AWS::Partition}:logs:*:*:*"
- Sid: ServiceCatalogPermission
Effect: Allow
Action:
- servicecatalog:*
Resource: '*'
- Sid: SageMakerProjectsPermission
Effect: Allow
Action:
- sagemaker:EnableSagemakerServicecatalogPortfolio
- sagemaker:DisableSagemakerServicecatalogPortfolio
- servicecatalog:ListAcceptedPortfolioShares
- servicecatalog:DisassociatePrincipalFromPortfolio
- servicecatalog:AssociatePrincipalWithPortfolio
- servicecatalog:AcceptPortfolioShare
- servicecatalog:RejectPortfolioShare
- iam:GetRole
Resource: '*'
- Sid: SageMakerDomainPermission
Effect: Allow
Action:
- sagemaker:CreateDomain
- sagemaker:DescribeDomain
- sagemaker:DeleteDomain
- sagemaker:UpdateDomain
- sagemaker:CreateUserProfile
- sagemaker:UpdateUserProfile
- sagemaker:DeleteUserProfile
- sagemaker:DescribeUserProfile
- sagemaker:CreateApp
- sagemaker:DescribeApp
- sagemaker:DeleteApp
- sagemaker:ListApps
- sagemaker:ListUserProfiles
Resource:
- !Sub "arn:${AWS::Partition}:sagemaker:*:*:domain/*"
- !Sub "arn:${AWS::Partition}:sagemaker:*:*:user-profile/*"
- !Sub "arn:${AWS::Partition}:sagemaker:*:*:app/*"
- Sid: SageMakerExecPassRole
Effect: Allow
Action:
- iam:PassRole
Resource: !GetAtt SageMakerExecutionRole.Arn
Roles:
- !Ref LambdaExecutionRole
SageMakerExecutionRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- sagemaker.amazonaws.com
Action:
- "sts:AssumeRole"
Path: /service-role/
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonSageMakerFullAccess
- arn:aws:iam::aws:policy/AdministratorAccess
SageMakerExecutionPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
Path: /
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: S3Permissions
Effect: Allow
Action:
- s3:*
Resource: '*'
- Sid: IAMPermissions
Effect: Allow
Action:
- iam:*
Resource: '*'
Roles:
- !Ref SageMakerExecutionRole
StudioDomainFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt LambdaExecutionRole.Arn
Code:
ZipFile: |
import json
import time
import boto3
import logging
import cfnresponse
from botocore.exceptions import ClientError
client = boto3.client('sagemaker')
def lambda_handler(event, context):
try:
if event['RequestType'] == 'Create':
handle_create(event, context)
elif event['RequestType'] == 'Update':
handle_update(event, context)
elif event['RequestType'] == 'Delete':
handle_delete(event, context)
except ClientError as exception:
print(exception)
logging.error(exception)
cfnresponse.send(event, context, cfnresponse.FAILED, {}, reason=str(exception))
def handle_create(event, context):
resource_config = event['ResourceProperties']
response_data = create_studio_domain(resource_config)
efs_client = boto3.client('efs')
efs_response = efs_client.describe_mount_targets(FileSystemId=response_data['HomeEfsFileSystemId'])
sg_response = efs_client.describe_mount_target_security_groups(MountTargetId = efs_response['MountTargets'][0]['MountTargetId'])
ec2_client = boto3.client('ec2')
ec2_response = ec2_client.describe_security_groups(GroupIds=sg_response['SecurityGroups'])
e = ec2_response['SecurityGroups'][0]['IpPermissions'][0]['UserIdGroupPairs'][0]['GroupId']
cfnresponse.send(event, context, cfnresponse.SUCCESS, {'DomainId': response_data['DomainId'],'EFSId':response_data['HomeEfsFileSystemId'], 'SG':e}, physicalResourceId=response_data['DomainId'])
def handle_delete(event, context):
print('Received delete event')
domain_id = event['PhysicalResourceId']
try:
client.describe_domain(DomainId=domain_id)
except ClientError as exception:
logging.error(exception)
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, physicalResourceId=event['PhysicalResourceId'])
return
delete_domain(domain_id)
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, physicalResourceId=event['PhysicalResourceId'])
def handle_update(event, context):
logging.info('Received Update event')
domain_id = event['PhysicalResourceId']
default_user_settings = event['ResourceProperties']['DefaultUserSettings']
update_domain(domain_id, default_user_settings)
cfnresponse.send(event, context, cfnresponse.SUCCESS, {'DomainId' : domain_id}, physicalResourceId=event['PhysicalResourceId'])
def create_studio_domain(config):
vpc_id = config['VPC']
subnet_ids = config['SubnetIds']
default_user_settings = config['DefaultUserSettings']
domain_name = config['DomainName']
response = client.create_domain(
DomainName=domain_name,
AuthMode='IAM',
DefaultUserSettings=default_user_settings,
SubnetIds=subnet_ids.split(','),
VpcId=vpc_id
)
domain_id = response['DomainArn'].split('/')[-1]
created = False
while not created:
response = client.describe_domain(DomainId=domain_id)
time.sleep(5)
if response['Status'] == 'InService':
created = True
return response
def delete_domain(domain_id):
response = client.delete_domain(DomainId=domain_id, RetentionPolicy={'HomeEfsFileSystem': 'Delete'})
print(response)
deleted = False
while not deleted:
try:
response = client.describe_domain(DomainId=domain_id)
print(response)
except ClientError as error:
print(error)
if error.response['Error']['Code'] == 'ResourceNotFound':
print('Deleted')
deleted = True
return
time.sleep(5)
return response
def update_domain(domain_id, default_user_settings):
response = client.update_domain(
DomainId=domain_id,
DefaultUserSettings=default_user_settings
)
updated = False
while not updated:
response = client.describe_domain(DomainId=domain_id)
if response['Status'] == 'InService':
updated = True
else:
logging.info('Updating .. %s', response['Status'])
time.sleep(5)
return response
Runtime: python3.8
Timeout: 900
DependsOn:
- LambdaExecutionPolicy
PortfolioShareFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt LambdaExecutionRole.Arn
Code:
ZipFile: |
import json
import time
import boto3
import logging
import cfnresponse
from botocore.exceptions import ClientError
client = boto3.client('sagemaker')
def lambda_handler(event, context):
try:
if event['RequestType'] == 'Create':
handle_create(event, context)
elif event['RequestType'] == 'Delete':
handle_delete(event, context)
cfnresponse.send(event, context, cfnresponse.SUCCESS, {},physicalResourceId=event['PhysicalResourceId'])
else:
time.sleep(5)
cfnresponse.send(event, context, cfnresponse.SUCCESS,{}, physicalResourceId=event['PhysicalResourceId'])
except ClientError as exception:
logging.error(exception)
cfnresponse.send(event, context, cfnresponse.FAILED, {}, reason=str(exception))
def handle_delete(event, context):
sagemaker=boto3.client('sagemaker')
sc=boto3.client('servicecatalog')
studio_role_arn = event['ResourceProperties']['StudioRoleArn']
sagemaker.disable_sagemaker_servicecatalog_portfolio()
pid = event['PhysicalResourceId']
# sc.reject_portfolio_share(PortfolioId=pid)
cfnresponse.send(event, context, cfnresponse.SUCCESS,{}, physicalResourceId=pid)
sc.disassociate_principal_from_portfolio(PortfolioId=pid,PrincipalARN=studio_role_arn,PrincipalType='IAM')
def handle_create(event, context):
sagemaker=boto3.client('sagemaker')
sc=boto3.client('servicecatalog')
studio_role_arn = event['ResourceProperties']['StudioRoleArn']
sagemaker.enable_sagemaker_servicecatalog_portfolio()
response=sc.list_accepted_portfolio_shares()
pid = ''
for portfolio in response['PortfolioDetails']:
if portfolio['ProviderName']=='Amazon SageMaker':
pid=portfolio['Id']
sc.associate_principal_with_portfolio(PortfolioId=pid,PrincipalARN=studio_role_arn,PrincipalType='IAM')
cfnresponse.send(event, context, cfnresponse.SUCCESS,{}, physicalResourceId=pid)
Runtime: python3.8
Timeout: 900
DependsOn:
- LambdaExecutionPolicy
UserProfileFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt LambdaExecutionRole.Arn
Code:
ZipFile: |
import time, logging
import boto3
import cfnresponse
from botocore.exceptions import ClientError
client = boto3.client('sagemaker')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info(f'event: {event}')
try:
if event['RequestType'] == 'Create':
handle_create(event, context)
elif event['RequestType'] == 'Update':
handle_update(event, context)
elif event['RequestType'] == 'Delete':
handle_delete(event, context)
except Exception as exp:
logger.exception(exp)
cfnresponse.send(event, context, cfnresponse.FAILED,{}, reason=str(exp))
def handle_create(event, context):
resource_config = event['ResourceProperties']
response_data = create_user_profile(resource_config)
cfnresponse.send(event, context, cfnresponse.SUCCESS,{'UserProfileName': response_data['UserProfileName']}, physicalResourceId=response_data['UserProfileName'])
def handle_delete(event, context):
user_profile_name = event['PhysicalResourceId']
domain_id = event['ResourceProperties']['DomainId']
paginator = client.get_paginator('list_user_profiles')
page_iterator = paginator.paginate(DomainIdEquals=domain_id)
for page in page_iterator:
for user_profile in page['UserProfiles']:
logger.info(f'Deleting user {user_profile}')
delete_user_profile(domain_id, user_profile['UserProfileName'])
cfnresponse.send(event, context, cfnresponse.SUCCESS, {},physicalResourceId=event['PhysicalResourceId'])
return
def handle_update(event, context):
user_profile_name = event['PhysicalResourceId']
domain_id = event['ResourceProperties']['DomainId']
user_settings = event['ResourceProperties']['UserSettings']
update_user_profile(domain_id, user_profile_name, user_settings)
cfnresponse.send(event, context, cfnresponse.SUCCESS, {},physicalResourceId=event['PhysicalResourceId'])
def create_user_profile(config):
domain_id = config['DomainId']
user_profile_name = config['UserProfileName']
user_settings = config['UserSettings']
response = client.create_user_profile(DomainId=domain_id, UserProfileName=user_profile_name,UserSettings=user_settings)
created = False
while not created:
response = client.describe_user_profile(DomainId=domain_id, UserProfileName=user_profile_name)
time.sleep(5)
if response['Status'] == 'InService':
created = True
return response
def delete_user_profile(domain_id, user_profile_name):
response = client.delete_user_profile(DomainId=domain_id, UserProfileName=user_profile_name)
logger.info(response)
deleted = False
while not deleted:
time.sleep(5)
try:
response = client.describe_user_profile(DomainId=domain_id, UserProfileName=user_profile_name)
if response is not None and 'Status' in response and response['Status'] == 'Deleted':
deleted = True
except:
deleted = True
return
def update_user_profile(domain_id, user_profile_name, user_settings):