Introduction to AWS SAM CLI: Simplify Serverless Development

CodeStax.Ai
7 min readMar 29, 2024

The Serverless architecture in cloud computing helps developers to easily create and deploy applications without worrying about the underlying infrastructure. The AWS SAM (Serverless Application Model) CLI is a framework that helps streamline the process of managing serverless apps on AWS. It’s an extension of AWS cloud formation it has several options to make building, testing, and deploying lambda functions easier.

Installation of SAM CLI:

Installing the AWS SAM CLI involves a few steps and prerequisites. The SAM CLI is supported on most major operating systems, including Windows, Linux, and macOS.

For detailed installation instructions, please refer to the official AWS SAM CLI documentation for Installation by clicking here.

AWS CLI: It’s recommended to have the AWS Command Line Interface (CLI) installed and configured with your AWS account credentials with necessary IAM permissions. Instructions can be found on the AWS CLI installation page.

Docker: For local testing of your serverless applications, Docker is required. Ensure Docker is installed and running on your system. You can download it from Docker’s official website (optional).

Getting started with SAM CLI :

$ sam init

By typing the sam initcommand, you have started a new serverless app with AWS SAM CLI it will ask some questions with choices Choose theAWS Quick Start Templatesand runtime. It helps you to set up your project with a boilerplate code that includes the template.yaml file that has the infrastructure definition of your serverless application. app.jscontains function logic.

The SAM Template

Let’s break down a simple example from the template.yaml file where we're setting up a Lambda function to grab all items from a database:

AWSTemplateFormatVersion: '2010-09-09'
Description: firstsamProject
Transform:
- 'AWS::Serverless-2016-10-31'
Resources:
getAllItemsFunction:
Type: AWS::Serverless::Function
Properties:
Handler: src/handlers/get-all-items.getAllItemsHandler
Runtime: nodejs16.x
Architectures:
- x86_64
MemorySize: 128
Timeout: 100
Description: A simple example includes a HTTP get method.
Events:
Api:
Type: Api
Properties:
Path: /
Method: GET
Outputs:
WebEndpoint:
Description: API Gateway endpoint URL for Prod stage
Value: !Sub 'https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/'
Globals:
Function:
Tracing: Active
LoggingConfig:
LogFormat: JSON
Api:
TracingEnabled: true
  • Transform: - 'AWS::Serverless-2016-10-31': This part is crucial for SAM templates. The Transform section tells AWS CloudFormation to process this template using the AWS Serverless Application Model. The date 2016-10-31 refers to the version of SAM you're using.
  • Resource: This section is where you'll define all the AWS resources you need for your application, like Lambda functions, API Gateway APIs, DynamoDB tables, etc. Each resource will be listed here with its configuration. In your snippet, this section is ready to be filled with resource definitions.
  • getAllItemsFunction: This is just a name we give to our Lambda function so we can refer to it easily.
  • Type: AWS::Serverless::Function: This tells AWS, "Hey, I want to create a Lambda function."
  • Properties: This section lists all the settings for our Lambda function.
  • Handler: This tells AWS where to find the code that should run. In our example, it's located in a file inside the src/handlers folder.
  • Runtime: This specifies the programming language our code uses, which is Node.js version 16 in this case.
  • MemorySize: This is how much system memory (RAM) we're giving our function. We're using 128 megabytes here.
  • Timeout: This is the maximum time AWS will wait for our function to do its job before stopping it. We've set it to 100 seconds.
  • Events: This section explains what will trigger our Lambda function to run. We've set it up so that when someone visits a certain web page (Path: /) and asks for data (using the GET method), our function will run and get the data from the database.
  • Outputs: This section defines the values that you can get information about once the stack is deployed such as WebEndpoint.
  • Functions: Applies default settings to all AWS Lambda functions defined in your template.
  • Tracing: Set to ‘Active’, which means AWS X-Ray tracing is enabled for all Lambda functions. This helps in debugging and analyzing the performance of your functions.
  • LoggingConfig: Configures logging for your functions. Here, it specifies that logs should be in JSON format, making them structured and easier to analyze.
  • Api: Applies to all AWS API Gateway APIs defined in your template.
  • TracingEnable: Set to ‘true’, which enables AWS X-Ray tracing for your APIs. This allows you to trace and analyze requests as they travel through your APIs.

This template.yaml file is super important because it helps AWS understand exactly what you need for your app, from the functions it should run to the permissions those functions need.

Local Development and Testing:

It’s one of the coolest features that SAM gives to test your app right on your computer, without needing to deploy it to AWS every time you want to check something and debug issues right from your favorite development tools.

$ sam build

This build command will create the binaries that are needed for run time in AWS lambda, before invoking the function locally sam build is required.

Testing Serverless API Locally :

$ sam local start-api

which will create a replica of the lambda run time environment locally using docker once it starts we can able to hit the endpoints just like actual aws endpoints hosted in the cloud.

Invoking Lambda Function locally :

In the example shown, the getAllItemsFunction lambda function was invoked locally using the testEvents.json file. The function simply prints the contents of the input event.

Deploying Application

The AWS CLI needs to be properly configured and provided with all the required permissions for the services that will be used during the deployment before executing.

sam deploy --guided

This command packages your application and prepares it for deployment to AWS. The --guided option walks you through the deployment process step by step, asking for necessary details like the stack name, AWS region, and more.

During the sam deploy --guided process, Confirm changes before deploy [Y/n]:is a safety net. It provides you with an opportunity to examine some of the changes that will be made in your AWS setup described in your template.yaml file. Pressing Y allows one to confirm such adjustments beforehand thus endorsing updates. This stage acts as a final control to ensure that everything is well in place before launching your app. As shown above screenshot.

When you get to the part that says, “Once you verify all the changes deploy this changeset. [Y/n]:”, Y tells AWS SAM, that it’ll then update everything changes mentioned in the changeset. Once it’s all set, you’ll get a hosted endpoint in Outputs as mentioned in the above screenshots.

Now, let’s go check the AWS console to see if our changes are showing up there.

All the changes have been updated successfully.

Conclusion:

You can also use SAM CLI with IDE’s like VSCode, PyCharm, IntelliJ, and more with AWS ToolKit or AWS’s own Cloud9 and there is also a lambda debugging feature you can now spot and fix bugs directly from your IDE using AWS ToolKit extension making development smoother and easier. AWS SAM CLI not only simplifies development but also enhances development.

Manickam V, an SDE 1, has around 2 years of experience in full-stack development. His journey is marked by a keen interest in unraveling new technologies and a commitment to devising the most effective solutions through a deep understanding of the challenges at hand. Specializing in JavaScript, Manickam’s approach is defined by his dedication to solving problems and his enthusiasm for pushing the boundaries of tech to enhance user experiences.

About CodeStax.Ai

At CodeStax.Ai, we stand at the nexus of innovation and enterprise solutions, offering technology partnerships that empower businesses to drive efficiency, innovation, and growth, harnessing the transformative power of no-code platforms and advanced AI integrations.

But the real magic? It’s our tech tribe behind the scenes. If you’ve got a knack for innovation and a passion for redefining the norm, we’ve got the perfect tech playground for you. CodeStax.Ai offers more than a job — it’s a journey into the very heart of what’s next. Join us, and be part of the revolution that’s redefining the enterprise tech landscape.

--

--

CodeStax.Ai

Tech tales from our powerhouse Software Engineering team!