Lambda Function to write a file in Amazon S3 using Java.

This article cover the case when we want lambda function to create,write and upload the file in S3.In one of my project we need to write the status of system in a file and upload it to S3 bucket.
In this article we will see how we can write a handler for lambda in java to write the file.
Steps to achieve the above scenario:
1. Create IAM role for Lambda.
2. Create a Lambda function in Java.
3. Create a jar with handler code.
4. Test the scenario.
Create IAM role for Lambda:
Go to AWS Console, type IAM and click the IAM service.
This will open the IAM service page.
Click the Roles from the left menu to display the Roles under Access management.
Click the Create role button on right.
Follow the steps to create role :
1.Select AWS service as a trusted entity.
2.Select Lambda in the list of services and click on the Next.
3.Add permissions (AWSLambdaBasicExecutionRole,AmazonS3FullAccess)
4.Give name to the role.
5.done.

Create a Lambda function in Java:
1. Type lambda in the console to list the lambda service and select it.
2. Click the Create function to generate new lambda function.
3. In Basic information give the function Name,Runtime (Java 8),Existing execution role (previously created).
4. Default Advanced settings.
5. Click Create function.

Next we need to create a jar and upload in our lambda function.
Steps to create a jar:
Create maven project using quick start in any IDE (Eclipse,IntelliJ).
Provide dependencies for aws-lambda-java-core, aws-lambda-java-events and aws-java-sdk-s3 in POM.xml.

Write a code below in the handler class.
Replace your credentials below.
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.S3Event;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.HeadBucketRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;public class LambdaToWriteInS3 implements RequestHandler<S3Event, Boolean>
{
private static final AmazonS3 s3client=AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("<youraccesskey>", "<yoursecretkey>"))))
.withRegion("us-east-1").build();
String bucketName = "status-file-bucket";
String fileData = "Status of System : \n AWS S3 : Available \n XYZ System is available \n Status End.";
String fileName = "Outbound_FIle_S3_"+new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());@Override
public Boolean handleRequest(S3Event s3Event, Context context) {
LambdaLogger logger = context.getLogger();
// create bucket - name must be unique for all S3 users
Boolean checkIfBucketExist= checkAccessToBucket(bucketName,s3client,logger);if(!checkIfBucketExist) {
s3client.createBucket(bucketName);
logger.log( " Bucket created " );
try
{
byte[] contentAsBytes = fileData.getBytes(StandardCharsets.UTF_8) ;
ByteArrayInputStream contentsAsStream = new ByteArrayInputStream(contentAsBytes);
ObjectMetadata md = new ObjectMetadata();
md.setContentLength(contentAsBytes.length);
s3client.putObject(new PutObjectRequest(bucketName, fileName, contentsAsStream, md));
logger.log( "File written and uploaded to S3" );
return true;
}
catch(AmazonServiceException e)
{
logger.log( "Error : "+ e.getMessage() );
return false;
}
catch(Exception ex)
{
logger.log("Error : "+ ex.getMessage());
return false;
}}
else{
logger.log( " Bucket Already exist! " );
return false;
}
}
public boolean checkAccessToBucket(final String bucketName,AmazonS3 s3client,LambdaLogger logger) {
try {
final HeadBucketRequest request = new HeadBucketRequest(bucketName);
s3client.headBucket(request);
return true;
} catch (AmazonServiceException ex) {
if (ex.getStatusCode() == 404 | ex.getStatusCode() == 403 || ex.getStatusCode() == 301) {
return false;
}
throw ex;
} catch (Exception ex) {
logger.log("exception in Access to Bucket "+ex.getMessage());
throw ex;
}
}
}
Build the project and Generate the jar.
mvn clean package
Upload jar to our Lambda function
Open the lambda function and go to the code section click on Upload from button. Select the jar created for lambda. upload it.

Edit runtime settings in code section
edit the handler name <package><classname>::handleRequest
Save changes.
Test the scenario:
To test our code go to our Lambda function , then go to Test section.
we will do a default setting as below, click Test.


Go to S3 bucket and check for our bucket. Open the bucket to see the file.


Download file to see the contents.

We can also check CloudWatch logs, go to your lambda function Monitor section. click on CloudWatch logs.


Thank you!