Search code examples
aws-cdkaws-step-functions

Access context object when defining a Step Function workflow in the CDK?


I would like to pass in the Step Function Execution ID of the current workflow to my Lambda function when it is executed.

I see in the documentation that to "access the context object, first specify the parameter name by appending .$ to the end" however, I cannot do this as I am defining my workflow using the CDK, which does not have access to parameters. I have to use InputPath.


Despite not being able to follow the instructions I tried a few things anyway. I have tried:

new tasks.LambdaInvoke(this, "InvokeLambdaTask", {
  lambdaFunction: myLambda
  inputPath: "$$.Execution.id"
})

and got the following error: Invalid path '$.Execution.id' : No results for path: $['Execution']['id']

I also tried a single dollar sign:

new tasks.LambdaInvoke(this, "InvokeLambdaTask", {
  lambdaFunction: myLambda
  inputPath: "$.Execution.id"
})

and got Invalid path '$.Execution.id' : Missing property in path $['Execution']

Is there any way to achieve this? I've seen a few other questions asking the more or less same thing, however I cannot really make use of these answers using the CDK.


Solution

  • I would like to pass in the Step Function Execution ID of the current workflow to my Lambda function

    The LambdaInvoke task's payload is supplied to the Lambda function as input. Note the two equivalent ways of referencing the JSONPath.

    new tasks.LambdaInvoke(this, "InvokeLambdaTask", {
      lambdaFunction: myLambda,
      payload: sfn.TaskInput.fromObject({
        executionId: sfn.JsonPath.stringAt("$$.Execution.Id"),
        "alsoExecutionId.$": "$$.Execution.Id",
      }),
    });
    

    The Lambda receives the Execution Id in the event payload:

    {
        executionId: "arn:aws:states:us-east-1:123456789012:execution:StateMachine2E01...",
        alsoExecutionId: "arn:aws:states:us-east-1:123456789012:execution:StateMachine2E01..."
    }
    

    The CDK ... does not have access to parameters.

    It does. The CDK renders the payload arg into the State Machine definition's Parameters:

    "Type": "Task",
    "Resource": "arn:aws:lambda:us-east-1:123456789012:function:Lambda...",
    "Parameters": {
        "executionId.$": "$$.Execution.Id",
        "alsoExecutionId.$": "$$.Execution.Id"
    }