As a full-stack developer, leveraging serverless architectures on AWS can greatly simplify deployment and operations. The AWS Serverless Application Model (SAM) makes building serverless applications easier by providing simplified YAML templates to define the various components. The SAM CLI tooling then allows you to build, test, debug, and deploy those applications from the command line.

In this comprehensive guide, we‘ll cover:

  • What is AWS SAM and the SAM CLI
  • Benefits of using SAM and serverless architectures
  • Installing the SAM CLI on Linux
  • Configuring credentials and permissions
  • Main commands for using the SAM CLI
  • Debugging locally with the SAM CLI
  • Deploying a serverless app with the SAM CLI
  • Removing the SAM CLI when finished

What is AWS SAM and the SAM CLI

AWS SAM (Serverless Application Model) provides developers with a simplified way to define the resources needed for a serverless application in AWS. This includes:

  • AWS Lambda functions
  • API Gateway endpoints
  • DynamoDB tables
  • S3 buckets
  • Other event sources and resources

The SAM specification makes it easier to visualize and understand what components make up an application.

The SAM CLI then brings that specification to life by providing a command line interface for building, testing, debugging, and deploying a SAM-defined application.

Some key capabilities include:

  • Local simulation of Lambda functions – The SAM CLI can invoke your functions locally using Docker to mimic the live AWS Lambda environment. This allows you to observe and debug behavior before deploying.

  • Building and packaging functions – The CLI will handle translating your function code into the appropriate artifacts and zip files needed for deployment.

  • Validation of SAM templates – Syntax and logical errors in your serverless application definition can be discovered early.

  • Integration with other AWS SDKs – Seamlessly interact with cloud services like DynamoDB when running locally.

  • Automated deployment processes – Get your serverless application up and running in AWS with a single CLI command.

The combination of AWS SAM for simplified infrastructure-as-code definitions and the SAM CLI for streamlined management unlocks the true potential of serverless for full-stack developers. Next, let‘s look at how to install this tool.

Benefits of Serverless and SAM for Developers

Before jumping into the installation and usage details, it‘s worth exploring why serverless and the SAM framework are so useful for full-stack developers.

Faster deployments – Serverless architectures remove the need to manage underlying servers or runtimes. By leveraging services like Lambda and API Gateway, you simply deploy application code. This means faster iterations.

Cost savings – With serverless, you only pay for the exact resources used to run your application code. There is no over-provisioning requirement to account for traffic spikes. This can drastically reduce costs.

Auto-scaling capabilities – Serverless applications automatically scale up and down to match demand without any manual intervention. Removing load capacity concerns allows you to focus on code.

Improved development workflows – The SAM CLI lets you build and test serverless apps locally without needing to continuously deploy or interact with the live AWS environment. This makes development faster.

Infrastructure as code – SAM‘s YAML templates allow you to define reusable, version-controlled infrastructure components for consistent deployments across environments.

Let‘s dive into setup!

Prerequisites

Before installing SAM CLI, there are a few requirements:

  • AWS CLI – The AWS Command Line interface must be configured on your workstation to manage services and credentials.
  • Docker – Local SAM runs will leverage Docker images to simulate the Lambda runtime environment.
  • AWS Credentials – An IAM user will need to be configured with appropriate permissions.

If you already meet these prerequisites, feel free to jump to the installation section below. Otherwise, let‘s cover how to get set up properly.

Installing the AWS CLI

The AWS CLI allows you to manage AWS services, resources, and APIs from the command line. It‘s an essential tool for any cloud developer.

Follow the official AWS CLI installation guide for installing on Linux, Windows, or macOS.

Once installed, you can configure the CLI to use your IAM credentials by running:

aws configure

You will need to input:

  • AWS Access Key ID
  • AWS Secret Access Key – These come from an IAM user you have access to
  • Default region name – Example us-east-1
  • Default output format – json

Verify the AWS CLI is working by running a test command like aws s3 ls to list your S3 buckets.

Installing Docker Community Edition

The SAM CLI relies on Docker to provide local simulations of the Lambda runtime environment. Having Docker installed allows you to observe and debug your serverless functions on your workstation by running sam local.

Follow the official Docker CE installation guides for Amazon Linux, Debian, Fedora, CentOS, Ubuntu, and other Linux distros.

For example, on Amazon Linux 2:

