AWS SAM(Serverless Application Model)is an open source framework that enables AWS users to build, test locally and deploy AWS Lambda to the Cloud. There are many tools to simplify the development of Serverless functions: cross-vendor Serverless framework, AWS-specific Serverless Application Model (SAM), and others. The AWS SAM is widely used in AWS cloud. It can organize related components configurations and deploy all the connected resources together as an entity. It uses cloud formation behind the scenes for building resources but fewer lines of code and some implicit permission handling. For regular deployment of AWS lambda using AWS Cloudformation requires AWS S3 folder for the code artifacts but deployment via AWS SAM cli it handles the folder on its own.

It provides an environment where you can test AWS Lambda locally and fix bugs, saving cost and time. It integrates well with AWS Code deploy, AWS Codebuild and AWS Codepipeline. The instructions for the build and deploy are provided in the form YAML file.

Prerequisites

Install the AWS CLI and AWS SAM on your operating system.
Windows — install using MSI installer link
Linux- Download the Zip file and follow the link
Mac- install using Brew and follow the link
All the code for this article is in the repo Code reference
Setup the Access key using AWS Configure

Build, Test and Deploy

  1. Build
  2. Test
  3. Deploy

Create SAM template

The SAM template is a YAML file similar to the AWS Cloudformation template. The SAM template file is template.yaml in the github repository mentioned before. With few lines of configuration, we can define the event trigger , AWS lambda code and destination of AWS Lambda. Below template, has the information to build AWS lambda function with an S3 trigger. The transform tag in the template.yaml file indicates AWS SAM template. Some of the IAM role is defined implicitly for S3 to trigger AWS Lambda. There are options define Lambda configuration parameters and settings in SAM template like Ephemeral storage, Memory Size, Timeout and Tracing etc.

AWSTemplateFormatVersion: '2016-10-31'
Transform: AWS::Serverless-2016-10-31
Description:
AWS Lambda SAM Build, deploy , test locally
Resources:
AWSSAMLambdaFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: LambdaCode/
Handler: app.lambda_handler
Runtime: python3.9
Timeout: 75
FunctionName: AWSSAMtest
MemorySize:512
Events:
CreateFileEvent:
Type: S3
Properties:
Bucket: !Ref SrcBucket
Events: s3:ObjectCreated:*
SrcBucket:
Type: AWS::S3::Bucket

Build

Create a local python project using any IDE. The python project folder should contain below files for SAM to work

* lambda.py — Main python code for the business logic,
* requirements.txt- contains all the required libraries. It is formed as subfolder in the AWS lambda console
* event.json — Sample event for the corresponding trigger event. It simulates real world scenarios like S3 event, MSK Kafka trigger
* template.yaml -AWS Cloudformation instructions to build the AWS lambda, Role and other triggers if required.

Test

To test AWS lambda locally, you can either invoke lambda with the event-generated command or enable HTTP trigger for Lambda invoke and run automated test.

Test Event generation and invoke by SAM

You can generate sample events for local testing using the SAM command line. The command sam local generate-event followed by the AWS resource name and parameters creates the event payload.

The command sam local invoke will invoke a local AWS lambda script and quits after the invocation is completed. Below command simulates a PUT event in the S3 bucket and simulates the invocation of AWS lambda on cloud locally

# using the SAM command you can generate certain AWS resource event locally and test Lambda locallysam local generate-event s3 [put/delete] --help# Below command automatically generate the put and delete event locally and pass it to Lambda.py code for testing purposes.sam local generate-event s3 [put/delete] --bucket <bucketname> --key <prefixname> | sam local invoke -e - <sample SAM function lambda.py >

Test AWS lambda using URL option

This approach allows invoking the local Lambda function and exposing the code using a URL. Once the Lambda is available as a URL then automated test cases can be applied before any code change and deployment . Using the boto3 AWS SDK you can automate the testing by providing different testing scenarios using the URL.

# browse to the folder and start the Lambda
sam local start-lambda [OPTIONS]
#publish the local lambda app to HTTP url
aws lambda invoke --function-name "SAMTestApp" --endpoint-url "http://127.0.0.1:3001" --no-verify-ssl out.txt

Deploy

Once the build and local testing is complete, the next step is to deploy lambda to AWS cloud. Using the command line interface, browse to the project folder and run the below command. In the deployment, SAM transforms and expands the SAM syntax into AWS CloudFormation syntax, enabling you to build serverless applications quicker

$ sam build

Above command builds the application and takes care of the dependencies to the related project. You will notice a new folder and build.toml created under the python project folder with details to the build and deploy AWS Lambda

$ sam deploy 
# or
$ sam-deploy --guided

Above command deploy will ask for some questions and confirmation before creating resources using cloud formation and continue with deployment. This process will take a few minutes based on the resource configuration. The deploy command locates all the required files like template.yaml in the current project folder. For more details

Check the AWS Cloudformation console to ensure all the components are build and successfully created. Also check the AWS lambda console to ensure that the function is created and IAM role for the lambda is created.

Using AWS SAM, we can build, test and deploy from a local Python IDE. It can be used to organize related components, share configuration such as memory and timeouts between resources, and deploy all related resources entity. It enables quicker development, dependent library installation and cost optimized route to develop AWS lambda script.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store