Send SNS Notification from AWS Lambda using Python
AWS tutorial shares sample Python codes for AWS Lambda developers to send SNS notifications on AWS cloud platform. If you are building Lambda functions on AWS platform for serverless architectures and want to send SNS notifications, you can use sample Python codes provided in this tutorial.
Let's start to build your AWS Lambda function.
Login to AWS Console with your user.
Among Services under Compute section, click Lambda to start building your serverless cloud solution development.
Press on Create function button
Type a name for your Lambda function.
Choose "Python 3.7" as the Runtime for the Lambda function.
You can continue with a new Lambda role for this new Lambda function.
Copy and paste following Python code into the Lambda function code inline editor.
Please replace the Target Arn value with the ARN value of the SNS topic which you want to send notifications from this AWS Lambda function.
To fetch the SNS topic ARN value, you can go to AWS Simple Notification Service SNS dashboard and list the Topics. You can either list all topics or filter for the name of the SNS topic you want to use for sending notifications to your subscribers. When the target topic is on the list, on ARN column you will see the Amazon Resource Name or ARN value to be copied into above Python codes in your Lambda function.
Click Save button then you are ready to test the Lambda function.
Press Test button. You can create a dummy test configuration. Because above sample sends static message to all subscribers and does not inherit a value from the triggering event as message context.
If you get following error message, then it is related with roles and permissions missing policy to access all S3 buckets list.
[ERROR] AuthorizationErrorException: An error occurred (AuthorizationError) when calling the Publish operation: User: arn:aws:sts::111111111111:assumed-role/sns-role-qgwup4z9/sns is not authorized to perform: SNS:Publish on resource: arn:aws:sns:eu-central-1:111111111111:KodyazSNS
On AWS Lambda function, switch to Configuration tab and Permissions section.
You will see the Execution Role name. Click on the role name which will redirect developers to the IAM console where the appropriate policy can be attached to allow Lambda execution role to publish notifications to the SNS topic.
Check execution role of the lambda function
The AWS Lambda execution role should be configured and granted the required permissions for sending notification messages via Amazon SNS service to execute the AWS Lambda function successfully