0
votes

I am trying to use AWS SNS to trigger a Lambda function written in Python 2.7 to deliver a small JSON payload. The Topic and subscription work fine, the Lambda instance is invoked, but the code is not extracting the message, I am using the following code:

import sys,requests,json,pymysql,logging,boto3

def lambda_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    message = event['Records'][0]['Sns']['Message']
    parsed_message = json.loads(message)
    print("From SNS: " + parsed_message)
    return(parsed_message)

I have tried to call the Python function but I do not know where the arguments should come from when I invoke it. Am I missing another call or piece of code that I will need to include in the Lambda function?

1
This has been solved, I had a section of code that was not indented. - LVillani

1 Answers

0
votes

SNS will send an event to AWS Lambda with its payload which you can print and preview in Monitoring -> CloudWatch Insights this way:

import json

def lambda_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))

To Test Lambda invocation, which won't be directly from SNS you need to provide Event Payload, which you've got from my previous code snippet.

This code sample works for Lambda Python3 environment:

lambda_handler.py

from __future__ import print_function
import json
print('Loading function')

def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))
    message = event['Records'][0]['Sns']['Message']
    print("From SNS: " + message)
    return message

Maybe you could just change your runtime from Python 2.7 to Python 3.7?