0

Yesterday my code was working while inserting my csv into dynamo db, It could not identify the bucket_name also Yesterday in the cloud watch logs the event was visible while uploading but today it is not

import boto3

s3_client = boto3.client('s3')
dynamodb = boto3.resource('dynamodb')

def lambda_handler(event, context):
    bucket_name = event['Records'][0]['s3']['bucket']['name']
    #bucket_name = event['query']['Records'][0]['s3']['bucket']['name']
    print (bucket_name)
    s3_file_name = event['Records'][0]['s3']['object']['key']
    resp = s3_client.get_object(Bucket=bucket_name,Key=s3_file_name)
    data = resp['Body'].read().decode('utf-8')
    employees = data.split("\n")
    table = dynamodb.Table('employees')
    for emp in employees:
        emp_data = emp.split(',')
        print (emp_data)

        try:
            table.put_item(
                Item = {
                    "emp_id": emp_data[0],
                    "Name": emp_data[1],
                    "Company": emp_data[2]
                }
            )
        except Exception as e:
            print ('endof file')
    return 'files saved to Dynamodb'

Today i got the error below

Response:

{
  "errorMessage": "'Records'",
  "errorType": "KeyError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 7, in lambda_handler\n    bucket_name = event['Records'][0]['s3']['bucket']['name']\n"
  ]
}
aysh
  • 493
  • 1
  • 11
  • 23

1 Answers1

1

The error means that event does not contain Records.

To check this and protect against the error you can do the following:

def lambda_handler(event, context):

    if 'Records' not in event:
        # execute some operations that you want
        # in case there are no Records 
        # in the event

        return


    # continue processing Records if 
    # they are available
    event['Records'][0]['s3']['bucket']['name']

    # the rest of your code
Marcin
  • 215,873
  • 14
  • 235
  • 294
  • why it is working yesterday that i was able to insert into dynamodb – aysh Jun 30 '20 at 02:55
  • 1
    @aysh I have no answer to this. Seems your lambda was invoked with different type of event than a regular S3 notification event. – Marcin Jun 30 '20 at 03:04
  • can you answer below even boutnty could not help. https://stackoverflow.com/questions/62587459/how-to-copy-from-one-bucket-to-another-bucket-in-s3-of-certain-suffix – aysh Jun 30 '20 at 03:12
  • @aysh Thanks for the link. I will look into the new question. I understand that my current answer was sufficient to solve the current issue with `Records`? – Marcin Jun 30 '20 at 03:17
  • 1
    i will work on your answer and edit so that new people will get benefited. Thanks Marcin. u r awesome – aysh Jun 30 '20 at 04:16
  • @aysh No problem. Glad I could help. – Marcin Jun 30 '20 at 04:17