Lambda Function Trigger
Welcome to CloudAffaire and this is Debjeet.
In the last blog post, we have modified our 1st Lambda function to show context and logging. We have also created version and alias of the function.
In this blog post, we are going to add a trigger to our existing lambda function. So far we had manually executed the lambda function using AWS CLI. But in this demo, the lambda function will be auto-triggered based on trigger events. In this demo, we will use S3 as a trigger. Our function will send an email notification whenever an object is uploaded to a specific bucket.
Prerequisite for this demo:
IAM role with proper access to CloudWatch, S3 and SNS.
We have already modified our existing IAM role my_lambda_role mapped with the lambda function to have full access in S3 and SNS.
We have also created a S3 bucket named cloudaffaire
And created an SNS topic to send an email notification
Lambda Function Trigger:
Step 1: Login to AWS console and navigate to ‘Lambda’.
Step 2: Click on the function name.
Step 3: Click on ‘S3’ from the left panel to add S3 trigger.
Step 4: Configure your trigger and click ‘Add’.
Note: We have selected all ‘object create event’, hence event will be triggered whenever a new object is uploaded in our S3 bucket.
Step 5: Modify the code to call S3 and SNS client and click ‘Save’.
AWSRegionName = 'ap-south-1'
S3 = boto3.client('s3', region_name = AWSRegionName)
sns = boto3.client('sns', region_name = AWSRegionName)
def lambda_handler(event, context):
BucketName = event['Records']['s3']['bucket']['name']
ObjectName = event['Records']['s3']['object']['key']
Message = ObjectName + ' has been uploaded in ' + BucketName + ' bucket!'
sns.publish(TopicArn = '<your_sns_topic_arn>', Message = Message)
except Exception as e:
except Exception as e:
Note: You can create a new version of the function before this modification. Modify the code indent before pasting.
Your Lambda Function should look like below
Note: Left-hand side depicts triggers and right-hand side depicts access. Our lambda function has S3 as trigger and access on S3, SNS, and CloudWatch.
Next, we will upload an object to the specified bucket which will trigger the lambda function and in turn send an email notification.
Step 6: Upload an object in S3 bucket.
Check the CloudWatch Logs
Check email which is subscribed to the SNS topic.
Hope you have enjoyed this article. In the next blog post, we will discuss environment variables in Lambda functions.
To get more details on Lambda, please refer below AWS documentation