DevOps

AWS SAM: Build And Deploy Lambda Effortlessly

Let’s discuss the AWS Serverless Application Model (SAM), which has completely transformed how I build and deploy cloud applications. Before discovering SAM, I wasted countless hours manually configuring AWS resources for my serverless application. Those days were frustrating. 😩

When I first started with AWS Lambda, I built everything through the console UI. Clicking around, copy-pasting code, praying nothing would break. Then I discovered infrastructure as code, and finally AWS SAM, which combines the best parts of serverless and DevOps practices. The difference was night and day!

AWS SAM is an open-source framework that simplifies serverless development on AWS. It extends CloudFormation to provide shorthand syntax for Lambda functions, APIs, databases, and event source mappings.

Why AWS SAM Will Change Your Development Life

SAM isn’t just another tool—it’s a complete game-changer for serverless development. Here’s why you absolutely need to adopt it:

  1. Simplifies CloudFormation – Writes 10 lines of code instead of 100+ lines of raw CloudFormation
  2. Local testing – Test your Lambda functions locally before deploying to the cloud
  3. Streamlined deployments – One command to package and deploy your entire application
  4. Built-in best practices – Encourages infrastructure as code from day one

Getting Started: Setting Up Your SAM Environment

Let’s dive right in! First, you’ll need to install the AWS SAM CLI.

Prerequisites:

  • An active AWS account
  • AWS CLI installed and configured
  • Docker (for local testing)
  • Python (if you’re developing a Python-based lambda)

Installation Steps:

If you are a macOS user like me (using Homebrew):

brew tap aws/tap
brew install aws-sam-cli

Windows users:

# Download the installer
# Run the .msi fileCode language: PHP (php)

And finally, for Linux users:

pip install aws-sam-cli

Once installed, verify with:

sam --version

Tip 💡: The first time I installed SAM, I forgot to set up my AWS credentials first. Don’t make the same mistake! Run aws configure Before you start using SAM.

Creating Your First SAM Application

Let’s create a simple API that returns a greeting message:

# Create a new SAM application
sam init

# Select AWS Quick Start Templates
# Choose Hello World Example
# Select your preferred runtime (I'll use Python)Code language: PHP (php)

This command creates a folder structure with everything you need. The most important file is template.yaml—This defines all your AWS resources using SAM syntax. Here’s what your template might look like:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambdaHandler
      Runtime: python3.13
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: getCode language: PHP (php)

This simple template creates:

  • A Lambda function using code from the hello_world directory
  • An API Gateway endpoint that triggers the function on GET requests to /hello

Building and Testing Locally

One of the biggest advantages of SAM is local testing. Before I discovered this feature, I was deploying every small change to AWS in a staging environment to test it. What a waste of time!

Build your application locally(make sure you are in the app directory):

sam build

Now, let’s run it:

sam local start-api

Visit http://localhost:3000/hello In your browser, you should see your Lambda function’s response! 🎉

You can also invoke individual functions:

sam local invoke HelloWorldFunction

Deploying to AWS

So, are you ready to go live? Deploying with SAM is incredibly simple:

sam deploy --guided

The --guided Flag walks you through configuration options the first time. It creates a samconfig.toml file that stores your preferences for future deployments.

During my first deployment, I was shocked at how quickly it was. SAM automatically packaged my code, uploaded it to S3, created all the resources, and gave me an API endpoint URL—all in a couple of minutes!

Automating Deployments with GitHub Actions

Manual deployments are suitable for learning, but in real-world projects, you’ll want to utilize automation. Let’s set up GitHub Actions to deploy our SAM application whenever we push to the main branch.

To start, let’s create a file at .github/workflows/deploy.yml:

name: Deploy SAM Application

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Setup AWS SAM CLI
        uses: aws-actions/setup-sam@v1
      
      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-1
      
      - name: Build and Deploy
        run: |
          sam build
          sam deploy --no-confirm-changeset --no-fail-on-empty-changesetCode language: HTTP (http)

Don’t forget to add your AWS credentials as secrets in your GitHub repository settings!

I implemented this workflow for a client project last year, and it eliminated all manual deployments. The team could focus on writing code while GitHub Actions handled the rest. Our deployment errors dropped to zero!

Adding DynamoDB Tables and More Resources

SAM makes it easy to add additional AWS resources. Let’s enhance our application with a DynamoDB table:

