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 ?