Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the table name in AWS dynamodb trigger function?

I am new with AWS and working on creating a lambda function on Python. The function will get the dynamodb table stream and write to a file in s3. Here the name of the file should be the name of the table. Can someone please tell me how to get the table name if the trigger that is invoking the lambda function?

Thanks for help.

like image 434
AIR Avatar asked Feb 08 '16 20:02

AIR


People also ask

Can DynamoDB trigger step function?

Writing results to the DatabaseAWS's DynamoDB is well-integrated into both Step Functions and Lambda, meaning that similar functionality can also be achieved directly through AWS Step Functions.


2 Answers

Since you mentioned you are new to AWS, I am going to answer descriptively.

I am assuming that you have set 'Stream enabled' setting for your DynamoDB table to 'Yes', and have set up this as an event source to your lambda function.

This is how I got the table name from the stream that invoked my lambda function -

def lambda_handler(event, context):
   print(json.dumps(event, indent=2)) # Shows what's in the event object
   for record in event['Records']:
      ddbARN = record['eventSourceARN']
      ddbTable = ddbARN.split(':')[5].split('/')[1]
      print("DynamoDB table name: " + ddbTable)
   return 'Successfully processed records.'

Basically, the event object that contains all the information about a particular DynamoDB stream that was responsible for that particular lambda function invoke, contains a parameter eventSourceARN. This eventSourceARN is the ARN (Amazon Resource Number) that uniquely identifies your DynamoDB table from which the event occurred.

This is a sample value for eventSourceARN -

arn:aws:dynamodb:us-east-1:111111111111:table/test/stream/2020-10-10T08:18:22.385

Notice the bold text above - test; this is the table name you are looking for.

In the line ddbTable = ddbARN.split(':')[5].split('/')[1] above, I have tried to split the entire ARN by ':' first, and then by '/' in order to get the value test. Once you have this value, you can call S3 APIs to write to a file in S3 with the same name.

Hope this helps.

like image 74
rk2 Avatar answered Sep 19 '22 23:09

rk2


Please note that eventSourceArn is not always provided. From my testing today, I didn't see eventSourceArn presented in record. You can also refer to the links:

  • Issue: https://github.com/aws/aws-sdk-js/issues/2226
  • API: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_Record.html
like image 25
Chunyang Wang Avatar answered Sep 22 '22 23:09

Chunyang Wang