Skip to content
Menu
myCloud myCloud

Personal short notes about Cloud

  • XMPie
  • AWS
    • AWS Topics
    • AWS Architecture
    • AWS CLI
    • AWS Health
    • AWS Policies
    • AWS Cost
  • CHEAT SHEETS
myCloud myCloud

Personal short notes about Cloud

S3 Event

By mikado on September 19, 2022September 30, 2022

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
Category: AWS Topics

Categories

  • AWS (4)
  • AWS Architecture (8)
  • AWS CLI (5)
  • AWS Cost (3)
  • AWS Health (4)
  • AWS Policies (2)
  • AWS Topics (24)
  • CHEAT SHEETS (16)
  • Container (21)
  • Datadog (4)
  • Jenkins (2)
  • Linux (9)
  • Microsoft (7)
  • Python (1)
  • SCRIPTS (9)
  • Terraform (5)
  • XMPie (6)
©2025 myCloud
Click to Copy