-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathhuman_approval.yaml
817 lines (776 loc) · 30.3 KB
/
human_approval.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
AWSTemplateFormatVersion: "2010-09-09"
Description: "AWS Step Functions Human based task example. It sends an email with an HTTP URL for approval."
Parameters:
Email:
Type: String
AllowedPattern: "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$"
ConstraintDescription: Must be a valid email address.
ContainerImage:
Type: String
s3Bucket:
Type: String
SageMakerExecutionRoleArn:
Type: String
Resources:
# Begin API Gateway Resources
ExecutionApi:
Type: AWS::ApiGateway::RestApi
Properties:
Name: "Human approval endpoint"
Description: "HTTP Endpoint backed by API Gateway and Lambda"
FailOnWarnings: true
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
ExecutionResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref ExecutionApi
ParentId: !GetAtt "ExecutionApi.RootResourceId"
PathPart: execution
ExecutionMethod:
Type: AWS::ApiGateway::Method
Properties:
AuthorizationType: NONE
HttpMethod: GET
Integration:
Type: AWS
IntegrationHttpMethod: POST
Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaApprovalFunction.Arn}/invocations"
IntegrationResponses:
- StatusCode: 302
ResponseParameters:
method.response.header.Location: "integration.response.body.headers.Location"
RequestTemplates:
application/json: |
{
"body" : $input.json('$'),
"headers": {
#foreach($header in $input.params().header.keySet())
"$header": "$util.escapeJavaScript($input.params().header.get($header))" #if($foreach.hasNext),#end
#end
},
"method": "$context.httpMethod",
"params": {
#foreach($param in $input.params().path.keySet())
"$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end
#end
},
"query": {
#foreach($queryParam in $input.params().querystring.keySet())
"$queryParam": "$util.escapeJavaScript($input.params().querystring.get($queryParam))" #if($foreach.hasNext),#end
#end
}
}
ResourceId: !Ref ExecutionResource
RestApiId: !Ref ExecutionApi
MethodResponses:
- StatusCode: 302
ResponseParameters:
method.response.header.Location: true
ApiGatewayAccount:
Type: AWS::ApiGateway::Account
Properties:
CloudWatchRoleArn: !GetAtt "ApiGatewayCloudWatchLogsRole.Arn"
ApiGatewayCloudWatchLogsRole:
Type: AWS::IAM::Role
Properties:
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- apigateway.amazonaws.com
Action:
- 'sts:AssumeRole'
Policies:
- PolicyName: ApiGatewayLogsPolicy
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- "logs:*"
Resource: !Sub "arn:${AWS::Partition}:logs:*:*:*"
ExecutionApiStage:
DependsOn:
- ApiGatewayAccount
Type: AWS::ApiGateway::Stage
Properties:
DeploymentId: !Ref ApiDeployment
MethodSettings:
- DataTraceEnabled: true
HttpMethod: '*'
LoggingLevel: INFO
ResourcePath: /*
RestApiId: !Ref ExecutionApi
StageName: states
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
ApiDeployment:
Type: AWS::ApiGateway::Deployment
DependsOn:
- ExecutionMethod
Properties:
RestApiId: !Ref ExecutionApi
StageName: DummyStage
# End API Gateway Resources
# Begin
# Lambda that will be invoked by API Gateway
LambdaApprovalFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile:
Fn::Sub: |
const AWS = require('aws-sdk');
var redirectToStepFunctions = function(lambdaArn, statemachineName, executionName, callback) {
const lambdaArnTokens = lambdaArn.split(":");
const partition = lambdaArnTokens[1];
const region = lambdaArnTokens[3];
const accountId = lambdaArnTokens[4];
console.log("partition=" + partition);
console.log("region=" + region);
console.log("accountId=" + accountId);
const executionArn = "arn:" + partition + ":states:" + region + ":" + accountId + ":execution:" + statemachineName + ":" + executionName;
console.log("executionArn=" + executionArn);
const url = "https://console.aws.amazon.com/states/home?region=" + region + "#/executions/details/" + executionArn;
callback(null, {
statusCode: 302,
headers: {
Location: url
}
});
};
exports.handler = (event, context, callback) => {
console.log('Event= ' + JSON.stringify(event));
const action = event.query.action;
const taskToken = event.query.taskToken;
const statemachineName = event.query.sm;
const executionName = event.query.ex;
const sagemakerTrainingJobName = event.query.trainingJobName;
const modelArtifacts = event.query.modelArtifacts;
const stepfunctions = new AWS.StepFunctions();
var message = "";
if (action === "approve") {
message = { "Status": "Approved! Model approved by ${Email}",
"TrainingJobName": sagemakerTrainingJobName,
"ModelArtifacts": modelArtifacts };
} else if (action === "reject") {
message = { "Status": "Rejected! Model rejected by ${Email}" };
} else {
console.error("Unrecognized action. Expected: approve, reject.");
callback({"Status": "Failed to process the request. Unrecognized Action."});
}
stepfunctions.sendTaskSuccess({
output: JSON.stringify(message),
taskToken: event.query.taskToken
})
.promise()
.then(function(data) {
redirectToStepFunctions(context.invokedFunctionArn, statemachineName, executionName, callback);
}).catch(function(err) {
console.error(err, err.stack);
callback(err);
});
}
Description: Lambda function that callback to AWS Step Functions
Handler: index.handler
Role: !GetAtt "LambdaApiGatewayIAMRole.Arn"
Runtime: nodejs12.x
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
LambdaApiGatewayInvoke:
Type: AWS::Lambda::Permission
Properties:
Action: "lambda:InvokeFunction"
FunctionName: !GetAtt "LambdaApprovalFunction.Arn"
Principal: "apigateway.amazonaws.com"
SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${ExecutionApi}/*"
LambdaApiGatewayIAMRole:
Type: AWS::IAM::Role
Properties:
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- "sts:AssumeRole"
Effect: "Allow"
Principal:
Service:
- "lambda.amazonaws.com"
Policies:
- PolicyName: CloudWatchLogsPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "logs:*"
Resource: !Sub "arn:${AWS::Partition}:logs:*:*:*"
- PolicyName: StepFunctionsPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "states:SendTaskFailure"
- "states:SendTaskSuccess"
Resource: "*"
# End Lambda that will be invoked by API Gateway
# Begin state machine that publishes to Lambda and sends an email with the link for approval
HumanApprovalLambdaStateMachine:
DependsOn:
- LambdaApprovalFunction
- LambdaHumanApprovalSendEmailFunction
Type: AWS::StepFunctions::StateMachine
Properties:
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
RoleArn: !GetAtt LambdaStateMachineExecutionRole.Arn
DefinitionString:
Fn::Sub: |
{
"StartAt": "Train model (r-fable-forecasting)",
"States": {
"Train model (r-fable-forecasting)": {
"Type": "Task",
"Resource": "arn:aws:states:::sagemaker:createTrainingJob.sync",
"Parameters": {
"AlgorithmSpecification": {
"TrainingImage": "${ContainerImage}",
"TrainingInputMode": "File"
},
"OutputDataConfig": {
"S3OutputPath": "s3://${s3Bucket}/output/r-fable-trip-forecasting"
},
"StoppingCondition": {
"MaxRuntimeInSeconds": 3600
},
"ResourceConfig": {
"InstanceCount": 1,
"InstanceType": "ml.m4.xlarge",
"VolumeSizeInGB": 5
},
"RoleArn": "${SageMakerExecutionRoleArn}",
"InputDataConfig":[
{
"ChannelName": "train",
"DataSource":{
"S3DataSource":{
"S3DataType": "S3Prefix",
"S3Uri.$": "States.Format('s3://{}/{}', $.detail.requestParameters.bucketName, $.detail.requestParameters.key)",
"S3DataDistributionType":"FullyReplicated"
}
}
}
],
"HyperParameters": {
"city.$": "$.city",
"ic": "aic",
"ets_trend_method": "A"
},
"TrainingJobName.$": "States.Format('r-fable-{}-{}', $.city, $.eventID)"
},
"Catch":[
{
"ErrorEquals":[
"States.ALL"
],
"ResultPath":"$.cause",
"Next":"Workflow Error"
}
],
"Next": "Evaluate model"
},
"Evaluate model": {
"Type": "Task",
"Resource": "arn:aws:states:::sagemaker:createProcessingJob.sync",
"Parameters": {
"AppSpecification": {
"ImageUri": "${ContainerImage}",
"ContainerEntrypoint": ["/usr/bin/Rscript", "/opt/fable_sagemaker.r", "evaluate"],
"ContainerArguments.$": "States.Array($.HyperParameters.city)"
},
"ProcessingInputs": [
{
"InputName": "model-input",
"S3Input": {
"LocalPath": "/opt/ml/processing/input",
"S3DataDistributionType": "FullyReplicated",
"S3DataType": "S3Prefix",
"S3InputMode": "File",
"S3Uri.$": "$.ModelArtifacts.S3ModelArtifacts"
}
}
],
"ProcessingOutputConfig": {
"Outputs": [
{
"OutputName": "evaluation-output",
"S3Output": {
"LocalPath": "/opt/ml/processing/output",
"S3UploadMode": "EndOfJob",
"S3Uri.$": "States.Format('s3://${s3Bucket}/output/r-fable-trip-forecasting/{}', $.TrainingJobName)"
}
}
]
},
"ProcessingResources": {
"ClusterConfig": {
"InstanceCount": 1,
"InstanceType": "ml.t3.large",
"VolumeSizeInGB": 5
}
},
"RoleArn": "${SageMakerExecutionRoleArn}",
"ProcessingJobName.$": "$.TrainingJobName"
},
"Catch":[
{
"ErrorEquals":[
"States.ALL"
],
"ResultPath":"$.cause",
"Next":"Workflow Error"
}
],
"Next": "Send email for approval"
},
"Workflow Error": {
"Type": "Fail",
"Error": "ErrorCode",
"Cause": "Caused By Message"
},
"Send email for approval":{
"Type": "Task",
"Resource": "arn:${AWS::Partition}:states:::lambda:invoke.waitForTaskToken",
"Parameters": {
"FunctionName": "${LambdaHumanApprovalSendEmailFunction.Arn}",
"Payload": {
"EvaluationReport.$": "States.Format('{}/forecast-report.png', $.ProcessingOutputConfig.Outputs[0].S3Output.S3Uri)",
"EvaluationReportBucket": "${s3Bucket}",
"EvaluationReportKey.$": "States.Format('output/r-fable-trip-forecasting/{}/forecast-report.png', $.ProcessingJobName)",
"TrainingJobName.$": "$.ProcessingJobName",
"ModelArtifacts.$": "$.ProcessingInputs[0].S3Input.S3Uri",
"ExecutionContext.$": "$$",
"APIGatewayEndpoint": "https://${ExecutionApi}.execute-api.${AWS::Region}.amazonaws.com/states"
}
},
"Catch":[
{
"ErrorEquals":[
"States.ALL"
],
"ResultPath":"$.cause",
"Next":"Workflow Error"
}
],
"Next": "ManualApprovalChoiceState"
},
"ManualApprovalChoiceState": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.Status",
"StringEquals": "Approved! Model approved by ${Email}",
"Next": "Approved Model"
},
{
"Variable": "$.Status",
"StringEquals": "Rejected! Model rejected by ${Email}",
"Next": "Rejected Model"
}
],
"Default": "Rejected Model"
},
"Approved Model": {
"Type": "Pass",
"Next": "Save Model"
},
"Rejected Model": {
"Type": "Pass",
"End": true
},
"Save Model": {
"Parameters": {
"PrimaryContainer": {
"Image": "${ContainerImage}",
"Environment": {},
"ModelDataUrl.$": "$.ModelArtifacts"
},
"ExecutionRoleArn": "${SageMakerExecutionRoleArn}",
"ModelName.$": "$.TrainingJobName"
},
"Resource": "arn:aws:states:::sagemaker:createModel",
"Type": "Task",
"End": true
}
}
}
LambdaHumanApprovalSendEmailFunction:
Type: AWS::Lambda::Function
Properties:
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
Handler: "index.lambda_handler"
Role: !GetAtt LambdaSendEmailExecutionRole.Arn
Runtime: "nodejs12.x"
Timeout: "25"
Code:
ZipFile:
Fn::Sub: |
const AWS = require('aws-sdk');
AWS.config.update({signatureVersion: 'v4'});
exports.lambda_handler = (event, context, callback) => {
console.log('event= ' + JSON.stringify(event));
console.log('context= ' + JSON.stringify(context));
const executionContext = event.ExecutionContext;
const executionName = executionContext.Execution.Name;
const sagemakerTraingingJob = event.TrainingJobName;
const modelArtifacts = event.ModelArtifacts;
const evaluationReportBucket = event.EvaluationReportBucket;
const evaluationReportKey = event.EvaluationReportKey;
const statemachineName = executionContext.StateMachine.Name;
const taskToken = executionContext.Task.Token;
const apigwEndpint = event.APIGatewayEndpoint;
const approveEndpointUrl = apigwEndpint + "/execution?action=approve&ex=" + executionName + "&sm=" + statemachineName + "&trainingJobName=" + sagemakerTraingingJob + "&modelArtifacts=" + encodeURIComponent(modelArtifacts) + "&taskToken=" + encodeURIComponent(taskToken);
console.log('approveEndpoint= ' + approveEndpointUrl);
const rejectEndpointUrl = apigwEndpint + "/execution?action=reject&ex=" + executionName + "&sm=" + statemachineName + "&taskToken=" + encodeURIComponent(taskToken);
console.log('rejectEndpoint= ' + rejectEndpointUrl);
// presign the report png for review
// https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getSignedUrl-property
var s3 = new AWS.S3();
var s3params = {Bucket: evaluationReportBucket, Key: evaluationReportKey, Expires: 86400};
var evaluationReportUrl = s3.getSignedUrl('getObject', s3params);
console.log('The Evaluation Report URL is', evaluationReportUrl);
var emailMessageHtml = '<h2 id="welcome-">Welcome!</h2>';
emailMessageHtml += '<p>This is an email requiring an approval for a step functions execution.</p>';
emailMessageHtml += '<p>Please check the following information and click "Approve" link if you want to approve.</p>';
emailMessageHtml += '<p>AWS StepFunctions Execution Name -> '+ executionName + '</p>';
emailMessageHtml += '<p>Amazon SageMaker Training Job Name -> ' + sagemakerTraingingJob + '</p>';
emailMessageHtml += '<p>Model Artifact -> ' + modelArtifacts + '</p>';
emailMessageHtml += '<p>Please review the <a href="' + evaluationReportUrl + '">model report</a>.</p>';
emailMessageHtml += '<img src="' + evaluationReportUrl + '" alt="image" width="800">';
emailMessageHtml += '<p>Click <a href="' + approveEndpointUrl + '">Approve</a> to approve the model.</p>';
emailMessageHtml += '<p>Click <a href="' + rejectEndpointUrl + '">Reject</a> to reject the model.</p>';
emailMessageHtml += '<p>Thanks for reviewing the model!</p>';
const ses = new AWS.SES({apiVersion: '2010-12-01'});
var params = {
Destination: {ToAddresses:["${Email}"]},
Message: {Body: {Html: {Charset:'UTF-8', Data: emailMessageHtml}},
Subject: {Charset: 'UTF-8', Data: 'Required approval from AWS Step Functions'}},
Source: "${Email}"
};
ses.sendEmail(params)
.promise()
.then(function(data) {
console.log("MessageID is " + data.MessageId);
callback(null);
}).catch(
function(err) {
console.error(err, err.stack);
callback(err);
});
};
LambdaVerifySESEmail:
Type: AWS::Lambda::Function
Properties:
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
Handler: "index.lambda_handler"
Role: !GetAtt LambdaSendEmailExecutionRole.Arn
Runtime: "nodejs12.x"
Timeout: "25"
Code:
ZipFile:
Fn::Sub: |
var AWS = require('aws-sdk');
var response = require('cfn-response');
exports.lambda_handler = (event, context, callback) => {
// For Delete requests, immediately send a SUCCESS response.
if (event.RequestType == "Delete") {
response.send(event, context, "SUCCESS");
return;
}
var responseStatus = "FAILED";
var responseData = {};
const ses = new AWS.SES({apiVersion: '2010-12-01'});
var params = {EmailAddress: "${Email}"};
ses.verifyEmailIdentity(params, function(err, data) {
if (err) {
console.log(err, err.stack);
responseData = {Error: "SES email verification failed"};
} // an error occurred
else {
console.log(data);
responseStatus = "SUCCESS";
} // successful response
response.send(event, context, responseStatus, responseData);
});
};
LambdaCustomExecution:
Type: AWS::CloudFormation::CustomResource
Version: "1.0"
Properties:
ServiceToken: !GetAtt LambdaVerifySESEmail.Arn
LambdaStateMachineExecutionRole:
Type: AWS::IAM::Role
Properties:
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: states.amazonaws.com
Action: "sts:AssumeRole"
Policies:
- PolicyName: XRayAccessPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "xray:PutTraceSegments"
- "xray:PutTelemetryRecords"
- "xray:GetSamplingRules"
- "xray:GetSamplingTargets"
Resource:
- "*"
- PolicyName: InvokeCallbackLambda
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "lambda:InvokeFunction"
Resource:
- !Sub "${LambdaHumanApprovalSendEmailFunction.Arn}"
- !Sub "${LambdaHumanApprovalSendEmailFunction.Arn}:*"
- PolicyName: CloudWatchLogsDelivery
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "logs:CreateLogDelivery"
- "logs:GetLogDelivery"
- "logs:UpdateLogDelivery"
- "logs:DeleteLogDelivery"
- "logs:ListLogDeliveries"
- "logs:PutResourcePolicy"
- "logs:DescribeResourcePolicies"
- "logs:DescribeLogGroups"
Resource:
- !Sub "arn:${AWS::Partition}:logs:*:*:*"
- PolicyName: InvokeSageMakerJobs
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "sagemaker:CreateProcessingJob"
- "sagemaker:DescribeProcessingJob"
- "sagemaker:StopProcessingJob"
Resource:
- !Sub "arn:aws:sagemaker:${AWS::Region}:${AWS::AccountId}:processing-job/*"
- Effect: Allow
Action:
- "sagemaker:CreateTrainingJob"
- "sagemaker:DescribeTrainingJob"
- "sagemaker:StopTrainingJob"
Resource:
- !Sub "arn:aws:sagemaker:${AWS::Region}:${AWS::AccountId}:training-job/*"
- Effect: Allow
Action:
- "sagemaker:CreateModel"
Resource:
- !Sub "arn:aws:sagemaker:${AWS::Region}:${AWS::AccountId}:model/*"
- Effect: Allow
Action:
- "events:PutTargets"
- "events:PutRule"
- "events:DescribeRule"
Resource:
- !Sub "arn:aws:events:${AWS::Region}:${AWS::AccountId}:rule/StepFunctionsGetEventsForSageMakerProcessingJobsRule"
- !Sub "arn:aws:events:${AWS::Region}:${AWS::AccountId}:rule/StepFunctionsGetEventsForSageMakerTrainingJobsRule"
- Effect: Allow
Action:
- "sagemaker:ListTags"
Resource:
- "*"
- Effect: Allow
Action:
- "iam:PassRole"
Resource:
- !Ref SageMakerExecutionRoleArn
Condition:
StringEquals:
iam:PassedToService: "sagemaker.amazonaws.com"
LambdaSendEmailExecutionRole:
Type: AWS::IAM::Role
Properties:
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: "sts:AssumeRole"
Policies:
- PolicyName: CloudWatchLogsPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
Resource: !Sub "arn:${AWS::Partition}:logs:*:*:*"
- PolicyName: S3BucketPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "s3:GetObject"
Resource:
- !Sub "arn:aws:s3:::${s3Bucket}/*"
- PolicyName: SESSendEmailPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "ses:SendEmail"
- "ses:SendRawEmail"
Resource:
- !Sub "arn:aws:ses:${AWS::Region}:${AWS::AccountId}:identity/${Email}"
- Effect: Allow
Action:
- "ses:VerifyEmailIdentity"
Resource:
- "*"
EventBridgeInvokeSfnRole:
Type: AWS::IAM::Role
Properties:
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: events.amazonaws.com
Action: "sts:AssumeRole"
Policies:
- PolicyName: EventBridgeInvokeSfnRole
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "states:StartExecution"
Resource:
- !Sub "${HumanApprovalLambdaStateMachine}"
EventRule:
Type: AWS::Events::Rule
Properties:
Description: "training triggered by s3 object put."
EventPattern:
source:
- "aws.s3"
detail-type:
- "AWS API Call via CloudTrail"
detail:
eventSource:
- "s3.amazonaws.com"
eventName:
- "PutObject"
requestParameters:
bucketName:
- !Ref s3Bucket
key:
- prefix: "r-fable-trip-forecasting/new-data"
State: "ENABLED"
Targets:
-
Arn:
Fn::GetAtt:
- "HumanApprovalLambdaStateMachine"
- "Arn"
Id: "HumanApprovalLambdaStateMachine"
InputTransformer:
InputPathsMap:
detail: "$.detail"
eventID: "$.id"
resources: "$.resources"
InputTemplate: '{"Comment": "Executed from EventBridge", "city": "Melbourne", "eventID":
<eventID>, "resources": <resources>, "detail":<detail>}'
RoleArn: !Sub "${EventBridgeInvokeSfnRole.Arn}"
S3CloudTrailBucket:
Type: AWS::S3::Bucket
Properties:
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
S3CloudTrailBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket:
Ref: S3CloudTrailBucket
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: "AWSCloudTrailAclCheck"
Effect: "Allow"
Principal:
Service: "cloudtrail.amazonaws.com"
Action: "s3:GetBucketAcl"
Resource:
!Sub "arn:aws:s3:::${S3CloudTrailBucket}"
- Sid: "AWSCloudTrailWrite"
Effect: "Allow"
Principal:
Service: "cloudtrail.amazonaws.com"
Action: "s3:PutObject"
Resource:
!Sub "arn:aws:s3:::${S3CloudTrailBucket}/AWSLogs/${AWS::AccountId}/*"
Condition:
StringEquals:
s3:x-amz-acl: "bucket-owner-full-control"
CloudTrailS3:
DependsOn: S3CloudTrailBucketPolicy
Type: AWS::CloudTrail::Trail
Properties:
EventSelectors:
- DataResources:
- Type: AWS::S3::Object
Values:
- !Sub "arn:aws:s3:::${s3Bucket}/"
IncludeManagementEvents: false
ReadWriteType: WriteOnly
IncludeGlobalServiceEvents: true
IsLogging: true
IsMultiRegionTrail: true
S3BucketName:
Ref: S3CloudTrailBucket
Tags:
- Key: CreatedFor
Value: reInvent2020 AIM404 Demo
# End state machine that publishes to Lambda and sends an email with the link for approval
Outputs:
ApiGatewayInvokeURL:
Value: !Sub "https://${ExecutionApi}.execute-api.${AWS::Region}.amazonaws.com/states"
StateMachineHumanApprovalArn:
Value: !Ref HumanApprovalLambdaStateMachine