/
project-s3-fs-ingestion.yaml
427 lines (390 loc) · 15.2 KB
/
project-s3-fs-ingestion.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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
AWSTemplateFormatVersion: 2010-09-09
Description: |
SageMaker Project for automated ingestion of a dataset from an S3 bucket to Feature Store.
This template creates a project to start a SageMaker pipeline, run data wrangler data processing, and ingest the processed data into a feature group.
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Pipeline Data
Parameters:
- PipelineNamePrefix
- PipelineDescription
- Label:
default: Input Data Location
Parameters:
- S3DataPrefix
- Label:
default: Transformation
Parameters:
- DataWranglerFlowUrl
- DataWranglerOutputName
- Label:
default: Destination
Parameters:
- FeatureGroupName
- Label:
default: Permissions
Parameters:
- LambdaExecutionRole
ParameterLabels:
PipelineNamePrefix:
default: Pipeline name prefix
PipelineDescription:
default: Pipeline description - optional
S3DataPrefix:
default: S3 Data prefix to monitor for new data
DataWranglerFlowUrl:
default: Data Wrangler flow URL
DataWranglerOutputName:
default: Data Wrangler output name (node_id.default)
FeatureGroupName:
default: Feature group name to ingest data
LambdaExecutionRole:
default: Execution role for the Lambda function
Parameters:
SageMakerProjectName:
Type: String
Description: Name of the project
MinLength: 1
MaxLength: 32
AllowedPattern: ^[a-zA-Z](-*[a-zA-Z0-9])*
SageMakerProjectId:
Type: String
Description: Service generated Id of the project.
PipelineNamePrefix:
Type: String
MaxLength: 241 # 256 - len(SageMakerProjectId) - 1
Default: 's3-fs-ingest-pipeline'
AllowedPattern: ^[a-zA-Z0-9](-*[a-zA-Z0-9])*
Description: Name of your data processing pipeline. The full name has a format <your custom name>-<project-id>
PipelineDescription:
Type: String
MaxLength: 3072
Default: 'Feature Store ingestion pipeline'
Description: Description of your data processing pipeline
DataWranglerFlowUrl:
Type: String
Description: S3 URL of the data wrangler .flow file
DataWranglerOutputName:
Type: String
Description: Output name must point to a correct node's ID in the flow file. The output name has a format <node-id>.default
S3DataPrefix:
Type: String
Description: S3 prefix pointing to a S3 location where a data file is uploaded to trigger the pipeline (without leading s3:// part)
FeatureGroupName:
Type: String
MaxLength: 64
AllowedPattern: ^[a-zA-Z0-9](-*[a-zA-Z0-9])*
Description: Name of the feature group name where the data will be ingested
LambdaExecutionRole:
Type: String
Default: 'Auto'
Description: Execution role for the lambda function. If Auto, a new IAM role will be created
Conditions:
CreateLambdaExecutionRoleCondition: !Equals [ !Ref LambdaExecutionRole, 'Auto' ]
Resources:
CodePipelineArtifactsBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
BucketName: !Sub sagemaker-cp-${SageMakerProjectName}-${SageMakerProjectId} # 12+32+15=59 chars max/ 63 allowed
AccessControl: Private
PublicAccessBlockConfiguration:
BlockPublicAcls: TRUE
BlockPublicPolicy: TRUE
IgnorePublicAcls: TRUE
RestrictPublicBuckets: TRUE
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: 'AES256'
DataLoadPipelineCodeCommitEventRule:
Type: AWS::Events::Rule
Properties:
# Max length allowed: 64
Name: !Sub sagemaker-${SageMakerProjectName}-${SageMakerProjectId}-build # max: 10+33+15+5=63 chars
Description: "Rule to start a pipeline upsert when data pipeline CodeCommit repository is updated"
EventPattern:
source:
- "aws.codecommit"
detail-type:
- "CodeCommit Repository State Change"
resources:
- !GetAtt DataLoadPipelineCodeCommitRepository.Arn
detail:
referenceType:
- "branch"
referenceName:
- "main"
State: "ENABLED"
Targets:
-
Arn:
!Sub 'arn:${AWS::Partition}:codepipeline:${AWS::Region}:${AWS::AccountId}:${DataLoadPipelineBuildPipeline}'
RoleArn:
!Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/service-role/AmazonSageMakerServiceCatalogProductsUseRole'
Id: !Sub codecommit-${SageMakerProjectName}-pipelinebuild
DataLoadPipelineCodeCommitRepository:
Type: AWS::CodeCommit::Repository
Properties:
# Max allowed length: 100 chars
RepositoryName: !Sub sagemaker-${SageMakerProjectName}-${SageMakerProjectId}-data-pipeline # max: 10+33+15+14=72
RepositoryDescription: !Sub SageMaker data transformation and ingestion pipeline building infrastructure as code for the project ${SageMakerProjectName}
Code:
S3:
Bucket: < S3_CFN_STAGING_BUCKET >
Key: amazon-sagemaker-reusable-components/seed-code/s3-fs-ingestion-v1.0.zip
BranchName: main
DataLoadPipelineBuildProject:
Type: AWS::CodeBuild::Project
Properties:
# Max length: 255 chars
Name: !Sub sagemaker-${SageMakerProjectName}-${SageMakerProjectId}-pipelinebuild # max: 10+33+15+13=71
Description: Pulls the code from data pipeline CodeCommit repository and upserts the SageMaker Pipeline
ServiceRole: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/service-role/AmazonSageMakerServiceCatalogProductsUseRole'
Artifacts:
Type: CODEPIPELINE
Environment:
Type: LINUX_CONTAINER
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/amazonlinux2-x86_64-standard:3.0
EnvironmentVariables:
- Name: SAGEMAKER_PROJECT_NAME
Value: !Ref SageMakerProjectName
- Name: SAGEMAKER_PROJECT_ID
Value: !Ref SageMakerProjectId
- Name: PIPELINE_DESCRIPTION
Value: !Ref PipelineDescription
- Name: PIPELINE_NAME_PREFIX
Value: !Ref PipelineNamePrefix
- Name: DW_FLOW_URL
Value: !Ref DataWranglerFlowUrl
- Name: DW_FLOW_OUTPUT_NAME
Value: !Ref DataWranglerOutputName
- Name: S3_DATA_PREFIX
Value: !Ref S3DataPrefix
- Name: FEATURE_GROUP_NAME
Value: !Ref FeatureGroupName
- Name: AWS_REGION
Value: !Ref AWS::Region
- Name: EXECUTION_ROLE
Value: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/service-role/AmazonSageMakerServiceCatalogProductsUseRole'
Source:
Type: CODEPIPELINE
BuildSpec: buildspec.yml
TimeoutInMinutes: 480
DataLoadPipelineBuildPipeline:
Type: AWS::CodePipeline::Pipeline
Properties:
# Max length: 100 chars
Name: !Sub sagemaker-${SageMakerProjectName}-${SageMakerProjectId}-pipelinebuild # max: 10+33+15+13=71
RoleArn: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:role/service-role/AmazonSageMakerServiceCatalogProductsUseRole'
ArtifactStore:
Type: S3
Location: !Ref CodePipelineArtifactsBucket
Stages:
- Name: Source
Actions:
- Name: DataLoadPipelineBuildSource
ActionTypeId:
Category: Source
Owner: AWS
Provider: CodeCommit
Version: '1'
Configuration:
PollForSourceChanges: 'false'
RepositoryName: !GetAtt DataLoadPipelineCodeCommitRepository.Name
BranchName: main
OutputArtifacts:
- Name: DataLoadPipelineSourceArtifact
- Name: Build
Actions:
- Name: UpsertSageMakerDataLoadPipeline
ActionTypeId:
Category: Build
Owner: AWS
Provider: CodeBuild
Version: '1'
InputArtifacts:
- Name: DataLoadPipelineSourceArtifact
OutputArtifacts:
- Name: DataLoadPipelineBuildArtifact
Configuration:
ProjectName: !Ref DataLoadPipelineBuildProject
RunOrder: 1
StartIngestionPipelineLambdaExecutionRole:
Type: 'AWS::IAM::Role'
Condition: CreateLambdaExecutionRoleCondition
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: SageMakerPipelinePermission
Effect: Allow
Action:
- sagemaker:StartPipelineExecution
Resource: !Sub 'arn:aws:sagemaker:${AWS::Region}:${AWS::AccountId}:pipeline/${PipelineNamePrefix}-${SageMakerProjectId}'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
StartIngestionPipelineLambda:
Type: AWS::Lambda::Function
Properties:
ReservedConcurrentExecutions: 1
Code:
ZipFile: |
import json
import os
import boto3
import logging
from time import gmtime, strftime
logger = logging.getLogger(__name__)
logging.root.setLevel(os.environ.get("LOG_LEVEL", "INFO"))
# configuration settings
SM_PIPELINE_NAME = os.environ.get("SM_PIPELINE_NAME", "")
s3 = boto3.resource('s3')
sm = boto3.client('sagemaker')
def lambda_handler(event, context):
try:
operation = event["detail"]["eventName"]
obj_key = event["detail"]["requestParameters"]["key"]
bucket_name = event["detail"]["requestParameters"]["bucketName"]
logger.info(f"Got the event: {operation} for the object: {bucket_name}/{obj_key}")
logger.info(f"Starting pipeline {SM_PIPELINE_NAME}")
start_pipeline = sm.start_pipeline_execution(
PipelineName=SM_PIPELINE_NAME,
PipelineExecutionDisplayName=f"{obj_key.split('/')[-1].replace('_','').replace('.csv','')}-{strftime('%d-%H-%M-%S', gmtime())}",
PipelineParameters=[
{
'Name': 'InputDataUrl',
'Value': f"s3://{bucket_name}/{obj_key}"
},
],
PipelineExecutionDescription=obj_key
)
logger.info(f"start_pipeline_execution returned {start_pipeline}")
except Exception as e:
logger.error(f"Exception in start_fs_ingestion function: {str(e)}")
return
Description: Start SageMaker pipeline with data transformation and FS ingestion
Environment:
Variables:
SM_PIPELINE_NAME: !Sub '${PipelineNamePrefix}-${SageMakerProjectId}'
Handler: index.lambda_handler
MemorySize: 128
Role: !If
- CreateLambdaExecutionRoleCondition
- !GetAtt StartIngestionPipelineLambdaExecutionRole.Arn
- !Ref LambdaExecutionRole
Runtime: python3.8
Timeout: 60
CloudTrailBucket:
# Bucket for CloudTrail logs
# We need CloudTrail to enable EventBridge notification for object put events on the data bucket
# We using the CloudTrail-based notification instead of S3 notifications
# because we don't want to overwrite the existing S3 notification on the data bucket
Type: AWS::S3::Bucket
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
BucketName: !Sub sagemaker-ct-${SageMakerProjectName}-${SageMakerProjectId} # 13+32+15=60 chars max/ 63 allowed
PublicAccessBlockConfiguration:
BlockPublicAcls: True
BlockPublicPolicy: True
IgnorePublicAcls: True
RestrictPublicBuckets: True
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: 'AES256'
OwnershipControls:
Rules:
- ObjectOwnership: BucketOwnerPreferred
# Bucket policy enables CloudTrail to write to the CloudTrailBucket
CloudTrailBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref CloudTrailBucket
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: "AWSCloudTrailAclCheck"
Effect: "Allow"
Principal:
Service: "cloudtrail.amazonaws.com"
Action: "s3:GetBucketAcl"
Resource: !Sub arn:aws:s3:::${CloudTrailBucket}
- Sid: "AWSCloudTrailWrite"
Effect: "Allow"
Principal:
Service: "cloudtrail.amazonaws.com"
Action: "s3:PutObject"
Resource: !Sub arn:aws:s3:::${CloudTrailBucket}/AWSLogs/${AWS::AccountId}/*
Condition:
StringEquals:
s3:x-amz-acl: "bucket-owner-full-control"
# The CloudTrail trail - uses the CloudTrailBucket as the trail name
S3ObjectCloudTrail:
Type: AWS::CloudTrail::Trail
DependsOn:
- CloudTrailBucketPolicy
Properties:
TrailName: !Sub cloudtrail-${CloudTrailBucket}
S3BucketName: !Ref CloudTrailBucket
IsLogging: true
IsMultiRegionTrail: false
EventSelectors:
- ReadWriteType: WriteOnly
- IncludeManagementEvents: false
DataResources:
- Type: AWS::S3::Object
Values:
- !Sub arn:aws:s3:::${S3DataPrefix}
IncludeGlobalServiceEvents: false
# Lambda resource permission for EventBridge to invoke the Lambda function
CloudTrailLambdaInvokePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref StartIngestionPipelineLambda
Principal: events.amazonaws.com
SourceAccount: !Ref AWS::AccountId
SourceArn: !GetAtt S3ObjectCreatedEventBridgeRule.Arn
# EventBridge event rule to invoke the Lambda function on `PutObject` and `CompleteMultipartUpload`
S3ObjectCreatedEventBridgeRule:
Type: AWS::Events::Rule
Properties:
Description: !Sub 'Invokes ${StartIngestionPipelineLambda} on object upload to the s3 prefix ${S3DataPrefix}'
Name: !Sub 's3-put-rule-${SageMakerProjectName}-${SageMakerProjectId}'
EventPattern:
source:
- 'aws.s3'
detail:
eventSource:
- 's3.amazonaws.com'
eventName:
- 'PutObject'
- 'CompleteMultipartUpload'
requestParameters:
bucketName:
- !Select [ 0, !Split [ '/', !Ref S3DataPrefix] ]
State: 'ENABLED'
Targets:
-
Arn: !GetAtt StartIngestionPipelineLambda.Arn
Id: !Sub 'target-${SageMakerProjectName}-${SageMakerProjectId}'