DEV Community

Cover image for How do you get S3 object list with AWS Lambda ?
nomurabbit
nomurabbit

Posted on

How do you get S3 object list with AWS Lambda ?

Introduction

AWS S3 is one of the most effective online storages for your business. If you were able to treat S3 objects by AWS Lambda just as you want, your tasks will progress much well. This is a commentary article that focuses getting S3 object list.


S3 buckets and IAM settings

S3 buckets settings for treating with AWS Lambda is very simple. You don't have to do anything special. The only a few things that you have to do are creating IAM user for AWS Lambda and adding several policies to the user.

The policy setting is the below. You will allow "s3:ListBucket" Action for the resource.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "s3:ListBucket",
            "Resource": "arn:aws:s3:::YOUR_BUCKET_NAME"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

In this case I'm trying to access "YOUR_BUCKET_NAME" bucket.

Source code with .NET

AWS Lambda supports .NET6 and you can write source codes with C#. This is much significant for some developers. If you've developed some systems with .NET, your .NET technical assets will help you very much to develop AWS Lambda.

It's very easy to use AWSSDK for S3. First initializing S3 client. Second creating a request instance. Finally running ListObjectsAsync methos and get response.

using Amazon.S3;

public string GetObjectlist(string tempPrefix)
{
    try
    {
        var returnString = "";

        var s3Client     = new AmazonS3Client(RegionEndpoint.YOUR_REGION);
        var request      = new Amazon.S3.Model.ListObjectsRequest
        {
            BucketName  = "S3_BUCKET_NAME",
            Prefix      = tempPrefix,
        };
        Amazon.S3.Model.ListObjectsResponse response = s3Client.ListObjectsAsync(request).Result;

        foreach (var objectItem in response.S3Objects)
        {
            if(returnString != "") 
            {
                returnString += "::";
            }
            returnString += objectItem.Key;
        }

        return returnString;
    }
    catch (System.Exception e)
    {
        throw e;
    }
}
Enter fullscreen mode Exit fullscreen mode

The response class layout is below.
https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/NS3Model.html

Conclusion

In this post I tried to introduce about getting S3 objects by AWS Lambda. I'll show you another AWS operation in next post. I wish my post makes your tasks done well.

Top comments (2)

Collapse
 
naucode profile image
Al - Naucode

Great article, keep the good work! Liked and followed! 🚀

Collapse
 
nilsawartz profile image
NilsaWartz

Good information shared! I am inspired to explain your ideas in this post!
vashikaran mantra for wife in hindi