If you're building serverless apps on AWS, you’ve probably come across AWS SAM CLI.
At first, it feels like just another tool… but once you understand it, you realize:
It’s basically CloudFormation on steroids (CloudFormation++) with developer superpowers.
Let’s break it down step by step.
🤔 What is AWS SAM?
AWS SAM (Serverless Application Model) is a framework that makes it easier to build and deploy Serverless applications.
👉 One of the things that stands out about SAM is its ability to bundle Lambda function code - something you don’t get out of the box with CloudFormation.
To clarify that a bit:
CloudFormation is primarily focused on defining infrastructure
SAM, on the other hand, goes a step further by handling:
Packaging your code (zipping it)
Uploading it to S3
Creating and deploying the CloudFormation stack
In simple terms, SAM bridges the gap between application code and infrastructure, making the whole deployment process much smoother.
🧠 How SAM actually works
SAM is an extension of CloudFormation and introduces simplified resource types like:
Type: AWS::Serverless::FunctionYou can reference local code directly:
CodeUri: ./src/Behind the scenes, SAM:
Zips your code
Uploads it to S3
Rewrites the template with S3 locations
🔥 Important Insight
SAM templates are a superset of CloudFormation
Any CloudFormation template works with SAM
SAM supports all CloudFormation resource types
Adds additional abstractions for serverless
👉 Think of it as: CloudFormation++
⚙️ Overview: How Deployment Works
Deploying with SAM is surprisingly simple and follows a consistent flow:
sam init→ create projectEdit
template.yaml→ define infrastructuresam build→ prepare artifactssam deploy→ upload and deploy
Under the hood:
sam buildcompiles your code and generates artifacts in.aws-sam/buildsam deployuploads both code and template to S3 (managed artifact bucket) and triggers a CloudFormation deployment
🛠️ Install SAM CLI
Refer official docs: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html
Verify installation:
sam --version📁 Initialize a SAM Project
sam initThis provides a guided setup:
Choose runtime (Python, .NET, etc.)
Select a starter template
📦 Project Structure
sam-app/
├── app.py
├── template.yaml
├── requirements.txt
└── events/📄 Understanding template.yaml
This is the heart of your application — it defines your infrastructure.
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.lambda_handler
Runtime: python3.9
CodeUri: .Key takeaway:
CodeUrican point to a local directorySAM automatically handles packaging and uploading
🔨 Build & Deploy
Build
sam buildArtifacts are generated in:
.aws-sam/build/Deploy (first time)
sam deploy --guidedIt configures:
Stack name
Region
S3 bucket (auto-created if you choose Yes)
More importantly, it stores all these values in samconfig.toml
👉 Always run sam deploy --guided initially so that proper defaults are stored. Subsequent deployments can simply use sam deploy without re-entering values.
Deploy (subsequent times)
sam deploySAM reuses configuration from:
samconfig.toml🧠 Best Practices
SAM deploys artifacts from the .aws-sam directory — not your source code. So whenever you make changes, always rebuild before deploying:
sam build
sam deployFor first-time deployments, use sam deploy --guided. After that, a simple sam deploy is enough since configurations are stored in samconfig.toml.
SAM automatically writes your deployment preferences into this file, which makes repeated deployments much smoother and less error-prone.
🧪 Working on an Existing SAM Project
No need to reinitialize.
Just run:
sam build
sam deployAlso note:
sam deploynow implicitly includes the functionality ofsam package
So you no longer need separate packaging steps.
⚙️ Advanced Flags You Should Know
You can let SAM create an S3 bucket automatically:
sam deploy --resolve-s3When you run it, SAM walks you through a series of prompts, including whether it should locate or create a managed S3 bucket. If you choose “Yes,” SAM automatically creates the bucket (similar to using --resolve-s3) and saves this configuration in samconfig.toml, so you don’t have to repeat the setup in future deployments.
Or explicitly provide one (recommended for CI/CD):
sam deploy --s3-bucket my-bucket🌍 Multi Environment Workflow - Important ❕
For development environments, SAM makes things very convenient by automatically managing artifact storage.
When you run
sam deployorsam deploy --guided, SAM creates a hidden CloudFormation stack:aws-sam-cli-managed-defaultThis stack provisions an S3 bucket used for storing deployment artifacts.
During
sam deploy --guided, SAM:Checks if a managed bucket already exists in that region
Reuses it if available
Otherwise creates a new one
🏗️ Best Practice for Higher Environments
While SAM-managed buckets are great for development, for staging and production you should not rely on defaults.
Instead, create dedicated buckets per environment:
myapp-dev-artifactsmyapp-stage-artifactsmyapp-prod-artifacts
⚙️ Use Custom Buckets in Deployment
sam deploy \
--s3-bucket myapp-dev-artifacts \
--region ap-south-1 \
--no-confirm-changeset \
--no-fail-on-empty-changeset💡 Why this matters
Better control over environments
Clear separation of artifacts
Easier debugging and auditing
Required for enterprise-grade CI/CD
⚠️ About Deployment Flags
--no-confirm-changesetSkips manual confirmation during deployment--no-fail-on-empty-changesetPrevents pipeline failures when no changes are detectedRollback behavior (default recommended):
❌ Do NOT disable rollback in most cases
✔ Keep rollback enabled so failed deployments revert safely
❓ Common Questions
Does SAM upload template and artifacts to the same bucket?
Yes, by default SAM uploads:
Packaged CloudFormation template
Lambda artifacts (zip files)
These are usually stored in the same S3 bucket, separated by prefixes.
How does SAM create bucket or ECR repo automatically?
When using sam deploy --guided or --resolve-s3, SAM:
Generates a unique bucket name
Uses account ID, region, and random suffix
Example:
aws-sam-cli-managed-default-samclisourcebucket-xyz👉 These SAM-managed artifact buckets are created per AWS account + region.
So if you deploy the same application in multiple regions, SAM will automatically create separate buckets for each region.
For container-based Lambdas, it similarly creates ECR repositories if needed.
How to explicitly control them (CI/CD friendly)?
You can (and should) specify them explicitly:
sam deploy \
--s3-bucket my-artifacts-bucket \
--image-repository my-ecr-repo \
--region ap-south-1This makes deployments:
Predictable
Environment-specific
CI/CD friendly
✅ Recommended Approach
Use your own CI/CD (GitHub Actions, Jenkins, etc.) and run:
sam build
sam deploy \
--s3-bucket my-bucket \
--image-repository my-ecr \
--no-confirm-changeset \
--no-fail-on-empty-changesetThis approach:
Removes dependency on
samconfig.tomlfor environment specific configurationsKeeps things explicit
Works across any CI/CD system
🧠 Final Mental Model
Think of SAM as a pipeline:
Your Code + template.yaml
↓
sam build
↓
.aws-sam/build (artifacts)
↓
sam deploy
↓
S3 upload + CloudFormation stack🚀 Quick Starter (TL;DR)
If you just want to get going or need a quick refresher:
sam initSelect appropriate template/runtime
sam buildsam deploy --guided(first time - stores config in samconfig.toml)Later:
sam buildsam deploy
For higher environments, create artifacts buckets by your own, and execute following commands in the pipeline.
sam buildsam deploy --s3-bucket my-bucket --no-confirm-changeset --no-fail-on-empty-changeset
🎯 Final Thoughts
AWS SAM simplifies serverless development by:
Removing packaging complexity
Reducing CloudFormation boilerplate
Enabling faster iteration
But the real power comes when you:
Understand what happens under the hood
Take control of deployment (especially in CI/CD)
