Read contents of S3 bucket using AWS lambda

Here is an example AWS Lambda function written in Python that reads a file from an S3 bucket. In this example, the lambda_handler function is the entry point for the Lambda function. It takes two parameters, event and context.

The event parameter contains information about the S3 bucket and object that triggered the Lambda function, and the context parameter contains information about the runtime environment of the function. 

Python Code:

Advertisements

import json 
import boto3 

s3 = boto3.client('s3') 

def lambda_handler(event, context): 

    # Get the object from the event 
    bucket_name = event['Records'][0]['s3']['bucket']['name'] 
    object_key = event['Records'][0]['s3']['object']['key']   

    # Read the file from S3 
    response = s3.get_object(Bucket=bucket_name, Key=object_key) 
    file_content = response['Body'].read().decode('utf-8')   

    # Print the file contents 
    print(file_content) 

    return { 
        'statusCode': 200, 
        'body': json.dumps('File read from S3 successfully!') 
    } 

First, the code imports the necessary libraries, json and boto3. json is used for encoding and decoding JSON data, and boto3 is the AWS SDK for Python.

Next, the code creates an S3 client object using the boto3.client method. This client will be used to interact with the S3 bucket.

The lambda_handler function is the entry point for the Lambda function. It takes two parameters, event and context. The event parameter contains information about the S3 bucket and object that triggered the Lambda function, and the context parameter contains information about the runtime environment of the function.

The function gets the bucket name and object key from the event parameter using event['Records'][0]['s3']['bucket']['name'] and event['Records'][0]['s3']['object']['key'], respectively. This information is used to retrieve the file from the S3 bucket.

The function reads the file from the S3 bucket using the s3.get_object method, passing in the Bucket and Key parameters. The response is a dictionary containing metadata about the object and the contents of the file, which are stored in the file_content variable.

Finally, the function prints the file contents to the console using the print function and returns a JSON object with a success message.

Note that in order for this Lambda function to work, you’ll need to configure an S3 trigger for the Lambda function. When a new object is added to the S3 bucket, the Lambda function will be triggered, and the lambda_handler function will execute, reading the contents of the file. 

Overall, this Lambda function reads the contents of a file from an S3 bucket when triggered by an S3 event and prints the contents to the console.

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *