Single Lambda function what works with multiple S3 buckets to send SNS message
Use case
Recently I came across scenario where I had one Lambda Application which wanted to send event from respective S3 bucket to respective SNS topics.
S3-A ----> Single Lambda-Application ----> SNS-AS3-B ----> Single Lambda-Application ----> SNS-BS3-C ----> Single Lambda-Application ----> SNS-C
How to achieve this?
Step 1: Create a IAM Role
Attach both policies to IAM role for example LambdaSNSPublish
CWLogsPolicy.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}SNSPublish.json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sns:Publish"
],
"Resource": "arn:aws:sns:*:*:*"
}
]
}
Step 2: Create Lambda Function
Use above the IAM role while creating a Lambda function with Runtime Python
import json
import boto3
client = boto3.client('sns')def lambda_handler(event, context):
# TODO implement
print((event))
for record in event['Records']:
if record['s3']['bucket']['name'] == '<BUCKET_NAME_1>':
response = client.publish(
TargetArn="<TOPIC_ARN_1>",
Message=json.dumps({'default': json.dumps(event)}),
MessageStructure='json')
print(response)
elif record['s3']['bucket']['name'] == '<BUCKET_NAME_2>':
response = client.publish(
TargetArn="<TOPIC_ARN_2>",
Message=json.dumps({'default': json.dumps(event)}),
MessageStructure='json')
print(response)
elif record['s3']['bucket']['name'] == '<BUCKET_NAME_3>':
response = client.publish(
TargetArn="<TOPIC_ARN_3>",
Message=json.dumps({'default': json.dumps(event)}),
MessageStructure='json')
print(response)return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
Step 3: Configure Amazon S3 Event Notifications
Using the Amazon S3 console, add a notification configuration requesting Amazon S3 to:
Publish events of the All object create events type to your Amazon Lambda created in Step 2.
This will all allow you to send messages to respective SNS topics. You can restrict the Lambda function, S3 events, SNS topics as per the ARNs.