Test AWS Lambda Locally with SAM CLI

published on 09 June 2025

AWS Lambda lets you run code without managing servers. But testing your Lambda functions locally is key to catching bugs early and saving time. The AWS SAM CLI makes this process easier by creating a local environment that mimics AWS Lambda's runtime.

Key Takeaways:

  • Why Test Locally? It speeds up development, reduces debugging costs, and catches issues early. However, it doesn’t fully replicate cloud resource permissions.
  • What You Need: Install Docker, AWS SAM CLI, AWS CLI, Python (if needed), and Git. Verify installations and ensure version compatibility.
  • How to Test: Use SAM CLI commands like sam local invoke (test individual functions), sam local start-api (simulate API Gateway), and sam local start-lambda (emulate Lambda service).
  • Debugging: Attach a debugger using the --debug-port flag, integrate with IDEs like VS Code or PyCharm, and inspect variables in real-time.
  • Best Practices: Use cached builds, warm containers, and environment variable files for efficient testing. Regularly update tools to avoid compatibility issues.
  • Limitations: Local testing doesn’t fully validate permissions, networking, or cloud-specific configurations. Always perform final testing in the cloud.

Quick Commands:

  • Invoke a Function:
    sam local invoke --event event.json MyFunction
    
  • Start API Gateway Locally:
    sam local start-api
    
  • Generate Sample Events:
    sam local generate-event apigateway http-api-proxy > event.json
    

Next Steps: Set up your environment, test locally, and use sam sync for fast cloud validation. While local testing is efficient, always validate in AWS for production readiness.

Setting Up Your Local Testing Environment

Installing Required Tools

To test Lambda functions locally, you'll need to install a few essential tools. Docker is a must-have, as it creates a containerized environment that replicates AWS Lambda's runtime. This is particularly important when using the SAM CLI's --use-container option to build deployment packages.

Next, you’ll need the AWS SAM CLI, a command-line tool designed for building, testing, and deploying serverless applications. The AWS CLI is also necessary for managing authentication and interacting with AWS services. If your Lambda functions are Python-based, ensure you install Python and pip as they’re required for SAM CLI examples. Lastly, Git is needed for the sam init command to download sample applications.

Before installing the SAM CLI, make sure Docker is up and running. If you’re not using Docker Desktop, note that starting with SAM CLI version 1.47.0, any Docker runtime-compatible solution will work. After installing these tools, verify that each one is functioning correctly.

Verifying Installations

Once you’ve installed the required tools, it’s crucial to confirm they’re working properly. The verification steps are similar across different operating systems.

  • Windows: Open Command Prompt or PowerShell and run:
    sam --version
    
    A successful installation will display: SAM CLI, <version>.
  • macOS: First, check the symlink by running:
    which sam
    
    This should return /usr/local/bin/sam. Then, verify the installation with:
    sam --version
    
  • Linux: Run:
    sam --version
    
    If the CLI isn’t found, you may need to add its directory to your PATH.

Additionally, verify Docker and AWS CLI installations by running:

docker --version
aws --version

Once confirmed, ensure all versions are compatible with each other.

Checking Version Compatibility

Keeping your tools up to date is essential to avoid compatibility issues and security risks. AWS frequently updates the SAM CLI to address bugs, introduce new features, and resolve vulnerabilities.

For instance, AWS Security Bulletin AWS-2025-008 highlighted critical vulnerabilities in earlier SAM CLI versions. Versions up to v1.132.0 were affected by CVE-2025-3047, which was resolved in v1.133.0. Similarly, versions up to v1.133.0 were impacted by CVE-2025-3048, resolved in v1.134.0.

"We recommend users upgrade to the latest version to address these issues. Additionally, users should ensure any forked or derivative code is patched to incorporate the new fixes." – AWS Security Bulletin AWS-2025-008

To mitigate these vulnerabilities, upgrade to at least version 1.134.0. After upgrading, rebuild your applications using the following command:

sam build --use-container

This will update symlinks and fully address CVE-2025-3048.

Staying on top of updates ensures your development environment remains secure and efficient, allowing you to effectively test and deploy your Lambda functions locally. Regular upgrades not only protect against vulnerabilities but also enhance your overall workflow.

Using AWS SAM CLI for Local Testing

AWS SAM CLI

Once your local testing environment is set up, you can use the SAM CLI to trigger and examine your Lambda functions in action.

Key Commands for Local Testing

The AWS SAM CLI offers several commands to help you test Lambda functions locally. The main command, sam local, includes subcommands tailored to different testing scenarios.

  • sam local invoke: Perfect for testing individual Lambda functions. This command lets you execute a single function, passing custom event payloads and environment variables to mimic specific scenarios.
  • sam local start-api: Spins up a local HTTP server that simulates API Gateway, allowing you to test Lambda functions integrated with API Gateway endpoints.
  • sam local start-lambda: Creates a local endpoint that emulates the Lambda service. This is particularly useful if you’re testing functions via the AWS CLI or SDKs.
  • sam local generate-event: Generates sample event payloads for various AWS services, providing realistic test data for your functions.

