How to create dynamic content using AWS Lambda?

How to create dynamic content using AWS Lambda?

Hello Everyone! Today we are going to see how you can generate dynamic content in Lamdba. We are going to use Java 8, Apache Maven, AWS SDK for Java, Apache Velocity to achieve this.

Uses Cases

There are several scenarios where you want to create dynamic content. For example, to create an HTML page response for an API method instead of returning just data in JSON/ XML. The other scenario is to generate a file or message with dynamic content. For instance, create welcome letters for your customers.

Let's Dive In

We are going to create welcome letters for our credit card customers. The letter's template is :

Hello ${name},

Say hi to your new credit card!
Your credit card number is ${creditCardNumber}.

Your Credit Company

Lambda would populate name and credit card number. The generated file is uploaded to S3 for further processing like printing and mailing.


Create an empty maven project and update pom to the following contents:

<project xmlns=""
    <description>Generate Dynamic content in Lambda</description>
        <!-- -->


We are adding AWS dependencies and apache velocity dependencies. The maven-shade-plugin to create a fat jar.


We will have our template, discussed earlier, in the resources folder (src/main/resources) with the name welcomeLetter.vm.


Create a class file with the following content:

package net.rajanpanchal.handlers;

import java.util.Map;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.RuntimeConstants;

import com.amazonaws.regions.Regions;

public class WelcomeLetterGeneratorHandler implements RequestHandler<Map<String, String>, String> {
    Regions clientRegion = Regions.US_EAST_1;
    String fileObjKeyName = "welcome_letter.txt";
    String bucketName = "welcomelettersbucket";
    static VelocityContext vContext;
    static Template t;
    AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(clientRegion).build();
    static {
        try {
            // Create a new Velocity Engine
            VelocityEngine velocityEngine = new VelocityEngine();
            // Set properties that allow reading vm file from classpath.
            Properties p = new Properties();
            velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file,class");
            t = velocityEngine.getTemplate("welcomeLetter.vm");
            vContext = new VelocityContext();

        } catch (Exception e) {
            throw new RuntimeException(e);


    public String handleRequest(Map<String, String> event, Context context) {
        String response = null;
        LambdaLogger logger = context.getLogger();
        try {
            // Add data to velocity context
            vContext.put("name", "Rajan");
            vContext.put("creditCardNumber", "1234 5678 9012 3456");
            File f = new File("/tmp/"+fileObjKeyName);

            FileWriter writer = new FileWriter(f);
            // merge template and Data
            t.merge(vContext, writer);

            // Upload a file as a new object with ContentType and title specified.
            PutObjectRequest request = new PutObjectRequest(bucketName, fileObjKeyName, f);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.addUserMetadata("title", "Welcome Letter");
            response  = new String("Success");
        } catch (Exception ex) {
            response =  new String("Error:"+ex.getMessage());

        return response;

In the static block we are creating a velocity engine, setting resource loaders for the engine ('class' and 'file' resource loaders). Then we get the template and create a context to hold data to populate on the template.

In Lambda handler handleRequest, we add data like name and credit card number to the context, and using a FileWriter object we merge the template and the data. Note that we create the file in /tmp/ directory in the Lambda execution environment. Lambda provides some disk space to the function to use. Then we upload this file to the S3 bucket (welcomelettersbucket) with the filename welcome_letter.txt. My bucket exists in US-EAST-1 as indicated by the variable clientRegion.


Now execute maven package command to generate the fat jar with all dependencies. A jar would be generated in the target folder.


Go to AWS Console, create a Lambda function with runtime Java 8, let it create a default execution role. Upload the jar under Function Code section. Edit Basic Settings and add our handler package and method name



Add S3 access policy to the Lambda execution role. Click on Permissions tab - > Execution Role hyperlink. It will take you to the IAM Role. For simplicity, I added AmazonS3FullAccess permission, but you can add fine-grain S3 access.


Go back to lambda and create Test event. Lambda executed successfully. AWS Lamdba Dynamic Content

Check S3 bucket, the file is saved. AWS Lambda Dynamic Content

AWS Lambda Dynamic Content

The file is ready for further processing!

Source Code:

AWS Lambda dynamic content


It's super easy to create dynamic content in Lambda using Apache Velocity and Java SDK. In addition, using lambda you only pay for what you use. Let me know your thoughts on the article in the comments and how you are going to use this?

If you like the post, feel free to share and follow me on Twitter for updates!