15
votes

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.

3

3 Answers

25
votes

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.

2
votes

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:

0
votes

One way to do it will be via pattern matching in Scala using regex:

val ddbArnRegex: Regex = """arn:aws:dynamodb:(.+):(.+):table/(.+)/stream/(.+)""".r

def parseTableName(ddbARN: String): Option[String] = {
  if (null == ddbARN) None
  ddbARN match {
    case ddbArnRegex(_, _, table, _) => Some(table)
    case _ => None
  }
}