Using Templates and Event Payloads

SAM templates and event payloads simplify local testing by letting you simulate real-world events. For instance, you can generate sample payloads using sam local generate-event and tweak them to match your needs.

Here’s an example of generating an API Gateway HTTP API event payload:

sam local generate-event apigateway http-api-proxy > events/apigateway_event.json

You can then invoke your function with:

sam local invoke --event events/apigateway_event.json

Want to test an S3 PUT event? Generate the payload like this:

sam local generate-event s3 put --bucket amzn-s3-demo-bucket > events/s3.json

And test your function with:

sam local invoke --event events/s3.json S3JsonLoggerFunction

For testing with environment variables, create a file (e.g., locals.json) and pass it with the --env-vars option. This is especially helpful for testing interactions with services like DynamoDB under different configurations.

To explore all event generation options, run:

sam local generate-event --help

When to Use Each Command

Choosing the right SAM CLI command depends on your testing scenario:

  • Use sam local invoke for quick testing of individual functions with specific events or configurations. It’s great for debugging, refining logic, or testing error handling.
  • Use sam local start-api to test functions tied to API Gateway endpoints. This command spins up a local HTTP server, so you can send requests using tools like curl and check responses.
  • Use sam local start-lambda when you need to emulate the Lambda service and invoke functions via the AWS CLI or SDKs, offering fine-grained control over testing.

After making changes to your function code, remember to run sam build if your application includes a .aws-sam directory. For interpreted languages that don’t use this directory, the SAM CLI updates the function automatically, enabling faster iterations.

While local testing is invaluable for development, keep in mind that it doesn’t validate all deployment details, such as permissions between resources. Always perform final testing in the cloud to ensure everything works as expected.

Debugging and Best Practices

Debugging Lambda Functions Locally

The AWS SAM CLI offers powerful tools for debugging your Lambda functions locally. You can set breakpoints, inspect variables, and step through your code, making it easier to identify and fix issues within your development workflow.

To enable debugging, use the --debug-port or -d flag with your SAM commands. For instance, to debug a specific function:

sam local invoke -d 9999 -e event.json HelloWorldFunction

This command runs your function in debug mode on port 9999, waiting for a debugger to connect. Once attached, your IDE can provide features like variable inspection and step-by-step execution.

IDE integration takes debugging a step further. AWS provides toolkits for various popular development environments, making it easier to debug directly from your editor:

IDE Runtime Support AWS Toolkit
Visual Studio Code Node.js, Python, .NET, Java, Go AWS Toolkit for Visual Studio Code
AWS Cloud9 Node.js, Python AWS Cloud9 (with AWS Toolkit)
WebStorm Node.js AWS Toolkit for JetBrains
PyCharm Python AWS Toolkit for JetBrains
IntelliJ Java AWS Toolkit for JetBrains

For example, you can set breakpoints in hello-world/app.json and use watch expressions to monitor variables, including deeply nested objects. By running the command above, you can attach a debugger and execute the code step by step using a launch configuration. This setup allows for real-time debugging, making it easier to troubleshoot and refine your functions.

If you're working with API Gateway, you can debug HTTP-triggered functions by using the sam local start-api command with the debug option:

sam local start-api -d 5858

This launches a local API server in debug mode, enabling you to inspect and debug functions triggered by HTTP requests.

Once your debugging workflow is in place, adopting some best practices can help streamline your local testing process.

Best Practices for Local Testing

To make your local testing efficient, focus on optimizing builds and reducing repetitive steps. The samconfig.toml file is a great way to set default parameters for SAM commands, ensuring consistency and saving time. Here's an example configuration:

[default.build.parameters]
cached = true
parallel = true

[default.local_start_api.parameters]
warm_containers = "EAGER"
env_vars = "env.json"
  • Cached builds (cached = true) and parallel execution (parallel = true) speed up the process by reusing previous build artifacts and running builds concurrently.
  • The --warm-containers option minimizes cold start delays by keeping containers active between invocations. For example:
sam local start-api --warm-containers EAGER

Setting this to "EAGER" preloads all containers at startup, making subsequent function calls nearly instant.

Another useful approach is to eliminate the .aws-sam folder and transpile code into a dist folder while using the tsc -w command to watch for changes. This setup allows you to test updates quickly without rebuilding everything, saving significant time during development.

Managing environment variables is another key step. Use the --env-vars flag to pass a file with local environment variables:

sam local invoke --env-vars locals.json MyFunction

This method lets you test different configurations without altering your code or templates, making it easy to simulate various scenarios.

