[AWS Lab] Asynchronous Lambda Invocation – EventBridge

In this lab, we will learn how to invoke a lambda function asynchronously from Amazon EventBridge.

  • Overview
  • Source: EventBridge
    • Build a custom event Bus and add a custom event Rule
  • Target: Lambda – Function
    • logs the received event
    • does not return any value
    • Python

1. Lambda – Create a Function

  • Function Name: “logMessage
  • Runtime: Python 3.9

2. Lambda – Function Code (Python)

  • Type the following code
  • Click “Deploy
import json
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    logger.info(json.dumps(event))

3. EventBridge – Create a custom event bus

  • Click the “Event buses” menu on the left pane
  • Click “Create event bus
    • Name: “serverless-bus

4. Event Bus – Create a Rule

  1. Click the “Rules” menu on the left pane
  2. Click “Create Rule
    • Name: “order-rule
    • Event bus: select “serverless-bus
    • Rule Type: “Rule with event pattern
  3. Define the Rule Pattern
    • Event source: “Other
    • Sample event – optional: Ignore this section
    • Creation Method: “Custom Patterns
    • Event pattern: enter the pattern below
  4. Select Target(s)
    • Type: “AWS Service
    • Select “Lambda Function” -> “logMessage
    • On the “Advanced settings” section, review the Retry policy
{
  "source": [
    "Order"
  ],
  "detail-type": [
    "New-Order"
  ]
}

5. EventBridge – Test

  • On the “serverless-bus” page, click “Send events
    • Event bus: “serverless-bus
    • Event source: “Order
    • Event type: “New-Order
    • Event detail:
{"detail": {"orderId": "100", "date":"2023-12-25"}}

Check the log using the step 6. You can see the invocation log.

  • Send another event
    • Event bus: “serverless-bus
    • Event source: “Order
    • Event type: “Cancel-Order
    • Event detail:
{"detail": {"orderId": "100", "date":"2023-12-25"}}

Check the log using the step 6, and you cannot find the invocation log since the event does not match the rule.


6. CouldWatch – Check the Lambda logs

  1. On the Lambda function page, click the “Monitor” tab
  2. Check some metrics on the page
  3. Click the “View logs in the CloudWatch” button
  4. On the CloudWatch page, click the “Log stream
  5. Check the logs

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s