Add conditional logic to your Step Functions workflow
In the previous topic, Integrate a service , you integrated a Lambda function. In this topic you will set up the if-else conditions in the Choice state
. A choice state determines the workflow execution path based on specific conditions.
You will add logic that chooses a path based on the applied credit amount returned by the RandomNumberforCredit
Lambda function. If the value is within a threshold limit, the credit application will be automatically approved and move to the next step. If the value exceeds the threshold limit, the workflow will require a human approval to continue the workflow.
You’ll mimic a 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 Amazon SDK
integration with Amazon Simple Notification Service. The workflow execution will be paused until it receives the task token back with a
SendTaskSuccess
API call. For information about integrating with others services using task tokens, see the
Wait for a Callback with Task Token in service integration patterns.
When you created the prototype state machine, you defined human approval and auto-approval steps. Now, you must 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 Amazon Web Services 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.
-
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. -
Specify the topic name as
TaskTokenTopic
. -
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-cn:sns:us-west-2:123456789012:TaskTokenTopic
-
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
.
-
In a new tab or window, open the Lambda console
and create a Node.js 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 Amazon Lambda Developer Guide. -
On the callback-human-approval page, replace the existing code in the Code source area with the following code.
// Lambda function that will automatically approve any task // in a message published to an Amazon SNS topic console.log('Loading function'); const AWS = require('aws-sdk'); const resultMessage = "Successful"; export const handler = async (event) => { 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; };
-
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 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 Amazon Lambda Developer Guide.
-
In the Function overview section of the
callback-human-approval
Lambda function, choose Add trigger. -
From the drop-down list of triggers, choose SNS as the trigger.
-
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.
-
Choose Add.
-
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.
-
On the callback-human-approval page, choose the Configuration tab, and then choose Permissions.
-
Under Execution role, choose the Role name to navigate to the Amazon Identity and Access Management console’s Roles page.
-
To add the required permission, choose Add permissions, and then choose Attach policies.
-
In the search box, type
AWSStepFunctions
and then press Enter. -
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 Configure input and output and Processing input and output.
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
-
Open the Step Functions console
window containing the workflow prototype you created in Create a state machine. -
Choose the Credit applied >= 5000? state and in the Configuration tab, specify the conditional logic as follows:
-
Under Choice Rules, choose the Edit icon in the Rule #1 tile to define the first choice rule.
-
Choose Add conditions.
-
In the Conditions for rule #1 dialog box, for Variable, enter
$
. -
For Operator, choose is less than.
-
For Value, choose Number constant, and then enter
5000
in the field next to the Value dropdown list. -
Choose Save conditions.
-
For the Then next state is: dropdown list, choose Auto-approve limit.
-
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.
-
For the Then next state is: dropdown list, choose Wait for human approval.
-
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.
-
-
Configure the Wait for human approval state as follows:
-
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.
-
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 Accessing execution data from the Context object in Step Functions .
-
In the box that appears, enter the following as message:
{ "TaskToken.$": "$$.Task.Token" }
-
Choose the Wait for callback checkbox.
-
Choose Done in the dialog box that appears.
-
-
Keep this window open and proceed to the next topic.
Next steps
In the next topic, Define parallel tasks you’ll learn how to perform multiple tasks in parallel.