Deploy Java Lambda using SAM and Buildkite

I’ve recently covered how to deploy a Node JS based Lambda using SAM and Buildkite. I would say that this should cover most use cases, since I believe a majority of AWS Lambdas are implemented with JavaScript.

However, Lambda supports many more programming languages than just JavaScript and one of the more important ones among them is certainly Java. In principle, deployment for Java and JavaScript is very similar: we provide a SAM template and an archive of a packaged application. However, Java uses a different toolset than JavaScript, so the build process of the app will be different.

In the following, I will briefly explain how to build and deploy a Java Lambda using Maven, SAM and Buildkite. If you want to get to the code straight away, find a complete sample project here:

First we define a simple Java based Lambda:

package com.amazonaws.handler;


public class SimpleHandler {
    public String myHandler(int myCount, Context context) {
        LambdaLogger logger = context.getLogger();
        logger.log("received : " + myCount);
        return String.valueOf(myCount);

Then add a pom.xml to define the build and dependencies of our Java application:

<project xmlns="" xmlns:xsi=""
    <name>Sample project for deploying a Java AWS Lambda function using SAM and Buildkite.</name>




We define the lambda using a SAM template. Note that we are referencing the JAR that is assembled using Maven target/lambda-java-sam-buildkite-1.0.0.jar.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >

        Timeout: 20

    Type: AWS::Serverless::Function 
      CodeUri: target/lambda-java-sam-buildkite-1.0.0.jar
      Handler: com.amazonaws.handler.SimpleHandler::myHandler
      Runtime: java8

Then we need Dockerfile that will run our build. Here we simply start with an image that has Maven preinstalled and then install Python and the AWS SAM CLI.

FROM zenika/alpine-maven:3-jdk8

# Installing python
RUN apk add --update \
    python \
    python-dev \
    py-pip \
    build-base \
  && pip install virtualenv \
  && rm -rf /var/cache/apk/*

RUN python --version

# Installing AWS CLI and SAM CLI
RUN apk update && \
    apk upgrade && \
    apk add bash && \
    apk add --no-cache --virtual build-deps build-base gcc && \
    pip install awscli && \
    pip install aws-sam-cli && \
    apk del build-deps

RUN mkdir /app

The following build script will run within this Dockerfile and first package the Java application into a Jar file using mvn package and then uses the SAM CLI to deploy the template and application.

#!/bin/bash -e

mvn package

echo "### SAM Deploy"

sam --version

sam package --template-file template.yaml --s3-bucket sam-buildkite-deployment-test --output-template-file packaged.yml

sam deploy --template-file ./packaged.yml --stack-name sam-buildkite-deployment-test --capabilities CAPABILITY_IAM

Finally we define the Buildkite template. Note that this template assumes the environment variables AWS_DEFAULT_REGION, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are provided by Buildkite.

  - name: Build and deploy to AWS
      - './.buildkite/'
      - docker-compose#v2.1.0:
          run: app
          config: 'docker-compose.yml'
            - AWS_DEFAULT_REGION
            - AWS_ACCESS_KEY_ID

Now we simply need to create a Buildkite pipeline and link it to a repository with our source code.

Deploy Lambda using SAM and Buildkite

One of the many good things about Lambdas on AWS is that they are quite easy to deploy. Simply speaking, all that one requires is a zip file of an application that then can be uploaded using an API call.

Things unfortunately quickly become more complicated, especially if the Lambda depends on other resources on AWS, as they often do. Thankfully there is a solution for this in the form of the AWS Serverless Application Model (SAM). AWS SAM enables to specify lambdas along with their resources and dependencies in a simple and coherent way.

AWS being AWS, there are plenty of examples of deploying Lambdas defined using SAM using AWS tooling, such as CodePipeline and CodeBuild. In this article, I will show that it is just as easy deploying Lambdas using Buildkite.

For those wanting to skip straight to the code, here the link to the GitHub repo with an example project:


This example uses the Buildkite Docker Compose Plugin that leverages a Dockerfile, which provides the AWS SAM CLI:

FROM python:alpine
# Install awscli and aws-sam-cli
RUN apk update && \
    apk upgrade && \
    apk add bash && \
    apk add --no-cache --virtual build-deps build-base gcc && \
    pip install awscli && \
    pip install aws-sam-cli && \
    apk del build-deps
RUN mkdir /app

The Buildkite pipeline assures the correct environment variables are passed to the Docker container so that the AWS CLI can be authenticated with AWS:

  - label: SAM deploy
    command: ".buildkite/"
      - docker-compose#v2.1.0:
          run: app
            - AWS_DEFAULT_REGION
            - AWS_ACCESS_KEY_ID
            - AWS_SECRET_ACCESS_KE

The script that is called in the pipeline simply calls the AWS SAM CLI to package the CloudFormation template and then deploys it:

#!/bin/bash -e

# Create packaged template and upload to S3
sam package --template-file template.yml \ 
            --s3-bucket sam-buildkite-deployment-test \
            --output-template-file packaged.yml

# Apply CloudFormation template
sam deploy --template-file ./packaged.yml \
           --stack-name sam-buildkite-deployment-test \
           --capabilities CAPABILITY_IAM

And that’s it already. This pipeline can easily be extended to deploy to different environments such as development, staging and production and to run unit and integration tests.

AWS Lambda: Cross-account pass role is not allowed.

Today I came across the following exception while working with the AWS SDK for Amazon Lambda:

com.amazonaws.AmazonServiceException: Cross-account pass role is not allowed. (Service: AWSLambda; Status Code: 403; Error Code: AccessDeniedException; Request ID: xxx)

At first I was a bit puzzled where this exception might come from; but when I found out what the problem was, it seemed to be pretty obvious:

I tried to upload a lambda function to one AWS account while specifying an execution role that belonged to another AWS account.

So that could easily be fixed by providing a role belonging to the correct account!

Alternatively, this error might also occur when you deploy a lambda function which has references to another cross-account role in the template.yaml file (as mentioned by Steven T in the comments below)


As mentioned in the comments by rjhintz, if you require to use the role from another user, you can do so by modifying the policy for the role as follows:


What is Amazon Flourish (for AWS)

According to a recent article on the New Stack Blog, the Amazon Serverless Team (responsible for instance for Amazon Lambda) is about to release a new open source product called ‘Floruish’.

Currently, there are very few details available on this product. These are some points I could find:

  • It will be a platform to manage components of serverless applications.
  • This includes versioning lambda functions and packaging lambda functions with other components such as database dependencies.
  • It will be open source (under Apache license)

As more details become available, I will update this post.

For now, here are some related resources regarding serverless applications with Amazon: