AWS SAM Local lets you test serverless apps on your computer before deploying to the cloud. Here's how to set it up:
-
Install prerequisites:
- AWS account
- Docker
- AWS CLI
- Python 3.7+
- AWS SAM CLI
-
Configure AWS credentials:
aws configure
-
Create a new SAM project:
sam init
-
Build your app:
sam build
-
Test locally:
sam local invoke sam local start-api
Key benefits:
- Test Lambda functions locally
- Debug in your IDE
- Simulate API Gateway events
- View function logs on your machine
Common issues:
- Docker not running
- Outdated SAM CLI version
- Missing AWS credentials
- Incorrect template.yaml file
Remember: Local testing is just the start. Always test in the cloud too for a complete picture of your app's performance.
Related video from YouTube
Prerequisites
Before you start with AWS SAM Local, you need a few things in place. Let's go through the essentials:
AWS Account Setup
First, you need an AWS account. Don't have one? Here's what to do:
- Go to https://portal.aws.amazon.com/billing/signup
- Follow the prompts to create your account
- This process will create an AWS account root user
Once that's done, create an IAM user for CLI access:
- Sign in to the AWS Management Console
- Go to the IAM service
- Create a new IAM user with programmatic access
- Give it the right permissions (like AWSLambdaFullAccess and AmazonAPIGatewayAdministrator)
- Save the access key ID and secret access key somewhere safe
"For CLI access, create an access key ID and secret access key. Use temporary credentials instead of long-term access keys when possible." - AWS Documentation
Docker Setup
Docker is key for AWS SAM Local. It mimics the AWS Lambda environment on your machine. Here's how to set it up:
For Amazon Linux 2:
sudo amazon-linux-extras install docker
sudo service docker start
sudo usermod -a -G docker ec2-user
For Amazon Linux 2023:
sudo yum install -y docker
sudo service docker start
sudo usermod -a -G docker ec2-user
After installing, log out and back in. Then check if it's working:
docker ps
Having trouble? Check out the Docker Docs for troubleshooting tips.
Development Tools
You'll also need:
- Python: Get it from https://www.python.org/downloads/
- AWS CLI: Follow the AWS Command Line Interface User Guide to install
- Visual Studio Code: Download from http://code.visualstudio.com/ (or use your favorite IDE)
Software Versions
Make sure you've got the right versions:
Software | Minimum Version | Check Version With |
---|---|---|
Python | 3.7 or later | python --version |
AWS CLI | 2.0 or later | aws --version |
AWS SAM CLI | Latest | sam --version |
Docker | Latest stable | docker --version |
"Starting September 2023, AWS will no longer maintain the AWS managed Homebrew installer for the AWS SAM CLI. Users are encouraged to switch to the community managed installer." - AWS SAM CLI Documentation
Keep these tools up to date for the best experience with AWS services.
Installing Required Software
To use AWS SAM Local, you need Docker, AWS CLI, and AWS SAM CLI. Here's how to set them up:
Docker
Docker lets you test serverless apps locally. Install it like this:
Amazon Linux 2:
sudo amazon-linux-extras install docker
sudo service docker start
sudo usermod -a -G docker ec2-user
Amazon Linux 2023:
sudo yum install -y docker
sudo service docker start
sudo usermod -a -G docker ec2-user
Log out, log back in, then check if Docker works:
docker ps
For Windows and macOS, grab Docker Desktop from Docker's website and install it.
AWS CLI
AWS CLI helps set up your AWS credentials. Here's what to do:
- Get the AWS CLI installer for your system from AWS's website.
- Install it.
- Open a new terminal and run:
aws --version
- Set up your AWS credentials:
aws configure
You'll need to enter your AWS Access Key ID, Secret Access Key, default region, and output format.
AWS SAM CLI
Now, let's get AWS SAM CLI:
macOS:
- Download the right
.pkg
file:- Intel:
aws-sam-cli-macos-x86_64.pkg
- Apple silicon:
aws-sam-cli-macos-arm64.pkg
- Intel:
- Run it and follow the steps.
- Install to
/usr/local/aws-sam-cli
. - Check it's working:
which sam
sam --version
Windows:
- Get the AWS SAM CLI 64-bit MSI installer.
- Run it.
- Open PowerShell and check:
sam --version
Linux:
- Download the installer for your system.
- Run these commands:
sudo ./sam-installation-package.sh install
sam --version
The installer creates a symlink between
/usr/local/bin/sam
and/usr/local/aws-sam-cli/sam
(or your chosen folder) so you can use thesam
command.
Heads up: Since September 2023, AWS doesn't maintain the Homebrew installer for AWS SAM CLI. Stick to these methods instead.
Setting Up Configurations
You've got the software installed. Now let's set up your environment for AWS SAM Local. We'll cover AWS credentials, SAM CLI config, Docker settings, and environment variables.
AWS Credentials
First, set up your AWS credentials:
- Open your terminal
- Run:
aws configure
- Enter your AWS Access Key ID, Secret Access Key, default region, and output format when prompted.
This info gets stored in a default
profile in your home directory's credentials and config files.
SAM CLI Config
The SAM CLI uses a samconfig.toml
file for project settings. Here's a sample:
version = 0.1
[default]
[default.global.parameters]
stack_name = "sam-app"
[default.build.parameters]
cached = true
parallel = true
[default.deploy.parameters]
capabilities = "CAPABILITY_IAM"
confirm_changeset = true
resolve_s3 = true
[default.sync.parameters]
watch = true
[default.local_start_api.parameters]
warm_containers = "EAGER"
You can customize these settings. For example, to set different parameters for production:
[prod]
[prod.sync.parameters]
watch = false
To use a specific config when deploying:
sam deploy --config-env "prod"
Docker Setup
Docker mimics the AWS Lambda environment locally. Here's what you need to do:
- Start Docker:
sudo service docker start
- Add your user to the docker group:
sudo usermod -a -G docker ec2-user
Log out and back in for this to take effect.
- If you need to run Lambda functions with a different architecture than your machine:
docker run --rm --privileged multiarch/qemu-user-static --reset -p yes
This is handy for running arm64
functions on an x86_64
machine.
Environment Variables
Managing different configs across environments is crucial. Here's how:
- Define parameters in your SAM template:
Parameters:
EnvType:
Type: String
Default: dev
AllowedValues:
- dev
- prod
- Use these parameters in your function resources:
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Environment:
Variables:
ENV_TYPE: !Ref EnvType
- Access these variables in your Lambda function:
import os
env_type = os.environ['ENV_TYPE']
- Provide values during deployment:
sam deploy --parameter-overrides EnvType=prod
This lets you maintain different configs for dev and prod without changing your code.
sbb-itb-6210c22
Setting Up Local Development
Let's dive into setting up your local environment for AWS SAM. It's not rocket science, but it's crucial for smooth serverless development.
First, fire up your terminal and run:
sam init
This creates a new SAM project with a structure like this:
sam-app/
├── README.md
├── events/
│ └── event.json
├── hello_world/
│ ├── app.py
│ └── requirements.txt
├── template.yaml
└── tests/
└── unit/
└── test_handler.py
Your Lambda function code lives in hello_world
, and template.yaml
is where the magic happens for your app's infrastructure.
Now, let's talk about the template.yaml
file. It's the backbone of your SAM app, defining your serverless resources. Here's a simple example:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: SAM Template for hello-world app
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.9
This template sets up a basic Lambda function. As you build out your app, you'll add more resources here.
Time to write some code. Open up hello_world/app.py
and add this:
import json
def lambda_handler(event, context):
return {
"statusCode": 200,
"body": json.dumps({
"message": "Hello from Lambda!"
}),
}
This function just returns a simple JSON response when called.
Want to test your function locally? No problem. Run these commands:
sam build
sam local invoke HelloWorldFunction
sam build
preps your app by creating a .aws-sam
directory. Then, sam local invoke
runs your function in a Docker container that mimics Lambda.
Need to test with a custom event? Create a JSON file (like events/custom-event.json
) and run:
sam local invoke HelloWorldFunction --event events/custom-event.json
For API testing, use:
sam local start-api
This fires up a local HTTP server so you can test your API endpoints.
"The SAM CLI provides a Lambda-like execution environment that lets you locally build, test, and debug applications defined by SAM templates." - Jon Bonso, Co-founder of Tutorials Dojo
Fix Common Problems
Setting up AWS SAM Local can be tricky. Let's tackle some common issues and how to solve them.
Docker Issues
Docker is key for AWS SAM Local, but it can cause headaches. Here's how to fix common Docker problems:
1. Docker not running
If you see this:
Running AWS SAM projects locally requires Docker. Have you got it installed?
Docker isn't running. To fix:
- Linux: Run
sudo service docker start
- macOS/Windows: Open Docker Desktop
2. Wrong Docker version
SAM Local needs a recent Docker version. If you're getting weird errors, update Docker:
docker --version
If it's old, get the latest from Docker's website.
3. Docker permission issues
On Linux, you might lack Docker permissions. Fix with:
sudo usermod -aG docker $USER
Log out and back in for it to work.
Permission Errors
Permission errors pop up when SAM can't access what it needs. Here's how to fix them:
1. AWS credentials not set
Seeing this?
Failed to create managed resources: Unable to locate credentials
Your AWS credentials aren't set up. Fix it:
aws configure
Enter your AWS Access Key ID and Secret Access Key when asked.
2. File permission issues
If SAM can't read your files, check their permissions:
ls -l
Files should be at least 644 (rw-r--r--). If not, fix with:
chmod 644 filename
Configuration Problems
Configuration issues can be sneaky. Here's how to spot and fix them:
1. Missing stack name
Getting this?
Error: Can't find exact resource information with given stack name
You forgot the stack name. Use:
sam remote invoke --stack-name your-stack-name
2. Incorrect SAM template
Check your template.yaml
. Common mistakes:
- Indentation errors
- Missing required fields
- Wrong resource types
Validate your template:
sam validate
Version Issues
Version conflicts can be a pain. Here's how to fix them:
1. Outdated SAM CLI
Weird errors? Your SAM CLI might be old. Update it:
pip install --upgrade aws-sam-cli
2. IDE plugin version mismatch
Make sure your IDE plugin works with your SAM CLI version. For example, AWS Toolkit version 1.10 needs SAM CLI version 0.41.0 or later.
"Even after updating to version 1.10, you might STILL GET THIS ERROR." - Steve Maurer
If updating doesn't help, try uninstalling and reinstalling both the SAM CLI and your IDE plugin.
When all else fails, check the AWS SAM CLI troubleshooting guide. It's updated often with solutions to the latest developer issues.
Conclusion
AWS SAM Local is a game-changer for serverless development. It lets you build, test, and debug your apps locally before cloud deployment. Here's a quick recap:
1. Set up your environment
Install Docker, AWS CLI, and AWS SAM CLI. Configure your AWS credentials and SAM CLI settings.
2. Create your project
Use sam init
to set up your project structure. Write your Lambda functions and define resources in template.yaml
.
3. Test locally
Use sam local invoke
and sam local start-api
to test your functions on your machine.
But remember: local testing is just the start. Kari Marttila, an AWS dev pro, says:
"When developing AWS Lambda code, you have several options to speed up the development cycle - if you are using Python, you should do most of the application logic just using the Python interpreter."
This can cut down your dev time big time. Running app logic in the Python interpreter is instant, while SAM can take about 20 seconds to build and invoke.
Don't skip cloud testing, though. AWS Prescriptive Guidance makes it clear:
"Testing in the cloud is valuable for all phases of testing, including unit tests, integration tests, and end-to-end tests."
To speed up cloud testing, check out AWS SAM Accelerate or AWS CDK watch mode. They'll help you push code changes to the cloud faster, so you can experiment more quickly.
As you dive deeper into AWS SAM, keep these tips in mind:
- Update your SAM CLI regularly
- Use
sam validate
to catch template issues early - Try
sam sync
for faster cloud testing - Keep your Lambda handler file lean and move logic to separate modules for quicker local testing
FAQs
How to configure sam cli?
Setting up the AWS SAM CLI is pretty straightforward:
1. Create your app
Run sam init
to set up your project. This gives you a basic template to work with.
2. Set up your infrastructure
Open the template.yaml
file. This is where you'll define your app's resources and permissions. Here's a simple example:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./
Handler: app.lambda_handler
Runtime: python3.9
3. Build your app
Use sam build
to get your app ready for deployment. This creates a .aws-sam
folder with your built stuff.
Pro tip: If you're using Node.js functions, try esbuild for faster builds.
How to install SAM in AWS?
Here's how to get SAM up and running:
- Sign up for AWS if you haven't already.
- Create an admin IAM user for safe access.
- Get your access key ID and secret key.
- Install the AWS CLI (method depends on your OS).
- Run
aws configure
to set up your AWS credentials.
Now, let's install SAM CLI:
- macOS: Download and run the
.pkg
file for your system. - Windows: Use the 64-bit MSI installer.
- Linux: Download the installer and run the script.
To make sure it worked, just type:
sam --version
Does Sam local use Docker?
Yep, SAM Local uses Docker to mimic the AWS Lambda environment on your machine. It's like having a mini-AWS on your computer.
SAM officially supports Docker Desktop, but since version 1.47.0, you can use other Docker runtimes if they play nice with the Docker API.
To get SAM Local working:
-
Install Docker. On Amazon Linux 2, it's:
sudo amazon-linux-extras install docker sudo service docker start sudo usermod -a -G docker ec2-user
-
Check if Docker's running:
docker ps
- When you use SAM Local, it'll automatically grab the Docker images it needs to fake the Lambda environment.