Resources:
  # ... existing resources ...
  
  UsersTable:
    Type: AWS::Serverless::SimpleTable
    Properties:
      PrimaryKey:
        Name: userId
        Type: StringCode language: PHP (php)

To give your Lambda function permission to access this table, add:

HelloWorldFunction:
  Type: AWS::Serverless::Function
  Properties:
    # ... existing properties ...
    Policies:
      - DynamoDBCrudPolicy:
          TableName: !Ref UsersTable
    Environment:
      Variables:
        USERS_TABLE: !Ref UsersTableCode language: PHP (php)

I once struggled for days with IAM permissions before discovering SAM’s policy templates. They automatically generate the correct IAM roles for common scenarios, saving hours of debugging cryptic permission errors.

Troubleshooting Common Issues

Even with SAM’s simplicity, you’ll hit some bumps along the way. Here are solutions to problems I’ve faced:

1. Deployment Errors

If you see CloudFormation stack errors:

sam logs -n FunctionName --stack-name your-stack-name

2. Local Testing Issues

If local testing fails with Docker errors, make sure Docker is running:

docker ps

3. Permission Problems

IAM is always tricky. If your function can’t access resources:

  • Check the function’s execution role
  • Verify you’re using the right policy templates
  • Double-check resource names and references

4. Cold Start Performance

Lambda functions can be slow on first execution. Consider:

  • Using Provisioned Concurrency
  • Optimizing your function’s code size
  • Moving initialization code outside the handler

Limitations and Best Practices

While SAM is amazing, be aware of these limitations:

  1. CloudFormation limits – SAM is built on CloudFormation, so it inherits its constraints (stack resource limits, update behaviors)
  2. Local testing differences – Some services can’t be fully emulated locally
  3. Debugging complexity – Distributed systems are inherently harder to debug

Best practices I’ve learned the hard way:

  1. Keep functions focused – One function, one responsibility
  2. Optimize package sizes – Smaller packages deploy faster and start quicker
  3. Use environment variables – Externalize configuration from code
  4. Structure your project well – Organize by feature, not by function type

Next Steps in Your Serverless Journey

Now that you’ve mastered the basics of AWS SAM, where should you go next?

  1. Explore step functions for orchestrating complex workflows
  2. Implement observability with AWS X-Ray and CloudWatch
  3. Add authentication to your APIs with Amazon Cognito
  4. Create custom layers for shared code between functions

Conclusion: Embrace the Serverless Revolution

AWS SAM transformed how I build cloud applications. The serverless approach eliminates infrastructure management, allowing me to focus solely on business logic. SAM makes this even easier by simplifying resource definitions and providing local testing capabilities. The productivity gains are substantial and real.

Have you tried AWS SAM yet? What serverless projects are you working on? Remember, the biggest mistake is overthinking it—start small, experiment, and build your way up to more complex architectures.

Happy serverless coding! 🚀

Frequently Asked Questions

How do I uninstall AWS SAM CLI?
brew uninstall aws-sam-cli on macOS, or choco uninstall aws-sam-cli on Windows. Removes everything but your stacks.

Can I combine SAM with Terraform?
Absolutely. Deploy supporting resources (VPC, RDS) via Terraform, output their ARNs, and reference them in your SAM template.

Is AWS SAM free?
Yes. The CLI and transform are open‑source. You only pay for the underlying AWS services you deploy.

What is the best way to delete a stack that SAM CLI created?
Easy. Just run sam delete , and it will take care of the rest!

Rana Ahsan

Rana Ahsan is a seasoned software engineer and technology leader specialized in distributed systems and software architecture. With a Master’s in Software Engineering from Concordia University, his experience spans leading scalable architecture at Coursera and TopHat, contributing to open-source projects. This blog, CodeSamplez.com, showcases his passion for sharing practical insights on programming and distributed systems concepts and help educate others. Github | X | LinkedIn

Recent Posts

Service Workers in React: Framework Integration Guide

Learn how to integrate service workers in React, Next.js, Vue, and Angular with practical code examples and production-ready implementations for modern web applications.

2 weeks ago

Service Worker Caching Strategies: Performance & Offline Apps

Master the essential service worker caching strategies that transform web performance. Learn Cache-First, Network-First, and Stale-While-Revalidate patterns with practical examples that'll make your apps blazingly…

3 weeks ago

Service Worker Lifecycle: Complete Guide for FE Developers

Master the intricate dance of service worker states and events that power modern PWAs. From registration through installation, activation, and termination, understanding the lifecycle unlocks…

4 weeks ago

This website uses cookies.