Monday, 4 July 2022

AWS LAMBDA - Practical

 

Lambda Configuration

Services -> Lambda

Create a Lambda Function

Click on the Create a function button.

Choose Author from scratch.

  • Function name: mylambdafunction
  • Runtime: Select Node.js 12x

Role: In the permissions section, select use an existing role.

  • Existing role: Select myrole

Click on Create function


Configuration Page: On this page, we need to configure our lambda function.

If you scroll down a little bit, you can see the Function code section. Here we need to write a NodeJs function which copies the object from the source bucket and paste it into the destination bucket.

Remove the existing code in AWS lambda index.js. Copy the below code and paste it into your lambda index.js file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var AWS = require("aws-sdk");
exports.handler = (event, context, callback) => {
var s3 = new AWS.S3();
var sourceBucket = "your_source_bucket_name";
var destinationBucket = "your_destination_bucket_name";
var objectKey = event.Records[0].s3.object.key;
var copySource = encodeURI(sourceBucket + "/" + objectKey);
var copyParams = { Bucket: destinationBucket, CopySource: copySource, Key: objectKey };
s3.copyObject(copyParams, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
console.log("S3 object copy successful.");
}
});
};

You need to change the source and destination bucket name (not ARN!) in the index.js file based on your bucket names.

Save the function by clicking on Deploy in the right corner.


Adding Triggers to Lambda Function

Go to the top and left page, click on + Add trigger under Designer`.

Scroll down the list and select S3 from the trigger list. Once you select S3, a form will appear. Enter these details:

  • Bucket: Select your source bucket - your_source_bucket_name.
  • Event type: All object create events

Leave other fields as default.

And check this option of Recursive invocation to avoid failures in case you upload multiple files at once.

Click on Add.

No comments:

Post a Comment