How to Get the S3 bucket object keys using Lambda

Fri, Mar 31, 2023

Read in 1 minutes

1.Problem Statement:

I have s3 bucket and N number of files as objects inside the bucket. I want to get the all the object keys using a lambda in python.

Lambda Function:


              import json 
              import boto3 
              from botocore.exceptions import ClientError
              import csv
              from datatime import datatime
              import logging
              from os import listdir

              s3 = boto3.cleint('s3')
              Count = 1
              Def lambda_handler(event,context):
              Keys = []
              resp = s3.list_objects_v2(Bucket='testbucket')
              for obj in resp['Contents']:
              Keys.append(obj['key'])
              Print("keys are")
              Print(keys)
              return {
                'files_array' :keys ,
              'bucket' : 'testbucket'
              }

In the above lambda , first the list of all the objects as ‘resp’ And looping the ‘resp’ and printing the keys.