I tried creating Step Functions through AWS CDK in python

Hi, it is Charu from Classmethod. Today, we will be talking about creating step functions through CDK. The language we will be using is Python.

AWS Step Functions is a powerful service that allows you to build serverless workflows to use multiple AWS services together. While AWS CDK offers a powerful solution for deploying infrastructure as code (IaC) using familiar programming languages.

Let's get started:

Step 1:

Open your terminal, make a new folder and set-up the CDK project using the following lines-

mkdir sf-cdk
cd sf-cdk
cdk init --language python

Step 2:

Now, we need to install the required dependencies for our application. Since, we are using python as our programming language, we need to install 'boto3'. Boto3 provides python API for AWS infrastructure services.

The Fun Fact: Why is it named boto3?

I got to know that boto3 was named after the fresh water dolphin native to the Amazon river.

To install boto3, open 'requirements.txt' file in your project directory and add the following lines-

aws-cdk-lib==2.87.0
constructs>=10.0.0,<11.0.0
boto3

Save the file and install the dependencies using pip.

pip install -r requirements.txt

The -r flag in the pip install -r requirements.txt command stands for "requirements file." It is used to specify a file that contains a list of Python package dependencies that need to be installed.

Step 3:

Now, let's create our step function state machine. Open the 'sf_cdk/sf_cdk_stack.py' file and replace it's content with the following code-

from aws_cdk import core as cdk
from aws_cdk import aws_stepfunctions, aws_stepfunctions_tasks, aws_lambda

from constructs import Construct

class SfCdkStack(cdk.Stack):

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        hello_lambda = aws_lambda.Function(self, "HelloLambda",
            runtime = aws_lambda.Runtime.PYTHON_3_9,
            handler = "index.handler",
            code = aws_lambda.Code.from_inline(
                """
                def handler(event, context):
                    return{
                        'message':'Hello, Step Functions!'
                    }
                """
            ))

        hello_task = aws_stepfunctions_tasks.LambdaInvoke(self, "HelloTask",
            lambda_function = hello_lambda)
  
        state_machine_definition = hello_task

        state_machine = aws_stepfunctions.StateMachine(
            self, "StateMachine",
            definition = state_machine_definition,
            timeout = cdk.Duration.minutes(5)
        )

        cdk.CfnOutput(self, "StateMacineARN", value = state_machine.state_machine_arn)

The above code defines a simple Step Functions state machine with a single Lambda task. The Lambda function will return a simple greeting message.

Step 4:

After defining the state machine, let's deploy the CDK stack by running the following lines in the terminal-

cdk bootstrap
cdk synth
cdk deploy

Remember that 'cdk bootstrap' only needs to be run once per AWS account per region. It is an AWS CDK command that you run to prepare your AWS environment to be able to deploy your CDK apps into.

Step 5:

Now let's test the Step Function State Machine. Go to AWS console and to your state machine and click on 'New Execution' button. In the input section, enter {} as the JSON input.

You should see the state machine progress through the "HelloTask" state and complete successfully, returning the greeting message.

Conclusion:

In this hands-on blog, we built an AWS Step Function state machine using the AWS CDK in Python. Now, you can explore the Step Functions documentation to explore your knowledge further.

Thanks for reading!

Happy Learning:)