Create a self initiating step function AWS CDK 2.0

AWS Step Function is a useful resource for handling many use cases like automating IT processes, ELT jobs and service integrations. State functions can be graphical represented as State machine. Step function component facilitate creation of state machine which can be designed in multiple step workflow. The workflow can include invoking a AWS lambda function, sending a message to SQS or starting a new execution under a state machine.

The unique use case we are trying to solve is to create a cyclic state machine definition which should run new executions of the same state machine every n “sec/min/hour”

We can easily create such a state machine through console by dragging/dropping the actions in workflow studio. But what if we want to do it through aws cdk the path is not that straighforward or you won’t easily find references to do so. So I wanted to create a step by step guide on how to achieve the same.

First, import the required the packages in your file by adding require statements. Note the require statements are different for CDK 1.0 vs CDK 2.0. The one I am using here is CDK 2.0

const sfn = require("aws-cdk-lib/aws-stepfunctions");
const tasks = require("aws-cdk-lib/aws-stepfunctions-tasks");
const lambda = require("aws-cdk-lib/aws-lambda");

Second, let’s add the first step of statemachine

const timeout = new sfn.Wait(this, "Cool-off timeout", {
   time: sfn.WaitTime.secondsPath("$.waitTimeInSeconds")

Next, let’s add the step to invoke already created lambda function. A little twist is we cannot pass a lambda ARN to lambdaInvoke call, so we need to wrap the function ARN into a lambda function wrapper.


const lambda = lambda.Fucntion.fromFunctionArn(this, <functionName>, <ARN>);

const lambdaInvoke = new tasks.LambdaInvoke(this, 'Invoke function', {
 lambdaFunction: lambda,
 payload: <input>
Now here is the catch for starting a new execution from the same state machine you need to pass the state machine as a parameter to the last step. But the question is how can we pass the state machine which we have not created yet. Answer is we can do the similar way we did with lambda function, cdk is not going to validate whether the resource exists or not in the process.
const stateMachine = sfn.StateMachine.fromStateMachineArn(this, <functionName>, <ARN>); 

const nextExecution = new tasks.StepFunctionsStartExecution(this, 'start next execution', { 
 stateMachine: stateMachine, 
 input: <input>
Since now we have defined all the steps for the state machine, let’s go ahead and create the state machine.
new sfn.StateMachine(this, 'stateMachine', {
 stateMachineName: "<name>",
 stateMachineType: sfn.stateMachineType.STANDARD,

Join Discussion

This site uses Akismet to reduce spam. Learn how your comment data is processed.