本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
本教學課程會示範如何部署人工核准專案,即讓 AWS Step Functions 執行在任務期間暫停,並等候直到使用者回應電子郵件。當使用者核准該任務可繼續進行時,工作流程就會前往下一個狀態。
部署本教學課程中包含的 AWS CloudFormation 堆疊將建立所有必要的資源,包括:
-
Amazon API Gateway 資源
-
AWS Lambda 函數
-
AWS Step Functions 狀態機器
-
Amazon Simple Notification Service 電子郵件主題
-
相關 AWS Identity and Access Management 角色和許可
注意
您需要提供您在建立 AWS CloudFormation 堆疊時可存取的有效電子郵件地址。
如需詳細資訊,請參閱AWS CloudFormation 《 使用者指南AWS::StepFunctions::StateMachine
》中的使用 CloudFormation 範本和資源。
步驟 1:建立 AWS CloudFormation 範本
-
複製AWS CloudFormation 範本來源程式碼一節中的範例程式碼。
-
將 AWS CloudFormation 範本的來源貼到本機電腦上的檔案中。
在此範例中,檔案名為
human-approval.yaml
。
步驟 2:建立堆疊
-
選擇建立堆疊,然後選擇使用新資源 (標準)。
-
在 Create stack (建立堆疊) 頁面上,執行下列動作:
-
在先決條件 - 準備範本區段中,確定已選取範本就緒。
-
在指定範本區段中,選擇上傳範本檔案,然後選擇選擇檔案以上傳您先前建立且包含範本原始碼
human-approval.yaml
的檔案。
-
-
選擇 Next (下一步)。
-
在 Specify stack details (指定堆疊詳細資訊) 頁面上,執行下列操作:
-
針對堆疊名稱,輸入堆疊的名稱。
-
在參數下,輸入有效的電子郵件地址。您將使用此電子郵件地址來訂閱 Amazon SNS 主題。
-
-
選擇下一步,然後再次選擇下一步。
-
在檢閱頁面上,選擇我確認 AWS CloudFormation 可能會建立 IAM 資源,然後選擇建立。
AWS CloudFormation 開始建立您的堆疊,並顯示 CREATE_IN_PROGRESS 狀態。程序完成時, AWS CloudFormation 會顯示 CREATE_COMPLETE 狀態。
-
(選用) 若要顯示堆疊中的資源,請選取堆疊,然後選擇 Resources (資源) 標籤。
步驟 3:核准 Amazon SNS 訂閱
建立 Amazon SNS 主題後,您會收到一封電子郵件,要求您確認訂閱。
-
開啟您在建立 AWS CloudFormation 堆疊時提供的電子郵件帳戶。
-
從 no-reply@sns.amazonaws.com 開啟訊息AWS 通知 - 訂閱確認
電子郵件會列出 Amazon SNS 主題的 Amazon Resource Name,以及確認連結。
-
選擇確認訂閱連結。
步驟 4:執行狀態機器
-
在 HumanApprovalLambdaStateMachine 頁面上,選擇開始執行。
隨即顯示開始執行對話方塊。
-
在啟動執行對話方塊中,執行下列動作:
-
(選用) 輸入自訂執行名稱以覆寫產生的預設值。
非 ASCII 名稱和記錄
Step Functions 接受包含非 ASCII 字元的狀態機器、執行、活動和標籤名稱。由於這類字元不適用於 Amazon CloudWatch,因此我們建議您僅使用 ASCII 字元,以便在 CloudWatch 中追蹤指標。
-
在輸入方塊中,輸入下列 JSON 輸入來執行您的工作流程。
{ "Comment": "Testing the human approval tutorial." }
-
選擇 Start execution (開始執行)。
ApprovalTest 狀態機器執行會啟動,並在 Lambda 回呼任務中暫停。
-
Step Functions 主控台會引導您前往標題為執行 ID 的頁面。此頁面稱為執行詳細資訊頁面。在此頁面上,您可以在執行進行時或完成後檢閱執行結果。
若要檢閱執行結果,請在圖形檢視中選擇個別狀態,然後選擇步驟詳細資訊窗格上的個別索引標籤,分別檢視每個狀態的詳細資訊,包括輸入、輸出和定義。如需您可以在執行詳細資訊頁面上檢視之執行資訊的詳細資訊,請參閱 執行詳細資訊概觀。
-
-
在您先前用於 Amazon SNS 主題的電子郵件帳戶中,開啟訊息並取得主體的必要核准 AWS Step Functions。
這封訊息會包含分別用於 Approve (核准) 與 Reject (拒絕) 的 URL。
-
選擇該 Approve (核准) URL。
工作流程會根據您的選擇繼續進行。
AWS CloudFormation 範本來源程式碼
使用此 AWS CloudFormation 範本部署人工核准程序工作流程的範例。
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.
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
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:
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
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 { SFN: StepFunctions } = require("@aws-sdk/client-sfn");
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 stepfunctions = new StepFunctions();
var message = "";
if (action === "approve") {
message = { "Status": "Approved! Task approved by ${Email}" };
} else if (action === "reject") {
message = { "Status": "Rejected! Task 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
})
.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
FunctionName: LambdaApprovalFunction
Handler: index.handler
Role: !GetAtt "LambdaApiGatewayIAMRole.Arn"
Runtime: nodejs18.x
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:
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:
Type: AWS::StepFunctions::StateMachine
Properties:
RoleArn: !GetAtt LambdaStateMachineExecutionRole.Arn
DefinitionString:
Fn::Sub: |
{
"StartAt": "Lambda Callback",
"TimeoutSeconds": 3600,
"States": {
"Lambda Callback": {
"Type": "Task",
"Resource": "arn:${AWS::Partition}:states:::lambda:invoke.waitForTaskToken",
"Parameters": {
"FunctionName": "${LambdaHumanApprovalSendEmailFunction.Arn}",
"Payload": {
"ExecutionContext.$": "$$",
"APIGatewayEndpoint": "https://${ExecutionApi}.execute-api.${AWS::Region}.amazonaws.com/states"
}
},
"Next": "ManualApprovalChoiceState"
},
"ManualApprovalChoiceState": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.Status",
"StringEquals": "Approved! Task approved by ${Email}",
"Next": "ApprovedPassState"
},
{
"Variable": "$.Status",
"StringEquals": "Rejected! Task rejected by ${Email}",
"Next": "RejectedPassState"
}
]
},
"ApprovedPassState": {
"Type": "Pass",
"End": true
},
"RejectedPassState": {
"Type": "Pass",
"End": true
}
}
}
SNSHumanApprovalEmailTopic:
Type: AWS::SNS::Topic
Properties:
Subscription:
-
Endpoint: !Sub ${Email}
Protocol: email
LambdaHumanApprovalSendEmailFunction:
Type: "AWS::Lambda::Function"
Properties:
Handler: "index.lambda_handler"
Role: !GetAtt LambdaSendEmailExecutionRole.Arn
Runtime: "nodejs18.x"
Timeout: "25"
Code:
ZipFile:
Fn::Sub: |
console.log('Loading function');
const { SNS } = require("@aws-sdk/client-sns");
exports.lambda_handler = (event, context, callback) => {
console.log('event= ' + JSON.stringify(event));
console.log('context= ' + JSON.stringify(context));
const executionContext = event.ExecutionContext;
console.log('executionContext= ' + executionContext);
const executionName = executionContext.Execution.Name;
console.log('executionName= ' + executionName);
const statemachineName = executionContext.StateMachine.Name;
console.log('statemachineName= ' + statemachineName);
const taskToken = executionContext.Task.Token;
console.log('taskToken= ' + taskToken);
const apigwEndpint = event.APIGatewayEndpoint;
console.log('apigwEndpint = ' + apigwEndpint)
const approveEndpoint = apigwEndpint + "/execution?action=approve&ex=" + executionName + "&sm=" + statemachineName + "&taskToken=" + encodeURIComponent(taskToken);
console.log('approveEndpoint= ' + approveEndpoint);
const rejectEndpoint = apigwEndpint + "/execution?action=reject&ex=" + executionName + "&sm=" + statemachineName + "&taskToken=" + encodeURIComponent(taskToken);
console.log('rejectEndpoint= ' + rejectEndpoint);
const emailSnsTopic = "${SNSHumanApprovalEmailTopic}";
console.log('emailSnsTopic= ' + emailSnsTopic);
var emailMessage = 'Welcome! \n\n';
emailMessage += 'This is an email requiring an approval for a step functions execution. \n\n'
emailMessage += 'Check the following information and click "Approve" link if you want to approve. \n\n'
emailMessage += 'Execution Name -> ' + executionName + '\n\n'
emailMessage += 'Approve ' + approveEndpoint + '\n\n'
emailMessage += 'Reject ' + rejectEndpoint + '\n\n'
emailMessage += 'Thanks for using Step functions!'
const sns = new SNS();
var params = {
Message: emailMessage,
Subject: "Required approval from AWS Step Functions",
TopicArn: emailSnsTopic
};
sns.publish(params)
.then(function(data) {
console.log("MessageID is " + data.MessageId);
callback(null);
}).catch(
function(err) {
console.error(err, err.stack);
callback(err);
});
}
LambdaStateMachineExecutionRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: states.amazonaws.com
Action: "sts:AssumeRole"
Policies:
- PolicyName: InvokeCallbackLambda
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "lambda:InvokeFunction"
Resource:
- !Sub "${LambdaHumanApprovalSendEmailFunction.Arn}"
LambdaSendEmailExecutionRole:
Type: "AWS::IAM::Role"
Properties:
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: SNSSendEmailPolicy
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "SNS:Publish"
Resource:
- !Sub "${SNSHumanApprovalEmailTopic}"
# 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