Skip to content

How To Call a Stem Function from a Lambda

0

I have an existing SF and a Lambda, but I now need to call the SF from the Lambda, and the configuration is failing. Is there any documentation on how to do this? I know how to integrate lambdas in SF, but not the other way around.

2 Answers
1

Hello.

To call StepFunctions from Lambda, you need to run the "start_execution" API in the SDK as shown in the code below.

import boto3
import os

sf = boto3.client("stepfunctions")
sfarn = os.environ['SFARN']

def lambda_handler(event, context):
    sf.start_execution(
        stateMachineArn=sfarn
    )

I have created the following CloudFormation example for you to try.
When you test run Lambda, the StepFunctions will be executed.

AWSTemplateFormatVersion: "2010-09-09"
Description: test

Resources:
  IAMManagedPolicyPolicyserviceroleXRayAccessPolicy:
    Type: "AWS::IAM::ManagedPolicy"
    Properties:
      ManagedPolicyName: !Sub XRayAccessPolicy-${AWS::AccountId}
      Path: "/service-role/"
      Description: "Allow AWS Step Functions to call X-Ray daemon on your behalf"
      Groups: []
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Resource:
          - "*"
          Action:
          - "xray:PutTraceSegments"
          - "xray:PutTelemetryRecords"
          - "xray:GetSamplingRules"
          - "xray:GetSamplingTargets"
          Effect: "Allow"

  IAMRole:
    Type: "AWS::IAM::Role"
    Properties:
      Path: "/service-role/"
      ManagedPolicyArns:
      - Ref: "IAMManagedPolicyPolicyserviceroleAWSLambdaBasicExecutionRole"
      MaxSessionDuration: 3600
      RoleName: !Sub sfexec-role-${AWS::AccountId}
      Policies:
      - PolicyDocument:
          Version: "2012-10-17"
          Statement:
          - Resource: "*"
            Action: "states:StartExecution"
            Effect: "Allow"
            Sid: "test"
        PolicyName: "test"
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Action: "sts:AssumeRole"
          Effect: "Allow"
          Principal:
            Service: "lambda.amazonaws.com"

  LambdaFunctionSfexec:
    Type: "AWS::Lambda::Function"
    Properties:
      MemorySize: 128
      Description: ""
      Timeout: 3
      Code:
        ZipFile: |
          import boto3
          import os

          sf = boto3.client("stepfunctions")
          sfarn = os.environ['SFARN']

          def lambda_handler(event, context):
              sf.start_execution(
                  stateMachineArn=sfarn
              )
      Role:
        Fn::GetAtt:
        - "IAMRole"
        - "Arn"
      FunctionName: !Sub sfexec-${AWS::AccountId}
      Runtime: "python3.14"
      RecursiveLoop: "Terminate"
      Environment:
        Variables:
          SFARN: !Sub arn:aws:states:ap-northeast-1:${AWS::AccountId}:stateMachine:test-${AWS::AccountId}
      EphemeralStorage:
        Size: 512
      Architectures:
      - "x86_64"
      Handler: index.lambda_handler

  IAMManagedPolicyPolicyserviceroleAWSLambdaBasicExecutionRole:
    Type: "AWS::IAM::ManagedPolicy"
    Properties:
      ManagedPolicyName: !Sub AWSLambdaBasicExecutionRole-${AWS::AccountId}
      Path: "/service-role/"
      Description: ""
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Resource:
          - "*"
          Action:
          - "logs:CreateLogStream"
          - "logs:PutLogEvents"
          - "logs:CreateLogGroup"
          Effect: "Allow"

  IAMRoleStepFunctionstestrole:
    Type: "AWS::IAM::Role"
    Properties:
      Path: "/service-role/"
      ManagedPolicyArns:
      - Ref: "IAMManagedPolicyPolicyserviceroleXRayAccessPolicy"
      MaxSessionDuration: 3600
      RoleName: !Sub StepFunctions-test-role-${AWS::AccountId}
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
        - Action: "sts:AssumeRole"
          Effect: "Allow"
          Principal:
            Service: "states.amazonaws.com"

  StepFunctionsStateMachineStateMachinetest:
    Type: "AWS::StepFunctions::StateMachine"
    Properties:
      DefinitionString: "{\"Comment\":\"A description of my state machine\",\"StartAt\"\
        :\"Pass\",\"States\":{\"Pass\":{\"Type\":\"Pass\",\"End\":true,\"Output\"\
        :{\"CurrentTime\":\"{% $now() %}\",\"CurrentTimestamp\":\"{% $toMillis($now())\
        \ %}\",\"YesterdayDateTime\":\"{% $fromMillis($toMillis($now()) - 86400000)\
        \ %}\",\"YesterdayTimestamp\":\"{% $toMillis($now()) - 86400000 %}\"}}},\"\
        QueryLanguage\":\"JSONata\"}"
      EncryptionConfiguration:
        Type: "AWS_OWNED_KEY"
      LoggingConfiguration:
        IncludeExecutionData: false
        Level: "OFF"
      StateMachineName: !Sub test-${AWS::AccountId}
      RoleArn:
        Fn::GetAtt:
        - "IAMRoleStepFunctionstestrole"
        - "Arn"
      Tags: []
      StateMachineType: "STANDARD"
      TracingConfiguration:
        Enabled: false
EXPERT

answered a year ago

0

To call a Step Function from a Lambda function, you'll need to use the AWS SDK to invoke the Step Function execution. Here's how you can do it:

  1. First, make sure your Lambda function has the necessary IAM permissions to start Step Function executions. You'll need to add the states:StartExecution permission to your Lambda's execution role.

  2. In your Lambda function code, use the AWS SDK to start the Step Function execution. Here's an example using Node.js:

const AWS = require('aws-sdk');
const stepfunctions = new AWS.StepFunctions();

exports.handler = async (event) => {
const params = {
stateMachineArn: 'arn:aws:states:region:account-id:stateMachine:your-state-machine-name',
name: 'ExecutionName-' + Date.now(), // Optional: provide a unique execution name
input: JSON.stringify(event) // Pass your Lambda event or any data to the Step Function
};

try {
const result = await stepfunctions.startExecution(params).promise();
console.log('Started execution:', result.executionArn);
return {
statusCode: 200,
body: JSON.stringify({ executionArn: result.executionArn })
};
} catch (error) {
console.error('Error starting Step Function execution:', error);
throw error;
}
};

For other languages, the approach is similar - you'll use the appropriate AWS SDK to call the StartExecution API of the Step Functions service.

Remember to:

  • Replace the stateMachineArn with your actual Step Function ARN
  • Configure appropriate IAM permissions for your Lambda function
  • Handle errors and responses according to your application's needs

This approach allows your Lambda function to trigger a Step Function execution and optionally pass data to it.
Sources
Step function integration with internal API using http task | AWS re:Post
Community | Point-to-Point Messaging with Amazon SQS

answered a year ago

  • Thanks for your reply. I'm looking for the configuration part of it, using CF.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.