0
votes

I was following the AWS tutorials on CloudTrail and CloudWatch and used it to setup a Rule that will trigger a Lambda when a PUT action occurs on an S3 bucket. The lambda will print name of bucket and other details.

import json
import urllib.parse
import boto3

# instantiate an S3 object
s3 = boto3.client('s3')

def lambda_handler(event, context):
    # Start processing by looking at Records key-value
    try:
        records = event['Records']
        if len(records) == 0:
            raise Exception("Records was zero!")
        else:
            packet = []
            for row in records:
                msg = "Received event type - {}".format(row["eventName"]) + \
                " caused by user - {}".format(
                    row["userIdentity"]["principalId"]) + \
                    " on bucket - {}".format(row["s3"]["bucket"]["name"]) + \
                    " whose owner is - {}".format(
                        row["s3"]["bucket"]["ownerIdentity"]["principalId"]) + \
                        " The specific object that got put was {}".format(
                            row["s3"]["object"]["key"]
                            )
                print(msg)
                packet.append(
                    {
                        "eventName":row["eventName"],
                        "userIdentity":row["userIdentity"]["principalId"],
                        "bucket":row["s3"]["bucket"]["name"],
                        "bucketOwner":row["s3"]\
                        ["bucket"]["ownerIdentity"]["principalId"],
                        "objectKey":row["s3"]["object"]["key"]
                        }                   )
            return {"statusCode":200, "body":packet}
    except:
        raise Exception("Could not find Records from Events")

I noticed that in Cloudwatch logs (under log groups) whenever I placed an file under an S3 bucket, I would see all the activity for the S3 bucket. But there were instances were the exception -> Could not find Records from Events - were present.

Why is the Lambda being triggered in this case here ?

2

2 Answers

0
votes

Can you print the exception and see what are the exception which are raised.

0
votes

Alternate-Solution - If cloudwatch is giving error. You can use notification configuration in s3. This will call the lambda when an object is created in s3.

Resources: bucket1: Type: AWS::S3::Bucket Properties: BucketName: !Ref SourceBucket NotificationConfiguration: LambdaConfigurations: - Event: 's3:ObjectCreated:*' Function: !GetAtt LambdaFunction.Arn BucketPermission: Type: AWS::Lambda::Permission Properties: Action: 'lambda:InvokeFunction' FunctionName: !Ref LambdaFunction Principal: s3.amazonaws.com SourceArn: !Sub arn:aws:s3:::${SourceBucket}