A serverless lambda function has to be designed, developed, built, debugged, and tested locally for my project. AWS Serverless Application Model (AWS SAM) is something that I came upon.
AWS SAM consists of two primary parts:
- AWS SAM template specification – An open-source framework that we can use to define our serverless application infrastructure on AWS.
- AWS SAM command line interface (AWS SAM CLI) – A command line tool that we can use with AWS SAM templates to build and run the serverless applications.
The SAM CLI offers a number of methods for locally creating, building, executing, and debugging lambda functions. Let’s explore with a Python sample project.
Create project
To start a SAM project, use the command below. Run the command to choose from a list of choices.
sam init
The project structure:
Configuration
The configurations for the runtime, lambda handler, architecture, environment variables needed for the lambda to execute, and a few other things are all included in the template.yaml
file.
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
sam-app
Sample SAM Template for sam-app
Globals:
Function:
Timeout: 3
MemorySize: 128
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.10
Architectures:
- x86_64
Develop
When lambda is triggered in our case, app.lambda_handler
would be called. I updated the lambda handler with some sample business logic.
import json
import requests
def lambda_handler(event, context):
try:
ip = requests.get("http://checkip.amazonaws.com/")
except requests.RequestException as e:
print(e)
raise e
return {
"statusCode": 200,
"body": json.dumps({
"message": "hello world",
"location": ip.text.replace("\n", "")
}),
}
Build
The SAM project would be built, prepared for deployment, and the necessary zip package would be created by the build command.
sam build
Run
The sam local invoke
subcommand initiates a one-time invocation of an AWS Lambda function locally. The AWS SAM CLI builds the function in a local container using Docker. It then invokes the function and outputs the function’s response.
sam local invoke
Conclusion
AWS SAM is a helpful toolbox for developing, building, executing, and debugging lambda functions before deploying them to the AWS environment.
References