Example project of an AWS Lambda triggering the execution of a Step Function. The Step Function contains tasks that insert and update items in the DynammDB table Tasks
. The AWS resources are deployed using the AWS CDK. The main stack is defined in the file aws-stepfunction-status-stack.ts.
Install npm modules
npm install
Compile typescript to js
npm run build
Deploy this stack to your default AWS account/region
cdk deploy
The following code in aws-stepfunction-status-stack.ts defines the DynamoDB Tasks
table.
const dynamoTable = new Table(this, 'Tasks', {
partitionKey: {
name: 'taskId',
type: AttributeType.STRING
},
sortKey: {
name: 'timestamp',
type: AttributeType.NUMBER
},
tableName: 'Tasks',
});
The primary key for the Tasks
table is the taskId. The sort key is the unix time represented as a number. The above code will produce the following DynamoDB table.
The step function consists of a combination of the following.
When assembled together in aws-stepfunction-status-stack.ts, the step function looks like the following.
The lambda function is written in Go and is responsible for starting the execution of the step function (see main.go). The Lambda function handler will process events with the following json structure.
{
"taskId": <id>
}
When the function is invoked, the Lambda runs the handler method. The handler method prepares the following json to be passed as the inital state to the step function.
{
"taskId": <id>,
"timestamp": <unix time stamp>
}
In order to invoke the lambda function, navigate to the console and click the Test
tab.
Add the following json in the Test Event
panel and then click the Test
button.
{
"taskId": "Breakfast"
}
Next, expand the Execution result
details panel. You should see the output of the log messages in the lambda function.
The state machine will go through the following states.
- Create Dynamo Task Item
- In this task, the DynamoDB item is created in the
Tasks
table.
- Execute long running task...wait 30 seconds
- In this task, we simulate a long running task by waiting 30 seconds. The
Tasks
table is not updated at this time.
- Update Dynamo Task Item
- The task is now complete. The last step is to set the Status to
Done
for the Breakfast.
https://docs.aws.amazon.com/step-functions/latest/dg/concepts-states.html
https://docs.aws.amazon.com/step-functions/latest/dg/connect-ddb.html
https://docs.aws.amazon.com/lambda/latest/dg/lambda-golang.html
https://docs.aws.amazon.com/step-functions/latest/dg/concepts-invoke-sfn.html
https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sfn
https://github.com/aws/aws-sdk-go-v2/tree/main/service/sfn
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html
https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html
https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-intrinsic-functions.html