Deploy an AWS Lambda function

AWS Lambda is a flexible and cost effective service which allows you to implement back-end functionality in a serverless environment. In this tutorial we will create a script to automate the deployment of Lambda functions. Apart from an AWS account, we will also need

  • The Lambda function name (ARN) and region. We can find the ARN by selecting our lambda function in the AWS Lambda service. The ARN is shown in the top right of the page: Lambda function ARN

  • The AWS cli to run our script

Deployment Script

The script we will use is tailored for a Node.js Lambda function, but it can be easily adjusted for other runtimes.

The executed steps are

  1. Parse the required AWS parameters (region and function name) from a .env file
  2. Include the files to be uploaded in a .zip file
  3. Upload the file to AWS
  4. Remove the zip file

Let's create a deploy_lambda.sh file with the following contents:

#!/bin/bash
set -e

. .env
ZIP_FILE="lambda.zip"
# Specify the files you want to include in your lambda function
FILES_TO_INCLUDE="index.js"

# Dependency installation, adjust according to your function
echo "Installing dependencies..."
npm i

echo "Building zip file..."
zip -r $ZIP_FILE $FILES_TO_INCLUDE
echo "Uploading lambda function..."
aws lambda update-function-code \
--function-name $AWS_FUNCTION_NAME \
--zip-file "fileb://$ZIP_FILE" \
--region "$AWS_REGION"
rm $ZIP_FILE
echo "Done!"

We will also need a .env file in the same folder as our script. An example:

AWS_REGION=ap-southeast-2
AWS_FUNCTION_NAME=arn:aws:lambda:ap-southeast-2:999:function:myLambdaFunction

Usage

⚠️ You may need to change the script's permissions first: chmod 755 deploy.lambda.sh

./deploy_lambda.sh

Results

Finally, we can include this script in our application's CI/CD pipeline to streamline the deployment of Lambda functions.