Skip to main content

Lambda Function with Amazon S3

 Amazon S3 service is used for file storage, where you can upload or remove files. We can trigger AWS Lambda on S3 when there are any file uploads in S3 buckets. AWS Lambda has a handler function which acts as a start point for AWS Lambda function. The handler has the details of the events. In this chapter, let us see how to use AWS S3 to trigger AWS Lambda function when we upload files in S3 bucket.

Steps for Using AWS Lambda Function with Amazon S3

To start using AWS Lambda with Amazon S3, we need the following −

  • Create S3 Bucket
  • Create role which has permission to work with s3 and lambda
  • Create lambda function and add s3 as the trigger.

Example

Let us see these steps with the help of an example which shows the basic interaction between Amazon S3 and AWS Lambda.

  • User will upload a file in Amazon S3 bucket
  • Once the file is uploaded, it will trigger AWS Lambda function in the background which will display an output in the form of a console message that the file is uploaded.
  • The user will be able to see the message in Cloudwatch logs once the file is uploaded.

The block diagram that explains the flow of the example is shown here −

Upload Function
Creating S3 Bucket

Let us start first by creating a s3 bucket in AWS console using the steps given below −

Step 1

Go to Amazon services and click S3 in storage section as highlighted in the image given below −

S3 Storage
Step 2

Click S3 storage and Create bucket which will store the files uploaded.

File Uploaded
Step 3

Once you click Create bucket button, you can see a screen as follows −

Click Create
Step 4

Enter the details Bucket name, Select the Region and click Create button at the bottom left side. Thus, we have created bucket with name : workingwithlambdaands3.

Select Region
Step 5

Now, click the bucket name and it will ask you to upload files as shown below −

Upload Bucket

Thus, we are done with bucket creation in S3.

Create Role that Works with S3 and Lambda

To create role that works with S3 and Lambda, please follow the Steps given below −

Step 1

Go to AWS services and select IAM as shown below −

Work With S3
Step 2

Now, click IAM -> Roles as shown below −

Iam Roles
Step 3

Now, click Create role and choose the services that will use this role. Select Lambda and click Permission button.

Permission Botton
Step 4

Add the permission from below and click Review.

Click Review
Step 5

Observe that we have chosen the following permissions −

Following Permission

Observe that the Policies that we have selected are AmazonS3FullAccess, AWSLambdaFullAccess and CloudWatchFullAccess.

Step 6

Now, enter the Role name, Role description and click Create Role button at the bottom.

Create The Role

Thus, our role named lambdawiths3service is created.

Create Lambda function and Add S3 Trigger

In this section, let us see how to create a Lambda function and add a S3 trigger to it. For this purpose, you will have to follow th Steps given below −

Step 1

Go to AWS Services and select Lambda as shown below −

Select Lambda
Step 2

Click Lambda and follow the process for adding Name. Choose the Runtime, Role etc. and create the function. The Lambda function that we have created is shown in the screenshot below −

Choose Runtime
Step 3

Now let us add the S3 trigger.







Step 4

Choose the trigger from above and add the details as shown below −

Choose Trigger
Step 5

Select the bucket created from bucket dropdown. The event type has following details −

Bucket Downdrop

Select Object Created (All), as we need AWS Lambda trigger when file is uploaded, removed etc.

Step 6

You can add Prefix and File pattern which are used to filter the files added. For Example, to trigger lambda only for .jpg images. Let us keep it blank for now as we need to trigger Lambda for all files uploaded. Click Add button to add the trigger.

File Pattern
Step 7

You can find the the trigger display for the Lambda function as shown below −

Trigger Display

Let’s add the details for the aws lambda function. Here, we will use the online editor to add our code and use nodejs as the runtime environment.

Step 8

To trigger S3 with AWS Lambda, we will have to use S3 event in the code as shown below −

exports.handler = function(event, context, callback) {
console
.log("Incoming Event: ", event);
const bucket = event.Records[0].s3.bucket.name;
const filename = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
const message = `File is uploaded in - ${bucket} -> ${filename}`;
console
.log(message);
callback
(null, message);
};

Note that the event param has the details of the S3event. We have consoled the bucket name and the file name which will get logged when you upload image in S3bucket.

Step 9

Now, let us save the changes and test the lambda function with S3upload. The following are the code details added in AWS Lambda −

Code Details

Step 10

Now, let us add the role, memory and timeout.

Memory Timeout
Step 11

Now, save the Lambda function. Open S3 from Amazon services and open the bucket we created earlier namely workingwithlambdaands3.

Upload the image in it as shown below −

Upload Image

Step 12

Click Upload button to add files as shown −

Click Upload

Step 13

Click Add files to add files. You can also drag and drop the files. Now, click Upload button.

Add Files

Thus, we have uploaded one image in our S3 bucket.

Step 14

To see the trigger details, go to AWS service and select CloudWatch. Open the logs for the Lambda function and use the following code −

exports.handler = function(event, context, callback) {
console
.log("Incoming Event: ", event);
const bucket = event.Records[0].s3.bucket.name;
const filename = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
const message = `File is uploaded in - ${bucket} -> ${filename}`;
console
.log(message);
callback
(null, message);
};

The output you can observe in Cloudwatch is as shown −

Observe Cloudwatch

AWS Lambda function gets triggered when file is uploaded in S3 bucket and the details are logged in Cloudwatch as shown below −

S3 Bucket

Comments

Popular posts from this blog

C++ How to use Date and Time

The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program. There are four time-related types: clock_t, time_t, size_t , and tm . The types clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer. The structure type tm holds the date and time in the form of a C structure having the following elements: struct tm { int tm_sec ; // seconds of minutes from 0 to 61 int tm_min ; // minutes of hour from 0 to 59 int tm_hour ; // hours of day from 0 to 24 int tm_mday ; // day of month from 1 to 31 int tm_mon ; // month of year from 0 to 11 int tm_year ; // year since 1900 int tm_wday ; // days since sunday int tm_yday ; // days since January 1st int tm_isdst ; // hours of daylight savin...

PERL Some good framework

1. Catalyst is the most popular agile Perl MVC web framework that encourages rapid development and clean design without getting in your way. Catalyst | Perl MVC web application framework 2. Mojolicious is a next generation web framework for the Perl programming language. Back in the early days of the web, many people learned Perl because of a wonderful Perl   ... Mojolicious - Perl real-time web framework 3. Documents for Perl  The Perl Archive Network, the gateway to all things Perl. The canonical location for Perl code and modules. The Comprehensive Perl Archive Network - www. cpan .org

PHP Error and Exception Handling

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences. Its very simple in PHP to handle an errors. Using die() function: While wirting your PHP program you should check all possible error condition before going ahead and take appropriate action when required. Try following example without having /tmp/test.xt file and with this file. <?php if(!file_exists("/tmp/test.txt")) { die("File not found"); } else { $file=fopen("/tmp/test.txt","r"); print "Opend file sucessfully"; } // Test of the code here. ?> This way you can write an efficient code. Using abive technique you can stop your program whenever it errors out and display more meaningful and user friendly meassage. Defining Custom Error Handling Function: You can write your own function to handling any error. PHP provides y...