DVA_EN

Step Functions – Conditional branching using Choice State

Step Functions – Conditional branching using Choice State

This section is about refactoring, which is the scope of the AWS DBA.

The following page covers the basics of Step Functions.

In the above page, we built a simple state machine consisting of two states.
This time, we will use Choice states to build a state machine that branches processing according to conditions.

Environment

Diagram of Step Functions - Conditional branching using Choice State

We will define three states in the Step Functions state machine.

Each state is a task that invokes the following Lambda functions.

  • Lambda function 1: Calculate UNIX time from the current date/time information and determine whether it is even or odd.
  • Lambda function 2: Returns a string indicating that the number is even.
  • Lambda function 3: Returns a string indicating that the number is odd.

The runtime environment for the functions is Python 3.8.

After the first state is completed, the next state to execute is branched by the Choice state.
The condition for branching is based on the result of the even/odd decision.
If the value is even, the state of Lambda function 2 is selected, and if the value is odd, the state of Lambda function 3 is selected.

CloudFormation Template Files

The above configuration is built using CloudFormation.
The CloudFormation templates are located at the following URL

awstut-dva/04/003 at main · awstut-an-r/awstut-dva
Contribute to awstut-an-r/awstut-dva development by creating an account on GitHub.

Explanation of key points of the template files

Lambda Function

Function 1

Resources:
  Function1:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: |
          import datetime
          import time
        
          def lambda_handler(event, context):
            now = datetime.datetime.now()
            epoch_time = int(time.mktime(now.timetuple()))
            
            return {
              'now':  now.strftime('%Y%m%d%H%M%S%f'),
              'epoch_time': {
                'value': epoch_time,
                'is_even': (not bool(epoch_time % 2))
              }
            }
      FunctionName: !Sub "${Prefix}-function-01"
      Handler: !Ref Handler
      Runtime: !Ref Runtime
      Role: !GetAtt FunctionRole.Arn
Code language: YAML (yaml)

No special configuration is required to run in Step Functions.

We will focus on the code to be executed.

Obtains the current date/time and converts it to UNIX time.
It then divides this UNIX time number by 2 to get the remainder, from which it determines if the number is even or odd.

The return statement returns a dictionary type object.
For example, the following object is returned.

{
  "now": "20221117135316055513",
  "epoch_time": {
    "value": 1668693196,
    "is_even": True
  }
}
Code language: JSON / JSON with Comments (json)

Function 2

Lambda itself is similar to Function 1.
We focus on the code to be executed.

import datetime
import time

def lambda_handler(event, context):
  return '{epoch_time} is even !'.format(
    epoch_time=event['epoch_time']['value'])
Code language: YAML (yaml)

Returns a string stating that the number is even.

To create the string, reference an event object.
This event is assumed to have the same structure as the dictionary type object generated by function 1.

Function 3

import datetime
import time

def lambda_handler(event, context):
  return '{epoch_time} is even !'.format(
    epoch_time=event['epoch_time']['value'])
Code language: YAML (yaml)

We will focus on the code to be executed here as well.

The content is almost identical to function 2.
It refers to the event object and returns a string indicating that the number is odd.

Step Functions

Resources:
  StateMachine:
    Type: AWS::StepFunctions::StateMachine
    Properties:
      Definition:
        Comment: !Sub "${Prefix}-StateMachine"
        StartAt: FirstState
        States:
          FirstState:
            Type: Task
            Resource: !Ref FunctionArn1
            Next: ChoiceState
          ChoiceState:
            Type: Choice
            Choices:
              - Variable: $.epoch_time.is_even
                BooleanEquals: true
                Next: EvenState
              - Variable: $.epoch_time.is_even
                BooleanEquals: false
                Next: OddState
          EvenState:
            Type: Task
            Resource: !Ref FunctionArn2
            End: true
          OddState:
            Type: Task
            Resource: !Ref FunctionArn3
            End: true
      LoggingConfiguration:
        Destinations:
          - CloudWatchLogsLogGroup:
              LogGroupArn: !GetAtt LogGroup.Arn
        IncludeExecutionData: true
        Level: ALL
      RoleArn: !GetAtt StateMachineRole.Arn
      StateMachineName: !Ref Prefix
      StateMachineType: STANDARD
Code language: YAML (yaml)

Check the overall structure of the state machine.

Looking at the StartAt property, we see that processing starts at FirstState.
In FirstState, function 1 is invoked.

After that, it moves to ChoiceState, where a conditional branch decision is made by referring to the value returned from FirstState.
The reference can be specified with a notation such as “$.epoch_time.is_even”.
In this case, the built-in function BooleanEquals is used to determine the truth value.
If this value is true, we move to EventState; if false, we move to OddState.

In EventState and OddState, function 2 and function 3 are invoked, respectively.
After the completion of each state, the processing of the entire state machine is complete.

Architecting

Using CloudFormation, we will build this environment and check the actual behavior.

Create CloudFormation stacks and check resources in stacks

Create a CloudFormation stacks.
For information on how to create stacks and check each stack, please refer to the following page

After checking the resources in each stack, information on the main resources created this time is as follows

  • Step Functions state machine: dva-04-003
  • Lambda function 1: dva-04-003-function-01
  • Lambda function 2: dva-04-003-function-02
  • Lambda function 3: dva-04-003-function-03

Check the state machine creation status from the AWS Management Console.

Detail of Step Function 1.

You can see that the state machine has been created successfully.
It is configured to branch from ChoiceState, proceed to one of the two states, and then terminate.

Check Action

1st time

Now that everything is ready, we will execute the state machine.
To execute from the AWS Management Console, press “Start execution”.

Detail of Step Function 2.

After waiting for a while, the state machine execution is successfully completed.
This time, we moved from ChoiceState to EventState.

Check the contents of Events.

Detail of Step Function 3.

The current date and time (2022/11/17 13:53:16) is obtained in FirstState, and converted to UNIX time, the result is “1668693196”.
As a result of the determination, the value of “is_even” is true because it is an even number.

Based on the “is_even” value, a conditional branching decision is made in ChoiceState, indicating that EvenState is selected.
Finally, EvenState is executed and “1668693196 is even ! was output.

Second time

Run the state machine again.

Detail of Step Function 4.

The state machine has been successfully executed.
This time we have moved from ChoiceState to OddtState.

Check the contents of Events.

Detail of Step Function 5.

FirstState obtains the current date and time (2022/11/17 14:03:33) and converts it to UNIX time, which is “1668693813”.
As a result of the judgment, the value of “is_even” is false because it is an odd number.

Based on the value of “is_even,” a conditional branch decision is made in ChoiceState, indicating that OddState is selected.
Finally, OddState is executed and “1668693813 is odd ! was output.

Summary

Using the Choice state of Step Functions, we have built a state machine that branches processing according to a condition.

タイトルとURLをコピーしました