For faster cloud testing, the sam sync command is a game-changer. While local testing covers most development needs, sam sync allows you to quickly push changes to the cloud for integration testing. It's much faster than a full deployment and helps maintain a rapid feedback loop.

Despite these optimizations, keep in mind that local testing has its limitations.

Local Testing Limitations

While the SAM CLI provides a robust local testing environment, it can't replicate every aspect of AWS's cloud services. Recognizing these limitations will help you design more effective testing strategies.

  • Resource permissions: Local testing doesn't verify whether your function has the correct permissions to access AWS resources like DynamoDB tables or S3 buckets. These checks only occur in the cloud.
  • Service integrations: While SAM CLI simulates many AWS services, the behavior isn't identical to what you'd experience in the cloud. For example, event sources like S3 triggers, DynamoDB streams, or SQS queues might behave differently when emulated locally.
  • Performance differences: Local testing runs on your development machine, which has different CPU, memory, and network characteristics compared to AWS Lambda's environment. A function that works fine locally might run into timeouts or memory limits in the cloud.
  • Networking and VPC configurations: If your Lambda function runs inside a VPC or has specific networking requirements, these setups can't be fully replicated locally.
  • Docker limitations: While Docker helps emulate the cloud environment, it's not perfect. Some nuances of AWS's infrastructure can't be reproduced on your local machine.

Finally, cost considerations are worth noting. While local testing reduces the need for frequent cloud deployments, running tests in the cloud is relatively inexpensive and provides a more accurate representation of your application's behavior. Always validate your functions in the cloud environment before moving to production to ensure everything works as expected.

sbb-itb-6210c22

Troubleshooting Common Issues

Common Issues and Fixes

When testing locally, you might encounter recurring errors. Below are some common problems and their solutions.

Docker errors often occur if Docker isn't properly installed or running. For example, the error message "Running AWS SAM projects locally requires Docker. Have you got it installed?" indicates an issue with Docker's configuration or status. Fixes for this vary by platform:

  • macOS: If you face a Docker socket permission issue, enable the default Docker socket in Docker Desktop settings and restart Docker.
  • Using Colima on macOS: Add export DOCKER_HOST="unix://$HOME/.colima/docker.sock" to your shell configuration file (e.g., .zshrc) so the SAM CLI can locate the Docker socket.
  • Ubuntu: Resolve permission issues by running sudo usermod -aG docker $USER, then log out, log back in, and restart Docker.

Insufficient disk space can trigger errors like "RuntimeError: Container does not exist" since Docker requires adequate storage to function.

Credential configuration issues may lead to errors such as "Failed to create managed resources: Unable to locate credentials." This can be resolved by ensuring AWS credentials are correctly set up via the AWS CLI or environment variables.

Windows file path limitations can cause "FileNotFoundError" when SAM CLI interacts with paths exceeding Windows' maximum length. You can fix this by enabling long paths in Windows 10 (version 1607 or later).

Dependency conflicts might arise when installing AWS SAM CLI with pip alongside other packages. If you see dependency resolver errors, consider using the native package installer or a virtual environment for SAM CLI installation.

Outdated CLI versions can result in errors like "No such command 'remote'." Upgrading to the latest version of AWS SAM CLI resolves compatibility issues and restores access to newer commands.

API Gateway testing issues might return responses such as {"message":"Missing Authentication Token"}. This usually means the test request URL is incorrect. Double-check and adjust the URL to fix the problem.

Network connectivity problems between containers can cause errors like "connect ECONNREFUSED 127.0.0.1:6379" when Lambda functions try to access services like Redis. Ensure that both the function and service containers share the same Docker network, and use the container's IP address or hostname.

These solutions can help you address recurring errors and set the stage for more focused debugging.

How to Isolate Problems

Once common issues are resolved, narrowing down problems requires a step-by-step approach. Here's how to isolate potential causes:

  • Run docker --version and docker ps to confirm Docker is installed and running.
  • Use sam validate to check for syntax errors in your SAM template.
  • Test with a simple "Hello World" function to confirm your SAM CLI installation works correctly. If this runs without issues, the problem likely lies in your application code.
  • Temporarily remove external libraries from your function to identify dependency-related issues.
  • Add the --debug flag to commands for detailed logs, which can help pinpoint specific failures.
  • Print environment variables within your function to check for misconfigurations that might differ between local and cloud setups.
  • Test components separately: use sam local start-api for API Gateway testing and sam local invoke for direct function invocation.
  • On Unix-based systems, verify file permissions to ensure SAM CLI can access required files and execute Docker commands.

Testing Environment Tips

