Tutorial 3: Implement an if-else condition in your workflow - AWS Step Functions

Tutorial 3: Implement an if-else condition in your workflow

You can implement if-else conditions in your workflows by using the Choice state. It determines the workflow execution path based on whether a specified condition evaluates to true or false.

In this tutorial, you’ll add conditional logic to determine if the applied credit amount returned by the RandomNumberforCredit Lambda function used in Tutorial 2 exceeds a specific threshold limit. If the amount exceeds the threshold limit, the application requires a human interaction for approval. Otherwise, the application is auto-approved and moves to the next step.

You’ll mimic the human interaction step by pausing the workflow execution until a task token is returned. To do this, you’ll pass a task token to the AWS SDK integration you’ll be using in this tutorial, which is Amazon Simple Notification Service. The workflow execution will be paused until it receives the task token back with a SendTaskSuccess API call. For more information about using task tokens, see Wait for a Callback with the Task Token.

Because you’ve already defined the steps for human approval and auto-approval in your workflow prototype, in this tutorial, you first create an Amazon SNS topic that receives the callback token. Then, you create a Lambda function to implement the callback functionality. Finally, you update your workflow prototype by adding the details of these AWS service integrations.

Step 1: Create an Amazon SNS topic that receives the callback token

To implement the human interaction step, you’ll publish to an Amazon Simple Notification Service topic and pass the callback task token to this topic. The callback task will pause the workflow execution until the task token is returned with a payload.

  1. Open the Amazon SNS console and create a Standard topic type. For information about creating a topic, see Create an Amazon SNS topic in the Amazon Simple Notification Service Developer Guide.

  2. Specify the topic name as TaskTokenTopic.

  3. Make sure to copy the topic ARN and save it in a text file. You’ll need the topic ARN while specifying the service integration for the Wait for human approval state. The following is an example topic ARN:

    arn:aws:sns:us-east-2:123456789012:TaskTokenTopic
  4. Create an email-based subscription for the topic and then confirm your subscription. For information about subscribing to a topic, see Create a subscription to the topic in the Amazon Simple Notification Service Developer Guide.

Step 2: Create a Lambda function to handle the callback

To handle callback functionality, you'll define a Lambda function and add the Amazon SNS topic you created in Step 1 as a trigger for this function. When you publish to the Amazon SNS topic with a task token, the Lambda function is invoked with the payload of the published message.

Step 2.1: Create the Lambda function to handle callback

In this function, you'll process the credit limit approval request and return the request’s result as successful with the SendTaskSuccess API call. This Lambda function will also return the task token it received from the Amazon SNS topic.

For simplicity, the Lambda function used for the human interaction step automatically approves any task and returns the task token with a SendTaskSuccess API call. You can name the Lambda function as callback-human-approval.

  1. In a new tab or window, open the Lambda console and create a Node.js 16.x Lambda function titled callback-human-approval. For information about creating a Lambda function using the console, see Create a Lambda function in the console in the AWS Lambda Developer Guide.

  2. On the callback-human-approval page, replace the existing code in the Code source area with the following code.

    // Sample Lambda function that will automatically approve any task whenever a message is published to an Amazon SNS topic by Step Functions. console.log('Loading function'); const AWS = require('aws-sdk'); const resultMessage = "Successful"; exports.handler = async (event, context) => { const stepfunctions = new AWS.StepFunctions(); let message = JSON.parse(event.Records[0].Sns.Message); let taskToken = message.TaskToken; console.log('Message received from SNS:', message); console.log('Task token: ', taskToken); // Return task token to Step Functions let params = { output: JSON.stringify(resultMessage), taskToken: taskToken }; console.log('JSON Returned to Step Functions: ', params); let myResult = await stepfunctions.sendTaskSuccess(params).promise(); console.log('State machine - callback completed..'); return myResult; };
  3. Keep this window open and perform the steps in the next section for further actions.

Step 2.2: Add the Amazon SNS topic as a trigger for the Lambda function

When you add the Amazon SNS topic you created in Step 1 of this tutorial as a trigger for the Lambda function you created in Step 2.1 of this tutorial, the Lambda function is triggered each time you publish to the Amazon SNS topic. When you publish to the Amazon SNS topic with a task token, the Lambda function is invoked with the payload of the published message. For more information about configuring triggers for Lambda functions, see Configuring triggers in the AWS Lambda Developer Guide.

  1. In the Function overview section of the callback-human-approval Lambda function, choose Add trigger.

  2. From the drop-down list of triggers, choose SNS as the trigger.

  3. For SNS topic, start typing the name of the Amazon SNS topic you created in Step 1 of this tutorial, and choose it from the dropdown list that appears.

  4. Choose Add.

  5. Keep this window open and perform the steps in the next section for further actions.

