-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathcore-main.yaml
408 lines (359 loc) · 13.8 KB
/
core-main.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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
AWSTemplateFormatVersion: '2010-09-09'
Description: |
Create the base infrastructure for SageMaker secure deployment: IAM roles and shared VPC network resources
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Stack name
Parameters:
- StackSetName
- Label:
default: Deployment options
Parameters:
- CreateIAMRoles
- CreateSharedServices
- CreateSCPortfolio
- Label:
default: IAM Role ARNs (only needed if created outside of this stack)
Parameters:
- DSAdministratorRoleArn
- SecurityControlExecutionRoleArn
- SCLaunchRoleArn
ParameterLabels:
StackSetName:
default: Common stack set name for core infrastructure resources
CreateIAMRoles:
default: Create IAM roles
CreateSharedServices:
default: Create shared services resources
CreateSCPortfolio:
default: Make a SageMaker Studio environment available as an AWS Service Catalog product
DSAdministratorRoleArn:
default: Data Science Administrator role ARN
SCLaunchRoleArn:
default: Service Catalog launch role ARN
SecurityControlExecutionRoleArn:
default: Security Control execution role ARN
Outputs:
AssumeDSAdministratorRole:
Description: URL for assuming the role of a cross-environment data science admin
Value: !If
- IAMRolesCondition
- !GetAtt IAMSharedRoles.Outputs.AssumeDSAdministratorRole
- !Sub
- 'https://signin.aws.amazon.com/switchrole?account=${AWS::AccountId}&roleName=${DSAdmininstratorRole}&displayName=${DSAdmininstratorRole}'
- DSAdmininstratorRole: !Select ['1', !Split [ '/', !Select ['5', !Split [':', !Ref DSAdministratorRoleArn ]]]]
SCLaunchRoleArn:
Description: Service Catalog Launch role ARN
Value: !If
- IAMRolesCondition
- !GetAtt IAMSharedRoles.Outputs.SCLaunchRoleArn
- !Ref SCLaunchRoleArn
Export:
Name: 'ds-service-catalog-launch-role-arn'
ProductId:
Description: Service Catalog data science product Id
Value: !If
- SCPortfolioCondition
- !GetAtt SharedServiceCatalogPortfolio.Outputs.ProductId
- ''
PortfolioId:
Description: Service Catalog data science portfolio Id
Value: !If
- SCPortfolioCondition
- !GetAtt SharedServiceCatalogPortfolio.Outputs.PortfolioId
- ''
ProductName:
Description: Service Catalog data science product name
Value: !If
- SCPortfolioCondition
- !GetAtt SharedServiceCatalogPortfolio.Outputs.ProductName
- ''
ProvisioningArtifactIds:
Description: Service Catalog data science provisioning artifact Ids
Value: !If
- SCPortfolioCondition
- !GetAtt SharedServiceCatalogPortfolio.Outputs.ProvisioningArtifactIds
- ''
ProvisioningArtifactNames:
Description: Service Catalog data science provisioning artifact names
Value: !If
- SCPortfolioCondition
- !GetAtt SharedServiceCatalogPortfolio.Outputs.ProvisioningArtifactNames
- ''
GetEnvironmentConfigurationLambdaArn:
Description: Lambda function to retrieve the data science enviroment configuration
Value: !GetAtt GetEnvironmentConfigurationLambda.Arn
Export:
Name: 'ds-get-environment-configuration-lambda-arn'
Parameters:
StackSetName:
Type: String
Description: A name to be used across core infrastructure nested stacks
CreateIAMRoles:
Type: String
Default: 'YES'
AllowedValues:
- 'YES'
- 'NO'
Description: Set to NO if you do not want to provision IAM roles (you must have already these roles provisioned up-front)
DSAdministratorRoleArn:
Type: String
Default: ''
Description: Data Science Administrator role ARN if it is created outside of this stack. Must be provided if Create IAM Roles = NO
SCLaunchRoleArn:
Type: String
Default: ''
Description: Service Catalog Launch role ARN if it is create outside of this stack. Must be provided if Create IAM Roles = NO
SecurityControlExecutionRoleArn:
Default: ''
Type: String
Description: Execution role ARN for security controls if it is create outside of this stack. Must be provided if Create IAM Roles = NO
CreateSharedServices:
Type: String
Default: 'NO'
AllowedValues:
- 'YES'
- 'NO'
Description: Set to YES if you do want to provision the shared services VPC network and PyPi mirror repository
CreateSCPortfolio:
Type: String
Default: 'YES'
AllowedValues:
- 'YES'
- 'NO'
Description: Set to YES if you want to make a SageMaker Studio environment available as a Service Catalog product
Conditions:
IAMRolesCondition: !Equals [ !Ref CreateIAMRoles, 'YES' ]
SharedServicesCondition: !Equals [ !Ref CreateSharedServices, 'YES' ]
SCPortfolioCondition: !Equals [ !Ref CreateSCPortfolio, 'YES' ]
Rules:
IAMRoles:
RuleCondition: !Equals [ !Ref CreateIAMRoles, 'NO' ]
Assertions:
- Assert: !And
- !Not [ !Equals [ !Ref DSAdministratorRoleArn, '' ] ]
- !Not [ !Equals [ !Ref SCLaunchRoleArn, '' ] ]
- !Not [ !Equals [ !Ref SecurityControlExecutionRoleArn, '' ] ]
AssertDescription: ARNs must be provided for all IAM roles if Create IAM Roles = NO
Resources:
GetEnvironmentConfigurationLambda:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import json
import boto3
import cfnresponse
sm = boto3.client("sagemaker")
ssm = boto3.client("ssm")
def get_environment(project_name, ssm_params):
r = sm.describe_domain(
DomainId=sm.describe_project(
ProjectName=project_name
)["CreatedBy"]["DomainId"]
)
del r["ResponseMetadata"]
del r["CreationTime"]
del r["LastModifiedTime"]
r = {**r, **r["DefaultUserSettings"]}
del r["DefaultUserSettings"]
i = {
**r,
**{t["Key"]:t["Value"]
for t in sm.list_tags(ResourceArn=r["DomainArn"])["Tags"]
if t["Key"] in ["EnvironmentName", "EnvironmentType"]}
}
for p in ssm_params:
try:
i[p["VariableName"]] = ssm.get_parameter(Name=f"{i['EnvironmentName']}-{i['EnvironmentType']}-{p['ParameterName']}")["Parameter"]["Value"]
except:
i[p["VariableName"]] = ""
return i
def lambda_handler(event, context):
try:
response_status = cfnresponse.SUCCESS
r = {}
if 'RequestType' in event and event['RequestType'] == 'Create':
r = get_environment(event["ResourceProperties"]["SageMakerProjectName"], event["ResourceProperties"]["SSMParams"])
print(r)
cfnresponse.send(event, context, response_status, r, '')
except Exception as exception:
print(exception)
cfnresponse.send(event, context, cfnresponse.FAILED, {}, physicalResourceId=event.get('PhysicalResourceId'), reason=str(exception))
Description: Get data science environment configuration for MLOps project setup
Handler: index.lambda_handler
MemorySize: 128
Role: !If
- IAMRolesCondition
- !GetAtt IAMSCSageMakerProjectRoles.Outputs.AmazonSageMakerServiceCatalogProductsLaunchRoleArn
- !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/service-role/AmazonSageMakerServiceCatalogProductsLaunchRole'
Runtime: python3.8
Timeout: 60
Tags:
- Key: DataScienceStackName
Value: !Ref StackSetName
LambdaExecutionRole:
Type: 'AWS::IAM::Role'
Condition: IAMRolesCondition
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: /
Policies:
- PolicyName: InlinePolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: IAMPermission
Effect: Allow
Action:
- 'iam:GetRole'
Resource: '*'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
Tags:
- Key: DataScienceStackName
Value: !Ref StackSetName
CheckIfIAMRolesExistLambda:
Type: AWS::Lambda::Function
Condition: IAMRolesCondition
Properties:
Code:
ZipFile: |
import json
import boto3
import cfnresponse
from botocore.exceptions import ClientError
iam = boto3.client('iam')
def lambda_handler(event, context):
try:
response_status = cfnresponse.SUCCESS
r = {}
if 'RequestType' in event and event['RequestType'] == 'Create':
r = check_roles(event['ResourceProperties']['RoleNames'])
cfnresponse.send(event, context, response_status, r, '')
except ClientError as exception:
print(exception)
cfnresponse.send(event, context, cfnresponse.FAILED, {}, physicalResourceId=event.get('PhysicalResourceId'), reason=str(exception))
def check_roles(roles):
ret = {}
for r in roles:
try:
iam.get_role(RoleName=r)
ret[r] = ""
except iam.exceptions.NoSuchEntityException:
ret[r] = r
return ret
Description: Checks if specified IAM roles exist
Handler: index.lambda_handler
MemorySize: 128
Role: !GetAtt LambdaExecutionRole.Arn
Runtime: python3.8
Timeout: 60
Tags:
- Key: DataScienceStackName
Value: !Ref StackSetName
CheckIfSageMakerSCProductsRolesExist:
Type: Custom::CheckIfIAMRolesExist
Condition: IAMRolesCondition
Properties:
ServiceToken: !GetAtt CheckIfIAMRolesExistLambda.Arn
RoleNames:
- AmazonSageMakerServiceCatalogProductsLaunchRole
- AmazonSageMakerServiceCatalogProductsUseRole
# SageMaker Project templates launch and use roles
IAMSCSageMakerProjectRoles:
Type: AWS::CloudFormation::Stack
Condition: IAMRolesCondition
Properties:
Parameters:
AmazonSageMakerServiceCatalogProductsLaunchRoleName:
!GetAtt CheckIfSageMakerSCProductsRolesExist.AmazonSageMakerServiceCatalogProductsLaunchRole
AmazonSageMakerServiceCatalogProductsUseRoleName:
!GetAtt CheckIfSageMakerSCProductsRolesExist.AmazonSageMakerServiceCatalogProductsUseRole
TemplateURL: core-iam-sc-sm-projects-roles.yaml
Tags:
- Key: DataScienceStackName
Value: !Ref StackSetName
# Shared IAM roles for personas and services
IAMSharedRoles:
Type: AWS::CloudFormation::Stack
Condition: IAMRolesCondition
Properties:
Parameters:
DSAdministratorRoleName: !Sub '${StackSetName}-${AWS::Region}-DataScienceAdministrator'
SageMakerDetectiveControlExecutionRoleName: !Sub '${StackSetName}-${AWS::Region}-DSSageMakerDetectiveControlRole'
SCLaunchRoleName: !Sub '${StackSetName}-${AWS::Region}-DSServiceCatalogLaunchRole'
TemplateURL: core-iam-shared-roles.yaml
Tags:
- Key: DataScienceStackName
Value: !Ref StackSetName
# Shared services VPC and related network resources
SharedServicesNetwork:
Type: AWS::CloudFormation::Stack
Condition: SharedServicesCondition
Properties:
Parameters:
StackSetName: !Ref StackSetName
TemplateURL: core-shared-services-network.yaml
Tags:
- Key: DataScienceStackName
Value: !Ref StackSetName
# Private PyPi mirror
SharedServicePyPIMirror:
Type: AWS::CloudFormation::Stack
DependsOn: SharedServicesNetwork
Condition: SharedServicesCondition
Properties:
Parameters:
StackSetName: !Ref StackSetName
TemplateURL: core-shared-services-ecs.yaml
Tags:
- Key: DataScienceStackName
Value: !Ref StackSetName
# Service Catalog with a Data Science product
SharedServiceCatalogPortfolio:
Type: AWS::CloudFormation::Stack
Condition: SCPortfolioCondition
Properties:
Parameters:
StackSetName: !Ref StackSetName
SCPortfolioPrincipalRoleArn: !If
- IAMRolesCondition
- !GetAtt IAMSharedRoles.Outputs.DSAdministratorRoleArn
- !Ref DSAdministratorRoleArn
SCProductLaunchRoleArn: !If
- IAMRolesCondition
- !GetAtt IAMSharedRoles.Outputs.SCLaunchRoleArn
- !Ref SCLaunchRoleArn
TemplateURL: core-sc-shared-portfolio.yaml
Tags:
- Key: DataScienceStackName
Value: !Ref StackSetName
# Security controls for the Data Science environment
DSSecurityControls:
Type: AWS::CloudFormation::Stack
Properties:
Parameters:
StackSetName: !Ref StackSetName
SecurityControlExecutionRoleArn: !If
- IAMRolesCondition
- !GetAtt IAMSharedRoles.Outputs.SageMakerDetectiveControlExecutionRoleArn
- !Ref SecurityControlExecutionRoleArn
TemplateURL: core-security-controls.yaml
Tags:
- Key: DataScienceStackName
Value: !Ref StackSetName