To maintain a stable testing setup, consider these practical tips:

  • Allocate sufficient Docker resources: Configure Docker Desktop with enough memory and CPU to handle Lambda testing. Resource shortages can lead to erratic behavior.
  • Avoid problematic file paths: Use consistent directory names without spaces or special characters to prevent path resolution errors.
  • Manage environment variables: Use separate configuration files for local, development, and production environments to simplify switching between setups.
  • Monitor system resources: Keep an eye on memory and CPU usage during testing, as Lambda functions running locally can be resource-intensive.
  • Keep tools up to date: Regularly update Docker, SAM CLI, and runtime environments to avoid compatibility issues.
  • Document your setup: Record the versions, configuration files, and environment variables you use. This helps team members replicate your environment.
  • Clean up Docker regularly: Run docker system prune to remove unused containers and free up storage.
  • Add health checks: Use simple scripts to verify Docker connectivity, AWS credential availability, and SAM CLI functionality.
  • Use separate testing data: Avoid using production data during tests by relying on local databases or mock services. This minimizes the risk of data corruption and ensures consistent results.

Conclusion

Key Takeaways

The AWS SAM CLI brings the cloud closer to your local machine, making Lambda testing faster and more affordable. By allowing you to simulate the cloud environment locally, it helps verify functionality, reliability, and performance while catching bugs early. This minimizes the risk of encountering problems during cloud testing or deployment, saving both time and money.

With rapid iteration cycles, development becomes more efficient. Instead of waiting for cloud deployments to test every code change, you can immediately validate your Lambda function logic on your local setup. The step-through debugging feature lets you examine code execution, check variables, and fix issues before they ever reach production.

AWS SAM CLI supports the entire lifecycle of serverless applications - from writing and building to deploying, testing, and monitoring. Its shorthand syntax simplifies the declaration of AWS CloudFormation and serverless resources, which are then transformed into infrastructure during deployment.

These practices lay the groundwork for a development workflow that integrates both local and cloud testing effectively.

Next Steps

Incorporate local testing into your development routine to identify issues early and reduce deployment expenses. Begin by setting up your environment with Docker and AWS SAM CLI, and make it a habit to test each code change locally before pushing it to the cloud.

While local testing is powerful, cloud validation remains crucial for aspects like resource permissions that can't be fully replicated locally. After local testing, use tools like the sam sync command to speed up the process of transferring your tested code to the cloud for final checks.

FAQs

How can I test AWS Lambda functions locally using the AWS SAM CLI, and what are its limitations?

The AWS SAM CLI lets you test Lambda functions on your local machine by simulating the runtime environment. With commands like sam local start-lambda and sam local invoke, you can replicate how your Lambda functions behave in the cloud. For instance, using sam local start-lambda creates a local endpoint that mimics the AWS Lambda service. This allows you to invoke your functions through the AWS CLI or SDKs, making it easier to debug and tweak your code without needing to deploy it to AWS.

That said, there are some limitations to keep in mind. The local environment may not fully match the cloud setup, especially when it comes to AWS service integrations, network settings, or IAM roles. For example, permissions and execution contexts in your local setup might behave differently compared to a live AWS environment, potentially leading to issues during deployment. Additionally, some event sources or more advanced features of AWS services might not be fully supported in the local simulation.

How can I efficiently test AWS Lambda functions locally using the SAM CLI?

To test AWS Lambda functions on your local machine using the SAM CLI, you'll need to set up a few tools first. Install the SAM CLI, Docker, and any other necessary dependencies. Once that's done, create a SAM project and take some time to understand its template structure - it'll make your workflow smoother.

You can use commands like sam local invoke to run individual Lambda functions or sam local start-api to test API Gateway endpoints. These commands create a local environment that mimics AWS, allowing you to debug and iterate on your code without racking up cloud costs. If you need more in-depth debugging, you can set breakpoints and step through your code using the SAM CLI's debugging features.

For testing that closely mirrors production, set up environment variables to match your live configuration. You should also use local mocks for any AWS services your Lambda functions interact with. This method helps catch potential issues early, making your functions more reliable and efficient before deployment.

How can I fix common issues with Docker or AWS credentials when testing Lambda functions locally using the AWS SAM CLI?

When troubleshooting common problems during local testing with the AWS SAM CLI, focus on these two critical areas:

Docker Issues

First, make sure Docker is properly installed, running, and accessible. If you see errors like "Cannot connect to the Docker daemon", it’s likely a permissions issue. Double-check that your user has the necessary permissions to interact with Docker. For sluggish performance, tweaking Docker's resource allocation - such as increasing CPU or memory limits - can make a noticeable difference.

AWS Credentials

Next, confirm that your AWS credentials are set up correctly by using the aws configure command. If you're working inside a Docker container, remember to pass your credentials as environment variables or mount your .aws directory to maintain access.

By tackling these two areas, you can fix many of the common hiccups you might face when testing Lambda functions locally with the AWS SAM CLI.

Related posts

Read more