Complete Guide: Triggering AWS Lambda Functions via S3 Bucket Events

I am Computer Science Graduate and Web Developer.
Setup Lambda Function
Click on the "Create Function" button.

Give the desired name and click on "Create Function" button.

After creation, you will get a dashboard like this.

Setup S3 Bucket
Click on the "Create Bucket" button.

Now give the desired name and click on the create button.
Create IAM to Have Access to S3
Click on the "Create Role" button to create a new IAM role.

Select the use case as Lambda.

Now select S3 full access IAM role.

Finally, give a name to your IAM role and click on the create button.
Attach IAM to Your Lambda
Navigate to your Lambda and select the "Permissions" tab from the configuration and click on the "Edit" button.

Select the name of IAM role you have created and click on the save button.

Add the Trigger
Now click on "Add Trigger" button to add the trigger.

Select S3 and your bucket name from the dropdown and click on "Add" button.

Write Below Code and Push to AWS Lambda
Now write the below code in
index.js, installaws-sdkpackage via npmCreate the zip file.

Click on "Upload From" button to upload this .zip file.

const AWS = require('aws-sdk'); const s3 = new AWS.S3(); exports.handler = async (event) => { try { for (const record of event.Records) { const bucketName = record.s3.bucket.name; const objectKey = decodeURIComponent(record.s3.object.key.replace(/\+/g, ' ')); console.log('Bucket Name:', bucketName); console.log('Object Key:', objectKey); const getObjectParams = { Bucket: bucketName, Key: objectKey }; const fileContent = await s3.getObject(getObjectParams).promise(); console.log('File Content:', fileContent.Body.toString('utf-8')); } return { statusCode: 200, body: JSON.stringify({ message: 'Successfully processed all S3 file uploads' }) }; } catch (error) { console.error('Error:', error); return { statusCode: 500, body: JSON.stringify({ message: 'Error processing S3 file uploads', error: error.message }) }; } };
Whenever You Upload Anything on S3 Lambda Will Get Triggered
Inside the bucket add the file by clicking on "Upload" button.

Now navigate to your Lambda function and click on cloud watch log group to check the logs.

Conclusion
From the Logs We Can See That Lambda Got Triggered when file uploaded to S3.
It Was Able to Read Bucket Name, File Name and Its Content.