sudo yum update -y
sudo amazon-linux-extras install docker
sudo systemctl start docker 
sudo usermod -a -G docker $USER

Once Docker is running, verify it by running:

docker images

Setting Up AWS Credentials and Permissions

The final prerequisite step is to configure an IAM user with credentials and permissions sufficient for SAM CLI usage.

  1. Log into the AWS console and navigate to the IAM dashboard.

  2. Click on Users and then Add user.

  3. Give your user a name like sam-developer and enable programmatic access by clicking the checkbox.

  4. Attach the AdministratorAccess IAM policy to start. This will give full permissions. For production deploys you‘d want to adhere to the principle of least privilege.

  5. Click through to create the user and capture both the Access key ID and Secret access key on the final page.

With the AWS CLI configured earlier, your SAM CLI will now automatically leverage these credentials when interacting with cloud resources and services.

Now let‘s finally install SAM CLI!

Installing the AWS SAM CLI on Linux

With the prerequisites in place, we‘re ready to install the SAM CLI itself. I‘ll cover the steps for an Amazon Linux 2 EC2 instance below.

1. Download the Linux Installer

Visit the AWS SAM GitHub releases page page and copy the link for the 64-bit Linux installer.

For example:

wget https://github.com/aws/aws-sam-cli/releases/latest/download/aws-sam-cli-linux-x86_64.zip

This will download the latest release to your current working directory.

2. Extract SAM CLI

Unzip the installer using unzip. This will extract the contents into a folder called aws-sam-cli-linux-x86_64

unzip aws-sam-cli-linux-x86_64.zip

3. Run the Install Script

Change directory into the extractor folder and execute the install script with sudo permissions.

cd aws-sam-cli-linux-x86_64
sudo ./install

The SAM CLI will now be installed into /usr/local/aws-sam-cli on your Linux environment.

4. Verify the Installation

You can check that the installation succeeded and verify the version by running:

sam --version

For me, this returns SAM CLI, version 1.27.0.

If you ever need to update to a newer version, re-run the install script with the --update flag.

At this point, the AWS SAM CLI is installed and ready to use!

Next, let‘s overview the common commands and workflows.

Main SAM CLI Commands

Now that we have SAM CLI installed, what can we actually do with it? Here I‘ll provide an overview of the most common and useful commands you‘ll leverage while building serverless applications.

# Create SAM app from a template
sam init 

# Build SAM app artifacts and dependencies 
sam build  

# Run SAM app locally 
sam local start-api

# Package SAM app for deployment
sam package --output-template-file packaged-template.yaml

# Deploy SAM app to AWS
sam deploy --template-file packaged-template.yaml

Let‘s explore some of these commands in more depth.

sam init

The sam init command creates a starter SAM template and supporting files for a new serverless application.

It will prompt you for some initial configuration like the runtime for Lambda functions (e.g Node.js, Python), the app template to base off (e.g. Hello World, Quick Start), and the project name.

For example:

sam init --runtime nodejs14.x --app-template hello-world --name my-first-sam-app 

This populates the directory with a simple demo app including:

  • template.yml – The SAM infrastructure-as-code definition
  • hello_world/ – Code for a Lambda function handler
  • events/ – Sample event data to invoke functions
  • tests/ – Example unit test module

The template gives you a starting point to add additional functions, APIs, permissions etc.

sam build

As you customize the application code, you‘ll need to compile everything down into artifacts that can be deployed.

The sam build command does just this by:

  • Zip packaging your Lambda function code
  • Downloading dependencies like npm packages
  • Building containers for custom runtimes if specified

The output prepared artifacts are written to .aws-sam/build folder by default.

For a Node.js app, this looks like:

Running NodejsNpmBuilder:NpmPack
Running NodejsNpmBuilder:CopyNpmrc
Running NodejsNpmBuilder:CopySource
Running NodejsNpmBuilder:NpmInstall
Running NodejsNpmBuilder:CleanUpNpmrc

Build Succeeded!

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Start API: sam local start-api

As this shows, sam build sets up everything you need before running or deploying your application next.

sam local

One of the most powerful SAM CLI capabilities is running your serverless application locally. The sam local command family allows this across a number of different scenarios.

For example, to run a local API endpoint:

sam local start-api

Or to locally test a Lambda function:

sam local invoke HelloWorldFunction

The function execution or API endpoint will operate just like in the cloud. But under the hood, the SAM CLI spins up Docker containers to simulate the Lambda runtime environment.

