From 7354ea569a03621f8a95e988ba7339050e6d8fd1 Mon Sep 17 00:00:00 2001 From: Sriram Madapusi Vasudevan Date: Thu, 27 Dec 2018 11:34:54 -0800 Subject: [PATCH 1/3] fix: formatting to md from rst - DESIGN - README - DEVELOPMENT_GUIDE --- DESIGN.md | 67 +++++++++++++++++ DESIGN.rst | 54 -------------- DEVELOPMENT_GUIDE.md | 169 ++++++++++++++++++++++++++++++++++++++++++ DEVELOPMENT_GUIDE.rst | 157 --------------------------------------- README.md | 115 ++++++++++++++++++++++++++++ README.rst | 126 ------------------------------- setup.py | 5 +- 7 files changed, 354 insertions(+), 339 deletions(-) create mode 100644 DESIGN.md delete mode 100644 DESIGN.rst create mode 100644 DEVELOPMENT_GUIDE.md delete mode 100644 DEVELOPMENT_GUIDE.rst create mode 100644 README.md delete mode 100644 README.rst diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000000..4355c23d91 --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,67 @@ +DESIGN DOCUMENT +=============== + +> \"..with proper design, the features come cheaply \" - Dennis Ritchie + +This document is intended to capture key decisions in the design of this +CLI. This is especially useful for new contributors to understand the +codebase and keep the changes aligned with design decisions. We will +update this document when new components are added or the CLI design +changes significantly. + +Tenets +====== + +These are some key guiding principles for the design: + +- Extensibility is by design. It is not an after thought. +- Each component must be self-contained and testable in isolation. +- Command line interface must be one of many supported input + mechanisms. +- SAM is one of many supported input formats. + +CLI Framework +============= + +This component implements generic CLI functionality that makes it easy +to write individual CLI commands. It performs: + +- CLI argument parsing +- Generating help text and man pages from RST docs of the command. +- Fetching configuration information from environment +- Consistent exit code generation +- [Future] HTTP Mode: Ability to call the CLI commands with same + parameters through a HTTP Endpoint. This is useful for IDEs and + other tools to integrate with this CLI. + +Each command, along with any subcommands, is implemented using Click +annotations. They are not directly wired with the core of the CLI. +Instead, commands are dynamically loaded into the CLI at run time by +importing the Python package implementing the command. For example, +assuming two commands are implemented at Python packages +``foo.cli.cmd1`` and ``foo.cli.cmd2``, then the CLI framework will +dynamically import these two packages and connect them to parent Click +instance. The CLI framework expects the command's Click object to be +exposed through an attribute called `cli`. + +For example: if ``foo.bar.hello`` is the package where ``hello`` command +is implemented, then ``/foo/bar/hello/__init__.py`` file is expected +to contain a Click object called `cli`. + +By convention, the name of last module in the package's name is the +command's name. ie. A package of ``foo.bar.baz`` will produce a command +name ``baz``. + +Commands that make up of the core functionality (like local, validate, +generate-event etc) are also implemented this way. They are baked into +the CLI, but in the future, we will provide options to completely remove +a command. + +By convention, each command is implemented as a separate Python package +where the `__init__.py` file exposes the `cli` attribute. This allows +new commands to be built and distributed as Python packages through PIP, +opening the architecture to support plugins in future. This structure +also forces commands implementations to be modular, reusable, and highly +customizable. When RC files are implemented, new commands can be added +or existing commands can be removed, with simple a configuration in the +RC file. diff --git a/DESIGN.rst b/DESIGN.rst deleted file mode 100644 index 1b4f3ef56d..0000000000 --- a/DESIGN.rst +++ /dev/null @@ -1,54 +0,0 @@ -DESIGN DOCUMENT -=============== - - "..with proper design, the features come cheaply " - Dennis Ritchie - - -This document is intended to capture key decisions in the design of this CLI. This is especially useful for new -contributors to understand the codebase and keep the changes aligned with design decisions. We will update -this document when new components are added or the CLI design changes significantly. - -Tenets -====== -These are some key guiding principles for the design: - -- Extensibility is by design. It is not an after thought. -- Each component must be self-contained and testable in isolation. -- Command line interface must be one of many supported input mechanisms. -- SAM is one of many supported input formats. - - -CLI Framework -============= -This component implements generic CLI functionality that makes it easy to write individual CLI commands. It performs: - -- CLI argument parsing -- Generating help text and man pages from RST docs of the command. -- Fetching configuration information from environment -- Consistent exit code generation -- [Future] HTTP Mode: Ability to call the CLI commands with same parameters through a HTTP Endpoint. This is useful for IDEs and other tools to integrate with this CLI. - -Each command, along with any subcommands, is implemented using Click annotations. They are not directly wired with -the core of the CLI. Instead, commands are dynamically loaded into the CLI at run time by importing the Python -package implementing the command. For example, assuming two commands are implemented at Python packages -"foo.cli.cmd1" and "foo.cli.cmd2", then the CLI framework will dynamically import these two packages and connect them -to parent Click instance. The CLI framework expects the command's Click object to be exposed through an attribute -called ``cli``. - -For example: if "foo.bar.hello" is the package where "hello" command is implemented, then -"/foo/bar/hello/__init__.py" file is expected to contain a Click object called ``cli``. - -By convention, the name of last module in the package's name is the command's name. ie. A package of "foo.bar.baz" -will produce a command name "baz". - -Commands that make up of the core functionality (like local, validate, generate-event etc) are also implemented -this way. They are baked into the CLI, but in the future, we will provide options to completely remove a command. - -By convention, each command is implemented as a separate Python package where the ``__init__.py`` file -exposes the ``cli`` attribute. This allows new commands to be built and distributed as Python packages -through PIP, opening the architecture to support plugins in future. This structure also forces commands implementations -to be modular, reusable, and highly customizable. When RC files are implemented, new commands can be added or existing -commands can be removed, with simple a configuration in the RC file. - - -.. _`click`: https://github.com/pallets/click diff --git a/DEVELOPMENT_GUIDE.md b/DEVELOPMENT_GUIDE.md new file mode 100644 index 0000000000..7b9117b25f --- /dev/null +++ b/DEVELOPMENT_GUIDE.md @@ -0,0 +1,169 @@ +DEVELOPMENT GUIDE +================= + +**Welcome hacker!** + +This document will make your life easier by helping you setup a +development environment, IDEs, tests, coding practices, or anything that +will help you be more productive. If you found something is missing or +inaccurate, update this guide and send a Pull Request. + +**Note**: `pyenv` currently only supports macOS and Linux. If you are a +Windows users, consider using [pipenv](https://docs.pipenv.org/). + +Environment Setup +----------------- + +### 1. Install Python Versions + +We support Python 2.7, 3.6 and 3.7 versions. Follow the idioms from this +[excellent cheatsheet](http://python-future.org/compatible_idioms.html) +to make sure your code is compatible with both Python versions. Our +CI/CD pipeline is setup to run unit tests against both Python versions. +So make sure you test it with both versions before sending a Pull +Request. [pyenv](https://github.com/pyenv/pyenv) is a great tool to +easily setup multiple Python versions. + +> Note: For Windows, type +> `export PATH="/c/Users//.pyenv/libexec:$PATH"` to add pyenv to +> your path. + +1. Install PyEnv - + `curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash` +2. `pyenv install 2.7.14` +3. `pyenv install 3.6.8` +4. `pyenv install 3.7.2` +5. Make Python versions available in the project: + `pyenv local 3.6.8 2.7.14 3.7.2` + +### 2. Activate Virtualenv + +Virtualenv allows you to install required libraries outside of the +Python installation. A good practice is to setup a different virtualenv +for each project. [pyenv](https://github.com/pyenv/pyenv) comes with a +handy plugin that can create virtualenv. + +Depending on the python version, the following commands would change to +be the appropriate python version. + +1. `pyenv virtualenv 3.7.2 samcli37` +2. `pyenv activate samcli37` for Python3.7 + +### 3. Install dev version of SAM CLI + +We will install a development version of SAM CLI from source into the +virtualenv for you to try out the CLI as you make changes. We will +install in a command called `samdev` to keep it separate from a global +SAM CLI installation, if any. + +1. Activate Virtualenv: `pyenv activate samcli37` +2. Install dev CLI: `make init` +3. Make sure installation succeeded: `which samdev` + +### 4. (Optional) Install development version of SAM Transformer + +If you want to run the latest version of [SAM +Transformer](https://github.com/awslabs/serverless-application-model/), +you can clone it locally and install it in your pyenv. This is useful if +you want to validate your templates against any new, unreleased SAM +features ahead of time. + +This step is optional and will use the specified version of +aws-sam-transformer from PyPi by default. + + +``cd ~/projects (cd into the directory where you usually place projects)`` + +``git clone https://github.com/awslabs/serverless-application-model/`` + +``git checkout develop `` + +Install the SAM Transformer in editable mode so that all changes you make to the SAM Transformer locally are immediately picked up for SAM CLI. + +``pip install -e . `` + +Move back to your SAM CLI directory and re-run init, If necessary: open requirements/base.txt and replace the version number of aws-sam-translator with the ``version number`` specified in your local version of `serverless-application-model/samtranslator/__init__.py` + +``cd ../aws-sam-cli`` + +``make init`` + +Running Tests +------------- + +### Unit testing with multiple Python versions + +[tox](http://tox.readthedocs.io/en/latest/) is used to run tests against +all supported Python versions. Follow these instructions to setup +multiple Python versions using [pyenv](https://github.com/pyenv/pyenv) +before running tox: + +1. Deactivate virtualenvs, if any: `pyenv deactivate` +2. `pip install tox` +3. Run tests against all supported Python versions: `tox` + +### Integration Test + +`make integ-test` - To run integration test against global SAM CLI +installation. It looks for a command named `sam` in your shell. + +`SAM_CLI_DEV=1 make integ-test` - To run integration tests against +development version of SAM CLI. This is useful if you are making changes +to the CLI and want to verify that it works. It is a good practice to +run integration tests before submitting a pull request. + +Code Conventions +---------------- + +Please follow these code conventions when making your changes. This will +align your code to the same conventions used in rest of the package and +make it easier for others to read/understand your code. Some of these +conventions are best practices that we have learnt over time. + +- Use [numpy + docstring](https://numpydoc.readthedocs.io/en/latest/format.html) + format for docstrings. Some parts of the code still use an older, + unsupported format. If you happened to be modifying these methods, + please change the docstring format as well. +- Don\'t write any code in `__init__.py` file +- Module-level logger variable must be named as `LOG` +- If your method wants to report a failure, it *must* raise a custom + exception. Built-in Python exceptions like `TypeError`, `KeyError` + are raised by Python interpreter and usually signify a bug in your + code. Your method must not explicitly raise these exceptions because + the caller has no way of knowing whether it came from a bug or not. + Custom exceptions convey are must better at conveying the intent and + can be handled appropriately by the caller. In HTTP lingo, custom + exceptions are equivalent to 4xx (user\'s fault) and built-in + exceptions are equivalent to 5xx (Service Fault) +- CLI commands must always raise a subclass of `click.ClickException` + to signify an error. Error code and message must be set as a part of + this exception and not explicitly returned by the CLI command. +- Don't use `*args` or `**kwargs` unless there is a really strong + reason to do so. You must explain the reason in great detail in + docstrings if you were to use them. +- Library classes, ie. the ones under `lib` folder, must **not** use + Click. Usage of Click must be restricted to the `commands` package. + In the library package, your classes must expose interfaces that are + independent of the user interface, be it a CLI thru Click, or CLI + thru argparse, or HTTP API, or a GUI. +- Do not catch the broader `Exception`, unless you have a really + strong reason to do. You must explain the reason in great detail in + comments. + +Design Document +--------------- + +A design document is a written description of the feature/capability you +are building. We have a [design document +template](./designs/_template.rst) to help you quickly fill in the +blanks and get you working quickly. We encourage you to write a design +document for any feature you write, but for some types of features we +definitely require a design document to proceed with implementation. + +**When do you need a design document?** + +- Adding a new command +- Making a breaking change to CLI interface +- Refactoring code that alters the design of certain components +- Experimental features diff --git a/DEVELOPMENT_GUIDE.rst b/DEVELOPMENT_GUIDE.rst deleted file mode 100644 index b1bc8e21f5..0000000000 --- a/DEVELOPMENT_GUIDE.rst +++ /dev/null @@ -1,157 +0,0 @@ -DEVELOPMENT GUIDE -================= - -**Welcome hacker!** - -This document will make your life easier by helping you setup a development environment, IDEs, tests, coding practices, -or anything that will help you be more productive. If you found something is missing or inaccurate, update this guide -and send a Pull Request. - -**Note**: ``pyenv`` currently only supports macOS and Linux. If you are a Windows users, consider using `pipenv`_. - -Environment Setup ------------------ - -1. Install Python Versions -~~~~~~~~~~~~~~~~~~~~~~~~~~ -We support Python 2.7, 3.6 and 3.7 versions. -Follow the idioms from this `excellent cheatsheet`_ to make sure your code is compatible with both Python versions. -Our CI/CD pipeline is setup to run unit tests against both Python versions. So make sure you test it with both -versions before sending a Pull Request. `pyenv`_ is a great tool to easily setup multiple Python versions. - - Note: For Windows, type ``export PATH="/c/Users//.pyenv/libexec:$PATH"`` to add pyenv to your path. - -#. Install PyEnv - ``curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash`` -#. ``pyenv install 2.7.14`` -#. ``pyenv install 3.6.4`` -#. ``pyenv install 3.7.0`` -#. Make Python versions available in the project: ``pyenv local 3.6.4 2.7.14 3.7.0`` - - -2. Activate Virtualenv -~~~~~~~~~~~~~~~~~~~~~~ -Virtualenv allows you to install required libraries outside of the Python installation. A good practice is to setup -a different virtualenv for each project. `pyenv`_ comes with a handy plugin that can create virtualenv. - -Depending on the python version, the following commands would change to be the appropriate python version. - -#. ``pyenv virtualenv 3.7.0 samcli37`` -#. ``pyenv activate samcli37`` for Python3.7 - - -3. Install dev version of SAM CLI -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -We will install a development version of SAM CLI from source into the virtualenv for you to try out the CLI as you -make changes. We will install in a command called ``samdev`` to keep it separate from a global SAM CLI installation, -if any. - -#. Activate Virtualenv: ``pyenv activate samcli37`` -#. Install dev CLI: ``make init`` -#. Make sure installation succeeded: ``which samdev`` - -4. (Optional) Install development version of SAM Transformer -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If you want to run the latest version of [SAM Transformer](https://github.com/awslabs/serverless-application-model/), you can clone it locally and install it in your pyenv. This is useful if you want to validate your templates against any new, unreleased SAM features ahead of time. - -This step is optional and will use the specified version of aws-sam-transformer from PyPi by default. - -```bash -# cd into the directory where you usually place projects and clone the latest SAM Transformer -cd ~/projects -git clone https://github.com/awslabs/serverless-application-model/ - -# cd into the new directory and checkout the relevant branch -cd serverless-application-model -git checkout develop - -# Install the SAM Transformer in editable mode so that all changes you make to -# the SAM Transformer locally are immediately picked up for SAM CLI. -pip install -e . - -# Move back to your SAM CLI directory and re-run init -# If necessary: open requirements/base.txt and replace the version number of aws-sam-translator with the -# version number specified in your local version of serverless-application-model/samtranslator/__init__.py -cd ../aws-sam-cli -make init -``` - -Running Tests -------------- - -Unit testing with multiple Python versions -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -`tox`_ is used to run tests against all supported Python versions. Follow these instructions to setup multiple Python -versions using `pyenv`_ before running tox: - -#. Deactivate virtualenvs, if any: ``pyenv deactivate`` -#. ``pip install tox`` -#. Run tests against all supported Python versions: ``tox`` - -Integration Test -~~~~~~~~~~~~~~~~ - -``make integ-test`` - To run integration test against global SAM CLI installation. It looks for a command named ``sam`` -in your shell. - -``SAM_CLI_DEV=1 make integ-test`` - To run integration tests against development version of SAM CLI. This is useful if -you are making changes to the CLI and want to verify that it works. It is a good practice to run integration tests -before submitting a pull request. - -Code Conventions ----------------- - -Please follow these code conventions when making your changes. This will align your code to the same conventions used -in rest of the package and make it easier for others to read/understand your code. Some of these conventions are -best practices that we have learnt over time. - -- Use `numpy docstring`_ format for docstrings. Some parts of the code still use an older, unsupported format. If you - happened to be modifying these methods, please change the docstring format as well. - -- Don't write any code in ``__init__.py`` file - -- Module-level logger variable must be named as ``LOG`` - -- If your method wants to report a failure, it *must* raise a custom exception. Built-in Python exceptions like - ``TypeError``, ``KeyError`` are raised by Python interpreter and usually signify a bug in your code. Your method must - not explicitly raise these exceptions because the caller has no way of knowing whether it came from a bug or not. - Custom exceptions convey are must better at conveying the intent and can be handled appropriately by the caller. - In HTTP lingo, custom exceptions are equivalent to 4xx (user's fault) and built-in exceptions are equivalent - to 5xx (Service Fault) - -- CLI commands must always raise a subclass of ``click.ClickException`` to signify an error. Error code and message - must be set as a part of this exception and not explicitly returned by the CLI command. - -- Don't use ``*args`` or ``**kwargs`` unless there is a really strong reason to do so. You must explain the reason - in great detail in docstrings if you were to use them. - -- Library classes, ie. the ones under ``lib`` folder, must **not** use Click. Usage of Click must be restricted to - the ``commands`` package. In the library package, your classes must expose interfaces that are independent - of the user interface, be it a CLI thru Click, or CLI thru argparse, or HTTP API, or a GUI. - -- Do not catch the broader ``Exception``, unless you have a really strong reason to do. You must explain the reason - in great detail in comments. - -Design Document ---------------- - -A design document is a written description of the feature/capability you are building. We have a -`design document template`_ to help you quickly fill in the blanks and get you working quickly. We encourage you to -write a design document for any feature you write, but for some types of features we definitely require a design -document to proceed with implementation. - -**When do you need a design document?** - -- Adding a new command -- Making a breaking change to CLI interface -- Refactoring code that alters the design of certain components -- Experimental features - - -.. _excellent cheatsheet: http://python-future.org/compatible_idioms.html -.. _pyenv: https://github.com/pyenv/pyenv -.. _tox: http://tox.readthedocs.io/en/latest/ -.. _numpy docstring: https://numpydoc.readthedocs.io/en/latest/format.html -.. _pipenv: https://docs.pipenv.org/ -.. _design document template: ./designs/_template.rst diff --git a/README.md b/README.md new file mode 100644 index 0000000000..e9a7cccf88 --- /dev/null +++ b/README.md @@ -0,0 +1,115 @@ +

