[AWS Lab] Asynchronous Lambda Invocation – SNS

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

  1. Click the “Topics” menu on the left pane
  2. Select the newly created topic “greetingTopic
  3. On the “Subscriptions” tab, click “Create subscription
    • Protocol: Lambda
    • Endpoint: copy the ARN of the Lambda function “logMessage
  4. 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

  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