An AWS-Lambda function can be attached to a certain bucket event. Whenever a file/folder is created or removed, an event can trigger lambda function execution.
A simple Lambda function to print the name of an uploaded File
This is a one class lambda project to print the name of an uploaded file. For maven we need to add those dependencies:
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.1.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
<version>1.3.0</version>
<type>jar</type>
</dependency>
</dependencies>
Now let's go to our HelloWorld Class:
package com;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.S3Event;
import com.amazonaws.services.s3.event.S3EventNotification;
public class HelloWorld implements RequestHandler< S3Event, String> {
@Override
public String handleRequest(S3Event event, Context ctx) {
S3EventNotification.S3EventNotificationRecord record=event.getRecords().get(0);
System.out.println("Bucket Name is "+record.getS3().getBucket().getName());
System.out.println("File Path is "+record.getS3().getObject().getKey());
return null;
}
}
Next step is to build the project using mvn.
After building the project, we need to upload it to AWS-Lambda. Go to Lambda, choose "create a lambda function". Skip the part where you choose the blueprint, because Java is usually not there.
Also, skip "Configure triggers" because we will configure it from a different location. The next page, enter a name for your first lambda function, then a small description and choose Java as runtime.
For the "Code entry type", choose "Upload from a .ZIP file" and then select your .zip file in the next location to upload it.
The tricky part on this page is the Handler field. In the handler field, you have to specify the location of the class the implements the RequestHandler. This class is the entry point for the lambda and your Lambda function won't work if this is not specified correctly. For our case handler is "com.HelloWorld"
Attaching a S3 trigger to Lambda:
Here we will attach a trigger to the S3 file upload
Monitoring Lambda Output
Now, we will upload a file to the bucket that has the lambda trigger. To see the lambda outputs and logs, go to "CloudWatch", then choose "Logs", then choose your Lambda function. You might see many entries under "Log Streams", choose the latest one and open it. You should be able to see the output of the lambda execution there.