Saturday, October 31, 2020

AWS - Attaching Lambda Trigger to DynamoDB Table

Attaching an existing Lambda as a DynamoDB Table's Stream trigger so that the Lambda can see the changes as they happen in the DynamoDB Table

Let's see how to attach an existing Lambda as a DynamoDB Table Stream trigger using code. If you disable/enable DynamoDB Stream for any reason the Lambda Trigger would get disconnected and this code would reattach the Lambda trigger back. This code is written in Java

  • Retrieve DynamoDB Table's Stream ARN. 
           String streamArn = null;  
           AmazonDynamoDBStreams dynamoDBStreamsClient = AmazonDynamoDBStreamsClientBuilder.standard().build();  
           // Create request  
           ListStreamsRequest listStreamRequest = new ListStreamsRequest();  
           listStreamRequest.setTableName(dynamoDBTable);  
           // Fetch Streams  
           ListStreamsResult response = dynamoDBStreamsClient.listStreams(listStreamRequest);  
           // Get the StreamARN  
           if (response != null && response.getStreams() != null && response.getStreams().size() > 0) {  
                Stream stream = response.getStreams().get(0);  
                streamArn = stream.getStreamArn();  
           }  
           return streamArn;

When a DynamoDB Table name is passed on to the above code, the 'listStreams' would return only a single Stream ARN, if the Table name is not passed it would return all the Table's Stream ARN.

  • Attach Lambda as a Trigger for DynamoDB Table's Stream. In the below code the 'eventSourceArn' is same as the 'streamArn' we retrieved above
           // create EventSourceMapping Request  
           CreateEventSourceMappingRequest createEventSourceMappingRequest = new CreateEventSourceMappingRequest();  
           // Set the Trigger enabled  
           createEventSourceMappingRequest.setEnabled(true);  
           // Set the Source of the Stream, in our case DynamoDB  
           createEventSourceMappingRequest.setEventSourceArn(eventSourceArn);  
           // Set the Starting position of the Stream to be consumed  
           createEventSourceMappingRequest.setStartingPosition("LATEST");  
           // Name of the Lambda function that gets triggered  
           createEventSourceMappingRequest.setFunctionName(functionName);  
           // Create Lambda Client  
           AWSLambda lambdaClient = AWSLambdaClientBuilder.standard().build();  
           // Execute SourceMapping request  
           CreateEventSourceMappingResult createEventSourceMappingResult = lambdaClient  
                     .createEventSourceMapping(createEventSourceMappingRequest);

Complete source code can be found here

No comments:

Post a Comment