Conditional Workflow State Machine (Part 1)

Conditional Workflow State Machine (Part 1)

Understanding how to build conditional workflows using AWS Step Functions

·

5 min read

The aim of this project is to create an AWS Step Function state machine. This state machine is designed to add two numbers and subsequently initiate distinct branches of workflows depending on whether the resultant sum is even or odd.

we will be using:

AWS Lambda

Step Function

Begin by creating two Lambda functions:

    1. Calculate if the result is even or odd.

      1. Another to convert the result to either binary or Roman numerals.

Step 1

Let's being to create the first python function in lambda.

Once created, paste the following code.

import json

def lambda_handler(event, context):
    # TODO implement 
    print(event)
    result = event['number1']+event['number2']
    if result%2 == 0:
        is_even = True
    else:
        is_even = False

    return {'is_even':is_even,'result':result}
  1. The code calculates the sum of two numbers (number1 and number2) extracted from the event dictionary.

  2. After calculating the sum, the code checks whether the result is even or odd.

    • If the remainder of the division (result % 2) is equal to 0, it means the result is even, so is_even is set to True.

    • Otherwise, is_even is set to False.

  3. Finally, the function returns a dictionary containing two keys:

  • is_even: A boolean value indicating whether the sum is even or not.

  • result: The result of the addition.

We can test the code by configuring a new test event.

10 + 5 = 15 and the number is odd, we get the output below.

We can configure the same test to try for an even result. Let's change the 5 to a 4 from the previous step and test again. You should get the output below.

The first lambda function is now ready to get triggered within the using step function.

Step 2

Second lambda function is to convert the number into binary or roman.

We begin by creating a new lambda function with a python runtime.

Here is the code breakdown which you can copy and paste.

Converting to Binary (dectobin function):

  • This function takes the result from the event.

  • It converts the result into its binary representation.

  • It returns the binary representation using pythons default function called binary (bin).

import json

def dectobin(event):
    return bin(event['result'])[2:]
  • Converting to Roman Numerals (printRoman function):

    • This function takes the result from the event.

    • It converts the result into Roman numeral format.

    • It returns the Roman numeral representation.

  •         def printRoman(event):
                roman=''
                num = [1, 4, 5, 9, 10, 40, 50, 90,
                    100, 400, 500, 900, 1000]
                sym = ["I", "IV", "V", "IX", "X", "XL",
                    "L", "XC", "C", "CD", "D", "CM", "M"]
                i = 12
                number = event['result']
                while number:
                    div = number // num[i]
                    number %= num[i]
    
                    while div:
                        roman=roman+sym[i]
                        print(sym[i], end = "")
                        div -= 1
                    i -= 1
                return roman
    

    Lambda Handler Function (lambda_handler):

    This function is the main entry point.

    • It checks if the is_binary flag is set in the event.

    • If is_binary is True, it calls the dectobin function to convert the number to binary.

    • If is_binary is False, it calls the printRoman function to convert the number to Roman numerals.

    • It returns a message indicating the converted number.

  •         def lambda_handler(event, context):
                print(event)
                if event['is_binary']:
                    number = dectobin(event)
                else:
                    number = printRoman(event) 
    
                return (f"number is:{number}")
    

    In summary, the code takes a number from an event, determines whether it should be converted to binary or Roman numerals based on a flag (is_binary), and then returns the converted number.

We can now test the code by configuring our test event.

Above you can see in the red boxes the binary number beneath the response.

We can attempt another test by changing the binary to false in test environment.

You can see the test output below. It converts the number into a roman numeral.

Now we can proceed to create our Step Function

Step 3

Browse to the step function service on your amazon console and create a new state machine using a blank template.

On the state browser, search for lambda invoke and drag your first state.

In the lambda invoke config, choose the lambda function we first created, the 'even_odd'.

In the payload option, use state input as a payload and leave the rest of the configuration as is.

In the next step we'll add our choice state.

On the state browser, search for choice and drag it under your lambda function in the Gui. This choice state is to test if the result returned by lambda function as true or false.

In the rule one, we will be calling the flag (is_even) that we have set from the code earlier in the lambda function into the choice state. We will be checking if (is_even) is equals to 2 or not.

In rule one, we will add a condition as below and save it.

If it is true, we will add a copy object state (s3 bucket). Let's search for copy on the state browser.

We will be using the below JSON code for the copyobject event we want to initiate.

{
  "Bucket": "statebucketinput",
  "CopySource.$": "States.Format('{}/{}','notificationsystemstore','2.png')",
  "Key": "output/2.png"
}
  1. "Bucket": "statebucketinput":

    • This part says the name of the place where the file is being moved to.
  2. "CopySource.$": "States.Format('{}/{}','notificationsystemstore','2.png')":

    • This part tells the system where to find the file that needs to be copied. It's giving directions to find the file you want to copy.

    • notificationsystemstore is the name of the storage where the original file is stored.

    • 2.png is the name file.

  3. "Key": "output/2.png":

    • This part says where the copied file should go after it's copied.

    • It's saying the copied file should go into a folder called "output".

    • The copied file will keep the same name, 2.png.

In simple terms, this JSON code is saying, "Take the file named '2.png' from the storage named 'notificationsystemstore' and put it into a new storage named 'statebucketinput' inside the folder called 'output'.

After copying object step, we want to add a failed state error message into our architecture. We will insert fail into our process from the state browser on the left. We don't need to add any config settings here just drag 'fail' into the config as shown below.

That's it for when the event flag is 'is_even = true' part of the config.