+

+ +SAM CLI (Beta) +============== + +![Build +Status](https://travis-ci.org/awslabs/aws-sam-cli.svg?branch=develop) +![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-cli.svg?maxAge=2592000) +![GitHub-release](https://img.shields.io/github/release/awslabs/aws-sam-cli.svg?maxAge=2592000) +![PyPI version](https://badge.fury.io/py/aws-sam-cli.svg) + +[Join the SAM developers channel (\#samdev) on +Slack](https://join.slack.com/t/awsdevelopers/shared_invite/enQtMzg3NTc5OTM2MzcxLTdjYTdhYWE3OTQyYTU4Njk1ZWY4Y2ZjYjBhMTUxNGYzNDg5MWQ1ZTc5MTRlOGY0OTI4NTdlZTMwNmI5YTgwOGM/) +to collaborate with fellow community members and the AWS SAM team. + +`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 CLI +can be used to test functions locally, start a local API Gateway from a +SAM template, validate a SAM template, fetch logs, generate sample +payloads for various event sources, and generate a SAM project in your +favorite Lambda Runtime. + +Main features +------------- + +- Develop and test your Lambda functions locally with `sam local` and + Docker +- Invoke functions from known event sources such as Amazon S3, Amazon + DynamoDB, Amazon Kinesis Streams, etc. +- Start local API Gateway from a SAM template, and quickly iterate + over your functions with hot-reloading +- Validate SAM templates +- Get started with boilerplate Serverless Service in your chosen + Lambda Runtime `sam init` + +Get Started +----------- + +Learn how to get started using the SAM CLI with these guides: + +- [Installation](docs/installation.rst): Set up your macOS, Linux or + Windows Machine to run serverless projects with SAM CLI. +- [Introduction to SAM and SAM CLI](docs/getting_started.rst) What is + SAM and SAM CLI, and how can you use it to make a simple hello-world + app. +- [Running and debugging serverless applications + locally](docs/usage.rst): Describes how to use SAM CLI for invoking + Lambda functions locally, running automated tests, fetching logs, + and debugging applications +- [Packaging and deploying your + application](docs/deploying_serverless_applications.rst): Deploy + your local application using an S3 bucket, and AWS CloudFormation. +- [Advanced](docs/advanced_usage.rst): Learn how to work with compiled + languages (such as Java and .NET), configure IAM credentials, + provide environment variables, and more. +- [Examples](https://github.com/awslabs/serverless-application-model/tree/master/examples/apps) + +Project Status +-------------- + +- \[x\] Python Versions support + - \[x\] Python 2.7 + - \[x\] Python 3.6 + - \[x\] Python 3.7 +- \[ \] Supported AWS Lambda Runtimes + - \[x\] `nodejs` + - \[x\] `nodejs4.3` + - \[x\] `nodejs6.10` + - \[x\] `nodejs8.10` + - \[x\] `java8` + - \[x\] `python2.7` + - \[x\] `python3.6` + - \[x\] `python3.7` + - \[x\] `go1.x` + - \[ \] `dotnetcore1.0` + - \[x\] `dotnetcore2.0` + - \[x\] `dotnetcore2.1` + - \[x\] `ruby2.5` + - \[x\] `Provided` +- \[x\] AWS credential support +- \[x\] Debugging support +- \[x\] Inline Swagger support within SAM templates +- \[x\] Validating SAM templates locally +- \[x\] Generating boilerplate templates + - \[x\] `nodejs` + - \[x\] `nodejs4.3` + - \[x\] `nodejs6.10` + - \[x\] `nodejs8.10` + - \[x\] `java8` + - \[x\] `python2.7` + - \[x\] `python3.6` + - \[x\] `python3.7` + - \[x\] `go1.x` + - \[x\] `dotnetcore1.0` + - \[x\] `dotnetcore2.0` + - \[x\] `ruby2.5` + - \[ \] `Provided` + +Contributing +------------ + +Contributions and feedback are welcome! Proposals and pull requests will +be considered and responded to. For more information, see the +[CONTRIBUTING](CONTRIBUTING.md) file. + +A special thank you +------------------- + +SAM CLI uses the open source +[docker-lambda](https://github.com/lambci/docker-lambda) Docker images +created by [@mhart](https://github.com/mhart). + diff --git a/README.rst b/README.rst deleted file mode 100644 index 75d90d9569..0000000000 --- a/README.rst +++ /dev/null @@ -1,126 +0,0 @@ -.. raw:: html - -

- -.. raw:: html - -

- -============== -SAM CLI (Beta) -============== - -|Build Status| |Apache-2.0| |Contributers| |GitHub-release| |PyPI version| - -`Join the SAM developers channel (#samdev) on -Slack `__ to collaborate with -fellow community members and the AWS SAM team. - -``sam`` is the AWS CLI tool for managing Serverless applications -written with `AWS Serverless Application Model -(SAM) `__. SAM -CLI can be used to test functions locally, start a local API Gateway -from a SAM template, validate a SAM template, fetch logs, generate sample payloads -for various event sources, and generate a SAM project in your favorite -Lambda Runtime. - - - -Main features -------------- - -- Develop and test your Lambda functions locally with ``sam local`` and - Docker -- Invoke functions from known event sources such as Amazon S3, Amazon - DynamoDB, Amazon Kinesis Streams, etc. -- Start local API Gateway from a SAM template, and quickly iterate over - your functions with hot-reloading -- Validate SAM templates -- Get started with boilerplate Serverless Service in your chosen Lambda - Runtime ``sam init`` - - -Get Started ------------ - -Learn how to get started using the SAM CLI with these guides: - -- `Installation `__: Set up your macOS, Linux or Windows Machine to run serverless projects with SAM CLI. -- `Introduction to SAM and SAM CLI `__ What is SAM and SAM CLI, and how can you use it to make a simple hello-world app. -- `Running and debugging serverless applications locally `__: Describes how to use SAM CLI for invoking Lambda functions locally, running automated tests, fetching logs, and debugging applications -- `Packaging and deploying your application `__: Deploy your local application using an S3 bucket, and AWS CloudFormation. -- `Advanced `__: Learn how to work with compiled languages (such as Java and .NET), configure IAM credentials, provide environment variables, and more. -- `Examples `__ - - -Project Status --------------- - -- [ ] Python Versions support - - - [x] Python 2.7 - - [x] Python 3.6 - -- [ ] Supported AWS Lambda Runtimes - - - [x] ``nodejs`` - - [x] ``nodejs4.3`` - - [x] ``nodejs6.10`` - - [x] ``nodejs8.10`` - - [x] ``java8`` - - [x] ``python2.7`` - - [x] ``python3.6`` - - [x] ``python3.7`` - - [x] ``go1.x`` - - [ ] ``dotnetcore1.0`` - - [x] ``dotnetcore2.0`` - - [x] ``dotnetcore2.1`` - - [x] ``ruby2.5`` - - [x] ``Provided`` - -- [x] AWS credential support -- [x] Debugging support -- [x] Inline Swagger support within SAM templates -- [x] Validating SAM templates locally -- [x] Generating boilerplate templates - - - [x] ``nodejs`` - - [x] ``nodejs4.3`` - - [x] ``nodejs6.10`` - - [x] ``nodejs8.10`` - - [x] ``java8`` - - [x] ``python2.7`` - - [x] ``python3.6`` - - [x] ``python3.7`` - - [x] ``go1.x`` - - [x] ``dotnetcore1.0`` - - [x] ``dotnetcore2.0`` - - [x] ``ruby2.5`` - - [ ] ``Provided`` - -Contributing ------------- - -Contributions and feedback are welcome! Proposals and pull requests will -be considered and responded to. For more information, see the -`CONTRIBUTING `__ file. - -A special thank you -------------------- - -SAM CLI uses the open source -`docker-lambda `__ Docker -images created by `@mhart `__. - - -.. raw:: html - - - -.. |Build Status| image:: https://travis-ci.org/awslabs/aws-sam-cli.svg?branch=develop -.. |Apache-2.0| image:: https://img.shields.io/npm/l/aws-sam-local.svg?maxAge=2592000 -.. |Contributers| image:: https://img.shields.io/github/contributors/awslabs/aws-sam-cli.svg?maxAge=2592000 -.. |GitHub-release| image:: https://img.shields.io/github/release/awslabs/aws-sam-cli.svg?maxAge=2592000 -.. |PyPI version| image:: https://badge.fury.io/py/aws-sam-cli.svg - -======= diff --git a/setup.py b/setup.py index dc07fd28f2..8d1fa26325 100644 --- a/setup.py +++ b/setup.py @@ -37,7 +37,8 @@ def read_version(): name='aws-sam-cli', version=read_version(), description='AWS SAM CLI is a CLI tool for local development and testing of Serverless applications', - long_description=read('README.rst'), + long_description=read('README.md'), + long_description_content_type='text/markdown', author='Amazon Web Services', author_email='aws-sam-developers@amazon.com', url='https://github.com/awslabs/aws-sam-cli', @@ -45,7 +46,7 @@ def read_version(): packages=find_packages(exclude=('tests', 'docs')), keywords="AWS SAM CLI", # Support Python 2.7 and 3.6 or greater - python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*', + python_requires=('>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*'), entry_points={ 'console_scripts': [ '{}=samcli.cli.main:cli'.format(cmd_name) From 6be3d72dcac76f0d8ab7545bd108168afd81c516 Mon Sep 17 00:00:00 2001 From: Sriram Madapusi Vasudevan Date: Thu, 27 Dec 2018 13:22:21 -0800 Subject: [PATCH 2/3] fix: change designs to md --- designs/_template.md | 99 +++++++ designs/_template.rst | 86 ------ designs/sam_build_cmd.md | 557 ++++++++++++++++++++++++++++++++++++++ designs/sam_build_cmd.rst | 515 ----------------------------------- 4 files changed, 656 insertions(+), 601 deletions(-) create mode 100644 designs/_template.md delete mode 100644 designs/_template.rst create mode 100644 designs/sam_build_cmd.md delete mode 100644 designs/sam_build_cmd.rst diff --git a/designs/_template.md b/designs/_template.md new file mode 100644 index 0000000000..31d5a00b8f --- /dev/null +++ b/designs/_template.md @@ -0,0 +1,99 @@ +Title: Template for design documents +==================================== + +Use this as a template to write a design document when adding new +commands or major features to SAM CLI. It helps other developers +understand the scope of the project, validate technical complexity and +feasibility. It also serves as a public documentation of how the feature +actually works. + +**Process:** + +1. Copy this template to another file in the `designs` folder. +2. Fill out the sections in the template. +3. Send a "Work In Progress" Pull Request with your design document. We can discuss the +designs in more detail and iterate on the requirements. Feel free to +start implementing a prototype if you think it will help flush out +design. +4. Once the PR is approved, create Github Issues for each task +listed in the document and start implementing them. + +What is the problem? +-------------------- + +What will be changed? +--------------------- + +Success criteria for the change +------------------------------- + +Out-of-Scope +------------ + +User Experience Walkthrough +--------------------------- + +Implementation +============== + +CLI Changes +----------- + +*Explain the changes to command line interface, including adding new +commands, modifying arguments etc* + +### Breaking Change + +*Are there any breaking changes to CLI interface? Explain* + +Design +------ + +*Explain how this feature will be implemented. Highlight the components +of your implementation, relationships* *between components, constraints, +etc.* + +`.samrc` Changes +---------------- + +*Explain the new configuration entries, if any, you want to add to +.samrc* + +Security +-------- + +*Tip: How does this change impact security? Answer the following +questions to help answer this question better:* + +**What new dependencies (libraries/cli) does this change require?** + +**What other Docker container images are you using?** + +**Are you creating a new HTTP endpoint? If so explain how it will be +created & used** + +**Are you connecting to a remote API? If so explain how is this +connection secured** + +**Are you reading/writing to a temporary folder? If so, what is this +used for and when do you clean up?** + +**How do you validate new .samrc configuration?** + +Documentation Changes +--------------------- + +Open Issues +----------- + +Task Breakdown +-------------- + +- \[x\] Send a Pull Request with this design document +- \[ \] Build the command line interface +- \[ \] Build the underlying library +- \[ \] Unit tests +- \[ \] Functional Tests +- \[ \] Integration tests +- \[ \] Run all tests on Windows +- \[ \] Update documentation diff --git a/designs/_template.rst b/designs/_template.rst deleted file mode 100644 index 1c7c1b0f7b..0000000000 --- a/designs/_template.rst +++ /dev/null @@ -1,86 +0,0 @@ -Title: Template for design documents -==================================== - -Use this as a template to write a design document when adding new commands or major features to SAM CLI. It helps -other developers understand the scope of the project, validate technical complexity and feasibility. It also -serves as a public documentation of how the feature actually works. - -**Process:** -1. Copy this template to another file in the ``designs`` folder -1. Fill out the sections in the template -1. Send a "Work In Progress" Pull Request with your design document. We can discuss the designs in more detail and -iterate on the requirements. Feel free to start implementing a prototype if you think it will help flush out design. -1. Once the PR is approved, create Github Issues for each task listed in the document and start implementing them. - -What is the problem? --------------------- - -What will be changed? ---------------------- - -Success criteria for the change -------------------------------- - -Out-of-Scope ------------- - -User Experience Walkthrough ---------------------------- - - -Implementation -============== - -CLI Changes ------------ -*Explain the changes to command line interface, including adding new commands, modifying arguments etc* - -Breaking Change -~~~~~~~~~~~~~~~ -*Are there any breaking changes to CLI interface? Explain* - -Design ------- -*Explain how this feature will be implemented. Highlight the components of your implementation, relationships* -*between components, constraints, etc.* - - -``.samrc`` Changes ------------------- -*Explain the new configuration entries, if any, you want to add to .samrc* - - -Security --------- - -*Tip: How does this change impact security? Answer the following questions to help answer this question better:* - -**What new dependencies (libraries/cli) does this change require?** - -**What other Docker container images are you using?** - -**Are you creating a new HTTP endpoint? If so explain how it will be created & used** - -**Are you connecting to a remote API? If so explain how is this connection secured** - -**Are you reading/writing to a temporary folder? If so, what is this used for and when do you clean up?** - -**How do you validate new .samrc configuration?** - - -Documentation Changes ---------------------- - -Open Issues ------------ - -Task Breakdown --------------- -- [x] Send a Pull Request with this design document -- [ ] Build the command line interface -- [ ] Build the underlying library -- [ ] Unit tests -- [ ] Functional Tests -- [ ] Integration tests -- [ ] Run all tests on Windows -- [ ] Update documentation diff --git a/designs/sam_build_cmd.md b/designs/sam_build_cmd.md new file mode 100644 index 0000000000..1f52752cb8 --- /dev/null +++ b/designs/sam_build_cmd.md @@ -0,0 +1,557 @@ +`sam build` command +=================== + +This is the design for a command to **build** a Lambda function. +**Build** is the operation of converting the function\'s source code to +an artifact that can be executed on AWS Lambda. + +What is the problem? +-------------------- + +To run a function on AWS Lambda, customers need to provide a zip file +containing an executable form of the code. The process of creating the +executable usually involves downloading dependent libraries, optionally +compiling the code on Amazon Linux, copying static assets, and arranging +the files in a directory structure that AWS Lambda accepts. In some +programming languages like Javascript, this process is fairly +straightforward (just zip a folder), and in others like Python, it is +much involved. + +Customers using SAM CLI can easily create Lambda function code (using +`sam init`) and package their artifact as a zip file (using +`sam package`), but they have to handle the build process themselves. +Customers usually implement their own build scripts or adopt other\'s +scripts from the internet. This is where many customers fall off the +cliff. + +What will be changed? +--------------------- + +In this proposal, we will be providing a new command, `sam build`, to +build Lambda functions for all programming languages that AWS Lambda +supports. The cardinality of the problem is number of programming +languages (N) times the number of package managers (M) per language. +Hence is it is nearly impossible to natively support each combination. +Instead, `sam build` will support an opinionated set of package managers +for all programming languages. In the future, we will provide an option +for customers to bring their own build commands or override the default +for any programming language. SAM CLI will still take care of the grunt +work of iterating through every function in the SAM template, figuring +out the source code location, creating temporary folders to store built +artifacts, running the build command and move artifacts to right +location. + +Success criteria for the change +------------------------------- + +1. Support all programming languages supported by AWS Lambda + - Nodejs with NPM + - Java with Maven + - Python with PIP + - Golang with Go CLI + - Dotnetcore with DotNet CLI +2. Each Lambda function in SAM template gets built +3. Produce stable builds (best effort): If the source files did not + change, built artifacts should not change. +4. Built artifacts should \"just work\" with `sam local` and + `sam package` suite of commands +5. Opt-in to building native dependencies that can run on AWS Lambda + using Docker. +6. Support one dependency manifest (ex: package.json) per each Lambda + function. +7. Support out-of-source builds: ie. source code of Lambda function is + outside the directory containing SAM template. +8. Integrate build action with `sam local/package/deploy` commands so + the Lambda functions will be automatically built as part of the + command without explicitly running the build command. + +Out-of-Scope +------------ + +1. Ability to provide arbitrary build commands for each Lambda Function + runtime. This will either override the built-in default or add build + support for languages/tools that SAM CLI does not support (ex: + java+gradle). +2. Supports adding data files ie. files that are not referenced by the + package manager (ex: images, css etc) +3. Support to exclude certain files from the built artifact (ex: using + .gitignore or using regex) +4. Support for building the app for debugging locally with debug + symbols (ex: Golang) +5. Support caching dependencies & re-installing them only when the + dependency manifest changes (ex: by maintaining hash of + package.json) +6. If the app contains a `buildspec.yaml`, automatically run it using + CodeBuild Local. +7. Watch for file changes and build automatically (ex: + `sam build --watch`) +8. Support other build systems by default Webpack, Yarn or Gradle. +9. Support in AWS CLI, `aws cloudformation`, suite of commands +10. Support for fine-grained hooks (ex: hooks that run pre-build, + post-build, etc) +11. Support one dependency manifest per app, shared by all the Lambda + functions (this is usually against best practices) + +User Experience Walkthrough +--------------------------- + +Let\'s assume customers has the following SAM template: + +> **NOTE**: Currently we advice customers to set *CodeUri* to a folder +> containing built artifacts that can be readily packaged by +> `sam package` command. But to use with *build* command, customers need +> to set *CodeUri* to the folder containing source code and not built +> artifacts. + +``` {.sourceCode .yaml} +MyFunction1: + Type: AWS::Lambda::Function + Properties: + ... + Code: ./source-code1 + ... + +MyFunction2: + Type: AWS::Serverless::Function + Properties: + ... + Code: ./source-code2 + ... +``` + +To build, package and deploy this app, customers would do the following: + +**1. Build:** Run the following command to build all functions in the +template and output a SAM template that can be run through the package +command: + +``` {.sourceCode .bash} +# Build the code and write artifacts to ./build folder +# NOTE: All arguments will have sensible defaults so users can just use `sam build` +$ sam build -t template.yaml -b ./build -o built-template.yaml +``` + +Output of the *sam build* command is a SAM template where CodeUri is +pointing to the built artifacts. Note the values of Code properties in +following output: + +``` {.sourceCode .bash} +$ cat built-template.yaml +MyFunction1: + Type: AWS::Lambda::Function + Properties: + ... + Code: ./build/MyFunction1 + ... + +MyFunction2: + Type: AWS::Serverless::Function + Properties: + ... + CodeUri: ./build/MyFunction2 + ... +``` + +**2. Package and Deploy:** Package the built artifacts by running the +*package* command on the template output by *build* command + +``` {.sourceCode .bash} +# Package the code +$ sam package --template-file built-template.yaml --s3-bucket mybucket --output-template-file packaged-template.yaml + +# Deploy the app +$ sam deploy --template-file packaged-template.yaml --stack-name mystack +``` + +### Other Usecases + +1. **Build Native Dependencies**: Pass the `--native` flag to the + *build* command. This will run the build inside a Docker container. +2. **Out-of-Source Builds**: In this scenario, Lambda function code is + present in a folder outside the folder containing the SAM template. + Absolute path to these folders are determined at runtime in a build + machine. Set the `--root=/my/folder` flag to absolute path to the + folder relative to which we will resolve relative *CodeUri* paths. +3. **Inherited dependency manifest**: By default, we will look for a + dependency manifest (ex: package.json) at same folder containing SAM + template. If a `--root` flag is set, we will look for manifest at + this folder. If neither locations have a manifest, we will look for + a manifest within the folder containing function code. Manifest + present within the code folder always overrides manifest at the + root. +4. **Arbitrary build commands**: Override build commands per-runtime by + specifying full path to the command in `.samrc`. +5. **Build & Run Locally**: Use the `--template` property of + `sam local` suite of commands to specify the template produced by + *build* command (ex: `build-template.yaml`) + +Implementation +============== + +CLI Changes +----------- + +*Explain the changes to command line interface, including adding new +commands, modifying arguments etc* + +1. Adding a new top-level command called `sam build`. +2. Add `built-template.yaml` to list of default template names searched + by `sam local` commands + +### Breaking Change + +*Are there any breaking changes to CLI interface? Explain* + +No Breaking Change to CLI interface + +Design +------ + +*Explain how this feature will be implemented. Highlight the components +of your implementation, relationships* *between components, constraints, +etc.* + +Build library provides the ability to execute build actions on each +registered resource. A build action is either a built-in functionality +or a custom build command provided by user. At a high level, the +algorithm looks like this: + +``` {.sourceCode .python} +for resource in sam_template: + # Find the appropriate builder + builder = get_builder(resource.Type) + + # Do the build + output_folder = make_build_folder(resource) + builder.build(resource.Code, resource.runtime, output_folder) +``` + +We will keep the implementation of build agnostic of the resource type. +This opens up the future possibility of adding build actions to any +resource types, not just Lambda functions. Initially we will start by +supporting only the resource types `AWS::Serverless::Function` and +`AWS::Lambda::Function`. + +### Build Folder + +Default Location: `$PKG_ROOT/build/` + +By default, we will create a folder called `build` right next to where +the SAM template is located. This will contain the built artifacts for +each resource. Customers can always override this folder location. + +Built artifacts for each resource will be stored within a folder named +with the LogicalID of the resource. This allows us to build separate zip +files for each Lambda, so users can update one Lambda without triggering +an update on another. The same model will work for building other +non-Lambda resources. + +*Advantages:* + +- Extensible to other resource types +- Supports parallel builds for each resource +- Aligned with a CloudFormation stack + +*Disadvantages:* + +- Too many build folders, and hence zip files, to manage. +- Difficult to share code between all Lambdas. + + + + $PKG_ROOT/build/ + artifacts.json (not for MVP) + MyFunction1/ + .... + + MyFunction2/ + ... + + MyApiGw/ + ... + + MyECRContainer/ + ... + +#### Future Extensions + +In the future, we will change the limitation around each folder being +named after the resource\'s LogicalID. Instead, we will support an +artifacts.json file that will map Lambda function resource's LogicalId +to the path to a folder that contains built artifacts for this function. +This allows us to support custom build systems that use different folder +layout. + +A well-known folder structure also helps "sam local" and "sam package" +commands to automatically discover the built artifacts for each Lambda +function and package it. + +### Stable Builds + +A build is defined to be stable if the built artifacts changes if and +only if the contents or metadata (ex: timestamp, ownership) on source +files changes. This is an important attribute of a build system. Since +SAM CLI relies on 3rd party package managers like NPM to do the heavy +lifting, we can only provide a "best effort" service here. By running +`sam build` on a build system that creates a new environment from +scratch (ex: Travis/CircleCI/CodeBuild/Jenkins etc), you can achieve +truly stable builds. For more information on why this is important, +refer to Debian\'s guide on [reproducible +builds](https://reproducible-builds.org/). + +SAM CLI does the following to produce stable builds: + +1. Clean build folder on every run +2. Include metadata when coping files and folders +3. Run build actions with minimal information passed from the + environment + +### Built-in Build Actions + +Build actions natively supported by SAM CLI follow a standard workflow: + +1. Search for a supported dependency manifest file. If a known manifest + is not present, we will abort the build. +2. Setup: Create build folder +3. Resolve: Install dependencies +4. Compile: Optionally, compile the code if necessary +5. Copy Source: Optionally, Copy Lambda function code to the build + folder + +Setup step is shared among all runtimes. Other steps in the workflow are +implemented differently for each runtime. + +#### Javascript using NPM + +Install dependencies specified by `package.json` and copy source files + +**Manifest Name**: `package.json` + +**Files Excluded From Copy Source**: `node_modules/*` + + ---------------------------------------------------- + Action Command + ------------- -------------------------------------- + Resolve `npm install` + + Compile No Op + + Copy Source Copy files and exclude node\_modules + ---------------------------------------------------- + +#### Java using Maven + +Let Maven take care of everything + +**Manifest Name**: `pom.xml` + +**Files Excluded From Copy Source**: N/A + + +| Action | Command | +|---------------|----------------| +| Resolve | No Op | +| Compile | `mvn package` | +| Copy Source | No Op | + + +#### Golang using Go CLI + +Go\'s CLI will build the binary. + +**Manifest Name**: `Gopkg.toml` + +**Files Excluded From Copy Source**: N/A + +| Action | Command | +|---------------|--------------------------------------------------| +| Resolve | `dep ensure -v` | +| Compile | `GOOS=linux go build -ldflags="-s -w" main.go` | +| Copy Source | No Op | + + +#### Dotnet using Dotnet CLI + +**Manifest Name**: `*.csproj` + +**Files Excluded From Copy Source**: N/A + + +| Action | Command | +|---------------|--------------------------------------------------------------------------------------| +| Resolve | No Op | +| Compile | `dotnet lambda package --configuration release --output-package $BUILD/package.zip` | +| Copy Source | No Op | + + +#### Python using PIP + +**Manifest Name**: `requirements.txt` + +**Files Excluded From Copy Source**: `*.pyc, __pycache__` + +| Action | Command | +|---------------|--------------------------------------------------------------------------------------| +| Resolve | `pip install --isolated --disable-pip-version-check -r requirements.txt -t $BUILD` | +| Compile | No Op | +| Copy Source | Copy all files | + + +### Implementation of Build Actions + +Some of the built-in build actions are implemented in the programming +language that the actions supports. For example, the Nodejs build action +will be implemented in Javascript to take advantage of language-specific +libraries. These modules are called **builders**. This is a reasonable +implementation choice because customers building Nodejs apps are +expected to have Node installed on their system. For languages like +Golang, we will delegate entire functionality to `go` tool by invoking +it as a subprocess. The SAM CLI distribution will now bundle Javascript +code within a Python package, which even though seems odd, carries +value. + +**Pros:** + +- Easy to lift & shift +- Easy to use language specific libraries that can support deeper + integrations in future like webpack build or running gulp scripts +- Sets precedence for other runtimes like Java which might need + reflexion to create the package +- Easier to get help from JS community who is more familiar with + building JS packages. + +**Cons:** + +- Vending JS files in Python package +- Might take dependency on certain version of Node. We can\'t enforce + that customers have this version of Node on their system. +- Might have to webpack all dependencies, minify and vend one file + that we just run using node pack.js. +- Could become a tech debt if this approach doesn\'t scale. + +#### Builder Interface + +In this implementation model, some steps in the build action are +implemented natively in Python and some in a separate programming +language. To complete a build operation, SAM CLI reads SAM template, +prepares necessary folder structure, and invokes the appropriate builder +process/command by passing necessary information through stdin as +JSON-RPC. SAM CLI waits for a JSON-RPC response back through stdout of +the process and depending on the status, either fails the build or +proceeds to next step. + +**Input:** + +``` {.sourceCode .json} +{ + "jsonrpc": "2.0", + + "id": "42", + + // Only supported method is `resolve-dependencies` + "method": "resolve-dependencies", + "params": { + "source_dir": "/folder/where/source/files/located", + "build_dir": "/directory/for/builder/artifacts", + "runtime": "aws lambda function runtime ex. node8.10", + "template_path": "/path/to/sam/template" + } +} +``` + +**Output:** + +``` {.sourceCode .json} +{ + "jsonrpc": "2.0", + + "id": "42", + + "result": { + // No result expected for successful execution + } +} +``` + +### Building Native Binaries + +To build native binaries, we need to run on an architecture and +operating system that is similar to AWS Lambda. We use the Docker +containers provided by [Docker +Lambda](https://github.com/lambci/docker-lambda) project to run the same +set of commands described above on this container. We will mount source +code folder and build folder into the container so the commands have +access to necessary files. + +`.samrc` Changes (Out-of-Scope) +------------------------------- + +*Explain the new configuration entries, if any, you want to add to +.samrc* + +We will add a new section to `.samrc` where customers can provide custom +build actions. This section will look like: + +``` {.sourceCode .json} +{ + "build": { + "actions": { + "java8": "gradle build", + "dotnetcore2.1": "./build.sh" + } + } +} +``` + +Security +-------- + +*Tip: How does this change impact security? Answer the following +questions to help answer this question better:* + +**What new dependencies (libraries/cli) does this change require?** + +**What other Docker container images are you using?** + +**Are you creating a new HTTP endpoint? If so explain how it will be +created & used** + +**Are you connecting to a remote API? If so explain how is this +connection secured** + +**Are you reading/writing to a temporary folder? If so, what is this +used for and when do you clean up?** + +**How do you validate new .samrc configuration?** + +Documentation Changes +--------------------- + +TBD + +Open Questions +-------------- + +1. Should we support `artifacts.json` now to be future-proof? **Answer: + NO** +2. Should we create the default `build` folder within a `.sam` folder + inside the project to provide a home for other scratch files if + necessary? **Answer: Out of Scope for current implementation** + +Task Breakdown +-------------- + +- \[x\] Send a Pull Request with this design document +- \[ \] Build the command line interface +- \[ \] Wire up SAM provider to discover function to build +- \[ \] Library to build Python functions for MVP (others languages + will follow next) +- \[ \] Add `built-template.yaml` to list of default template names + searched by `sam local` commands +- \[ \] Update `sam init` templates to include `sam build` in the + README +- \[ \] Unit tests +- \[ \] Functional Tests +- \[ \] Integration tests +- \[ \] Run all tests on Windows +- \[ \] Update documentation diff --git a/designs/sam_build_cmd.rst b/designs/sam_build_cmd.rst deleted file mode 100644 index 05aedd62e0..0000000000 --- a/designs/sam_build_cmd.rst +++ /dev/null @@ -1,515 +0,0 @@ -.. contents:: **Table of Contents** - :depth: 2 - :local: - -``sam build`` command -===================== -This is the design for a command to **build** a Lambda function. **Build** is the operation of converting the function's -source code to an artifact that can be executed on AWS Lambda. - - -What is the problem? --------------------- -To run a function on AWS Lambda, customers need to provide a zip file containing an executable form of the code. The -process of creating the executable usually involves downloading dependent libraries, optionally compiling the code -on Amazon Linux, copying static assets, and arranging the files in a directory structure that AWS Lambda accepts. -In some programming languages like Javascript, this process is fairly straightforward (just zip a folder), and in -others like Python, it is much involved. - -Customers using SAM CLI can easily create Lambda function code (using ``sam init``) and package their artifact as a -zip file (using ``sam package``), but they have to handle the build process themselves. Customers usually implement -their own build scripts or adopt other's scripts from the internet. This is where many customers fall off the cliff. - - -What will be changed? ---------------------- -In this proposal, we will be providing a new command, ``sam build``, to build Lambda functions for all programming -languages that AWS Lambda supports. The cardinality of the problem is number of programming languages (N) times the -number of package managers (M) per language. Hence is it is nearly impossible to natively support each combination. -Instead, ``sam build`` will support an opinionated set of package managers for all programming languages. In the future, -we will provide an option for customers to bring their own build commands or override the default for any programming -language. SAM CLI will still take care of the grunt work of iterating through every function in the SAM template, -figuring out the source code location, creating temporary folders to store built artifacts, running the build command -and move artifacts to right location. - - -Success criteria for the change -------------------------------- -#. Support all programming languages supported by AWS Lambda - - * Nodejs with NPM - * Java with Maven - * Python with PIP - * Golang with Go CLI - * Dotnetcore with DotNet CLI - - -#. Each Lambda function in SAM template gets built - -#. Produce stable builds (best effort): If the source files did not change, built artifacts should not change. - -#. Built artifacts should "just work" with ``sam local`` and ``sam package`` suite of commands - -#. Opt-in to building native dependencies that can run on AWS Lambda using Docker. - -#. Support one dependency manifest (ex: package.json) per each Lambda function. - -#. Support out-of-source builds: ie. source code of Lambda function is outside the directory containing SAM template. - -#. Integrate build action with ``sam local/package/deploy`` commands so the Lambda functions will be automatically - built as part of the command without explicitly running the build command. - - -Out-of-Scope ------------- -#. Ability to provide arbitrary build commands for each Lambda Function runtime. This will either override the built-in - default or add build support for languages/tools that SAM CLI does not support (ex: java+gradle). -#. Supports adding data files ie. files that are not referenced by the package manager (ex: images, css etc) -#. Support to exclude certain files from the built artifact (ex: using .gitignore or using regex) -#. Support for building the app for debugging locally with debug symbols (ex: Golang) -#. Support caching dependencies & re-installing them only when the dependency manifest changes - (ex: by maintaining hash of package.json) -#. If the app contains a ``buildspec.yaml``, automatically run it using CodeBuild Local. -#. Watch for file changes and build automatically (ex: ``sam build --watch``) -#. Support other build systems by default Webpack, Yarn or Gradle. -#. Support in AWS CLI, ``aws cloudformation``, suite of commands -#. Support for fine-grained hooks (ex: hooks that run pre-build, post-build, etc) -#. Support one dependency manifest per app, shared by all the Lambda functions (this is usually against best practices) - - -User Experience Walkthrough ---------------------------- -Let's assume customers has the following SAM template: - - **NOTE**: Currently we advice customers to set *CodeUri* to a folder containing built artifacts that can be readily - packaged by ``sam package`` command. But to use with *build* command, customers need to set *CodeUri* to the folder - containing source code and not built artifacts. - -.. code-block:: yaml - - MyFunction1: - Type: AWS::Lambda::Function - Properties: - ... - Code: ./source-code1 - ... - - MyFunction2: - Type: AWS::Serverless::Function - Properties: - ... - Code: ./source-code2 - ... - - -To build, package and deploy this app, customers would do the following: - -**1. Build:** Run the following command to build all functions in the template and output a SAM template that can be run through -the package command: - -.. code-block:: bash - - # Build the code and write artifacts to ./build folder - # NOTE: All arguments will have sensible defaults so users can just use `sam build` - $ sam build -t template.yaml -b ./build -o built-template.yaml - - -Output of the *sam build* command is a SAM template where CodeUri is pointing to the built artifacts. Note the values of -Code properties in following output: - -.. code-block:: bash - - $ cat built-template.yaml - MyFunction1: - Type: AWS::Lambda::Function - Properties: - ... - Code: ./build/MyFunction1 - ... - - MyFunction2: - Type: AWS::Serverless::Function - Properties: - ... - CodeUri: ./build/MyFunction2 - ... - -**2. Package and Deploy:** Package the built artifacts by running the *package* command on the template output -by *build* command - -.. code-block:: bash - - # Package the code - $ sam package --template-file built-template.yaml --s3-bucket mybucket --output-template-file packaged-template.yaml - - # Deploy the app - $ sam deploy --template-file packaged-template.yaml --stack-name mystack - -Other Usecases -~~~~~~~~~~~~~~~ - -#. **Build Native Dependencies**: Pass the ``--native`` flag to the *build* command. This will run the build inside - a Docker container. -#. **Out-of-Source Builds**: In this scenario, Lambda function code is present in a folder outside the folder containing - the SAM template. Absolute path to these folders are determined at runtime in a build machine. Set the - ``--root=/my/folder`` flag to absolute path to the folder relative to which we will resolve relative *CodeUri* paths. -#. **Inherited dependency manifest**: By default, we will look for a dependency manifest (ex: package.json) at same - folder containing SAM template. If a ``--root`` flag is set, we will look for manifest at this folder. If neither - locations have a manifest, we will look for a manifest within the folder containing function code. Manifest present - within the code folder always overrides manifest at the root. -#. **Arbitrary build commands**: Override build commands per-runtime by specifying full path to the command in - ``.samrc``. -#. **Build & Run Locally**: Use the ``--template`` property of ``sam local`` suite of commands to specify the - template produced by *build* command (ex: ``build-template.yaml``) - -Implementation -============== - -CLI Changes ------------ -*Explain the changes to command line interface, including adding new commands, modifying arguments etc* - -#. Adding a new top-level command called ``sam build``. -#. Add ``built-template.yaml`` to list of default template names searched by ``sam local`` commands - - -Breaking Change -~~~~~~~~~~~~~~~ -*Are there any breaking changes to CLI interface? Explain* - -No Breaking Change to CLI interface - -Design ------- -*Explain how this feature will be implemented. Highlight the components of your implementation, relationships* -*between components, constraints, etc.* - -Build library provides the ability to execute build actions on each registered resource. A build action is either -a built-in functionality or a custom build command provided by user. At a high level, the algorithm looks like this: - -.. code-block:: python - - for resource in sam_template: - # Find the appropriate builder - builder = get_builder(resource.Type) - - # Do the build - output_folder = make_build_folder(resource) - builder.build(resource.Code, resource.runtime, output_folder) - - -We will keep the implementation of build agnostic of the resource type. This opens up the future possibility of adding -build actions to any resource types, not just Lambda functions. Initially we will start by supporting only the -resource types ``AWS::Serverless::Function`` and ``AWS::Lambda::Function``. - -Build Folder -~~~~~~~~~~~~ -Default Location: ``$PKG_ROOT/build/`` - -By default, we will create a folder called ``build`` right next to where the SAM template is located. -This will contain the built artifacts for each resource. Customers can always override this folder location. - -Built artifacts for each resource will be stored within a folder named with the LogicalID of the resource. -This allows us to build separate zip files for each Lambda, so users can update one Lambda without triggering an update -on another. The same model will work for building other non-Lambda resources. - -*Advantages:* - -* Extensible to other resource types -* Supports parallel builds for each resource -* Aligned with a CloudFormation stack - -*Disadvantages:* - -* Too many build folders, and hence zip files, to manage. -* Difficult to share code between all Lambdas. - -:: - - $PKG_ROOT/build/ - artifacts.json (not for MVP) - MyFunction1/ - .... - - MyFunction2/ - ... - - MyApiGw/ - ... - - MyECRContainer/ - ... - - -Future Extensions -^^^^^^^^^^^^^^^^^ -In the future, we will change the limitation around each folder being named after the resource's LogicalID. -Instead, we will support an artifacts.json file that will map Lambda function resource's LogicalId to the path to a -folder that contains built artifacts for this function. This allows us to support custom build systems that use -different folder layout. - -A well-known folder structure also helps “sam local” and “sam package” commands to automatically discover the -built artifacts for each Lambda function and package it. - -Stable Builds -~~~~~~~~~~~~~ -A build is defined to be stable if the built artifacts changes if and only if the contents or metadata -(ex: timestamp, ownership) on source files changes. This is an important attribute of a build system. Since SAM CLI -relies on 3rd party package managers like NPM to do the heavy lifting, we can only provide a "best effort" service here. -By running ``sam build`` on a build system that creates a new environment from scratch -(ex: Travis/CircleCI/CodeBuild/Jenkins etc), you can achieve truly stable builds. For more information on why this -is important, refer to Debian's guide on `reproducible builds `_. - - -SAM CLI does the following to produce stable builds: - -#. Clean build folder on every run -#. Include metadata when coping files and folders -#. Run build actions with minimal information passed from the environment - - -Built-in Build Actions -~~~~~~~~~~~~~~~~~~~~~~ -Build actions natively supported by SAM CLI follow a standard workflow: - -#. Search for a supported dependency manifest file. If a known manifest is not present, we will abort the build. -#. Setup: Create build folder -#. Resolve: Install dependencies -#. Compile: Optionally, compile the code if necessary -#. Copy Source: Optionally, Copy Lambda function code to the build folder - -Setup step is shared among all runtimes. Other steps in the workflow are implemented differently for each runtime. - -Javascript using NPM -^^^^^^^^^^^^^^^^^^^^ - -Install dependencies specified by ``package.json`` and copy source files - -**Manifest Name**: ``package.json`` - -**Files Excluded From Copy Source**: ``node_modules/*`` - -+-------------+--------------------------------------+ -| Action | Command | -+=============+======================================+ -| Resolve | ``npm install`` | -+-------------+--------------------------------------+ -| Compile | No Op | -+-------------+--------------------------------------+ -| Copy Source | Copy files and exclude node_modules | -+-------------+--------------------------------------+ - - -Java using Maven -^^^^^^^^^^^^^^^^ - -Let Maven take care of everything - -**Manifest Name**: ``pom.xml`` - -**Files Excluded From Copy Source**: N/A - -+-------------+-----------------+ -| Action | Command | -+=============+=================+ -| Resolve | No Op | -+-------------+-----------------+ -| Compile | ``mvn package`` | -+-------------+-----------------+ -| Copy Source | No Op | -+-------------+-----------------+ - -Golang using Go CLI -^^^^^^^^^^^^^^^^^^^ - -Go's CLI will build the binary. - -**Manifest Name**: ``Gopkg.toml`` - -**Files Excluded From Copy Source**: N/A - -+-------------+---------------------------------------------------+ -| Action | Command | -+=============+===================================================+ -| Resolve | ``dep ensure -v`` | -+-------------+---------------------------------------------------+ -| Compile | ``GOOS=linux go build -ldflags="-s -w" main.go`` | -+-------------+---------------------------------------------------+ -| Copy Source | No Op | -+-------------+---------------------------------------------------+ - - -Dotnet using Dotnet CLI -^^^^^^^^^^^^^^^^^^^^^^^ - -**Manifest Name**: ``*.csproj`` - -**Files Excluded From Copy Source**: N/A - -+-------------+----------------------------------------------------------------------------------------+ -| Action | Command | -+=============+========================================================================================+ -| Resolve | No Op | -+-------------+----------------------------------------------------------------------------------------+ -| Compile | ``dotnet lambda package --configuration release --output-package $BUILD/package.zip`` | -+-------------+----------------------------------------------------------------------------------------+ -| Copy Source | No Op | -+-------------+----------------------------------------------------------------------------------------+ - - -Python using PIP -^^^^^^^^^^^^^^^^ - -**Manifest Name**: ``requirements.txt`` - -**Files Excluded From Copy Source**: ``*.pyc, __pycache__`` - -+-------------+---------------------------------------------------------------------------------------+ -| Action | Command | -+=============+=======================================================================================+ -| Resolve | ``pip install --isolated --disable-pip-version-check -r requirements.txt -t $BUILD`` | -+-------------+---------------------------------------------------------------------------------------+ -| Compile | No Op | -+-------------+---------------------------------------------------------------------------------------+ -| Copy Source | Copy all files | -+-------------+---------------------------------------------------------------------------------------+ - -Implementation of Build Actions -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Some of the built-in build actions are implemented in the programming language that the actions supports. For example, -the Nodejs build action will be implemented in Javascript to take advantage of language-specific libraries. These -modules are called **builders**. This is a reasonable implementation choice because customers building Nodejs apps are -expected to have Node installed on their system. For languages like Golang, we will delegate entire functionality -to ``go`` tool by invoking it as a subprocess. The SAM CLI distribution will now bundle Javascript code within a Python -package, which even though seems odd, carries value. - - -**Pros:** - -- Easy to lift & shift -- Easy to use language specific libraries that can support deeper integrations in future like webpack build or - running gulp scripts -- Sets precedence for other runtimes like Java which might need reflexion to create the package -- Easier to get help from JS community who is more familiar with building JS packages. - -**Cons:** - -- Vending JS files in Python package -- Might take dependency on certain version of Node. We can't enforce that customers have this version of Node on their system. -- Might have to webpack all dependencies, minify and vend one file that we just run using node pack.js. -- Could become a tech debt if this approach doesn't scale. - -Builder Interface -^^^^^^^^^^^^^^^^^ - -In this implementation model, some steps in the build action are implemented natively in Python and some in a separate -programming language. To complete a build operation, SAM CLI reads SAM template, prepares necessary folder structure, -and invokes the appropriate builder process/command by passing necessary information through stdin as JSON-RPC. SAM CLI -waits for a JSON-RPC response back through stdout of the process and depending on the status, either fails the build -or proceeds to next step. - -**Input:** - -.. code-block:: json - - { - "jsonrpc": "2.0", - - "id": "42", - - // Only supported method is `resolve-dependencies` - "method": "resolve-dependencies", - "params": { - "source_dir": "/folder/where/source/files/located", - "build_dir": "/directory/for/builder/artifacts", - "runtime": "aws lambda function runtime ex. node8.10", - "template_path": "/path/to/sam/template" - } - } - - -**Output:** - -.. code-block:: json - - { - "jsonrpc": "2.0", - - "id": "42", - - "result": { - // No result expected for successful execution - } - } - - -Building Native Binaries -~~~~~~~~~~~~~~~~~~~~~~~~ -To build native binaries, we need to run on an architecture and operating system that is similar to AWS Lambda. We use -the Docker containers provided by `Docker Lambda `_ project to run the same -set of commands described above on this container. We will mount source code folder and build folder into the container -so the commands have access to necessary files. - -``.samrc`` Changes (Out-of-Scope) ---------------------------------- -*Explain the new configuration entries, if any, you want to add to .samrc* - -We will add a new section to ``.samrc`` where customers can provide custom build actions. This section will look like: - -.. code-block:: json - - { - "build": { - "actions": { - "java8": "gradle build", - "dotnetcore2.1": "./build.sh" - } - } - } - -Security --------- - -*Tip: How does this change impact security? Answer the following questions to help answer this question better:* - -**What new dependencies (libraries/cli) does this change require?** - -**What other Docker container images are you using?** - -**Are you creating a new HTTP endpoint? If so explain how it will be created & used** - -**Are you connecting to a remote API? If so explain how is this connection secured** - -**Are you reading/writing to a temporary folder? If so, what is this used for and when do you clean up?** - -**How do you validate new .samrc configuration?** - - -Documentation Changes ---------------------- -TBD - -Open Questions --------------- - -#. Should we support ``artifacts.json`` now to be future-proof? **Answer: NO** -#. Should we create the default ``build`` folder within a ``.sam`` folder inside the project to provide a home for - other scratch files if necessary? **Answer: Out of Scope for current implementation** - - -Task Breakdown --------------- -- [x] Send a Pull Request with this design document -- [ ] Build the command line interface -- [ ] Wire up SAM provider to discover function to build -- [ ] Library to build Python functions for MVP (others languages will follow next) -- [ ] Add ``built-template.yaml`` to list of default template names searched by ``sam local`` commands -- [ ] Update ``sam init`` templates to include ``sam build`` in the README -- [ ] Unit tests -- [ ] Functional Tests -- [ ] Integration tests -- [ ] Run all tests on Windows -- [ ] Update documentation - - From 82cd06ca128821490ef143589352095f80299e5b Mon Sep 17 00:00:00 2001 From: Sriram Madapusi Vasudevan Date: Fri, 28 Dec 2018 11:00:53 -0800 Subject: [PATCH 3/3] fix: docs directory to md - remove sphinx builds - add links to official aws quick start documentation --- README.md | 4 +- docs/Makefile | 20 - docs/advanced_usage.md | 265 +++++++ docs/advanced_usage.rst | 272 ------- docs/conf.py | 169 ---- docs/deploying_serverless_applications.md | 80 ++ docs/getting_started.rst | 66 -- docs/installation.rst | 15 - docs/make.bat | 36 - ...bugging_serverless_applications_locally.md | 142 ++++ ...ugging_serverless_applications_locally.rst | 113 --- docs/usage.md | 747 ++++++++++++++++++ docs/usage.rst | 737 ----------------- 13 files changed, 1236 insertions(+), 1430 deletions(-) delete mode 100644 docs/Makefile create mode 100644 docs/advanced_usage.md delete mode 100644 docs/advanced_usage.rst delete mode 100644 docs/conf.py create mode 100644 docs/deploying_serverless_applications.md delete mode 100644 docs/getting_started.rst delete mode 100644 docs/installation.rst delete mode 100644 docs/make.bat create mode 100644 docs/running_and_debugging_serverless_applications_locally.md delete mode 100644 docs/running_and_debugging_serverless_applications_locally.rst create mode 100644 docs/usage.md delete mode 100644 docs/usage.rst diff --git a/README.md b/README.md index e9a7cccf88..0970e3fd39 100644 --- a/README.md +++ b/README.md @@ -41,9 +41,9 @@ Get Started Learn how to get started using the SAM CLI with these guides: -- [Installation](docs/installation.rst): Set up your macOS, Linux or +- [Installation](https://aws.amazon.com/serverless/sam/): Set up your macOS, Linux or Windows Machine to run serverless projects with SAM CLI. -- [Introduction to SAM and SAM CLI](docs/getting_started.rst) What is +- [Introduction to SAM and SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-quick-start.html) What is SAM and SAM CLI, and how can you use it to make a simple hello-world app. - [Running and debugging serverless applications diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index 0d692e8b5c..0000000000 --- a/docs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# Minimal makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -SPHINXPROJ = SAMCLI -SOURCEDIR = . -BUILDDIR = _build - -# Put it first so that "make" without argument is like "make help". -help: - @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - -.PHONY: help Makefile - -# Catch-all target: route all unknown targets to Sphinx using the new -# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). -%: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/advanced_usage.md b/docs/advanced_usage.md new file mode 100644 index 0000000000..4fa33fd076 --- /dev/null +++ b/docs/advanced_usage.md @@ -0,0 +1,265 @@ +Advanced Usage +============== + +- [Compiled Languages](#compiled-languages) +- [IAM Credentials](#iam-credentials) +- [Lambda Environment Variables](#lambda-environment-variables) + - [Environment Variable file](#environment-variable-file) + - [Shell environment](#shell-environment) + - [Combination of Shell and Environment Variable + file](#combination-of-shell-and-environment-variable-file) +- [Identifying local execution from Lambda function + code](#identifying-local-execution-from-lambda-function-code) +- [Static Assets](#static-assets) +- [Local Logging](#local-logging) +- [Remote Docker](#remote-docker) + +Compiled Languages +------------------ + +**Java** + +To use SAM CLI 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. + +For example: + +``` {.sourceCode .yaml} +AWSTemplateFormatVersion: 2010-09-09 +Transform: AWS::Serverless-2016-10-31 + +Resources: + ExampleJavaFunction: + Type: AWS::Serverless::Function + Properties: + Handler: com.example.HelloWorldHandler + CodeUri: ./target/HelloWorld-1.0.jar + Runtime: java8 +``` + +You 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. + +``` {.sourceCode .bash} +// Build the JAR file +$ mvn package shade:shade + +// Invoke with SAM Local +$ echo '{ "some": "input" }' | sam local invoke + +// Or start local API Gateway simulator +$ sam local start-api +``` + +**.NET Core** + +To use SAM Local with compiled languages, such as .NET Core that require +a packaged artifact (e.g. a ZIP), you can specify the location of the +artifact with the `AWS::Serverless::Function` `CodeUri` property in your +SAM template. + +For example: + +``` {.sourceCode .yaml} +AWSTemplateFormatVersion: 2010-09-09 +Transform: AWS::Serverless-2016-10-31 + +Resources: + ExampleDotNetFunction: + Type: AWS::Serverless::Function + Properties: + Handler: HelloWorld::HelloWorld.Function::Handler + CodeUri: ./artifacts/HelloWorld.zip + Runtime: dotnetcore2.0 +``` + +You should then build your ZIP file using your normal build process. + +You can generate a .NET Core example by using the +`sam init --runtime dotnetcore` command. + +IAM Credentials +--------------- + +SAM CLI will invoke functions with your locally configured IAM +credentials. + +As with the AWS CLI and SDKs, SAM CLI will look for credentials in the +following order: + +1. Environment Variables (`AWS_ACCESS_KEY_ID`, + `AWS_SECRET_ACCESS_KEY`). +2. The AWS credentials file (located at `~/.aws/credentials` on Linux, + macOS, or Unix, or at `C:\Users\USERNAME \.aws\credentials` on + Windows). +3. Instance profile credentials (if running on Amazon EC2 with an + assigned instance role). + +In order to test API Gateway with a non-default profile from your AWS +credentials file append `--profile ` to the `start-api` +command: + +``` {.sourceCode .bash} +// Test API Gateway locally with a credential profile. +$ sam local start-api --profile some_profile +``` + +See 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. + +Lambda Environment Variables +---------------------------- + +If 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: + +For example, consider the SAM template snippet: + +``` {.sourceCode .yaml} +Resources: + MyFunction1: + Type: AWS::Serverless::Function + Properties: + Handler: index.handler + Runtime: nodejs4.3 + Environment: + Variables: + TABLE_NAME: prodtable + BUCKET_NAME: prodbucket + + MyFunction2: + Type: AWS::Serverless::Function + Properties: + Handler: app.handler + Runtime: nodejs4.3 + Environment: + Variables: + STAGE: prod + TABLE_NAME: prodtable +``` + +Environment Variable file +------------------------- + +Use the `--env-vars` argument of the `invoke` or `start-api` commands to +provide a JSON file that contains values to override the environment +variables already defined in your function template. The file should be +structured as follows: + +``` {.sourceCode .json} +{ + "MyFunction1": { + "TABLE_NAME": "localtable", + "BUCKET_NAME": "testBucket" + }, + "MyFunction2": { + "TABLE_NAME": "localtable", + "STAGE": "dev" + }, +} +``` + +``` {.sourceCode .bash} +$ sam local start-api --env-vars env.json +``` + +Shell environment +----------------- + +Variables 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. + +Following command will make value of `mytable` available to both +`MyFunction1` and `MyFunction2` + +``` {.sourceCode .bash} +$ TABLE_NAME=mytable sam local start-api +``` + +Combination of Shell and Environment Variable file +-------------------------------------------------- + +For 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. + +1. Environment Variable file +2. Shell's environment +3. Hard-coded values from the template + +Identifying local execution from Lambda function code +----------------------------------------------------- + +When your Lambda function is invoked using SAM CLI, 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. + +Static Assets +------------- + +Often, 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 CLI 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 ""`. + +Local Logging +------------- + +Both `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 CLI and want to capture logs for +analysis. + +Example: + +``` {.sourceCode .bash} +$ sam local invoke --log-file ./output.log +``` + +Remote Docker +------------- + +Sam CLI 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. + +If mounted, you can use the remote docker normally using +`--docker-volume-basedir` or environment variable +`SAM_DOCKER_VOLUME_BASEDIR`. + +Example - Docker Toolbox (Windows): + +When you install and run Docker Toolbox, the Linux VM with Docker is +automatically installed in the virtual box. + +The /c/ path for this Linux VM is automatically shared with C: on the +host machine. + +``` {.sourceCode .powershell} +$ sam local invoke --docker-volume-basedir /c/Users/shlee322/projects/test "Ratings" +``` + +### Learn More + +- [Project Overview](../README.md) +- [Getting started with SAM and the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-quick-start.html) +- [Usage](usage.md) +- [Packaging and deploying your + application](deploying_serverless_applications.md) diff --git a/docs/advanced_usage.rst b/docs/advanced_usage.rst deleted file mode 100644 index eaeb72e819..0000000000 --- a/docs/advanced_usage.rst +++ /dev/null @@ -1,272 +0,0 @@ - -============== -Advanced Usage -============== -- `Compiled Languages <#compiled-languages>`__ -- `IAM Credentials <#iam-credentials>`__ -- `Lambda Environment Variables <#lambda-environment-variables>`__ - - - `Environment Variable file <#environment-variable-file>`__ - - `Shell environment <#shell-environment>`__ - - `Combination of Shell and Environment Variable file <#combination-of-shell-and-environment-variable-file>`__ - -- `Identifying local execution from Lambda function - code <#identifying-local-execution-from-lambda-function-code>`__ -- `Static Assets <#static-assets>`__ -- `Local Logging <#local-logging>`__ -- `Remote Docker <#remote-docker>`__ - -Compiled Languages ------------------- - -**Java** - -To use SAM CLI 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. - -For example: - -.. code:: yaml - - AWSTemplateFormatVersion: 2010-09-09 - Transform: AWS::Serverless-2016-10-31 - - Resources: - ExampleJavaFunction: - Type: AWS::Serverless::Function - Properties: - Handler: com.example.HelloWorldHandler - CodeUri: ./target/HelloWorld-1.0.jar - Runtime: java8 - -You 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. - -.. code:: bash - - // Build the JAR file - $ mvn package shade:shade - - // Invoke with SAM Local - $ echo '{ "some": "input" }' | sam local invoke - - // Or start local API Gateway simulator - $ sam local start-api - - -**.NET Core** - -To use SAM Local with compiled languages, such as .NET Core that require a packaged artifact (e.g. a ZIP), you can specify the location of the artifact with the ``AWS::Serverless::Function`` ``CodeUri`` property in your SAM template. - -For example: - -.. code:: yaml - - AWSTemplateFormatVersion: 2010-09-09 - Transform: AWS::Serverless-2016-10-31 - - Resources: - ExampleDotNetFunction: - Type: AWS::Serverless::Function - Properties: - Handler: HelloWorld::HelloWorld.Function::Handler - CodeUri: ./artifacts/HelloWorld.zip - Runtime: dotnetcore2.0 - -You should then build your ZIP file using your normal build process. - -You can generate a .NET Core example by using the ``sam init --runtime dotnetcore`` command. - -.. _IAMCreds - -IAM Credentials ---------------- - -SAM CLI will invoke functions with your locally configured IAM -credentials. - -As with the AWS CLI and SDKs, SAM CLI will look for credentials in the -following order: - -1. Environment Variables (``AWS_ACCESS_KEY_ID``, - ``AWS_SECRET_ACCESS_KEY``). -2. The AWS credentials file (located at ``~/.aws/credentials`` on Linux, - macOS, or Unix, or at ``C:\Users\USERNAME \.aws\credentials`` on - Windows). -3. Instance profile credentials (if running on Amazon EC2 with an - assigned instance role). - -In order to test API Gateway with a non-default profile from your AWS -credentials file append ``--profile `` to the -``start-api`` command: - -.. code:: bash - - // Test API Gateway locally with a credential profile. - $ sam local start-api --profile some_profile - -See this `Configuring the AWS -CLI `__ -for more details. - -Lambda Environment Variables ----------------------------- - -If 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: - -For example, consider the SAM template snippet: - -.. code:: yaml - - - Resources: - MyFunction1: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs4.3 - Environment: - Variables: - TABLE_NAME: prodtable - BUCKET_NAME: prodbucket - - MyFunction2: - Type: AWS::Serverless::Function - Properties: - Handler: app.handler - Runtime: nodejs4.3 - Environment: - Variables: - STAGE: prod - TABLE_NAME: prodtable - - -Environment Variable file -------------------------- - -Use the ``--env-vars`` argument of the ``invoke`` or ``start-api`` commands -to provide a JSON file that contains values to override the environment -variables already defined in your function template. The file should be -structured as follows: - -.. code:: json - - { - "MyFunction1": { - "TABLE_NAME": "localtable", - "BUCKET_NAME": "testBucket" - }, - "MyFunction2": { - "TABLE_NAME": "localtable", - "STAGE": "dev" - }, - } - -.. code:: bash - - $ sam local start-api --env-vars env.json - - -Shell environment ------------------ - -Variables 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. - -Following command will make value of ``mytable`` available to both -``MyFunction1`` and ``MyFunction2`` - -.. code:: bash - - $ TABLE_NAME=mytable sam local start-api - -Combination of Shell and Environment Variable file --------------------------------------------------- - -For 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. - -1. Environment Variable file -2. Shell’s environment -3. Hard-coded values from the template - -Identifying local execution from Lambda function code ------------------------------------------------------ - -When your Lambda function is invoked using SAM CLI, 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. - -Static Assets -------------- - -Often, 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 CLI 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 ""``. - -Local Logging -------------- - -Both ``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 CLI and want to capture logs for -analysis. - -Example: - -.. code:: bash - - $ sam local invoke --log-file ./output.log - -Remote Docker -------------- - -Sam CLI 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. - -If mounted, you can use the remote docker normally using -``--docker-volume-basedir`` or environment variable -``SAM_DOCKER_VOLUME_BASEDIR``. - -Example - Docker Toolbox (Windows): - -When you install and run Docker Toolbox, the Linux VM with Docker is -automatically installed in the virtual box. - -The /c/ path for this Linux VM is automatically shared with C: on the -host machine. - -.. code:: powershell - - $ sam local invoke --docker-volume-basedir /c/Users/shlee322/projects/test "Ratings" - -Learn More -========== - -- `Project Overview <../README.rst>`__ -- `Installation `__ -- `Getting started with SAM and the SAM CLI `__ -- `Usage `__ -- `Packaging and deploying your application `__ \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py deleted file mode 100644 index 74ad42a370..0000000000 --- a/docs/conf.py +++ /dev/null @@ -1,169 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# -# SAM CLI documentation build configuration file, created by -# sphinx-quickstart on Fri Apr 27 12:48:05 2018. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# -# import os -# import sys -# sys.path.insert(0, os.path.abspath('.')) - - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -# -# needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# -# source_suffix = ['.rst', '.md'] -source_suffix = '.rst' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = 'SAM CLI' -copyright = '2018, AWS SAM' -author = 'AWS SAM' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = '' -# The full version, including alpha/beta/rc tags. -release = '' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = False - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -html_theme = 'alabaster' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# -# html_theme_options = {} - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# Custom sidebar templates, must be a dictionary that maps document names -# to template names. -# -# This is required for the alabaster theme -# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars -html_sidebars = { - '**': [ - 'relations.html', # needs 'show_related': True theme option to display - 'searchbox.html', - ] -} - - -# -- Options for HTMLHelp output ------------------------------------------ - -# Output file base name for HTML help builder. -htmlhelp_basename = 'SAMCLIdoc' - - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - (master_doc, 'SAMCLI.tex', 'SAM CLI Documentation', - 'AWS SAM', 'manual'), -] - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - (master_doc, 'samcli', 'SAM CLI Documentation', - [author], 1) -] - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - (master_doc, 'SAMCLI', 'SAM CLI Documentation', - author, 'SAMCLI', 'One line description of project.', - 'Miscellaneous'), -] - - - diff --git a/docs/deploying_serverless_applications.md b/docs/deploying_serverless_applications.md new file mode 100644 index 0000000000..ca65d54a99 --- /dev/null +++ b/docs/deploying_serverless_applications.md @@ -0,0 +1,80 @@ +Once you have created a Lambda function and a template.yaml file, you +can use the AWS CLI to package and deploy your serverless application. + +Packaging and deploying your application +======================================== + +In order to complete the procedures below, you need to first complete +the following: + +> [Set up an AWS +> Account](https://docs.aws.amazon.com/lambda/latest/dg/setup.html). +> +> [Set up the AWS +> CLI](https://docs.aws.amazon.com/lambda/latest/dg/setup-awscli.html) . + +Packaging your application +========================== + +To package your application, create an Amazon S3 bucket that the package +command will use to upload your ZIP deployment package (if you haven\'t +specified one in your example.yaml file). You can use the following +command to create the Amazon S3 bucket: + +``` {.sourceCode .bash} +aws s3 mb s3://bucket-name --region +``` + +Next, open a command prompt and type the following: + +``` {.sourceCode .bash} +sam package \ + --template-file path/template.yaml \ + --output-template-file serverless-output.yaml \ + --s3-bucket s3-bucket-name +``` + +The package command returns an AWS SAM template named +serverless-output.yaml that contains the CodeUri that points to the +deployment zip in the Amazon S3 bucket that you specified. This template +represents your serverless application. You are now ready to deploy it. + +Deploying your application +========================== + +To deploy the application, run the following command: + +``` {.sourceCode .bash} +sam deploy \ + --template-file serverless-output.yaml \ + --stack-name new-stack-name \ + --capabilities CAPABILITY_IAM +``` + +Note that the value you specify for the \--template-file parameter is +the name of the SAM template that was returned by the package command. +In addition, the `--capabilities` parameter is optional. The +AWS::Serverless::Function resource will implicitly create a role to +execute the Lambda function if one is not specified in the template. You +use the `--capabilities` parameter to explicitly acknowledge that AWS +CloudFormation is allowed to create roles on your behalf. + +When you run the aws sam deploy command, it creates an AWS +CloudFormation ChangeSet, which is a list of changes to the AWS +CloudFormation stack, and then deploys it. Some stack templates might +include resources that can affect permissions in your AWS account, for +example, by creating new AWS Identity and Access Management (IAM) users. +For those stacks, you must explicitly acknowledge their capabilities by +specifying the `--capabilities` parameter. + +To verify your results, open the AWS CloudFormation console to view the +newly created AWS CloudFormation stack and the Lambda console to view +your function. + +Learn More +---------- + +- [Project Overview](../README.md) +- [Getting started with SAM and the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-quick-start.html) +- [Usage](usage.md) +- [Advanced](advanced_usage.md) diff --git a/docs/getting_started.rst b/docs/getting_started.rst deleted file mode 100644 index 1631e78a51..0000000000 --- a/docs/getting_started.rst +++ /dev/null @@ -1,66 +0,0 @@ -Getting started with SAM and the SAM CLI -======================================== -The following sections introduce the Serverless Application Model (SAM) and the the tools available to implement it (SAM CLI): - -What is SAM -=========== -The AWS Serverless Application Model (AWS SAM) is a model to define serverless applications. AWS SAM is natively supported by AWS CloudFormation and defines simplified syntax for expressing serverless resources. The specification currently covers APIs, Lambda functions and Amazon DynamoDB tables. SAM is available under Apache 2.0 for AWS partners and customers to adopt and extend within their own toolsets. - -What is SAM CLI -=============== -Based on AWS SAM, SAM CLI is an AWS CLI tool that provides an environment for you to develop, test, and analyze your serverless applications locally before uploading them to the Lambda runtime. Whether you're developing on Linux, Mac, or Microsoft Windows, you can use SAM CLI to create a local testing environment that simulates the AWS runtime environment. The SAM CLI also allows faster, iterative development of your Lambda function code because there is no need to redeploy your application package to the AWS Lambda runtime. - - -Installing Docker -~~~~~~~~~~~~~~~~~ - -To use SAM CLI, you first need to install Docker, an open-source software container platform that allows you to build, manage and test applications, whether you're running on Linux, Mac or Windows. For more information and download instructions, see `Docker `__. - -Once you have Docker installed, SAM CLI automatically provides a customized Docker image called docker-lambda. This image is designed specifically by an AWS partner to simulate the live AWS Lambda execution environment. This environment includes installed software, libraries, security permissions, environment variables, and other features outlined at Lambda Execution Environment and Available Libraries. - -Using docker-lambda, you can invoke your Lambda function locally. In this environment, your serverless applications execute and perform much as in the AWS Lambda runtime, without your having to redeploy the runtime. Their execution and performance in this environment reflect such considerations as timeouts and memory use. - - Important - - Because this is a simulated environment, there is no guarantee that your local testing results will exactly match those in the actual AWS runtime. -For more information, see `docker-lambda `__. - -Installing SAM CLI -~~~~~~~~~~~~~~~~~~ - -The easiest way to install SAM CLI is to use `pip `__. - -.. code:: bash - - pip install aws-sam-cli - -Then verify that the installation succeeded. - -.. code:: bash - - sam --version - -If pip doesn't work for you, you can download the latest binary and start using SAM CLI immediately. You can find the binaries under the Releases section in the `SAM CLI GitHub Repository `__. - -Creating a hello-world app (init) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To get started with a project in SAM, you can use the 'sam init' command provided by the SAM CLI to get a fully deployable boilerplate serverless application in any of the supported runtimes. SAM init provides a quick way for customers to get started with creating a Lambda-based application and allow them to grow their idea into a production application by using other commands in the SAM CLI. - -To use 'sam init', nagivate to a directory where where you want the serverless application to be created. Using the SAM CLI, run the following command (using the runtime of your choice. The following example uses Python for demonstration purposes.): - -.. code:: - - $ sam init --runtime python - [+] Initializing project structure... - [SUCCESS] - Read sam-app/README.md for further instructions on how to proceed - [*] Project initialization is now complete -This will create a folder in the current directory titled sam-app. This folder will contain an `AWS SAM template `__, along with your function code file and a README file that provides further guidance on how to proceed with your SAM application. The SAM template defines the AWS Resources that your application will need to run in the AWS Cloud. - -Learn More -========== - -- `Project Overview <../README.rst>`__ -- `Installation `__ -- `Usage `__ -- `Packaging and deploying your application `__ -- `Advanced `__ \ No newline at end of file diff --git a/docs/installation.rst b/docs/installation.rst deleted file mode 100644 index e22dcc6906..0000000000 --- a/docs/installation.rst +++ /dev/null @@ -1,15 +0,0 @@ -============== -Installation -============== - -Installation Instructions for AWS SAM CLI are linked below. - -- `Homebrew for Mac`_ -- `Linuxbrew for Linux`_ -- `MSI for Windows`_ -- `Pip`_ - -.. _Pip: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install-using-pip.html -.. _MSI for Windows: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install-windows.html -.. _Homebrew for Mac: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install-mac.html -.. _Linuxbrew for Linux: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install-linux.html \ No newline at end of file diff --git a/docs/make.bat b/docs/make.bat deleted file mode 100644 index 95f33dc2ee..0000000000 --- a/docs/make.bat +++ /dev/null @@ -1,36 +0,0 @@ -@ECHO OFF - -pushd %~dp0 - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set SOURCEDIR=. -set BUILDDIR=_build -set SPHINXPROJ=SAMCLI - -if "%1" == "" goto help - -%SPHINXBUILD% >NUL 2>NUL -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.http://sphinx-doc.org/ - exit /b 1 -) - -%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% -goto end - -:help -%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% - -:end -popd diff --git a/docs/running_and_debugging_serverless_applications_locally.md b/docs/running_and_debugging_serverless_applications_locally.md new file mode 100644 index 0000000000..099cb12ccc --- /dev/null +++ b/docs/running_and_debugging_serverless_applications_locally.md @@ -0,0 +1,142 @@ +Running and debugging serverless applications locally +===================================================== + +SAM CLI works with AWS SAM, allowing you to invoke functions defined in +SAM templates, whether directly or through API Gateway endpoints. By +using SAM CLI, you can analyze your SAM application\'s performance in +your own testing environment and update accordingly. + +Invoking Lambda functions locally +--------------------------------- + +``` {.sourceCode .bash} +# Invoking function with event file + +$ echo '{"message": "Hey, are you there?" }' | sam local invoke "Ratings" + +# For more options + +$ sam local invoke --help +``` + +Running API Gateway Locally +--------------------------- + +start-api: Creates a local HTTP server hosting all of your Lambda +functions. When accessed by using a browser or the CLI, this operation +launches a Docker container locally to invoke your function. It reads +the CodeUri property of the AWS::Serverless::Function resource to find +the path in your file system containing the Lambda function code. This +path can be the project's root directory for interpreted languages like +Node.js or Python, a build directory that stores your compiled +artifacts, or for Java, a .jar file. + +If you use an interpreted language, local changes are made available +without rebuilding. This approach means you can reinvoke your Lambda +function with no need to restart the CLI. + +invoke: Invokes a local Lambda function once and terminates after +invocation completes. + +``` {.sourceCode .} +$ sam local start-api + +2018-05-08 08:48:38 Mounting HelloWorld at http://127.0.0.1:3000/ [GET] +2018-05-08 08:48:38 Mounting HelloWorld at http://127.0.0.1:3000/thumbnail [GET] +2018-05-08 08:48:38 You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template +2018-05-08 08:48:38 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit) +``` + +Debugging With SAM CLI +---------------------- + +Both sam local invoke and sam local start-api support local debugging of +your functions. To run SAM CLI with debugging support enabled, specify +\--debug-port or -d on the command line. + +``` {.sourceCode .bash} +# Invoke a function locally in debug mode on port 5858 + +$ sam local invoke -d 5858 function logical id + +# Start local API Gateway in debug mode on port 5858 + +$ sam local start-api -d 5858 +``` + +If you use sam local start-api, the local API Gateway exposes all of +your Lambda functions. But because you can specify only one debug port, +you can only debug one function at a time. + +Connecting a Debugger to your IDE +--------------------------------- + +For compiled languages or projects requiring complex packing support, we +recommend that you run your own build solution and point AWS SAM to the +directory that contains the build dependency files needed. You can use +the following IDEs or one of your choosing. + +- Cloud9 +- Eclipse +- Visual Studio Code + +Integrating other services +-------------------------- + +You can use the AWS Serverless Application Model to integrate other +services as event sources to your application. For example, assume you +have an application that requires a Dynamo DB table. The following shows +an example: + +``` {.sourceCode .yaml} +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Resources: + ProcessDynamoDBStream: + Type: AWS::Serverless::Function + Properties: + Handler: handler + Runtime: runtime + Policies: AWSLambdaDynamoDBExecutionRole + Events: + Stream: + Type: DynamoDB + Properties: + Stream: !GetAtt DynamoDBTable.StreamArn + BatchSize: 100 + StartingPosition: TRIM_HORIZON + + DynamoDBTable: + Type: AWS::DynamoDB::Table + Properties: + AttributeDefinitions: + - AttributeName: id + AttributeType: S + KeySchema: + - AttributeName: id + KeyType: HASH + ProvisionedThroughput: + ReadCapacityUnits: 5 + WriteCapacityUnits: 5 + StreamSpecification: + StreamViewType: NEW_IMAGE +``` + +Validate your SAM template +-------------------------- + +You can use SAM CLI to validate your template against the official AWS +Serverless Application Model specification. The following is an example +if you specify either an unsupported runtime or deprecated runtime +version. + +``` {.sourceCode .} +$ sam validate + +Error: Invalid Serverless Application Specification document. Number of errors found: 1. Resource with id [SkillFunction] is invalid. property Runtim not defined for resource of type AWS::Serverless::Function + +$ sed -i 's/Runtim/Runtime/g` template.yaml + +$ sam validate +template.yaml is a valid SAM Template +``` diff --git a/docs/running_and_debugging_serverless_applications_locally.rst b/docs/running_and_debugging_serverless_applications_locally.rst deleted file mode 100644 index 7fa47250c3..0000000000 --- a/docs/running_and_debugging_serverless_applications_locally.rst +++ /dev/null @@ -1,113 +0,0 @@ -Running and debugging serverless applications locally -===================================================== -SAM CLI works with AWS SAM, allowing you to invoke functions defined in SAM templates, whether directly or through API Gateway endpoints. By using SAM CLI, you can analyze your SAM application's performance in your own testing environment and update accordingly. - -Invoking Lambda functions locally -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: bash - - # Invoking function with event file - - $ echo '{"message": "Hey, are you there?" }' | sam local invoke "Ratings" - - # For more options - - $ sam local invoke --help - - -Running API Gateway Locally -~~~~~~~~~~~~~~~~~~~~~~~~~~~ -start-api: Creates a local HTTP server hosting all of your Lambda functions. When accessed by using a browser or the CLI, this operation launches a Docker container locally to invoke your function. It reads the CodeUri property of the AWS::Serverless::Function resource to find the path in your file system containing the Lambda function code. This path can be the project's root directory for interpreted languages like Node.js or Python, a build directory that stores your compiled artifacts, or for Java, a .jar file. - -If you use an interpreted language, local changes are made available without rebuilding. This approach means you can reinvoke your Lambda function with no need to restart the CLI. - -invoke: Invokes a local Lambda function once and terminates after invocation completes. - -.. code:: - - $ sam local start-api - - 2018-05-08 08:48:38 Mounting HelloWorld at http://127.0.0.1:3000/ [GET] - 2018-05-08 08:48:38 Mounting HelloWorld at http://127.0.0.1:3000/thumbnail [GET] - 2018-05-08 08:48:38 You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template - 2018-05-08 08:48:38 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit) - -Debugging With SAM CLI -~~~~~~~~~~~~~~~~~~~~~~ - -Both sam local invoke and sam local start-api support local debugging of your functions. To run SAM CLI with debugging support enabled, specify --debug-port or -d on the command line. - -.. code:: bash - - # Invoke a function locally in debug mode on port 5858 - - $ sam local invoke -d 5858 function logical id - - # Start local API Gateway in debug mode on port 5858 - - $ sam local start-api -d 5858 - -If you use sam local start-api, the local API Gateway exposes all of your Lambda functions. But because you can specify only one debug port, you can only debug one function at a time. - -Connecting a Debugger to your IDE -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -For compiled languages or projects requiring complex packing support, we recommend that you run your own build solution and point AWS SAM to the directory that contains the build dependency files needed. You can use the following IDEs or one of your choosing. - -- Cloud9 -- Eclipse -- Visual Studio Code - -Integrating other services -~~~~~~~~~~~~~~~~~~~~~~~~~~ -You can use the AWS Serverless Application Model to integrate other services as event sources to your application. For example, assume you have an application that requires a Dynamo DB table. The following shows an example: - -.. code:: yaml - - AWSTemplateFormatVersion: '2010-09-09' - Transform: AWS::Serverless-2016-10-31 - Resources: - ProcessDynamoDBStream: - Type: AWS::Serverless::Function - Properties: - Handler: handler - Runtime: runtime - Policies: AWSLambdaDynamoDBExecutionRole - Events: - Stream: - Type: DynamoDB - Properties: - Stream: !GetAtt DynamoDBTable.StreamArn - BatchSize: 100 - StartingPosition: TRIM_HORIZON - - DynamoDBTable: - Type: AWS::DynamoDB::Table - Properties: - AttributeDefinitions: - - AttributeName: id - AttributeType: S - KeySchema: - - AttributeName: id - KeyType: HASH - ProvisionedThroughput: - ReadCapacityUnits: 5 - WriteCapacityUnits: 5 - StreamSpecification: - StreamViewType: NEW_IMAGE - -Validate your SAM template -~~~~~~~~~~~~~~~~~~~~~~~~~~ -You can use SAM CLI to validate your template against the official AWS Serverless Application Model specification. The following is an example if you specify either an unsupported runtime or deprecated runtime version. - -.. code:: - - $ sam validate - - Error: Invalid Serverless Application Specification document. Number of errors found: 1. Resource with id [SkillFunction] is invalid. property Runtim not defined for resource of type AWS::Serverless::Function - - $ sed -i 's/Runtim/Runtime/g` template.yaml - - $ sam validate - template.yaml is a valid SAM Template - diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000000..8fb6b5fecd --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,747 @@ +Usage +===== + +**Create a sample app with sam init command**: `sam init` or +`sam init --runtime ` + +`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. + +Alternatively, you can find other sample SAM Templates by visiting +[SAM](https://github.com/awslabs/serverless-application-model) official +repository. + +- [Invoke functions locally](#invoke-functions-locally) +- [Run automated tests for your Lambda functions + locally](#run-automated-tests-for-your-lambda-functions-locally) +- [Generate sample event source + payloads](#generate-sample-event-payloads) +- [Run API Gateway locally](#run-api-gateway-locally) +- [Debugging Applications](#debugging-applications) + - [Debugging Python functions](#debugging-python-functions) +- [Fetch, tail, and filter Lambda function + logs](#fetch-tail-and-filter-lambda-function-logs) +- [Validate SAM templates](#validate-sam-templates) +- [Package and Deploy to Lambda](#package-and-deploy-to-lambda) + +Invoke functions locally +------------------------ + +![SAM CLI Invoke Sample](../media/sam-invoke.gif) + +You 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. + +``` {.sourceCode .yaml} +Resources: + Ratings: # <-- Logical ID + Type: 'AWS::Serverless::Function' + ... +``` + +**Syntax** + +``` {.sourceCode .bash} +# Invoking function with event file +$ sam local invoke "Ratings" -e event.json + +# Invoking function with event via stdin +$ echo '{"message": "Hey, are you there?" }' | sam local invoke "Ratings" + +# For more options +$ sam local invoke --help +``` + +Run automated tests for your Lambda functions locally +----------------------------------------------------- + +You can use the `sam local invoke` command to manually test your code by +running Lambda function locally. With SAM CLI, you can easily author +automated integration tests by first running tests against local Lambda +functions before deploying to the cloud. The `sam local start-lambda` +command starts a local endpoint that emulates the AWS Lambda service's +invoke endpoint, and you can invoke it from your automated tests. +Because this endpoint emulates the Lambda service\'s invoke endpoint, +you can write tests once and run them (without any modifications) +against the local Lambda function or against a deployed Lambda function. +You can also run the same tests against a deployed SAM stack in your +CI/CD pipeline. + +Here is how this works: + +**1. Start the Local Lambda Endpoint** + +Start the local Lambda endpoint by running the following command in the +directory that contains your AWS SAM template: + +``` {.sourceCode .bash} +sam local start-lambda +``` + +This command starts a local endpoint at that +emulates the AWS Lambda service, and you can run your automated tests +against this local Lambda endpoint. When you send an invoke to this +endpoint using the AWS CLI or SDK, it will locally execute the Lambda +function specified in the request and return a response. + +**2. Run integration test against local Lambda endpoint** + +In your integration test, you can use AWS SDK to invoke your Lambda +function with test data, wait for response, and assert that the response +what you expect. To run the integration test locally, you should +configure AWS SDK to send Lambda Invoke API call to local Lambda +endpoint started in previous step. + +Here is an Python example (AWS SDK for other languages have similar +configurations): + +``` {.sourceCode .python} +import boto3 +import botocore + +# Set "running_locally" flag if you are running the integration test locally +running_locally = True + +if running_locally: + + # Create Lambda SDK client to connect to appropriate Lambda endpoint + lambda_client = boto3.client('lambda', + region_name="us-west-2", + endpoint_url="http://127.0.0.1:3001", + use_ssl=False, + verify=False, + config=botocore.client.Config( + signature_version=botocore.UNSIGNED, + read_timeout=0, + retries={'max_attempts': 0}, + ) + ) +else: + lambda_client = boto3.client('lambda') + + +# Invoke your Lambda function as you normally usually do. The function will run +# locally if it is configured to do so +response = lambda_client.invoke(FunctionName="HelloWorldFunction") + +# Verify the response +assert response == "Hello World" +``` + +This code can run without modifications against a Lambda function which +is deployed. To do so, set the `running_locally` flag to `False` . This +will setup AWS SDK to connect to AWS Lambda service on the cloud. + +Connecting to docker network +---------------------------- + +Both `sam local invoke` and `sam local start-api` support connecting the +create lambda docker containers to an existing docker network. + +To connect the containers to an existing docker network, you can use the +`--docker-network` command-line argument or the `SAM_DOCKER_NETWORK` +environment variable along with the name or id of the docker network you +wish to connect to. + +``` {.sourceCode .bash} +# Invoke a function locally and connect to a docker network +$ sam local invoke --docker-network my-custom-network + +# Start local API Gateway and connect all containers to a docker network +$ sam local start-api --docker-network b91847306671 -d 5858 +``` + +Generate sample event payloads +------------------------------ + +To make local development and testing of Lambda functions easier, you +can generate and customize event payloads for the following services: + +- Amazon Alexa +- Amazon API Gateway +- AWS Batch +- AWS CloudFormation +- Amazon CloudFront +- AWS CodeCommit +- AWS CodePipeline +- Amazon Cognito +- AWS Config +- Amazon DynamoDB +- Amazon Kinesis +- Amazon Lex +- Amazon Rekognition +- Amazon S3 +- Amazon SES +- Amazon SNS +- Amazon SQS +- AWS Step Functions + +**Syntax** + +``` {.sourceCode .bash} +$ sam local generate-event +``` + +You can generate multiple types of events from each service. For +example, to generate the event from S3 when a new object is created, +use: + +``` {.sourceCode .bash} +$ sam local generate-event s3 put +``` + +To generate the event from S3 when an object is deleted, you can use: + +``` {.sourceCode .bash} +$ sam local generate-event s3 delete +``` + +For more options, see `sam local generate-event --help`. + +Run API Gateway locally +----------------------- + +`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. + +![SAM CLI Start API](../media/sam-start-api.gif) + +**Syntax** + +``` {.sourceCode .bash} +$ sam local start-api +``` + +`sam` will automatically find any functions within your SAM template +that have `Api` event sources defined, and mount them at the defined +HTTP paths. + +In the example below, the `Ratings` function would mount +`ratings.py:handler()` at `/ratings` for `GET` requests. + +``` {.sourceCode .yaml} +Ratings: + Type: AWS::Serverless::Function + Properties: + Handler: ratings.handler + Runtime: python3.6 + Events: + Api: + Type: Api + Properties: + Path: /ratings + Method: get +``` + +By 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`. + +For example: + +``` {.sourceCode .javascript} +// Example of a Proxy Integration response +exports.handler = (event, context, callback) => { + callback(null, { + statusCode: 200, + headers: { "x-custom-header" : "my custom header value" }, + body: "hello world" + }); +} +``` + +For 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). + +If 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 CLI will also print the following error log +message to help you diagnose the problem: + + ERROR: Function ExampleFunction returned an invalid response (must include one of: body, headers or statusCode in the response object) + +Debugging Applications +---------------------- + +Both `sam local invoke` and `sam local start-api` support local +debugging of your functions. + +To run SAM Local with debugging support enabled, just specify +`--debug-port` or `-d` on the command line. SAM CLI debug port option +`--debug-port` or `-d` will map that port to the local Lambda container +execution your IDE needs to connect to. + +``` {.sourceCode .bash} +# Invoke a function locally in debug mode on port 5858 +$ sam local invoke -d 5858 + +# Start local API Gateway in debug mode on port 5858 +$ sam local start-api -d 5858 +``` + +Note: 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. You will need to hit +your API before SAM CLI binds to the port allowing the debugger to +connect. + +Here is an example showing how to debug a NodeJS function with Microsoft +Visual Studio Code: + +![SAM Local debugging example](../media/sam-debug.gif) + +In order to setup Visual Studio Code for debugging with AWS SAM CLI, use +the following launch configuration after setting directory where the +template.yaml is present as workspace root in Visual Studio Code: + +``` {.sourceCode .json} +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Attach to SAM CLI", + "type": "node", + "request": "attach", + "address": "localhost", + "port": 5858, + // From the sam init example, it would be "${workspaceRoot}/hello_world" + "localRoot": "${workspaceRoot}/{directory of node app}", + "remoteRoot": "/var/task", + "protocol": "inspector", + "stopOnEntry": false + } + ] + } +``` + +Note: localRoot is set based on what the CodeUri points at +template.yaml, if there are nested directories within the CodeUri, that +needs to be reflected in localRoot. + +Note: Node.js versions \--below\-- 7 (e.g. Node.js 4.3 and Node.js 6.10) +use the `legacy` protocol, while Node.js versions including and above 7 +(e.g. Node.js 8.10) use the `inspector` protocol. Be sure to specify the +corresponding protocol in the `protocol` entry of your launch +configuration. This was tested with VS code version 1.26, 1.27 and 1.28 +for `legacy` and `inspector` protocol. + +Debugging Python functions +-------------------------- + +Python debugging requires you to enable remote debugging in your Lambda +function code, therefore it\'s a 2-step process: + +1. Install [ptvsd](https://pypi.org/project/ptvsd/) library and enable + within your code +2. Configure your IDE to connect to the debugger you configured for + your function + +As this may be your first time using SAM CLI, let\'s start with a +boilerplate Python app and install both app\'s dependencies and ptvsd: + +``` {.sourceCode .bash} +sam init --runtime python3.6 --name python-debugging +cd python-debugging/ + +# Install dependencies of our boilerplate app +pip install -r requirements.txt -t hello_world/build/ + +# Install ptvsd library for step through debugging +pip install ptvsd -t hello_world/build/ + +cp hello_world/app.py hello_world/build/ +``` + +### Ptvsd configuration + +As we installed ptvsd library in the previous step, we need to enable +ptvsd within our code, therefore open up `hello_world/build/app.py` and +add the following ptvsd specifics. + +``` {.sourceCode .python} +import ptvsd + +# Enable ptvsd on 0.0.0.0 address and on port 5890 that we'll connect later with our IDE +ptvsd.enable_attach(address=('0.0.0.0', 5890), redirect_output=True) +ptvsd.wait_for_attach() +``` + +**0.0.0.0** instead of **localhost** for listening across all network +interfaces and **5890** is the debugging port of your preference. + +### Visual Studio Code + +Now that we have both dependencies and ptvsd enabled within our code we +configure Visual Studio Code (VS Code) Debugging - Assuming you\'re +still in the application folder and have code command in your path, +let\'s open up VS Code: + +``` {.sourceCode .bash} +code . +``` + +`NOTE`: If you don\'t have code in your Path, please open up a new +instance of VS Code from `python-debugging/` folder we created earlier. + +In order to setup VS Code for debugging with AWS SAM CLI, use the +following launch configuration: + +``` {.sourceCode .json} +{ + "version": "0.2.0", + "configurations": [ + { + "name": "SAM CLI Python Hello World", + "type": "python", + "request": "attach", + "port": 5890, + "host": "localhost", + "pathMappings": [ + { + "localRoot": "${workspaceFolder}/hello_world/build", + "remoteRoot": "/var/task" + } + ] + } + ] + } +``` + +For VS Code, the property **localRoot** under **pathMappings** key is +really important and there are 2 aspects you should know as to why this +is setup this way: + +1. **localRoot**: This path will be mounted in the Docker Container and + needs to have both application and dependencies at the root level +2. **workspaceFolder**: This path is the absolute path where VS Code + instance was opened + +If you opened VS Code in a different location other than +`python-debugging/` you need to replace it with the absolute path where +`python-debugging/` is. + +Once complete with VS Code Debugger configuration, make sure to add a +breakpoint anywhere you like in `hello_world/build/app.py` and then +proceed as follows: + +1. Run SAM CLI to invoke your function +2. Hit the URL to invoke the function and initialize ptvsd code + execution +3. Start the debugger within VS Code + +``` {.sourceCode .bash} +# Remember to hit the URL before starting the debugger in VS Code + +sam local start-api -d 5890 + +# OR + +# Change HelloWorldFunction to reflect the logical name found in template.yaml + +sam local generate-event apigateway aws-proxy | sam local invoke HelloWorldFunction -d 5890 +``` + +Debugging Golang functions +-------------------------- + +Golang function debugging is slightly different when compared to +Node.JS, Java, and Python. We require +[delve](https://github.com/derekparker/delve) as the debugger, and wrap +your function with it at runtime. The debugger is run in headless mode, +listening on the debug port. + +When debugging, you must compile your function in debug mode: + +`GOARCH=amd64 GOOS=linux go build -gcflags='-N -l' -o ` + +You must compile [delve]{.title-ref} to run in the container and provide +its local path via the [\--debugger-path]{.title-ref} argument. Build +delve locally as follows: + +`GOARCH=amd64 GOOS=linux go build -o /dlv github.com/derekparker/delve/cmd/dlv` + +NOTE: The output path needs to end in [/dlv]{.title-ref}. The docker +container will expect the dlv binary to be in the \ +and will cause mounting issue otherwise. + +Then invoke [sam]{.title-ref} similar to the following: + +`sam local start-api -d 5986 --debugger-path ` + +NOTE: The `--debugger-path` is the path to the directory that contains +the [dlv]{.title-ref} binary compiled from the above. + +The following is an example launch configuration for Visual Studio Code +to attach to a debug session. + +``` {.sourceCode .json} +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Connect to Lambda container", + "type": "go", + "request": "launch", + "mode": "remote", + "remotePath": "", + "port": , + "host": "127.0.0.1", + "program": "${workspaceRoot}", + "env": {}, + "args": [], + }, + ] +} +``` + +Debugging .NET Core 2.1 / 2.0 Functions +--------------------------------------- + +.NET Core function debugging is similiar to golang function debugging +and requires you to have `vsdbg` available on your machine to later +provide it to SAM CLI. VS Code will launch debugger inside Lambda +container and talk to it using `pipeTransport` configuration. + +When debugging, you must compile your function in debug mode: + +Either locally using .NET SDK + +``` {.sourceCode .bash} +dotnet publish -c Debug -o +``` + +Or via Docker + +``` {.sourceCode .bash} +docker run --rm --mount type=bind,src=$PWD,dst=/var/task lambci/lambda:build-dotnetcore dotnet publish -c Debug -o +``` + +**NOTE: both of these commands should be run from the directory with +.csproj file** + +You must get `vsdbg` built for AWS Lambda runtime container on your host +machine and provide its local path via the `--debugger-path` argument. +Get compatible debugger version as follows: + +``` {.sourceCode .bash} +# Create directory to store vsdbg +mkdir + +# Get and install vsdbg on runtime container. Mounted folder will let you have it under on your machine too +docker run --rm --mount type=bind,src=,dst=/vsdbg --entrypoint bash lambci/lambda:dotnetcore2.0 -c "curl -sSL https://aka.ms/getvsdbgsh | bash /dev/stdin -v latest -l /vsdbg" +``` + +Then invoke `sam` similar to the following: + +`sam local start-api -d --debugger-path ` + +NOTE: The `--debugger-path` is the path to the directory that contains +the `vsdbg` binary installed from the above. + +The following is an example launch configuration for Visual Studio Code +to attach to a debug session. + +``` {.sourceCode .json} +{ + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Docker Attach", + "type": "coreclr", + "request": "attach", + "processId": "1", + + "pipeTransport": { + "pipeProgram": "sh", + "pipeArgs": [ + "-c", + "docker exec -i $(docker ps -q -f publish=) ${debuggerCommand}" + ], + "debuggerPath": "/tmp/lambci_debug_files/vsdbg", + "pipeCwd": "${workspaceFolder}", + }, + + "windows": { + "pipeTransport": { + "pipeProgram": "powershell", + "pipeArgs": [ + "-c", + "docker exec -i $(docker ps -q -f publish=) ${debuggerCommand}" + ], + "debuggerPath": "/tmp/lambci_debug_files/vsdbg", + "pipeCwd": "${workspaceFolder}", + } + }, + + "sourceFileMap": { + "/var/task": "${workspaceFolder}" + } + } + ] +} +``` + +Passing Additional Runtime Debug Arguments +------------------------------------------ + +To pass additional runtime arguments when debugging your function, use +the environment variable `DEBUGGER_ARGS`. This will pass a string of +arguments directly into the run command SAM CLI uses to start your +function. + +For example, if you want to load a debugger like iKPdb at runtime of +your Python function, you could pass the following as `DEBUGGER_ARGS`: +`-m ikpdb --ikpdb-port=5858 --ikpdb-working-directory=/var/task/ --ikpdb-client-working-directory=/myApp --ikpdb-address=0.0.0.0`. +This would load iKPdb at runtime with the other arguments you've +specified. In this case, your full SAM CLI command would be: + +``` {.sourceCode .bash} +$ DEBUGGER_ARGS="-m ikpdb --ikpdb-port=5858 --ikpdb-working-directory=/var/task/ --ikpdb-client-working-directory=/myApp --ikpdb-address=0.0.0.0" echo {} | sam local invoke -d 5858 myFunction +``` + +You may pass debugger arguments to functions of all runtimes. + +To simplify troubleshooting, we added a new command called `sam logs` to +SAM CLI. `sam logs` lets you fetch logs generated by your Lambda +function from the command line. In addition to printing the logs on the +terminal, this command has several nifty features to help you quickly +find the bug. Note: This command works for all AWS Lambda functions; not +just the ones you deploy using SAM. + +Fetch, tail, and filter Lambda function logs +-------------------------------------------- + +To simplify troubleshooting, SAM CLI has a command called `sam logs`. +`sam logs` lets you fetch logs generated by your Lambda function from +the command line. In addition to printing the logs on the terminal, this +command has several nifty features to help you quickly find the bug. + +Note: This command works for all AWS Lambda functions; not just the ones +you deploy using SAM. + +**Basic Usage: Using CloudFormation Stack** + +When your function is a part of a CloudFormation stack, you can fetch +logs using the function\'s LogicalID: + +``` {.sourceCode .bash} +sam logs -n HelloWorldFunction --stack-name mystack +``` + +**Basic Usage: Using Lambda Function name** + +Or, you can fetch logs using the function\'s name + +``` {.sourceCode .bash} +sam logs -n mystack-HelloWorldFunction-1FJ8PD +``` + +**Tail Logs** + +Add `--tail` option to wait for new logs and see them as they arrive. +This is very handy during deployment or when troubleshooting a +production issue. + +``` {.sourceCode .bash} +sam logs -n HelloWorldFunction --stack-name mystack --tail +``` + +**View logs for specific time range** You can view logs for specific +time range using the `-s` and `-e` options + +``` {.sourceCode .bash} +sam logs -n HelloWorldFunction --stack-name mystack -s '10min ago' -e '2min ago' +``` + +**Filter Logs** + +Use the `--filter` option to quickly find logs that match terms, phrases +or values in your log events + +``` {.sourceCode .bash} +sam logs -n HelloWorldFunction --stack-name mystack --filter "error" +``` + +In the output, SAM CLI will underline all occurrences of the word +"error" so you can easily locate the filter keyword within the log +output. + +**Error Highlighting** + +When your Lambda function crashes or times out, SAM CLI will highlight +the timeout message in red. This will help you easily locate specific +executions that are timing out within a giant stream of log output. + +![](https://user-images.githubusercontent.com/22755571/42301038-3363a366-7fc8-11e8-9d0e-308b209cb92b.png) + +**JSON pretty printing** + +If your log messages print JSON strings, SAM CLI will automatically +pretty print the JSON to help you visually parse and understand the +JSON. + +![](https://user-images.githubusercontent.com/22755571/42301064-50c6cffa-7fc8-11e8-8f31-04ef117a9c5a.png) + +Validate SAM templates +---------------------- + +Validate your templates with `$ sam validate`. Currently this command +will validate that the template provided is valid JSON / YAML. As with +most SAM CLI commands, it will look for a `template.[yaml|yml]` file in +your current working directory by default. You can specify a different +template file/location with the `-t` or `--template` option. + +**Syntax** + +``` {.sourceCode .bash} +$ sam validate +/template.yml is a valid SAM Template +``` + +Note: The validate command requires AWS credentials to be configured. +See [IAM Credentials](#iam-credentials). + +Package and Deploy to Lambda +---------------------------- + +Once you have developed and tested your Serverless application locally, +you can deploy to Lambda using `sam package` and `sam deploy` command. + +`sam 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. + +`sam 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. + +Example: + +``` {.sourceCode .bash} +# Package SAM template +$ sam package --template-file sam.yaml --s3-bucket mybucket --output-template-file packaged.yaml + +# Deploy packaged SAM template +$ sam deploy --template-file ./packaged.yaml --stack-name mystack --capabilities CAPABILITY_IAM +``` + +Learn More +---------- + +- [Project Overview](../README.md) +- [Getting started with SAM and the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-quick-start.html) +- [Packaging and deploying your + application](deploying_serverless_applications.md) +- [Advanced](advanced_usage.md) diff --git a/docs/usage.rst b/docs/usage.rst deleted file mode 100644 index ee12e26f24..0000000000 --- a/docs/usage.rst +++ /dev/null @@ -1,737 +0,0 @@ -===== -Usage -===== - -**Create a sample app with sam init command**: ``sam init`` or ``sam init --runtime `` - -``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. - -Alternatively, you can find other sample SAM Templates by visiting `SAM `__ official repository. - - -- `Invoke functions locally <#invoke-functions-locally>`__ -- `Run automated tests for your Lambda functions locally <#run-automated-tests-for-your-lambda-functions-locally>`__ -- `Generate sample event source - payloads <#generate-sample-event-payloads>`__ -- `Run API Gateway locally <#run-api-gateway-locally>`__ -- `Debugging Applications <#debugging-applications>`__ - - - `Debugging Python functions <#debugging-python-functions>`__ -- `Fetch, tail, and filter Lambda function logs <#fetch-tail-and-filter-lambda-function-logs>`__ -- `Validate SAM templates <#validate-sam-templates>`__ -- `Package and Deploy to - Lambda <#package-and-deploy-to-lambda>`__ - -Invoke functions locally ------------------------- - -.. figure:: ../media/sam-invoke.gif - :alt: SAM CLI Invoke Sample - - SAM CLI Invoke Sample - -You 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. - -.. code:: yaml - - Resources: - Ratings: # <-- Logical ID - Type: 'AWS::Serverless::Function' - ... - -**Syntax** - -.. code:: bash - - # Invoking function with event file - $ sam local invoke "Ratings" -e event.json - - # Invoking function with event via stdin - $ echo '{"message": "Hey, are you there?" }' | sam local invoke "Ratings" - - # For more options - $ sam local invoke --help - - -Run automated tests for your Lambda functions locally ------------------------------------------------------ -You can use the ``sam local invoke`` command to manually test your code -by running Lambda function locally. With SAM CLI, you can easily -author automated integration tests by -first running tests against local Lambda functions before deploying to the -cloud. The ``sam local start-lambda`` command starts a local -endpoint that emulates the AWS Lambda service’s invoke endpoint, and you -can invoke it from your automated tests. Because this endpoint emulates -the Lambda service's invoke endpoint, you can write tests once and run -them (without any modifications) against the local Lambda function or -against a deployed Lambda function. You can also run the same tests -against a deployed SAM stack in your CI/CD pipeline. - -Here is how this works: - -**1. Start the Local Lambda Endpoint** - -Start the local Lambda endpoint by running the following command in the directory that contains your AWS -SAM template: - -.. code:: bash - - sam local start-lambda - -This command starts a local endpoint at http://127.0.0.1:3001 that -emulates the AWS Lambda service, and you can run your automated tests -against this local Lambda endpoint. When you send an invoke to this -endpoint using the AWS CLI or SDK, it will locally execute the Lambda -function specified in the request and return a response. - -**2. Run integration test against local Lambda endpoint** - -In your integration test, you can use AWS SDK to invoke your Lambda function -with test data, wait for response, and assert that the response what you -expect. To run the integration test locally, you should configure AWS -SDK to send Lambda Invoke API call to local Lambda endpoint started in -previous step. - -Here is an Python example (AWS SDK for other languages have similar -configurations): - -.. code:: python - - import boto3 - import botocore - - # Set "running_locally" flag if you are running the integration test locally - running_locally = True - - if running_locally: - - # Create Lambda SDK client to connect to appropriate Lambda endpoint - lambda_client = boto3.client('lambda', - region_name="us-west-2", - endpoint_url="http://127.0.0.1:3001", - use_ssl=False, - verify=False, - config=botocore.client.Config( - signature_version=botocore.UNSIGNED, - read_timeout=0, - retries={'max_attempts': 0}, - ) - ) - else: - lambda_client = boto3.client('lambda') - - - # Invoke your Lambda function as you normally usually do. The function will run - # locally if it is configured to do so - response = lambda_client.invoke(FunctionName="HelloWorldFunction") - - # Verify the response - assert response == "Hello World" - -This code can run without modifications against a Lambda function which -is deployed. To do so, set the ``running_locally`` flag to ``False`` . -This will setup AWS SDK to connect to AWS Lambda service on the cloud. - -Connecting to docker network ----------------------------- - -Both ``sam local invoke`` and ``sam local start-api`` support connecting -the create lambda docker containers to an existing docker network. - -To connect the containers to an existing docker network, you can use the -``--docker-network`` command-line argument or the ``SAM_DOCKER_NETWORK`` -environment variable along with the name or id of the docker network you -wish to connect to. - -.. code:: bash - - # Invoke a function locally and connect to a docker network - $ sam local invoke --docker-network my-custom-network - - # Start local API Gateway and connect all containers to a docker network - $ sam local start-api --docker-network b91847306671 -d 5858 - - -Generate sample event payloads ------------------------------- - -To make local development and testing of Lambda functions easier, you -can generate and customize event payloads for the following services: - -- Amazon Alexa -- Amazon API Gateway -- AWS Batch -- AWS CloudFormation -- Amazon CloudFront -- AWS CodeCommit -- AWS CodePipeline -- Amazon Cognito -- AWS Config -- Amazon DynamoDB -- Amazon Kinesis -- Amazon Lex -- Amazon Rekognition -- Amazon S3 -- Amazon SES -- Amazon SNS -- Amazon SQS -- AWS Step Functions - -**Syntax** - -.. code:: bash - - $ sam local generate-event - -You can generate multiple types of events from each service. For example, -to generate the event from S3 when a new object is created, use: - -.. code:: bash - - $ sam local generate-event s3 put - -To generate the event from S3 when an object is deleted, you can use: - -.. code:: bash - - $ sam local generate-event s3 delete - -For more options, see ``sam local generate-event --help``. - -Run API Gateway locally ------------------------ - -``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. - -.. figure:: ../media/sam-start-api.gif - :alt: SAM CLI Start API - - SAM CLI Start API - -**Syntax** - -.. code:: bash - - $ sam local start-api - -``sam`` will automatically find any functions within your SAM -template that have ``Api`` event sources defined, and mount them at the -defined HTTP paths. - -In the example below, the ``Ratings`` function would mount -``ratings.py:handler()`` at ``/ratings`` for ``GET`` requests. - -.. code:: yaml - - Ratings: - Type: AWS::Serverless::Function - Properties: - Handler: ratings.handler - Runtime: python3.6 - Events: - Api: - Type: Api - Properties: - Path: /ratings - Method: get - -By default, SAM uses `Proxy -Integration `__ -and expects the response from your Lambda function to include one or -more of the following: ``statusCode``, ``headers`` and/or ``body``. - -For example: - -.. code:: javascript - - // Example of a Proxy Integration response - exports.handler = (event, context, callback) => { - callback(null, { - statusCode: 200, - headers: { "x-custom-header" : "my custom header value" }, - body: "hello world" - }); - } - -For examples in other AWS Lambda languages, see `this -page `__. - -If your function does not return a valid `Proxy -Integration `__ -response then you will get a HTTP 500 (Internal Server Error) when -accessing your function. SAM CLI will also print the following error log -message to help you diagnose the problem: - -:: - - ERROR: Function ExampleFunction returned an invalid response (must include one of: body, headers or statusCode in the response object) - -Debugging Applications ----------------------- - -Both ``sam local invoke`` and ``sam local start-api`` support local -debugging of your functions. - -To run SAM Local with debugging support enabled, just specify -``--debug-port`` or ``-d`` on the command line. SAM CLI debug port option ``--debug-port`` or ``-d`` will map that port to the local Lambda container execution your IDE needs to connect to. - -.. code:: bash - - # Invoke a function locally in debug mode on port 5858 - $ sam local invoke -d 5858 - - # Start local API Gateway in debug mode on port 5858 - $ sam local start-api -d 5858 - - -Note: 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. You will need to -hit your API before SAM CLI binds to the port allowing the debugger to -connect. - -Here is an example showing how to debug a NodeJS function with Microsoft -Visual Studio Code: - -.. figure:: ../media/sam-debug.gif - :alt: SAM Local debugging example - - SAM Local debugging example - -In order to setup Visual Studio Code for debugging with AWS SAM CLI, use -the following launch configuration after setting directory where the template.yaml is present -as workspace root in Visual Studio Code: - -.. code:: json - - { - "version": "0.2.0", - "configurations": [ - { - "name": "Attach to SAM CLI", - "type": "node", - "request": "attach", - "address": "localhost", - "port": 5858, - // From the sam init example, it would be "${workspaceRoot}/hello_world" - "localRoot": "${workspaceRoot}/{directory of node app}", - "remoteRoot": "/var/task", - "protocol": "inspector", - "stopOnEntry": false - } - ] - } - -Note: localRoot is set based on what the CodeUri points at template.yaml, -if there are nested directories within the CodeUri, that needs to be -reflected in localRoot. - -Note: Node.js versions --below-- 7 (e.g. Node.js 4.3 and Node.js 6.10) -use the ``legacy`` protocol, while Node.js versions including and above -7 (e.g. Node.js 8.10) use the ``inspector`` protocol. Be sure to specify -the corresponding protocol in the ``protocol`` entry of your launch -configuration. This was tested with VS code version 1.26, 1.27 and 1.28 -for ``legacy`` and ``inspector`` protocol. - -Debugging Python functions --------------------------- - -Python debugging requires you to enable remote debugging in your Lambda function code, therefore it's a 2-step process: - -1. Install `ptvsd `__ library and enable within your code -2. Configure your IDE to connect to the debugger you configured for your function - -As this may be your first time using SAM CLI, let's start with a boilerplate Python app and install both app's dependencies and ptvsd: - -.. code:: bash - - sam init --runtime python3.6 --name python-debugging - cd python-debugging/ - - # Install dependencies of our boilerplate app - pip install -r requirements.txt -t hello_world/build/ - - # Install ptvsd library for step through debugging - pip install ptvsd -t hello_world/build/ - - cp hello_world/app.py hello_world/build/ - -Ptvsd configuration -^^^^^^^^^^^^^^^^^^^ - -As we installed ptvsd library in the previous step, we need to enable ptvsd within our code, therefore open up ``hello_world/build/app.py`` and add the following ptvsd specifics. - -.. code:: python - - import ptvsd - - # Enable ptvsd on 0.0.0.0 address and on port 5890 that we'll connect later with our IDE - ptvsd.enable_attach(address=('0.0.0.0', 5890), redirect_output=True) - ptvsd.wait_for_attach() - -**0.0.0.0** instead of **localhost** for listening across all network interfaces and **5890** is the debugging port of your preference. - -Visual Studio Code -^^^^^^^^^^^^^^^^^^ - -Now that we have both dependencies and ptvsd enabled within our code we configure Visual Studio Code (VS Code) Debugging - Assuming you're still in the application folder and have code command in your path, let's open up VS Code: - -.. code:: bash - - code . - -``NOTE``: If you don't have code in your Path, please open up a new instance of VS Code from ``python-debugging/`` folder we created earlier. - -In order to setup VS Code for debugging with AWS SAM CLI, use -the following launch configuration: - -.. code:: json - - { - "version": "0.2.0", - "configurations": [ - { - "name": "SAM CLI Python Hello World", - "type": "python", - "request": "attach", - "port": 5890, - "host": "localhost", - "pathMappings": [ - { - "localRoot": "${workspaceFolder}/hello_world/build", - "remoteRoot": "/var/task" - } - ] - } - ] - } - -For VS Code, the property **localRoot** under **pathMappings** key is really important and there are 2 aspects you should know as to why this is setup this way: - -1. **localRoot**: This path will be mounted in the Docker Container and needs to have both application and dependencies at the root level -2. **workspaceFolder**: This path is the absolute path where VS Code instance was opened - -If you opened VS Code in a different location other than ``python-debugging/`` you need to replace it with the absolute path where ``python-debugging/`` is. - -Once complete with VS Code Debugger configuration, make sure to add a breakpoint anywhere you like in ``hello_world/build/app.py`` and then proceed as follows: - -1. Run SAM CLI to invoke your function -2. Hit the URL to invoke the function and initialize ptvsd code execution -3. Start the debugger within VS Code - -.. code:: bash - - # Remember to hit the URL before starting the debugger in VS Code - - sam local start-api -d 5890 - - # OR - - # Change HelloWorldFunction to reflect the logical name found in template.yaml - - sam local generate-event apigateway aws-proxy | sam local invoke HelloWorldFunction -d 5890 - - -Debugging Golang functions --------------------------- - -Golang function debugging is slightly different when compared to Node.JS, -Java, and Python. We require `delve `__ -as the debugger, and wrap your function with it at runtime. The debugger -is run in headless mode, listening on the debug port. - -When debugging, you must compile your function in debug mode: - -``GOARCH=amd64 GOOS=linux go build -gcflags='-N -l' -o `` - -You must compile `delve` to run in the container and provide its local path -via the `--debugger-path` argument. Build delve locally as follows: - -``GOARCH=amd64 GOOS=linux go build -o /dlv github.com/derekparker/delve/cmd/dlv`` - -NOTE: The output path needs to end in `/dlv`. The docker container will expect the dlv binary to be in the -and will cause mounting issue otherwise. - -Then invoke `sam` similar to the following: - -``sam local start-api -d 5986 --debugger-path `` - -NOTE: The ``--debugger-path`` is the path to the directory that contains the `dlv` binary compiled from the above. - -The following is an example launch configuration for Visual Studio Code to -attach to a debug session. - -.. code:: json - - { - "version": "0.2.0", - "configurations": [ - { - "name": "Connect to Lambda container", - "type": "go", - "request": "launch", - "mode": "remote", - "remotePath": "", - "port": , - "host": "127.0.0.1", - "program": "${workspaceRoot}", - "env": {}, - "args": [], - }, - ] - } - - -Debugging .NET Core 2.1 / 2.0 Functions ---------------------------------------- - -.NET Core function debugging is similiar to golang function debugging and requires you to have ``vsdbg`` available on your -machine to later provide it to SAM CLI. VS Code will launch debugger inside Lambda container and talk to it using ``pipeTransport`` configuration. - -When debugging, you must compile your function in debug mode: - -Either locally using .NET SDK - -.. code:: bash - - dotnet publish -c Debug -o - -Or via Docker - -.. code:: bash - - docker run --rm --mount type=bind,src=$PWD,dst=/var/task lambci/lambda:build-dotnetcore dotnet publish -c Debug -o - -**NOTE: both of these commands should be run from the directory with .csproj file** - -You must get ``vsdbg`` built for AWS Lambda runtime container on your host machine and provide its local path -via the ``--debugger-path`` argument. Get compatible debugger version as follows: - -.. code:: bash - - # Create directory to store vsdbg - mkdir - - # Get and install vsdbg on runtime container. Mounted folder will let you have it under on your machine too - docker run --rm --mount type=bind,src=,dst=/vsdbg --entrypoint bash lambci/lambda:dotnetcore2.0 -c "curl -sSL https://aka.ms/getvsdbgsh | bash /dev/stdin -v latest -l /vsdbg" - -Then invoke ``sam`` similar to the following: - -``sam local start-api -d --debugger-path `` - -NOTE: The ``--debugger-path`` is the path to the directory that contains the ``vsdbg`` binary installed from the above. - -The following is an example launch configuration for Visual Studio Code to attach to a debug session. - -.. code:: json - - { - "version": "0.2.0", - "configurations": [ - { - "name": ".NET Core Docker Attach", - "type": "coreclr", - "request": "attach", - "processId": "1", - - "pipeTransport": { - "pipeProgram": "sh", - "pipeArgs": [ - "-c", - "docker exec -i $(docker ps -q -f publish=) ${debuggerCommand}" - ], - "debuggerPath": "/tmp/lambci_debug_files/vsdbg", - "pipeCwd": "${workspaceFolder}", - }, - - "windows": { - "pipeTransport": { - "pipeProgram": "powershell", - "pipeArgs": [ - "-c", - "docker exec -i $(docker ps -q -f publish=) ${debuggerCommand}" - ], - "debuggerPath": "/tmp/lambci_debug_files/vsdbg", - "pipeCwd": "${workspaceFolder}", - } - }, - - "sourceFileMap": { - "/var/task": "${workspaceFolder}" - } - } - ] - } - - -Passing Additional Runtime Debug Arguments ------------------------------------------- - -To pass additional runtime arguments when debugging your function, use -the environment variable ``DEBUGGER_ARGS``. This will pass a string -of arguments directly into the run command SAM CLI uses to start your -function. - -For example, if you want to load a debugger like iKPdb at runtime of -your Python function, you could pass the following as -``DEBUGGER_ARGS``: -``-m ikpdb --ikpdb-port=5858 --ikpdb-working-directory=/var/task/ --ikpdb-client-working-directory=/myApp --ikpdb-address=0.0.0.0``. -This would load iKPdb at runtime with the other arguments you’ve -specified. In this case, your full SAM CLI command would be: - -.. code:: bash - - $ DEBUGGER_ARGS="-m ikpdb --ikpdb-port=5858 --ikpdb-working-directory=/var/task/ --ikpdb-client-working-directory=/myApp --ikpdb-address=0.0.0.0" echo {} | sam local invoke -d 5858 myFunction - -You may pass debugger arguments to functions of all runtimes. - -To simplify troubleshooting, we added a new command called ``sam logs`` -to SAM CLI. ``sam logs`` lets you fetch logs generated by your Lambda -function from the command line. In addition to printing the logs on the -terminal, this command has several nifty features to help you quickly -find the bug. Note: This command works for all AWS Lambda functions; not -just the ones you deploy using SAM. - -Fetch, tail, and filter Lambda function logs --------------------------------------------- -To simplify troubleshooting, SAM CLI has a command called ``sam logs``. -``sam logs`` lets you fetch logs generated by your Lambda -function from the command line. In addition to printing the logs on the -terminal, this command has several nifty features to help you quickly -find the bug. - -Note: This command works for all AWS Lambda functions; not -just the ones you deploy using SAM. - -**Basic Usage: Using CloudFormation Stack** - -When your function is a part -of a CloudFormation stack, you can fetch logs using the function's -LogicalID: - -.. code:: bash - - sam logs -n HelloWorldFunction --stack-name mystack - -**Basic Usage: Using Lambda Function name** - -Or, you can fetch logs using the function's name - -.. code:: bash - - sam logs -n mystack-HelloWorldFunction-1FJ8PD - -**Tail Logs** - -Add ``--tail`` option to wait for new logs and see them as -they arrive. This is very handy during deployment or when -troubleshooting a production issue. - -.. code:: bash - - sam logs -n HelloWorldFunction --stack-name mystack --tail - -**View logs for specific time range** -You can view logs for specific time range using the ``-s`` and ``-e`` options - -.. code:: bash - - sam logs -n HelloWorldFunction --stack-name mystack -s '10min ago' -e '2min ago' - -**Filter Logs** - -Use the ``--filter`` option to quickly find logs that -match terms, phrases or values in your log events - -.. code:: bash - - sam logs -n HelloWorldFunction --stack-name mystack --filter "error" - -In the output, SAM CLI will underline all occurrences of the word -“error” so you can easily locate the filter keyword within the log -output. - -**Error Highlighting** - -When your Lambda function crashes or times out, -SAM CLI will highlight the timeout message in red. This will help you -easily locate specific executions that are timing out within a giant -stream of log output. - -.. figure:: https://user-images.githubusercontent.com/22755571/42301038-3363a366-7fc8-11e8-9d0e-308b209cb92b.png - :alt: SAM CLI Logs Error Highlighting - - -**JSON pretty printing** - -If your log messages print JSON strings, SAM -CLI will automatically pretty print the JSON to help you visually parse -and understand the JSON. - -.. figure:: https://user-images.githubusercontent.com/22755571/42301064-50c6cffa-7fc8-11e8-8f31-04ef117a9c5a.png - :alt: SAM CLI Logs JSON Pretty Print - -Validate SAM templates ----------------------- - -Validate your templates with ``$ sam validate``. Currently this command -will validate that the template provided is valid JSON / YAML. As with -most SAM CLI commands, it will look for a ``template.[yaml|yml]`` file -in your current working directory by default. You can specify a -different template file/location with the ``-t`` or ``--template`` -option. - -**Syntax** - -.. code:: bash - - $ sam validate - /template.yml is a valid SAM Template - -Note: The validate command requires AWS credentials to be configured. See `IAM Credentials <#iam-credentials>`__. - -Package and Deploy to Lambda ----------------------------- - -Once you have developed and tested your Serverless application locally, -you can deploy to Lambda using ``sam package`` and ``sam deploy`` -command. - -``sam 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. - -``sam 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 `__ -and -`aws cloudformation deploy `__ -respectively - Please consult the AWS CLI command documentation for usage. - -Example: - -.. code:: bash - - # Package SAM template - $ sam package --template-file sam.yaml --s3-bucket mybucket --output-template-file packaged.yaml - - # Deploy packaged SAM template - $ sam deploy --template-file ./packaged.yaml --stack-name mystack --capabilities CAPABILITY_IAM - -Learn More ----------- - -- `Project Overview <../README.rst>`__ -- `Installation `__ -- `Getting started with SAM and the SAM CLI `__ -- `Packaging and deploying your application `__ -- `Advanced `__