I recently needed to write a Lambda function to do some resource cleanup in AWS, so I decided to take the opportunity to explore the AWS Serverless Application Model (SAM). I still have a lot to learn with SAM, but I thought I would share the Jenkins job I use for deploying my Lambda function.

While there is a Jenkins Plugin for the SAM, I wanted to figure out how to do it without relying on the plugin in case I ever want to use a different deployment tool.

During the first stage of my Jenkins job, I prepare the build environment by creating a Python 3 virtual environment and install the aws-sam-cli tool.

stage('Prepare Build Environment') {
    sh """
        python3 -m venv venv
        . venv/bin/activate
        pip install aws-sam-cli
    """
    env.PATH = "${env.WORKSPACE}/venv/bin:${env.WORKSPACE}/bin:${env.PATH}"

In the next stage, I use the sam CLI to package the function and push it to S3. The ${params.project} is a prefix for the S3 bucket, and the $key is set to the name of the github repo.

stage('Build Lambda Job') {
    sh """
        sam package \
            --template-file template.yaml \
            --output-template-file package.yml \
            --s3-bucket ${params.project}-lambda \
            --s3-prefix ${key}
    """
}

For the final stage, I use the sam CLI to deploy the function to AWS. I wanted the job to be considered a success even if it did not deploy because nothing changed, so I added the command line switch --no-fail-on-empty-changeset to enable that outcome.

stage('Deploy Lambda Job') {
    sh """
        sam deploy \
            --template-file package.yml \
            --stack-name ${key} \
            --capabilities CAPABILITY_IAM \
            --no-fail-on-empty-changeset
    """
}

I really like the ease in which I was able to develop and deploy my little function wtih SAM. We have a few other functions that we will be migrating over to this framework in the next few months