node.js - 如何使用 serverless-step-functions 插件中的定义调​​用 AWS Step Function?

标签 node.js amazon-web-services aws-lambda serverless-framework aws-step-functions

我正在使用 Serverless Framework 创建我的 Lambda 函数,并使用 serverless-step-functions 插件来定义我的步骤函数。

是否可以使用在 serverless.yml 文件中定义的名称直接从其中一个 lambda 函数调用步骤函数?

最佳答案

我试图解决同样的问题,这个问题和 self 回答非常有帮助。但是,我想添加另一个答案,其中包含更多详细信息和一个工作示例,以帮助 future 的读者。


您可能需要两件事:

1- 启动状态机
2- 从状态机调用一个特定函数(通常用于测试目的)

下面的演示使用了这两种情况。

首先,我们需要配置 serverless.yml 文件来声明状态机、Lambda 函数和正确的 IAM 权限。

service: test-state-machine

provider:
  name: aws
  runtime: nodejs4.3
  region: us-east-1
  stage: dev
  environment:
    AWS_ACCOUNT: 1234567890 # use your own AWS ACCOUNT number here

    # define the ARN of the State Machine
    STEP_FUNCTION_ARN: "arn:aws:states:${self:provider.region}:${self:provider.environment.AWS_ACCOUNT}:stateMachine:${self:service}-${self:provider.stage}-lambdaStateMachine"

    # define the ARN of function step that we want to invoke
    FUNCTION_ARN: "arn:aws:lambda:${self:provider.region}:${self:provider.environment.AWS_ACCOUNT}:function:${self:service}-${self:provider.stage}-stateMachineFirstStep"  

functions:
  # define the Lambda function that will start the State Machine
  lambdaStartStateMachine: 
    handler: handler.lambdaStartStateMachine  
    role: stateMachine # we'll define later in this file

  # define the Lambda function that will execute an arbitrary step
  lambdaInvokeSpecificFuncFromStateMachine: 
    handler: handler.lambdaInvokeSpecificFuncFromStateMachine
    role: specificFunction # we'll define later in this file

  stateMachineFirstStep:
    handler: handler.stateMachineFirstStep

# define the State Machine
stepFunctions:
  stateMachines:
    lambdaStateMachine:
      Comment: "A Hello World example"
      StartAt: firstStep
      States: 
        firstStep: 
          Type: Task
          Resource: stateMachineFirstStep
          End: true    

# define the IAM permissions of our Lambda functions
resources:
  Resources:
    stateMachine:
      Type: AWS::IAM::Role
      Properties:
        RoleName: stateMachine
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Principal:
                Service:
                  - lambda.amazonaws.com
              Action: sts:AssumeRole
        Policies:
          - PolicyName: stateMachine
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: "Allow"
                  Action:
                    - "states:StartExecution"
                  Resource: "${self:provider.environment.STEP_FUNCTION_ARN}"
    specificFunction:
      Type: AWS::IAM::Role
      Properties:
        RoleName: specificFunction
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Principal:
                Service:
                  - lambda.amazonaws.com
              Action: sts:AssumeRole
        Policies:
          - PolicyName: specificFunction
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: "Allow"
                  Action:
                    - "lambda:InvokeFunction"
                  Resource: "${self:provider.environment.FUNCTION_ARN}"

package:
  exclude:
    - node_modules/**
    - .serverless/**

plugins:
  - serverless-step-functions

handler.js 文件中定义 Lambda 函数。

const AWS = require('aws-sdk');

module.exports.lambdaStartStateMachine = (event, context, callback) => {
  const stepfunctions = new AWS.StepFunctions();
  const params = {
    stateMachineArn: process.env.STEP_FUNCTION_ARN,
    input: JSON.stringify({ "msg": "some input" })
  };

  // start a state machine
  stepfunctions.startExecution(params, (err, data) => {
    if (err) {
      callback(err, null);
      return;
    }

    const response = {
      statusCode: 200,
      body: JSON.stringify({
        message: 'started state machine',
        result: data
      })
    };

    callback(null, response);
  });
};

module.exports.lambdaInvokeSpecificFuncFromStateMachine = (event, context, callback) => {  
  const lambda = new AWS.Lambda();
  const params = {
    FunctionName: process.env.FUNCTION_ARN,
    Payload: JSON.stringify({ message: 'invoked specific function' })
  };

  // invoke a specific function of a state machine
  lambda.invoke(params, (err, data) => {
    if (err) {
      callback(err, null);
      return;
    }

    const response = {
      statusCode: 200,
      body: JSON.stringify({
        message: 'invoke specific function of a state machine',
        result: data
      })
    };

    callback(null, response);
  });
};

module.exports.stateMachineFirstStep = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'state machine first step',
      input: event
    }),
  };

  callback(null, response);
};

部署执行:

serverless deploy stepf  
serverless deploy  

测试使用:

serverless invoke -f lambdaStartStateMachine  
serverless invoke -f lambdaInvokeSpecificFuncFromStateMachine

关于node.js - 如何使用 serverless-step-functions 插件中的定义调​​用 AWS Step Function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42034563/

相关文章:

node.js - Socket.io和node.js,无法理解内存使用情况

node.js - 如何在express Js中获取客户的国家?

JavaScript 面向对象。尝试在 JavaScript 中学习 OOP

java - 某些服务器生成的事件不会通过 Websockets 传递到生产环境中的客户端

php - 使用 PHP 上传到 Amazon S3

amazon-web-services - 将 secret 管理器密码导入到内部函数 Fn::Sub:

amazon-dynamodb - 发电机数据库 : Scan query does not return all the data

node.js - 防止快速中间件针对同一父路径执行

amazon-web-services - 无法在AWS中验证电话号码

python - AWS Lambda 中缺少处理程序错误