部署人工核准專案範例 - AWS Step Functions

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

部署人工核准專案範例

本教學課程會示範如何部署人工核准專案,即讓 AWS Step Functions 執行在任務期間暫停,並等候直到使用者回應電子郵件。當使用者核准該任務可繼續進行時,工作流程就會前往下一個狀態。

部署本教學課程中包含的 AWS CloudFormation 堆疊將會建立所有必要的資源,包括:

  • Amazon API Gateway 資源

  • 一個 AWS Lambda 函數

  • 一个 AWS Step Functions 状态机

  • Amazon 簡易通知服務電子郵件主題

  • 相關 AWS Identity and Access Management 角色和權限

注意

建立 AWS CloudFormation 堆疊時,您必須提供有效的電子郵件地址。

若要取得更多資訊,請參閱《使用指南》中的〈AWS CloudFormation 使用 CloudFormation 範本AWS::StepFunctions::StateMachine資源〉

步驟 1:建立 AWS CloudFormation 範本

  1. 複製AWS CloudFormation 模板源代碼一節中的範例程式碼。

  2. 將 AWS CloudFormation 範本的來源貼到本機電腦上的檔案中。

    在此範例中,檔案名為 human-approval.yaml

步驟 2:建立堆疊

  1. 登入 AWS CloudFormation 主控台

  2. 選擇 [建立堆疊],然後選擇 [使用新資源 (標準)]。

  3. Create stack (建立堆疊) 頁面上,執行下列動作:

    1. 在 [先決條件-準備範本] 區段中,確定已選取 [範本已準備就緒]。

    2. 在 [指定範本] 區段中,選擇 [上傳範本檔案],然後選擇 [選擇檔案] 以上傳您先前建立的包含範本原始程式碼human-approval.yaml檔案。

  4. 選擇下一步

  5. Specify stack details (指定堆疊詳細資訊) 頁面上,執行下列操作:

    1. 堆疊名稱中,輸入堆疊的名稱。

    2. 在「參數」下,輸入有效的電子郵件地址。您將使用此電子郵件地址訂閱 Amazon SNS 主題。

  6. 選擇 [下一步],然後再選擇 [下一步]。

  7. 在 [檢閱] 頁面上,選擇 [我確認 AWS CloudFormation 可能會建立 IAM 資源],然後選擇 [建立]。

    AWS CloudFormation 會開始建立您的堆疊,並顯示「建立中 _ 進度」狀態。當程序完成時, AWS CloudFormation 會顯示「建立 _ 完成」狀態。

  8. (選用) 若要顯示堆疊中的資源,請選取堆疊,然後選擇 Resources (資源) 標籤。

    顯示資源

步驟 3:批准 Amazon SNS 訂閱

建立 Amazon SNS 主題後,您會收到一封電子郵件,要求您確認訂閱。

  1. 開啟您在建立 AWS CloudFormation 堆疊時提供的電子郵件帳戶。

  2. 打開消息AWS 通知-來自 no-reply@sns.amazonaws.com 的訂閱確認

    電子郵件會列出 Amazon SNS 主題的亞馬遜資源名稱,以及一個確認連結。

  3. 選擇確認訂閱連結。

    訂閱確認!

步驟 4:運行狀態機

  1. HumanApprovalLambdaStateMachine頁面上,選擇 [開始執行]。

    此時會顯示「開始執行」對話方塊。

  2. 在 [開始執行] 對話方塊中,執行下列動作:

    1. (選擇性) 若要識別您的執行項目,您可以在「名稱」(Name) 方塊中指定執行項目的名稱。默認情況下,Step Functions 自動生成一個唯一的執行名稱。

      注意

      Step Functions 可讓您建立狀態機器、執行項目和活動的名稱,以及包含非 ASCII 字元的標籤。這些非 ASCII 名稱不適用於 Amazon CloudWatch。若要確保您可以追蹤 CloudWatch 量度,請選擇僅使用 ASCII 字元的名稱。

    2. 在 [入] 方塊中,輸入下列 JSON 輸入以執行您的工作流程。

      { "Comment": "Testing the human approval tutorial." }
    3. 選擇 Start execution (開始執行)

      ApprovalTest態機器執行會啟動,並在 Lambda 回呼工作暫停。

    4. Step Functions 主控台會將您導向至標題為執行 ID 的頁面。此頁面稱為「執行詳細資訊」頁面。在此頁面上,您可以在執行進行時或完成之後複查執行結果。

      若要複查執行結果,請在「圖形」檢視中選擇個別狀態,然後選擇步驟詳情窗格上的個別索引標籤,分別檢視每個狀態的詳細資訊,包括輸入、輸出和定義。如需有關可在「執行詳細資訊」頁面檢視之執行資訊的詳細資訊,請參閱執行詳細資訊頁面 — 介面概觀

      正在等候回呼的執行
  3. 在您之前用於 Amazon SNS 主題的電子郵件帳戶中,開啟主旨為「需要核准來源」的訊息 AWS Step Functions。

    這封訊息會包含分別用於 Approve (核准)Reject (拒絕) 的 URL。

  4. 選擇該 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 += 'Please 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