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
- Click the “Rules” menu on the left pane
- Click “Create Rule”
- Name: “order-rule“
- Event bus: select “serverless-bus“
- Rule Type: “Rule with event pattern“
- Define the Rule Pattern
- Event source: “Other“
- Sample event – optional: Ignore this section
- Creation Method: “Custom Patterns“
- Event pattern: enter the pattern below
- 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
- On the Lambda function page, click the “Monitor” tab
- Check some metrics on the page
- Click the “View logs in the CloudWatch” button
- On the CloudWatch page, click the “Log stream“
- Check the logs