DEV Community

عبدالله عياد | Abdullah Ayad for AWS Community Builders

Posted on • Edited on

Lambda Function (Part 4) Final Part

-------------- See part 3 from here ----------------

Logging Results to CloudWatch

Introduction
The last Lambda function you need to create is the simplest one. It updates your CompleteLevel metric on CloudWatch. The task runs at the end of each branch and conditional step.

This is the representation of the task:

"CWMetric": {
    "Type": "Task",
    "Resource": "arn:aws:lambda:us-west-2:ACCOUNT_ID:function:PutMetric",
    "End": true
}
Enter fullscreen mode Exit fullscreen mode

There is nothing special here, but the End field set to true indicates that after this function, the flow ends.

Instructions

  1. In the AWS Management Console search bar, enter Lambda, and click the Lambda result under Services:

  2. Click on Create function.

  3. Check Author from scratch and fill all fields as given below:

Function name: PutMetric
Runtime: Python 3.7

  1. Toggle the drop-down Change default execution role and fill all fields as given below:

Select the role or create your own

  1. Click Create function.

This function will be executed after both branches in your first parallel step. Because it comes after a parallel step, this function will receive an array loaded with the results of all the previous functions.

  1. Move into the Code source section of the Lambda function and double-click lambda_function.py, replacing the contents with the code below:
import boto3
import json
cw_client = boto3.client('cloudwatch')
metric_name = 'CompleteLevel'
def lambda_handler(event, context):
    source_event = {}
    if len(event) > 0:
        source_event = event[0]
    time_played = source_event.get('time_played', False)    
    cw_client.put_metric_data(
        Namespace='FLOW',
        MetricData=[{
            "MetricName": metric_name,
            "Value": time_played,
            "Unit": "Seconds"
        }]
    )

    return True
Enter fullscreen mode Exit fullscreen mode

Remember that the result of this function is going to be the result of your entire execution. Up until this point, each Lambda function returned the event parameter (which is used as input to the next step). This last step simply returns True. This will be the result of the entire execution.

  1. To deploy your function, click Deploy.

In the next step, you will finally see how to both create and test this flow.

Creating a State Machine

Introduction
You have created all the Lambda functions required and are now ready to create your state machine.

Instructions

  1. In the AWS Console search bar, search for step functions and click the Step Functions result under Services:

  2. Expand the left menu and click on State machines:

  3. Click on Create state machine.

  4. Check Write your workflow in code and Type: Standard:

Image description

Note: AWS provides several different kinds of blueprints to help you to get started. After the lab, it is recommended you tinker around with several different blueprints and see what happens. In this lab, you have covered only a few types of steps. You can also expand the Help me decide section to understand the differences between types.

  1. To implement your state machine, Copy the following JSON template into the Definition:
{
  "Comment": "An example of the Amazon States Language using a Parallel and a Choice state to execute two branches at the same time.",
  "StartAt": "StartTask",
  "States": {
    "StartTask": {
      "Type": "Parallel",
      "Next": "CWMetric",
      "Branches": [
        {
          "StartAt": "Gen Report",
          "States": {
            "Gen Report": {
              "Type": "Task",
              "Resource": "arn:aws:lambda:us-west-2:ACCOUNT_ID:function:GenerateReport",
              "End": true
            }
          }
        },
        {
          "StartAt": "UpdateDB",
          "States": {
            "UpdateDB": {
              "Type": "Choice",
              "Choices": [
                {
                  "Variable": "$.level",
                  "StringEquals": "latest",
                  "Next": "Last Level"
                }
              ],
              "Default": "Simple Level"
            },
            "Last Level": {
              "Type": "Task",
              "Resource": "arn:aws:lambda:us-west-2:ACCOUNT_ID:function:EndsLastLevel",
              "End": true
            },
            "Simple Level": {
              "Type": "Task",
              "Resource": "arn:aws:lambda:us-west-2:ACCOUNT_ID:function:EndsSimpleLevel",
              "End": true
            }
          }
        }
      ]
    },
    "CWMetric": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-west-2:ACCOUNT_ID:function:PutMetric",
      "End": true
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Replace each occurrence of “ACCOUNT_ID” in the JSON template with your account ID.

  2. Click the refresh button in the visual workflow area to view the result as a flow diagram:

Image description

  1. Now click on Next at the bottom of the page.

The last thing you need to do is choose a name and configure the IAM Role that the AWS Step Functions service will assume to execute your state machine.

  1. Proceed through the state machine wizard and enter CompleteLevelFlow as the Name:

  2. Under Permissions, select the role or create a new one:

This role is a service role that will be assumed by the AWS Step Functions service, the only permission that this service needs is the lambda:invokeFunction permission.

  1. Click Create state machine.

You have created your first state machine. Now it's time to run it and verify it's working correctly.

  1. As mentioned before, each execution needs an input that will be passed to the first task. Click the Start execution button and paste the JSON in the Input field.
{
    "user_id": "12345678901234567890",
    "level": "latest",
    "score": 10,
    "max_score": 100,
    "time_played": 9885983982,
    "total_score": 10000
}
Enter fullscreen mode Exit fullscreen mode

Note: it's ok to leave the execution id with the random one AWS generates for you.

In this JSON, all the parameters that your execution needs are reported. In fact, all the information about the user is included, which level has been finished, and its related scores.

  1. Click the Start Execution button at the lower-right of your console. Here is an example screenshot of the AWS console after successful execution of your state machine:

Image description

In the upper section, you can see the overall Execution Details. On the boxes below, you can see a flowchart that indicates which state the process is in and the Step details. You can expand the Input, Output, and Exception sections you can see detail about the status of the task and what were the input and outputs used during execution. Error information can also be displayed here, which is really useful if any debugging efforts are needed.

At the bottom of the page is a list of all transactions and events of this execution. Observe the list of all transactions and events. You can expand/collapse each transaction by clicking on the arrow adjacent to the ID number. Of course, every Lambda call is logged to CloudWatch as well.

Now you can play around with this service using either this state machine or creating another one on your own.

GitHub
LinkedIn
Facebook
Medium

Top comments (0)