This unlocks rapid iteration by allowing you to quickly test changes without re-deploying or interacting with remote AWS services.

Let‘s focus specifically on local debugging next, which is incredibly valuable.

Debugging Serverless Apps Locally

Debugging applications running on remote Lambda functions can be challenging. But the SAM CLI has great support for local debugging workflows.

This leverages the sam local invoke command covered earlier.

There are two options to enable debugging:

  1. Debug with an IDE like VS Code

    • Add DebugArgs property to template.yml function
    • Launch sam local invoke in debug mode
    • Attach VS Code debugger to exposed port
  2. Interactive Debugging with PDB

    • Specify a DebugPort property
    • Launch sam local invoke
    • Interact directly with the debugger (Python example)

For example, here is how to setup interactive PDB based debugging in Python:

1. Update SAM template

In template.yml, specify a DebugPort on the function:

MyFunction:
  Type: AWS::Serverless::Function 
  Properties:
    CodeUri: my_function/
    Handler: app.lambda_handler
    Runtime: python3.7
    DebugPort: 5858

2. Run SAM local in debug mode

This will enable the port and pause execution until a debugger attaches:

sam local invoke MyFunction -d 5858  

3. Import PDB and set tracepoints

In your handler code, import Python‘s PDB:

import pdb

def lambda_handler(event, context):

    pdb.set_trace() # Execution will pause here

    return {
        ‘statusCode‘: 200
    }

4. Interact with the debugger

Once code execution hits the tracepoint, the debugger CLI will be activated:

> /opt/python/fakelocal/app.py(5)lambda_handler()
-> return {
(Pdb) 

You can now step through execution, print variables, evaluate expressions etc.

Having this ability to interactively develop and debug locally before deploying to the cloud is extremely beneficial. It encourages fast development iterations.

Okay, with our app debugged and validated – let‘s look at actually deploying next.

Deploying a SAM Application

While hot reloading changes locally is great, eventually you‘ll want to formally deploy your serverless application to AWS.

The SAM CLI handles all the intricate details around packaging artifacts, resolving dependencies between cloud resources, creating stacks in CloudFormation, and managing permissions.

The flow generally consists of:

  1. Use sam package to upload artifacts to S3
  2. Run sam deploy to launch stack

For example:

# Package artifacts
sam package \
    --output-template-file packaged-template.yaml \
    --s3-bucket my-artifacts-bucket

# Deploy to CloudFormation  
sam deploy \
    --template-file packaged-template.yaml \
    --stack-name my-sam-app \       
    --capabilities CAPABILITY_IAM

That‘s it! After just these two commands, your serverless application will be deployed and running in AWS.

The sam deploy command handles translating the SAM YAML template into native CloudFormation, orchestrates stack updates, and monitors rollout progress.

As this shows, getting a complete infrastructure-as-code serverless application deployed takes just minutes thanks to SAM CLI and CloudFormation.

Of course – that means cleaning up afterwards is also just as straightforward when you are done.

Uninstalling AWS SAM CLI

When you no longer need the SAM CLI on your system, uninstalling it is simple.

1. Identify Install Location

Use which sam to identify where the SAM CLI lives:

which sam
/usr/local/bin/sam

2. Remove Binary and Folder

Delete the sam binary and the containing folder:

sudo rm /usr/local/bin/sam  
sudo rm -rf /usr/local/aws-sam-cli

And that‘s it! The AWS SAM CLI has been cleanly removed.

Of course, your serverless application will continue running uninterrupted in the cloud.

Conclusion

The AWS SAM framework and CLI toolbox unlock the simplicity and productivity of serverless for full-stack developers.

SAM‘s simplified infrastructure-as-code templates paired with robust local testing, debugging, and deployment capabilities can greatly accelerate development workflows.

We first looked at the benefits of serverless and SAM – including faster deployments, cost savings, auto-scaling, and improved CI/CD.

We then covered a complete install guide for Linux including all the prerequisites like the AWS CLI, Docker, and setting up IAM credentials.

Finally, we explored some of the most useful sam commands for initializing projects, building artifacts, running and debugging locally, and ultimately deploying applications with best practices.

The AWS SAM model offers the perfect entrypoint for taking advantage of serverless architectures on AWS as a full-stack developer.

I encourage you to try it out on your next project! Let me know if you have any other questions.

Similar Posts