Serverless / Docker / Jenkins / sls / Lambda / API Gateway /

Automate the build of serverless to lambda with Docker and Jenkins

14 October 2016 | Author: Arthur Marinis


In the wake of doing things faster with serverless, the serverless.com project and the benefits you get from running code in Lambda (when it makes sense), I wanted to be able to automate the deployment of my serverless projects in Jenkins.

To do this, I had to make some decisions on the coding practice, and yes it's not perfect but it works.

First up, I used serverless.com's open source project tool (v0.5.6 to be precise), note that v1.0 is now available and very different. I have not had a chance to look at it yet.

I decided that my npm libraries will be in the root directory, because it was easier to perform the sls function deploy -s dev at the root level rather than in each individual folder. To save on massive projects deployed to each lambda function, browserify was used to optimise the code. And yes, it does take longer to compile but makes for smaller deployments.

I then created a docker container for serverless (sls) because I could not find any out there. You can find this at base2/sls in Docker hub.

The rest is jenkins. When we commit to master, it triggers a Jenkins job. The below is the complete Jenkins job. We have set parameters for the variables. Hopefully it is self explanatory


#!/bin/bash

chmod 777 -R $WORKSPACE

cd api

mkdir .aws
echo '[dns_master]' >> .aws/credentials
echo 'aws_access_key_id = $AWS_KEY'  >> .aws/credentials
echo 'aws_secret_access_key = $AS_SECRET'  >> .aws/credentials
echo 'region= $AWS_REGION'  >> .aws/credentials


docker run --rm --name node_sls -v $PWD:/app bitnami/node:latest npm install

docker run -e USER_ID=`id -u` -e GROUP_ID=`id -g` --rm --name sls_sls --user ec2-user -v $PWD:/home/ec2-user/ base2/sls:sls0.5.6 project init -n assetWeb -s $SLS_STAGE -r $AWS_REGION -p dns_master -c true

 # The region name should change based on the region you are dpeloying to
 echo $DEV > _meta/variables/s-variables-dev-apnortheast1.json
 echo $STAGING > _meta/variables/s-variables-staging-apnortheast1.json
 echo $PROD > _meta/variables/s-variables-prod-apnortheast1.json

docker run --rm --name sls_res -e USER_ID=`id -u` -e GROUP_ID=`id -g` --user ec2-user -v $PWD:/home/ec2-user/ base2/sls:sls0.5.6 resources deploy -s $SLS_STAGE
docker run --rm --name sls_fun -e USER_ID=`id -u` -e GROUP_ID=`id -g` --user ec2-user -v $PWD:/home/ec2-user/ base2/sls:sls0.5.6 function deploy -s $SLS_STAGE --debug
docker run --rm --name sls_evt -e USER_ID=`id -u` -e GROUP_ID=`id -g` --user ec2-user -v $PWD:/home/ec2-user/ base2/sls:sls0.5.6 event deploy -s $SLS_STAGE --debug
docker run --rm --name sls_edp -e USER_ID=`id -u` -e GROUP_ID=`id -g` --user ec2-user -v $PWD:/home/ec2-user/ base2/sls:sls0.5.6 endpoint deploy -s $SLS_STAGE --all --debug