{"id":21072444,"url":"https://github.com/binarymist/aws-sam-local","last_synced_at":"2025-03-14T03:10:46.434Z","repository":{"id":46060753,"uuid":"301585108","full_name":"binarymist/aws-sam-local","owner":"binarymist","description":null,"archived":false,"fork":false,"pushed_at":"2021-11-16T22:31:57.000Z","size":13458,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"PaulMaddox-patch-1","last_synced_at":"2025-01-20T22:12:32.511Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/binarymist.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-10-06T01:41:55.000Z","updated_at":"2020-10-06T01:44:06.000Z","dependencies_parsed_at":"2022-07-22T19:02:55.764Z","dependency_job_id":null,"html_url":"https://github.com/binarymist/aws-sam-local","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binarymist%2Faws-sam-local","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binarymist%2Faws-sam-local/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binarymist%2Faws-sam-local/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/binarymist%2Faws-sam-local/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/binarymist","download_url":"https://codeload.github.com/binarymist/aws-sam-local/tar.gz/refs/heads/PaulMaddox-patch-1","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243515569,"owners_count":20303258,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-19T18:56:35.150Z","updated_at":"2025-03-14T03:10:46.399Z","avatar_url":"https://github.com/binarymist.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://github.com/awslabs/aws-sam-local\" align=\"center\"\u003e\n    \u003cimg src=\"media/sam-local-banner.png\" alt=\"SAM Local\" title=\"SAM\" align=\"center\" /\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n# SAM Local (Beta)\n\n[![Build Status](https://travis-ci.org/awslabs/aws-sam-local.svg?branch=develop)](https://travis-ci.org/awslabs/aws-sam-local) ![Apache-2.0](https://img.shields.io/npm/l/aws-sam-local.svg?maxAge=2592000) ![Contributers](https://img.shields.io/github/contributors/awslabs/aws-sam-local.svg?maxAge=2592000) ![GitHub-release](https://img.shields.io/github/release/awslabs/aws-sam-local.svg?maxAge=2592000) ![npm-release](https://img.shields.io/npm/v/aws-sam-local.svg?maxAge=2592000)\n\n **`sam`** is the AWS CLI tool for managing Serverless applications written with [AWS Serverless Application Model (SAM)](https://github.com/awslabs/serverless-application-model). SAM Local can be used to test functions locally, start a local API Gateway from a SAM template, validate a SAM template, and generate sample payloads for various event sources.\n\n- [SAM Local (Beta)](#sam-local-beta)\n    - [Main features](#main-features)\n    - [Installation](#installation)\n        - [Prerequisites](#prerequisites)\n        - [Windows, Linux, OSX with NPM [Recommended]](#windows-linux-osx-with-npm-recommended)\n        - [Binary release](#binary-release)\n        - [Build From Source](#build-from-source)\n    - [Usage](#usage)\n        - [Invoke functions locally](#invoke-functions-locally)\n        - [Generate sample event source payloads](#generate-sample-event-source-payloads)\n        - [Run API Gateway locally](#run-api-gateway-locally)\n        - [Debugging Applications](#debugging-applications)\n            - [Debugging Python functions](#debugging-python-functions)\n        - [Validate SAM templates](#validate-sam-templates)\n        - [Package and Deploy to Lambda](#package-and-deploy-to-lambda)\n    - [Getting started](#getting-started)\n    - [Advanced](#advanced)\n        - [Compiled Languages (Java)](#compiled-languages-java)\n        - [IAM Credentials](#iam-credentials)\n        - [Lambda Environment Variables](#lambda-environment-variables)\n            - [Environment Variable file](#environment-variable-file)\n            - [Shell environment](#shell-environment)\n            - [Combination of Shell and Environment Variable file](#combination-of-shell-and-environment-variable-file)\n        - [Identifying local execution from Lambda function code](#identifying-local-execution-from-lambda-function-code)\n        - [Static Assets](#static-assets)\n        - [Local Logging](#local-logging)\n        - [Remote Docker](#remote-docker)\n    - [Project Status](#project-status)\n    - [Contributing](#contributing)\n    - [A special thank you](#a-special-thank-you)\n    - [Examples](#examples)\n  \n## Main features\n\n* Develop and test your Lambda functions locally with `sam local` and Docker\n* Invoke functions from known event sources such as Amazon S3, Amazon DynamoDB, Amazon Kinesis, etc.\n* Start local API Gateway from a SAM template, and quickly iterate over your functions with hot-reloading\n* Validate SAM templates\n\n## Installation\n\n### Prerequisites\n\nRunning Serverless projects and functions locally with SAM Local requires Docker to be installed and running. SAM Local will use the `DOCKER_HOST` environment variable to contact the docker daemon.\n\n - OSX: [Docker for Mac](https://store.docker.com/editions/community/docker-ce-desktop-mac)\n - Windows: [Docker Toolbox](https://download.docker.com/win/stable/DockerToolbox.exe)\n - Linux: Check your distro’s package manager (e.g. yum install docker)\n\nFor OSX and Windows users: SAM local requires that the project directory (or any parent directory) is listed in Docker file sharing options.\n\nVerify that docker is working, and that you can run docker commands from the CLI (e.g. ‘docker ps’). You do not need to install/fetch/pull any containers – SAM Local will do it automatically as required.\n\n\n### Windows, Linux, OSX with NPM [Recommended]\n\nThe easiest way to install **`sam`** is to use [NPM](npmjs.com).\n\n```bash\nnpm install -g aws-sam-local\n```\n\nVerify the installation worked:\n```bash\nsam --version\n```\n\nIf you get a permission error when using npm (such as `EACCES: permission denied`), please see the instructions on this page of the NPM documentation: [https://docs.npmjs.com/getting-started/fixing-npm-permissions](https://docs.npmjs.com/getting-started/fixing-npm-permissions).\n\n### Binary release\n\nWe also release the CLI as binaries that you can download and instantly use. You can find them under [Releases] in this repo. In case you cannot find the version or architecture you're looking for you can refer to [Build From Source](#build-from-source) section for build details.\n\n### Build From Source\n\nFirst, install Go (v1.8+) on your machine: [https://golang.org/doc/install](https://golang.org/doc/install), then run the following:\n\n```bash\n$ go get github.com/awslabs/aws-sam-local \n```\n\nThis will install **`sam`** to your `$GOPATH/bin` folder. Make sure this directory is in your `$PATH` (or %%PATH%% on Windows) and you should then be able to use the SAM Local. Please note that due to the package name, the binary will be installed as `aws-sam-local` rather than `sam`.\n\n```bash\naws-sam-local --help\n```\n\n## Usage\n\n**`sam`** requires a SAM template in order to know how to invoke your function locally, and it's also true for spawning API Gateway locally - If no template is specified `template.yaml` will be used instead.\n\nYou can find sample SAM templates either under **`samples`** located in this repo or by visiting [SAM] official repository.\n\n### Invoke functions locally\n\n![SAM Local Invoke Sample](media/sam-invoke.gif)\n\nYou can invoke your function locally by passing its **SAM logical ID** and an event file. Alternatively, `sam local invoke` accepts stdin as an event too.\n\n```yaml\nResources: \n  Ratings:  # \u003c-- Logical ID\n    Type: 'AWS::Serverless::Function'\n  ...\n```\n\n**Syntax**\n\n```bash\n# Invoking function with event file\n$ sam local invoke \"Ratings\" -e event.json\n\n# Invoking function with event via stdin\n$ echo '{\"message\": \"Hey, are you there?\" }' | sam local invoke \"Ratings\"\n\n# For more options\n$ sam local invoke --help\n```\n\n### Generate sample event source payloads\n\nTo make local development and testing of Lambda functions easier, you can generate mock/sample event payloads for the following services:\n\n* S3\n* Kinesis\n* DynamoDB\n* Cloudwatch Scheduled Event\n* Cloudtrail\n* API Gateway\n\n**Syntax**\n\n```bash\nsam local generate-event \u003cservice\u003e\n```\n\nAlso, you can invoke an individual lambda function locally from a sample event payload - Here's an example using S3:\n\n```bash\nsam local generate-event s3 --bucket \u003cbucket\u003e --key \u003ckey\u003e | sam local invoke \u003cfunction logical id\u003e\n```\n\nFor more options, see `sam local generate-event --help`.\n\n### Run API Gateway locally\n\n`sam local start-api` spawns a local API Gateway to test HTTP request/response functionality. Features hot-reloading to allow you to quickly develop, and iterate over your functions.\n\n![SAM Local Start API](media/sam-start-api.gif)\n\n**Syntax**\n\n```bash\nsam local start-api\n```\n\n**`sam`** will automatically find any functions within your SAM template that have `Api` event sources defined, and mount them at the defined HTTP paths.\n\nIn the example below, the `Ratings` function would mount `ratings.py:handler()` at `/ratings` for `GET` requests.\n\n```yaml\nRatings:\n  Type: AWS::Serverless::Function\n  Properties:\n    Handler: ratings.handler\n    Runtime: python3.6\n    Events:\n      Api:\n        Type: Api\n        Properties:\n          Path: /ratings\n          Method: get\n```\n\nBy default, SAM uses [Proxy Integration](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html) and expects the response from your Lambda function to include one or more of the following: `statusCode`, `headers` and/or `body`.\n\nFor example:\n\n```javascript\n// Example of a Proxy Integration response\nexports.handler = (event, context, callback) =\u003e {\n    callback(null, {\n        statusCode: 200,\n        headers: { \"x-custom-header\" : \"my custom header value\" },\n        body: \"hello world\"\n    });\n}\n```\n\nFor examples in other AWS Lambda languages, see [this page](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html).\n\nIf your function does not return a valid [Proxy Integration](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html) response then you will get a HTTP 500 (Internal Server Error) when accessing your function. SAM Local will also print the following error log message to help you diagnose the problem:\n\n```\nERROR: Function ExampleFunction returned an invalid response (must include one of: body, headers or statusCode in the response object)\n```\n\n### Debugging Applications\n\nBoth `sam local invoke` and `sam local start-api` support local debugging of your functions.\n\nTo run SAM Local with debugging support enabled, just specify `--debug-port` or `-d` on the command line. \n\n```bash\n# Invoke a function locally in debug mode on port 5858 \n$ sam local invoke -d 5858 \u003cfunction logical id\u003e \n\n# Start local API Gateway in debug mode on port 5858\n$ sam local start-api -d 5858\n```\n\nNote: If using `sam local start-api`, the local API Gateway will expose all of your lambda functions but, since you can specify a single debug port, you can only debug one function at a time.\n\nHere is an example showing how to debug a NodeJS function with Microsoft Visual Studio Code:\n\n![SAM Local debugging example](media/sam-debug.gif)\n\nIn order to setup Visual Studio Code for debugging with AWS SAM Local, use the following launch configuration:\n\n```\n{\n    \"version\": \"0.2.0\",\n    \"configurations\": [\n        {\n            \"name\": \"Attach to SAM Local\",\n            \"type\": \"node\",\n            \"request\": \"attach\",\n            \"address\": \"localhost\",\n            \"port\": 5858,\n            \"localRoot\": \"${workspaceRoot}\",\n            \"remoteRoot\": \"/var/task\"\n        }\n    ]\n}\n``` \n\n#### Debugging Python functions\n\nUnlike Node.JS and Java, Python requires you to enable remote debugging in your Lambda function code. If you enable debugging with `--debug-port` or `-d` for a function that uses one of the Python runtimes, SAM Local will just map through that port from your host machine through to the Lambda runtime container. You will need to enable remote debugging in your function code. To do this, use a python package such as [remote-pdb](https://pypi.python.org/pypi/remote-pdb). When configuring the host the debugger listens on in your code, make sure to use `0.0.0.0` not `127.0.0.1` to allow Docker to map through the port to your host machine. \n\n### Validate SAM templates\n\nValidate your templates with `$ sam validate`.\nThis command will validate your template against the official [AWS Serverless Application Model specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md).\nAs with most SAM Local commands, it will look for a `template.yaml` file in your current working directory by default. You can specify a different template file/location with the `-t` or `--template` option.\n\n**Syntax**\n\n```bash\n$ sam validate\nERROR: Resource \"HelloWorld\", property \"Runtime\": Invalid value node. Valid values are \"nodejs\", \"nodejs4.3\", \"nodejs6.10\", \"java8\", \"python2.7\", \"python3.6\", \"dotnetcore1.0\", \"nodejs4.3-edge\" (line: 11; col: 6)\n\n# Let's fix that error...\n$ sed -i 's/node/nodejs6.10/g' template.yaml\n\n$ sam validate\nValid!\n```\n\n### Package and Deploy to Lambda\nOnce you have developed and tested your Serverless application locally, you can deploy to Lambda using `sam package` and `sam deploy` command. `package` command will zip your code artifacts, upload to S3 and produce a SAM file that is ready to be deployed to Lambda using AWS CloudFormation. `deploy` command will deploy the packaged SAM template to CloudFormation. Both `sam package` and `sam deploy` are identical to their AWS CLI equivalents commands [`aws cloudformation package`](http://docs.aws.amazon.com/cli/latest/reference/cloudformation/package.html) and [`aws cloudformation deploy`](http://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/index.html) respectively. Please consult the AWS CLI command documentation for usage.\n\nExample:\n\n```bash\n# Package SAM template\n$ sam package --template-file sam.yaml --s3-bucket mybucket --output-template-file packaged.yaml\n\n# Deploy packaged SAM template\n$ sam deploy --template-file ./packaged.yaml --stack-name mystack --capabilities CAPABILITY_IAM\n```\n\n\n## Getting started\n\n* Check out [HOWTO Guide](HOWTO.md) section for more details\n\n## Advanced\n\n### Compiled Languages (Java)\n\nTo use SAM Local with compiled languages, such as Java that require a packaged artifact (e.g. a JAR, or ZIP), you can specify the location of the artifact with the `AWS::Serverless::Function` `CodeUri` property in your SAM template.\n\nFor example:\n\n```\nAWSTemplateFormatVersion: 2010-09-09\nTransform: AWS::Serverless-2016-10-31\n\nResources:\n  ExampleJavaFunction:\n    Type: AWS::Serverless::Function\n    Properties:\n      Handler: com.example.HelloWorldHandler\n      CodeUri: ./target/HelloWorld-1.0.jar\n      Runtime: java8\n```\n\nYou should then build your JAR file using your normal build process. Please note that JAR files used with AWS Lambda should be a shaded JAR file (or uber jar) containing all of the function dependencies.\n\n```\n// Build the JAR file\n$ mvn package shade:shade\n\n// Invoke with SAM Local\n$ echo '{ \"some\": \"input\" }' | sam local invoke\n\n// Or start local API Gateway simulator\n$ sam local start-api\n```\n\nYou can find a full Java example in the [samples/java](samples/java) folder\n\n### IAM Credentials\n\nSAM Local will invoke functions with your locally configured IAM credentials.\n\nAs with the AWS CLI and SDKs, SAM Local will look for credentials in the following order:\n\n1. Environment Variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`).\n2. The AWS credentials file (located at `~/.aws/credentials` on Linux, macOS, or Unix, or at `C:\\Users\\USERNAME \\.aws\\credentials` on Windows).\n3. Instance profile credentials (if running on Amazon EC2 with an assigned instance role).\n\nSee this [Configuring the AWS CLI](http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#config-settings-and-precedence) for more details.\n\n### Lambda Environment Variables\nIf your Lambda function uses environment variables, you can provide values for them will passed to the Docker container. Here is how you would do it:\n\nFor example, consider the SAM template snippet:\n\n```yaml\n\nResources:\n  MyFunction1:\n    Type: AWS::Serverless::Function\n    Properties:\n      Handler: index.handler\n      Runtime: nodejs4.3\n      Environment:\n        Variables:\n          TABLE_NAME: prodtable\n          BUCKET_NAME: prodbucket\n\n  MyFunction2:\n    Type: AWS::Serverless::Function\n    Properties:\n      Handler: app.handler\n      Runtime: nodejs4.3\n      Environment:\n        Variables:\n          STAGE: prod\n          TABLE_NAME: prodtable\n\n\n\n```\n\n#### Environment Variable file\nUse `--env-vars` argument of `invoke` or `start-api` commands to provide a JSON file that contains values for environment variables defined in your function. The file should be structured as follows:\n\n```json\n{\n  \"MyFunction1\": {\n    \"TABLE_NAME\": \"localtable\",\n    \"BUCKET_NAME\": \"testBucket\"\n  },\n  \"MyFunction2\": {\n    \"TABLE_NAME\": \"localtable\",\n    \"STAGE\": \"dev\"\n  },\n}\n\n```\n\n```bash\n$ sam local start-api --env-vars env.json\n```\n\n#### Shell environment \nVariables defined in your Shell's environment will be passed to the Docker container, if they map to a Variable in your Lambda function. Shell variables are globally applicable to functions ie. If two functions have a variable called `TABLE_NAME`, then the value for `TABLE_NAME` provided through Shell's environment will be availabe to both functions. \n\nFollowing command will make value of `mytable` available to both `MyFunction1` and `MyFunction2`\n\n```bash\n$ TABLE_NAME=mytable sam local start-api\n```\n\n#### Combination of Shell and Environment Variable file\nFor greater control, you can use a combination shell variables and external environment variable file. If a variable is defined in both places, the one from the file will override the shell. Here is the order of priority, highest to lowest. Higher priority ones will override the lower.\n\n1. Environment Variable file\n1. Shell's environment\n1. Hard-coded values from the template\n\n### Identifying local execution from Lambda function code\nWhen your Lambda function is invoked using SAM Local, it sets an environment variable `AWS_SAM_LOCAL=true` in the Docker container. Your Lambda function can use this property to enable or disable functionality that would not make sense in local development. For example: Disable emitting metrics to CloudWatch (or) Enable verbose logging etc.\n\n### Static Assets\nOften, it's useful to serve up static assets (e.g CSS/HTML/Javascript etc) when developing a Serverless application. On AWS, this would normally be done with CloudFront/S3. SAM Local by default looks for a `./public/` directory in your SAM project directory and will serve up all files from it at the root of the HTTP server when using `sam local start-api`. You can override the default static asset directory by using the `-s` or `--static-dir` command line flag. You can also disable this behaviour completely by setting `--static-dir \"\"`. \n\n### Local Logging\nBoth `invoke` and `start-api` command allow you to pipe logs from the function's invocation into a file. This will be useful if you are running automated tests against SAM Local and want to capture logs for analysis. \n\nExample:\n```bash\n$ sam local invoke --log-file ./output.log\n```\n\n\n### Remote Docker\nSam Local loads function code by mounting filesystem to a Docker Volume. As a result, The project directory must be pre-mounted on the remote host where the Docker is running.\n\nIf mounted, you can use the remote docker normally using `--docker-volume-basedir` or environment variable `SAM_DOCKER_VOLUME_BASEDIR`.\n\nExample - Docker Toolbox (Windows):\n\nWhen you install and run Docker Toolbox, the Linux VM with Docker is automatically installed in the virtual box.\n\nThe /c/ path for this Linux VM is automatically shared with C:\\ on the host machine.\n```powershell\nsam local invoke --docker-volume-basedir /c/Users/shlee322/projects/test \"Ratings\"\n```\n\n\n## Project Status\n  \n* [ ] Supported AWS Lambda Runtimes\n  - [x] `nodejs`\n  - [x] `nodejs4.3`\n  - [x] `nodejs6.10`\n  - [x] `java8`\n  - [x] `python2.7`\n  - [x] `python3.6`\n  - [ ] `dotnetcore1.0`\n* [x] AWS credential support \n* [x] Debugging support\n* [ ] Inline Swagger support within SAM templates\n\n## Contributing\n\nContributions and feedback are welcome! Proposals and pull requests will be considered and responded to. For more information, see the [CONTRIBUTING](CONTRIBUTING.md) file.\n\n## A special thank you\n\nSAM Local uses the open source [docker-lambda](https://github.com/lambci/docker-lambda) Docker images created by [@mhart](https://github.com/mhart). \n\n## Examples\n\nYou can find sample functions code and a SAM template used in this README under the [samples] folder within this repo.\n\n\u003c!-- Links --\u003e\n[SAM]: https://github.com/awslabs/serverless-application-model\n[HOWTO]: HOWTO.md\n[Releases]: https://github.com/awslabs/aws-sam-local/releases\n[Samples]: https://github.com/awslabs/aws-sam-local/tree/master/samples\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinarymist%2Faws-sam-local","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbinarymist%2Faws-sam-local","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbinarymist%2Faws-sam-local/lists"}