S3 Event CreateObject and DeleteObject triggers lambda with SNS topic as destination
I want to get notified (Email, SMS) when an object is created or deleted in my S3 bucket.
Architecture
Services used
- S3
- Lambda
- SNS
- IAM
Deployment
1. Set the Lambda function
2. Set the triggers for both Create and Delete S3 events
3. Create the SNS topic (Email/SMS)
4. Set SNS as the destination of the lumbda
import json
import urllib.parse
import boto3
s3 = boto3.client('s3')
sns = boto3.client('sns')
def lambda_handler(event, context):
aws_region = boto3.session.Session().region_name
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
s3_url = "https://"+bucket+".s3."+aws_region+".amazonaws.com/"+key
eventname = event['Records'][0]['eventName']
sns_message = str("Notification: " + eventname + "\n\n FILE NAME: " + key + "\n\n URL:\n"+ s3_url +" \n\n")
try:
print(eventname)
if eventname == "ObjectRemoved:Delete":
print("File is being Deleted")
sns_message += str("File Deleted")
else:
response = s3.get_object(Bucket=bucket, Key=key)
sns_message += str("-------------------------------- \n\n")
subject= "Notification S3 in [" + bucket + "]"
print(subject)
sns_response = sns.publish(
TargetArn='arn:aws:sns:us-east-1:5**********1:Alert-MIKA',
Message= str(sns_message),
Subject= str(subject)
)
except Exception as e:
print(e)
print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
raise e