Lambda , S3 Integration

0

 Lambda , S3 Integration:

Lambda : it is server-less  service to perform dynamic operation under multiple S3 Services . it provide set of methods and API to communicate with various services without using resource.


Task 1:

Connect S3 to lambda to show bucket name, filename and file content when we upload file into s3:



1)  Edit Existing Role of Lambda with S3


{

"Version": "2012-10-17",

"Statement": [

{

"Sid": "Statement1",

"Effect": "Allow",

"Action": [

"s3:GetObject",

"s3:ListBucket"

],

"Resource": [

"arn:aws:s3:::s3lambdapracticeindore/*"

]

}

]

}


2)  Code of S3 method to display content of S3 bucket file:


import json
import boto3
import os
def lambda_handler(event, context):
    bucket_name = event['Records'][0]['s3']['bucket']['name']
    object_key = event['Records'][0]['s3']['object']['key']
    print(f"Bucket name: {bucket_name}")
    print(f"Object key: {object_key}")
    s3_client = boto3.client('s3')
    response = s3_client.get_object(Bucket=bucket_name, Key=object_key)
    content = response['Body'].read().decode('utf-8')
    print(f"File content: {content}")
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

Task 3:

Connect S3 to lambda to Put Object on any bucket, filename and file content

should be pass dynamically from lambda function.


import json
import boto3
import os
def lambda_handler(event, context):
    s3_client = boto3.client('s3')
    response = s3_client.put_object(
            Bucket="s3lambdapracticeindore",
            Key="welcome.txt",
            Body="welcome in my custom file "
        )
  return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!'),
        'response_status': response
    }


Edit Policy rules:
{ "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Action": [ "s3:GetObject", "s3:ListBucket", "s3:PutObject" ], "Resource": [ "arn:aws:s3:::s3lambdapracticeindore/*" ] } ] }


Task 2:

Connect S3 to lambda to Put Object and Get Object on any bucket, filename and

file content

import json
import boto3
import os
def lambda_handler(event, context):
    s3_client = boto3.client('s3')
    response = s3_client.put_object(
            Bucket="s3lambdapracticeindore",
            Key="welcome1.txt",
            Body="welcome in my new custom file "
        )
    response1 = s3_client.get_object(Bucket="s3lambdapracticeindore",
Key="welcome1.txt")
    content = response1['Body'].read().decode('utf-8')
    print(f"File content: {content}")
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!'),
        'response_status': response
    }


Tags

Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)