In this lab, we will learn how to invoke a lambda function asynchronously from Amazon SNS.
- Overview
- Source: SNS
- Create a topic
- Target: Lambda – Function
- logs the received event
- does not return any value
- subscribes the SNS topic
- 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))
- Copy the ARN of the function somewhere.
3. SNS – Create a topic
- Click the “Topics” menu on the left pane
- Click the “Create topic” button
- Select “Standard”
- Name: “greetingTopic“
4. SNS – Create a Subscription
- Click the “Topics” menu on the left pane
- Select the newly created topic “greetingTopic“
- On the “Subscriptions” tab, click “Create subscription”
- Protocol: Lambda
- Endpoint: copy the ARN of the Lambda function “logMessage“
- Under “Subscription filter policy“, select the “Message attributes“, and enter the following filter
{
"type": [
"greeting",
"Greeting"
]
}
5. SNS – Publish Message, Lambda/CloudWatch – Test and Check the log
- On the “greetingTopic” page, click “Publish message”
- Subject: New Greeting 1
- Message body: Hello!
- Add a new Attribute:
- Type: string
- Name: type
- Value: dummy
Check the log using the step 6, and you cannot find the invocation log since the message does not include the filter string.
- Publish another message
- Subject: New Greeting 2
- Message body: Hello!, World
- Add a new Attribute:
- Type: string
- Name: type
- Value: Greeting
Check the log and you can see the invocation log.
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