Step 2.3: Provide necessary permissions to the Lambda function IAM role

You must provide the callback-human-approval Lambda function the permissions to access Step Functions for returning the task token along with the SendTaskSucess API call.

  1. On the callback-human-approval page, choose the Configuration tab, and then choose Permissions.

  2. Under Execution role, choose the Role name to navigate to the AWS Identity and Access Management console’s Roles page.

  3. To add the required permission, choose Add permissions, and then choose Attach policies.

  4. In the search box, type AWSStepFunctions and then press Enter.

  5. Choose AWSStepFunctionsFullAccess and then scroll down to choose Attach policies. This adds the policy containing the necessary permission for the callback-human-approval Lambda function role.

Step 3: Update the workflow – add if-else condition logic in the Choice state

In the Step Functions console, define conditional logic for your workflow using the Choice state. If the output returned by the RandomNumberforCredit Lambda function is less than 5000, the requested credit is auto-approved. If the output returned is greater than or equal to 5000, the workflow execution proceeds to the human interaction step for the credit limit approval.

In the Choice state, you use a comparison operator to compare an input variable with a specific value. You can specify the input variable as the execution input while starting a state machine execution or use the output of a preceding step as input for the current step. By default, the output of a step is stored in a variable called Payload. To use the Payload variable’s value for comparison in the Choice state, use the $ syntax as shown in the following procedure.

For information about how information flows from one state to another and specifying input and output in your workflows, see Tutorial 7: Configure input and output and Input and Output Processing in Step Functions.

Note

If the Choice state uses an input variable specified in the state machine execution input for comparison, use the $.variable_name syntax to perform the comparison. For example, to compare a variable, such as myAge, use the syntax $.myAge.

Because in this step, the Choice state will receive input from the Get credit limit state, you’ll use the $ syntax for the Choice state configuration. To explore how the result of the state machine execution differs when you use the $.variable_name syntax in the Choice state configuration to refer to the output from a preceding step, see the Debugging the invalid path Choice state error section in Tutorial 8.

To add if-else condition logic using the Choice state
  1. Open the Step Functions console window containing the workflow prototype you created in Tutorial 1: Create the prototype for your state machine.

  2. Choose the Credit applied >= 5000? state and in the Configuration tab, specify the conditional logic as follows:

    1. Under Choice Rules, choose the Edit icon in the Rule #1 tile to define the first choice rule.

    2. Choose Add conditions.

    3. In the Conditions for rule #1 dialog box, for Variable, enter $.

    4. For Operator, choose is less than.

    5. For Value, choose Number constant, and then enter 5000 in the field next to the Value dropdown list.

    6. Choose Save conditions.

    7. For the Then next state is: dropdown list, choose Auto-approve limit.

    8. Choose Add new choice rule, and then define the second choice rule when the credit amount is greater than or equal to 5000 by repeating substeps 2.b through 2.f. For Operator, choose is greater than or equal to.

    9. For the Then next state is: dropdown list, choose Wait for human approval.

    10. In the Default rule box, choose the Edit icon to define the default choice rule, and then choose Wait for human approval from the Default state dropdown list. You define the Default rule to specify the next state to transition to if none of the Choice state conditions evaluate to true or false.

  3. Configure the Wait for human approval state as follows:

    1. In the Configuration tab, for Topic, start typing the name of the Amazon SNS topic, TaskTokenTopic, and choose the name as it appears in the dropdown list.

    2. For Message, choose Enter message from the dropdown list. In the Message field, you specify the message you want to publish to the Amazon SNS topic. For this tutorial, you publish a task token as the message.

      A task token lets you pause a Standard type Step Functions workflow until an external process is complete and the task token is returned. When you specify a Task state as a callback task by specifying the .waitForTaskToken service integration pattern, a task token is generated and placed in the context object when the task is started. The context object is an internal JSON structure that is available during an execution, and contains information about your state machine and its execution. For more information about context objects, see Context object.

    3. In the box that appears, enter the following as message:

      { "TaskToken.$": "$$.Task.Token" }
    4. Choose the Wait for callback checkbox.

    5. Choose Done in the dialog box that appears.

  4. Keep this window open and proceed to the next tutorial for further actions.

Next steps

In the next tutorial, you’ll learn how to perform multiple tasks in parallel.