Articles → AWS → Get The List Of Objects Inside The S3 Bucket Using The Lambda Function In AWS

Get The List Of Objects Inside The S3 Bucket Using The Lambda Function In AWS






Creation Of S3 Bucket




Picture showing a S3 bucket created in AWS console
Click to Enlarge



Picture showing the text file uploaded in the S3 bucket
Click to Enlarge


Creation Of A Lambda Function




Picture showing the lambda function created in AWS console
Click to Enlarge


Install AWS-SDK Package




npm init -y






npm install aws-sdk









Write Code To Read Data From The S3 Bucket




import AWS from aws-sdk;

const s3 = new AWS.S3();
export const handler = async(event) => {
    // TODO implement
    
    
    const bucketName = gyansangrah;
    
    // Set the parameters for the S3 listObjectsV2 operation
    const params = {
        Bucket: bucketName
    };
    
    // List all the objects in the S3 bucket
    try {
        const data = await s3.listObjectsV2(params).promise();
        const objects = data.Contents.map(obj => obj.Key);
        console.log(`Objects in ${bucketName}: ${objects}`);
        return objects;
    } catch (err) {
        console.log(`Error listing objects: ${err}`);
        throw err;
    }
    
    const response = {
        statusCode: 200,
        body: JSON.stringify(Hello from Lambda!),
    };
    return response;
};



Add Permission To The Lambda Function Role




Picture showing the AmazonS3FullAccess permission assigned to the lambda function role
Click to Enlarge


Upload Code To Lambda Function




Picture showing an option to upload the code in the lambda function
Click to Enlarge



Picture showing the confirmation message when the zip file is uploaded in the lambda function
Click to Enlarge


Execute The Lambda Function




Picture showing the output of execution of the lambda function
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Monday, September 25, 2023

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250