Sample Step-Functions to handle a support call
Tags: aws, stepfunction, lambda
Published: 2022-07-16 14:30:20

AWS Step Functions is a low-code, visual workflow service that developers use to build distributed applications, automate IT and business processes.
In this example I will use AWS Step Functions to handle a call center call regarding room Reservation/Cancel in a hotel call center.

First, have a look at this visual representation of the "State Machine" that illustrate how the call can go, giving the agent two steps to choose from, every step will trigger a lambda function written to handle the logic of either Reserve or Cancel a Reservation

![State Machine ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cg9dm37t5ah7gs17kzbs.png)

AWS Step Functions state machines are defined in JSON using the declarative Amazon States Language, you can use the editor to build the state machine, or use the visual editor to help you.

But before we create the step function we need to create the lambda functions that it will invoke in its workflow
I have two functions written in Python as follows

Reserve

```
import json
import urllib
import boto3
import datetime

print('Loading function...')

def lambda_handler(message, context):
    # input example
    # {' TransactionType': 'Reserve'}

    #1. Log input message
    print("Received message from step Function:")
    print(message)

    #2. Construct response object
    response = {}
    response['TransactionType'] = message['TransactionType']
    response['Timestamp'] = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%s")
    response['Message'] = 'Hello from lambda, I am inside the ProcessReserve function'

    return response
```
Cancel

```
import json
import urllib
import boto3
import datetime

print('Loading function...')

def lambda_handler(message, context):
    # input example
    # {'TransactionType': 'Cancel'}

    #1. Log input message
    print("Received message from step Function:")
    print(message)

    #2. Construct response object
    response = {}
    response['TransactionType'] = message['TransactionType']
    response['Timestamp'] = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%s")
    response['Message'] = 'Hello from lambda, I am inside the ProcessCancel function'

    return response

```

Now I will go the AWS lambda from the console, to create both functions 
I will choose "Author from scratch", and give it the name, then put in the code, and click "Deploy"

![Create Lambda functions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pt1wza6vhijx81qaxwxo.png)


![Put in the code and deploy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3pvk63sinck88eyz91pq.png)

Now, remember to copy the lambda functions ARNs as you will need them in the code for the "State Machine" that we will create.


Here is where you start with creating the Step Function!
Open AWS Step Function home page and click on the icon on the top left 

![Open Step function homepage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8p5epqicuu6vwlxqx4dx.png)

Click on State Machine from the left pane, them click on "Create State Machine"

![Create State Machine](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eri4yjzj6b2j2bxfo1p7.png)

You can either choose "Design your workflow visually", or "Write your workflow in code"
I will just use the following code:

```
{
  "Comment": "A simple AWS Step Functions state machine that automates a call center support session.",
  "StartAt": "ProcessTransaction",
  "States": {
    "ProcessTransaction": {
        "Type" : "Choice",
        "Choices": [ 
          {
            "Variable": "$.TransactionType",
            "StringEquals": "Reserve",
            "Next": "ProcessReserve"
          },
          {
            "Variable": "$.TransactionType",
            "StringEquals": "Cancel",
            "Next": "ProcessCancel"
          }
      ]
    },
    "ProcessReserve": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:205057638875:function:Reserve",
      "End": true
    },
     "ProcessCancel": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:205057638875:function:Cancel",
      "End": true
    }
  }
}
```
**Please notice that lambda functions ARNs in the code above need to be replaced with your own if you will try this in your account.**

In the "Type" section, I will just accept the default which is "Standard", and in the "Definition" section I will insert the code above. It will look like this

![State Machine code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w9kkkleay4zsd2odrg89.png)

Then, click next.

In the name section I will give the state machine a name, and for the "Permissions", I will create a new "IAM Role"
(The IAM role that defines which resources your state machine has permission to access during execution.)

![Create IAM Role](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nqhcn2ziyr11vjkm3bbk.png)

Then, click on "Create a State Machine"

You can investigate the "IAM Role" that is created for you, with "AWS Managed Policy"
Just click on the "IAM Role ARN", then in the permissions tap, click on the policy, and here is the policy JSON code from my account, you can see the it gives the step function the permission to invoke the lambda functions that it uses

![IAM Policy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/89p8krhazya9lttknv4r.png)

Now, the step function is ready to go, and we can use the state machine to test it.

Here is the state machine

![State Machine](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7g9icjx2pr4u6ikhvbjw.png)

I will click on it, then click on "Start Execution"

![Start Execution](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h35ddvqajsu4tch70x1p.png)

I will pass the following code to function which should direct it to Reserve a room for the client

```
{
"TransactionType": "Reserve"
}
```
It will look like this

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6p8fny70oo152rceolac.png)

Here we can see the execution is succeeded 

![Execution Succeeded](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgkfeuop2lnjfd9rw7ry.png)

And further more you can investigate the "Execution Event History" here:

![Execution Event History](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtif8774i2xzqugjrqyd.png)

That concludes the sample demo

You can read more about AWS Step Functions Use Cases here https://aws.amazon.com/step-functions/use-cases/

Thank your for reading