简体   繁体   中英

AWS CDK Typescript, how to trigger step function from lambda?

I'm trying to trigger a step-function from a lambda, so I have this configuration:


let DIST_FOLDER = path.join(__dirname, "dist");

export class ServerStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // State Machine code

    let executorLambda = new lambda.Function(this, "executorFunction", {
      runtime: lambda.Runtime.NODEJS_12_X,
      handler: "main.handler",
      code: new lambda.AssetCode(path.join(DIST_FOLDER, "executor-lambda")),
      timeout: Duration.seconds(60)
    });

    let executorTask = new Task(this, "executorTask", {
      task: new InvokeFunction(executorLambda)
    });

    let chain = Chain.start(executorTask);

    let stateMachine = new StateMachine(this, "executorStateMachine", {
      definition: chain
    });

    // Back-end and api
    let backend = new lambda.Function(this, "backend", {
      runtime: lambda.Runtime.NODEJS_12_X,
      handler: "main.handler",
      code: new lambda.AssetCode(path.join(DIST_FOLDER, "backend-lambda")),
      environment: {
        STEP_FUNCTION_ARN: stateMachine.stateMachineArn
      }
    });

    new apigateway.LambdaRestApi(this, "strest-api", { handler: backend });
  }
}

and my api-gateway connected lambda is:

import { StartExecution } from "@aws-cdk/aws-stepfunctions-tasks";

export async function handler(event: any, context: any) {
  let env = process.env;
  let STEP_FUNCTION_ARN = env.STEP_FUNCTION_ARN || "STEP_FUNCTION_ARN";
  let body = JSON.stringify({
    msg: "Hello world",
    stepFunctionArn: STEP_FUNCTION_ARN
  });

  let stateMachineExecution = new StartExecution({ // Here I get an error, I don't know how to pass the correct step function arn or resource
    stateMachineArn: STEP_FUNCTION_ARN
  })

  return {
    statusCode: 200,
    body
  };
}

Has anybody experience with this?

The problem appears to be in your Lambda function:

import { StartExecution } from "@aws-cdk/aws-stepfunctions-tasks";

The StartExecution you're importing from the CDK is really the infrastructure construct. In order to make calls agains AWS's APIs you need the AWS SDK:

import { StepFunctions } from 'aws-sdk'

const stepfunctions = new StepFunctions();

export async function handler(event: any, context: any) {
  ...

  stepfunctions.startExecution({
    stateMachineArn: STEP_FUNCTION_ARN,
    name: '...',
    input: JSON.stringify({msg: 'Hello World!'})
  })

  ...
}

See the respective docs for more information. And make sure to give your Lambda the necessary permissions to invoke the Step Functions in question.

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM