Merge branch 'master' into version-lock

This commit is contained in:
Nik Graf 2016-11-01 08:24:31 +01:00
commit e8248b5e8a
156 changed files with 4457 additions and 2738 deletions

View File

@ -12,7 +12,7 @@
**The Serverless Framework** Build applications comprised of microservices that run in response to events, auto-scale for you, and only charge you when they run. This lowers the total cost of maintaining your apps, enabling you to build more logic, faster.
The Framework uses new event-driven compute services, like AWS Lambda, Google CloudFunctions, and more. It's a command line tool, providing scaffolding, workflow automation and best practices for developing and deploying your serverless architecture. It's also completely extensible via plugins.
The Framework uses new event-driven compute services, like AWS Lambda, Google CloudFunctions, and more. It's a command-line tool, providing scaffolding, workflow automation and best practices for developing and deploying your serverless architecture. It's also completely extensible via plugins.
Serverless is an MIT open-source project, actively maintained by a full-time, venture-backed team.
@ -38,7 +38,7 @@ Serverless is an MIT open-source project, actively maintained by a full-time, ve
* ##### Install via npm:
* `npm install -g serverless`
* ##### Set-up your [Provider Credentials](./docs/02-providers/aws/01-setup.md)
* ##### Set-up your [Provider Credentials](./docs/providers/aws/guide/credentials.md)
* ##### Create a Service:
* Creates a new Serverless Service/Project
@ -69,13 +69,13 @@ Serverless is an MIT open-source project, actively maintained by a full-time, ve
* Removes all Functions, Events and Resources from your AWS account.
* `serverless remove`
Check out our in-depth [Serverless Framework Guide](./docs/01-guide/README.md) for more information.
Check out our in-depth [Serverless Framework Guide](./docs/providers/aws/guide/README.md) for more information.
## <a name="services"></a>Services (V1.0)
The following are services you can instantly install and use by running `serverless install --url <service-github-url>`
* [CRUD](https://github.com/pmuens/serverless-crud) - CRUD service
* [CRUD](https://github.com/pmuens/serverless-crud) - CRUD service, [Scala Port](https://github.com/jahangirmohammed/serverless-crud-scala)
* [GraphQL Boilerplate](https://github.com/serverless/serverless-graphql) - GraphQL application Boilerplate service
* [Authentication](https://github.com/laardee/serverless-authentication-boilerplate) - Authentication boilerplate service
* [Mailer](https://github.com/eahefnawy/serverless-mailer) - Service for sending emails
@ -88,6 +88,7 @@ The following are services you can instantly install and use by running `serverl
* [Authorizer](https://github.com/eahefnawy/serverless-authorizer) - Service that uses API Gateway custom authorizers
* [Thumbnails](https://github.com/eahefnawy/serverless-thumbnails) - Service that takes an image url and returns a 100x100 thumbnail
* [Boilerplate](https://github.com/eahefnawy/serverless-boilerplate) - Opinionated boilerplate
* [ES6 + Jest](https://github.com/americansystems/serverless-es6-jest) - ES6 + Jest Boilerplate
**Note**: the `serverless install` command will only work on V1.0 or later.
@ -109,6 +110,7 @@ The following are services you can instantly install and use by running `serverl
Use these plugins to overwrite or extend the Framework's functionality…
* [serverless-offline](https://github.com/dherault/serverless-offline) - Emulate AWS Lambda and API Gateway locally to speed up your development cycles.
* [serverless-webpack](https://github.com/elastic-coders/serverless-webpack) - Bundle your lambdas with Webpack
* [serverless-alexa-plugin](https://github.com/rajington/serverless-alexa-plugin) - Support Alexa Lambda events
* [serverless-run-function](https://github.com/lithin/serverless-run-function-plugin) - Run functions locally
@ -119,6 +121,7 @@ Use these plugins to overwrite or extend the Framework's functionality…
* [serverless-plugin-stage-variables](https://github.com/svdgraaf/serverless-plugin-stage-variables)
* [serverless-dynamodb-local](https://github.com/99xt/serverless-dynamodb-local/tree/v1)
* [serverless-wsgi](https://github.com/logandk/serverless-wsgi) - Deploy Python WSGI applications (Flask/Django etc.)
* [serverless-command-line-event-args](https://github.com/horike37/serverless-command-line-event-args) - Event json passes to your Lambda function in commandline
## <a name="v1-projects"></a>Example Projects (V1.0)
@ -191,7 +194,6 @@ Serverless Projects are shareable and installable. You can publish them to npm
## Plugins (v0.5.x)
Serverless is composed of Plugins. A group of default Plugins ship with the Framework, and here are some others you can add to improve/help your workflow:
* [Meta Sync](https://github.com/serverless/serverless-meta-sync) - Securely sync your the variables in your project's `_meta/variables` across your team.
* [Offline](https://github.com/dherault/serverless-offline) - Emulate AWS Lambda and Api Gateway locally to speed up your development cycles.
* [Hook Scripts](https://github.com/kennu/serverless-plugin-hookscripts) - Easily create shell script hooks that are run whenever Serverless actions are executed.
* [CORS](https://github.com/joostfarla/serverless-cors-plugin) - Adds support for CORS (Cross-origin resource sharing).
* [Serve](https://github.com/Nopik/serverless-serve) - Simulate API Gateway locally, so all function calls can be run via localhost.

View File

@ -1,41 +0,0 @@
<!--
title: Installing Serverless
menuText: Installation
description: How to install Serverless
layout: Doc
-->
# Installation
Let's start by installing Node.js and Serverless.
## Installing Node.js
Serverless is a [Node.js](https://nodejs.org) CLI tool so the first thing you need to do is to install Node.js on your machine.
Go to the official [Node.js website](https://nodejs.org), download and follow the [installation instructions](https://nodejs.org/en/download/) to install Node.js on your local machine.
**Note:** Serverless runs on Node v4 or higher. So make sure that you pick a recent Node version.
You can verify that Node.js is installed successfully by running `node --version` in your terminal. You should see the corresponding Node version number printed out.
## Installing Serverless
Great! Now we've got everything in place to install Serverless. Serverless can be easily installed via
[npm](https://npmjs.org) which was installed alongside Node.js.
Open up a terminal and type `npm install -g serverless` to install Serverless.
Once the installation process is done you can verify that Serverless is installed successfully by running `serverless --version`
## Provider Account Setup
In order for serverless to act on your behalf, you will need to connect your providers account. (AWS, Azure, etc.)
[AWS account Setup](../02-providers/aws/01-setup.md)
## Conclusion
We've just installed Node.js and Serverless on our local machine and configured our AWS account! Now lets create our first service.
[Next step > Creating Your First Service](./02-creating-services.md)

View File

@ -1,66 +0,0 @@
<!--
title: Creating Serverless Services
menuText: Creating Services
description: Creating a Serverless Service
layout: Doc
-->
# Creating a service
You can create a service based on a specific template that specifies which provider and runtime to use.
To create a service with a `nodejs` runtime running on `aws` just pass the `aws-nodejs` template to the create command:
```
serverless create --template aws-nodejs --name my-special-service
```
This will create a service and generate `serverless.yml`, `handler.js` and `event.json` files in the current working directory and set the name of the service to `my-special-service` in `serverless.yml`.
You can also check out the [create command docs](../03-cli-reference/01-create.md) for all the details and options.
## Open the service inside your editor
Let's take a closer look at the skeleton Serverless has created for us.
You'll see the following files in your working directory:
- `serverless.yml`
- `handler.js`
- `event.json`
- `.gitignore`
### serverless.yml
Each *Serverless service* configuration is managed in the `serverless.yml` file. The main responsibilities of this file are:
- Declares a Serverless service
- Defines one or multiple functions in the service
- Defines the provider the service will be deployed to (and the runtime if provided)
- Defines custom plugins to be used
- Defines events that trigger each function to execute (e.g. HTTP requests)
- Defines one set of resources (e.g. 1 AWS CloudFormation stack) required by the functions in this service
- Events listed in the `events` section may automatically create the resources required for the event upon deployment
- Allow flexible configuration using Serverless Variables.
You can see the name of our service, the provider configuration and the first function inside the `functions` definition which points to the `handler.js` file. Any further service configuration will be done in this file.
### `handler.js`
The `handler.js` file includes a function skeleton which returns a simple message. The function definition in `serverless.yml` will point to this `handler.js` file and the function inside of it.
Check out the code inside of the `handler.js` so you can play around with it once we've deployed the service.
### `event.json`
This file contains event data we'll use later on to invoke our function.
## Other services to get started
Take a look at the our [list of Serverless services](https://github.com/serverless/serverless/blob/master/README.md#services).
## Conclusion
We've just created our very first service with one simple `create` command. With that in place we're ready to deploy
our service (which now includes one example function) to our provider (in this case Amazon Web Services).
[Next step > Deploying our service](./03-deploying-services.md)

View File

@ -1,43 +0,0 @@
<!--
title: Deploying Serverless Services
menuText: Deploying Services
layout: Doc
-->
# Deploying a service
Make sure you're still working in the same directory you created the service in.
Run `serverless deploy -v` to start the deployment process (make sure that the credentials for your provider are properly configured). This command also prints the progress during the deployment, as we've configured the `verbose` mode.
Serverless now deploys the whole service to the configured provider. It uses the default `dev` stage and `us-east-1` region.
If you need to change the default stage and region, in your `serverless.yml` file, set the `stage` and `region` properties inside a `provider` object:
```yml
# serverless.yml
service: service-name
provider:
name: aws
stage: beta
region: us-west-2
```
After you run `serverless deploy -v`, the progress of the deployment process displays in your terminal.
A success message tells you when everything is deployed and ready to use!
## Deploying to a different stage and region
If you want to deploy to different stages and regions later on, provide corresponding options to the `deploy` command.
For example, deploy to the `production` stage in the `eu-central-1` region by running a `deploy` command that looks like
this: `serverless deploy --stage production --region eu-central-1`.
Check out the [deploy command docs](../03-cli-reference/03-deploy.md) for all the details and options.
## Conclusion
You've just deployed your service! Let's invoke the services function in the next step.
[Next step > Invoking a function](./04-invoking-functions.md)

View File

@ -1,51 +0,0 @@
<!--
title: Invoking Serverless Functions
menuText: Invoking Services
description: How to invoke a Serverless function and watch the logs
layout: Doc
-->
# Invoking a function
We've just created and deployed our very first service to our cloud provider.
The service skeleton which Serverless created for us included a function with a corresponding function handler (the `handler.js` file).
Let's invoke this function to see if the service was deployed successfully.
## Invoking the `hello` function
Run `serverless invoke --function hello -p event.json` in the service directory to tell Serverless that you want to run the function on the providers infrastructure.
The function will be invoked and returns the result back to Serverless which will print it out on the terminal.
As a result of this you should see the functions message printed out on the console.
You can also change the message returned by your function in `handler.js` or change the event.json file to see how your function output will change.
You can also check out the [invoke command docs](../03-cli-reference/04-invoke.md) for all the details and options.
## Viewing Function Logs
After you deploy your service, and invoke it to generate some default logs provided by AWS, you can view those logs right from your terminal using the `serverless logs` command.
### Viewing the `hello` function logs
Run `serverless logs --function hello` to fetch the logs of the `hello` function from CloudWatch. If your function has never been invoked, you may not see any output/logs. For testing we recommend you invoke your function first before logging.
By default, Serverless will fetch all the logs that happened in the past 30 minutes. You can overwrite this behavior by providing extra options. (keep reading!).
The logs will then be displayed on your terminal. By default, AWS logs a `START`, `END` & `REPORT` logs for each invocation, plus of course any logging functionality you have in your code. You should see all these logs on the screen.
The logs command provides different options you can use. Please take a look at the
[logs command documentation](../03-cli-reference/05-logs.md) to see what else you can do.
## Conclusion
We've just invoked a function through the Serverless CLI on the providers infrastructure and got a message back which was printed on the console.
A service with functions alone is just the beginning. Event sources provide a really easy and great way to empower your service and perform automatic function calls based upon incoming events (e.g. an incoming HTTP request).
Let's take a closer look at how we can use different event sources and attach them to our function.
[Next step > Event sources](./05-event-sources.md)

View File

@ -1,81 +0,0 @@
<!--
title: Setting up Events for your functions
menuText: Setting up Events
description: How to set up events triggering your functions
layout: Doc
-->
# Event sources
Serverless is used to build event driven architectures. Basically everything which can trigger a function is an event. Events could be HTTP requests, events fired from a cloud storage (like a S3 bucket), scheduled events, etc.
Events are provider specific, so not every event syntax is available for every provider. We're documenting every event in-depth in the provider specific documentation. Before we deep dive, lets look at how to add a simple HTTP Event to our function.
## Adding a HTTP event
Go to the Serverless service directory and open up the `serverless.yml`
file in your editor. First, we need to add an `events` property to the function to tell Serverless that this
function will have events attached:
```yml
functions:
hello:
handler: handler.hello
events:
```
This `events` property is used to store all the event definitions for the function.
Each event will be added inside this `events` section. Events are added as an array as you can have multiple events of the same type associated with a function.
Let's add a `http` event with a path of `greet` and a method of `get`:
```yml
functions:
hello:
handler: handler.hello
events:
- http: GET greet
```
That's it. There's nothing more to do to setup a `http` event. Let's (re)deploy our service so that Serverless will
translate this event definition to provider specific syntax and sets it up for us.
## (Re)deploying
We can redeploy our updated service by simply running `serverless deploy` again.
Serverless will show the progress on the terminal and tell you once the service is updated.
## Calling our HTTP endpoint
Let's test our deployed HTTP endpoint.
After deploying your service you should see the URL for your http endpoint in the terminal:
```bash
endpoints:
GET - https://dxaynpuzd4.execute-api.us-east-1.amazonaws.com/dev/greet
```
We can now simply call it:
```bash
$ curl https://dxaynpuzd4.execute-api.us-east-1.amazonaws.com/dev/greet
```
You've successfully executed the function through the HTTP endpoint!
Serverless provides more than just a HTTP event source. You can find the full list of all available event sources with
corresponding examples in the provider specific docs:
* [AWS event documentation](../02-providers/aws/events/).
## Conclusion
Event sources are a great way to extend the functionality of your functions.
They are pretty easy to setup. You simply need to add them to the corresponding function in your services `serverless.yml` file and (re)deploy the service.
But what if you want to add custom provider specific resources to your service which are not yet available as event sources or through plugins?
Let's take a look at this now.
[Next step > Managing custom provider resources](./06-custom-provider-resources.md)

View File

@ -1,66 +0,0 @@
<!--
title: Creating custom provider resources
menuText: Creating custom resources
description: How to extend your
layout: Doc
-->
# Custom provider resources
Sometimes you want to add custom provider resources to your service to use provider specific functionality which is not yet available through events or plugins. Serverless has you covered and enables you a convenient way to add those resources with the help of the `resources` section in the `serverless.yml` file.
**Note:** Your custom resources are merged on top of the resources Serverless defines. This gives you the power to overwrite existing resources easily, even the ones that are created automatically by Serverless. You need to be careful though to not disrupt Serverless functionality.
## Adding custom provider resources
Serverless uses the services `resources` object as a place to add more custom resources.
You can use this place to add custom provider resources by writing the resource definition in the provider specific YAML syntax inside the `resources` object. You can also use [Serverless Variables](./08-serverless-variables.md) for sensitive data or reusable configuration in your resources templates.
**Note:** You'll have the whole flexibility to overwrite / attach any kind of resource to your CloudFormation stack. You can add `Resources`, `Outputs` or even overwrite the `Description`. Please be cautious as overwriting existing parts of your CloudFormation stack might introduce unexpected behavior.
```yml
# serverless.yml
resources:
Resources:
CustomProviderResource:
Type: ResourceType
Properties:
Key: Value
Outputs:
CustomOutput:
Description: "Description for my output"
Value: "My Custom Output"
```
### Example custom resources - S3 bucket
Sometimes you need an extra S3 bucket to store some data in (say, thumbnails). This works by adding an extra S3 Bucket Resource to your `serverless.yml`:
```yml
service: lambda-screenshots
provider: aws
functions:
resources:
Resources:
ThumbnailsBucket:
Type: AWS::S3::Bucket
Properties:
# You can also set properties for the resource, based on the CloudFormation properties
BucketName: my-awesome-thumbnails
# Or you could reference an environment variable
# BucketName: ${env:BUCKET_NAME}
```
Now that you have this additional resource defined in your `serverless.yml` file, you can simply run `serverless deploy` and that will deploy these custom resources for you along with your service and set up the additional bucket for you.
## Conclusion
The `resources` section inside the `serverless.yml` file is a place
where you can add custom, provider specific resource definitions which should be created on service deployment.
It gives you access to the whole feature set your provider offers and makes Serverless even more extensible.
The last thing we need to learn is how we can remove our service. Let's take a look at this now.
[Next step > Removing your service](./07-removing-services.md)

View File

@ -1,28 +0,0 @@
<!--
title: Removing Services
menuText: Removing Services
description: How to remove a deployed service
layout: Doc
-->
# Removing a service
The last step we want to introduce in this guide is how to remove the service.
Removal is done with the help of the `remove` command. Just run `serverless remove -v` to trigger the removal process. As in the deploy step we're also running in the `verbose` mode so you can see all details of the remove process.
Serverless will start the removal and informs you about it's process on the console. A success message is printed once the whole service is removed.
**Note:** The removal process will only remove the service on your providers infrastructure. The service directory will still remain on your local machine so you can still modify and (re)deploy it to another stage, region or provider later on.
## Conclusion
We've just removed the whole service from our provider with a simple `serverless remove` command.
## What's next?
You can either dive deeper into our [Advanced Guides](./#advanced-guides) or read through the provider specific documentation we provide:
* [AWS Documentation](../02-providers/aws/)
Have fun with building your Serverless services and if you have feedback on the please let us know in [our Forum](forum.serverless.com) or [open an Issue in our Github repository](https://github.com/serverless/serverless/issues/new) for any bugs you might encounter or if you have an idea for a new feature.

View File

@ -1,54 +0,0 @@
<!--
title: Installing Serverless Plugins
menuText: Installing Plugins
layout: Doc
-->
# Adding custom plugins
Serverless is extendable through plugins. Plugins can provide new CLI commands or hook into existing plugins to extend their functionality.
Serverless uses the plugin infrastructure to run the core plugins. The plugin infrastructure is extendable by third party developers too. Using the same system, you can extend the framework to suit your custom needs.
Let's take a look into this now.
## Installing a plugin
First we need to install the corresponding plugin in the services root directory with the help of npm:
`npm install --save custom-serverless-plugin`.
Note: Custom plugins are added on a per service basis and are not applied globally
## Adding the plugin to a service
We need to tell Serverless that we want to use the plugin inside our service. We do this by adding the name of the plugin to the `plugins` section in the `serverless.yml` file.
```yml
# serviceXYZ serverless.yml file
plugins:
- custom-serverless-plugin
```
Plugins might want to add extra information which should be accessible to Serverless. The `custom` section in the `serverless.yml` file is the place where you can add necessary
configurations for your plugins (the plugins author / documentation will tell you if you need to add anything there):
```yml
plugins:
- custom-serverless-plugin
custom:
customkey: customvalue
```
## Load order
Keep in mind that the order you define your plugins matters. When Serverless loads all the [core plugins](https://github.com/serverless/serverless/tree/master/lib/plugins) and then the custom plugins in the order you've defined them.
```yml
plugins:
- plugin1
- plugin2
```
In this case `plugin1` is loaded before `plugin2`.

View File

@ -1,55 +0,0 @@
<!--
title: Excluding files from packaging
menuText: Packaging Services
layout: Doc
-->
# Excluding files from packaging
Sometimes you might like to have more control over your function artifacts and how they are packaged.
You can use the `package` and `exclude` configuration for more control over the packaging process.
## Exclude
Exclude allows you to define globs that will be excluded from the resulting artifact.
## Artifact
For complete control over the packaging process you can specify your own zip file for your service. Serverless won't zip your service if this is configured so `exclude` will be ignored.
## Example
```yaml
service: my-service
package:
exclude:
- tmp/**
- .git
artifact: path/to/my-artifact.zip
```
## Packaging functions separately
If you want even more controls over your functions for deployment you can configure them to be packaged independently. This allows you more control for optimizing your deployment. To enable individual packaging set `individually` to true in the service wide packaging settings.
Then for every function you can use the same `exclude/artifact` config options as you can service wide. The `exclude` option will be merged with the service wide options to create one `exclude` config per function during packaging.
```yaml
service: my-service
package:
individually: true
exclude:
- excluded-by-default.json
functions:
hello:
handler: handler.hello
package:
exclude:
# We're excluding this file so it will not be in the final package of this function only
- included-by-default.json
world:
handler: handler.hello
package:
exclude:
- event.json
```

View File

@ -1,21 +0,0 @@
<!--
title: Excluding files from packaging
menuText: Packaging Services
layout: Doc
-->
# Environment Variables in Serverless
Environment variables are a very important and often requested feature in Serverless. It is one of our highest priority features, but to implement it to the extent we want it to be available will take more time as of now. Until then you'll be able to use the following tools for different languages to set environment variables and make them available to your code.
## Javascript
You can use [dotenv](https://www.npmjs.com/package/dotenv) to load files with environment variables. Those variables can be set during your CI process or locally and then packaged and deployed together with your function code.
## Python
You can use [python-dotenv](https://github.com/theskumar/python-dotenv) to load files with environment variables. Those variables can be set during your CI process or locally and then packaged and deployed together with your function code.
## Java
For Java the easiest way to set up environment like configuration is through [property files](https://docs.oracle.com/javase/tutorial/essential/environment/properties.html). While those will not be available as environment variables they are very commonly used configuration mechanisms throughout Java.

View File

@ -1,39 +0,0 @@
<!--
title: Serverless.yml reference
menuText: Serverless.yml reference
layout: Doc
-->
# Serverless.yml reference
The following is a reference of all non provider specific configuration. The details of those config options and further options can be found in [our guide](./) and the provider [provider configuration](../02-providers).
```yml
service: aws-nodejs # Name of the Service
defaults: # default configuration parameters for Serverless
variableSyntax: '\${{([\s\S]+?)}}' # Overwrite the default "${}" variable syntax to be "${{}}" instead. This can be helpful if you want to use "${}" as a string without using it as a variable.
provider: # Provider specific configuration. Check out each provider for all the variables that are available here
name: aws
plugins: # Plugins you want to include in this Service
- somePlugin
custom: # Custom configuration variables that should be used with the variable system
somevar: something
package: # Packaging include and exclude configuration
exclude:
- exclude-me.js
include:
- include-me.js
artifact: my-service-code.zip
functions: # Function definitions
hello:
handler: handler.hello
events: # Events triggering this function
resources: # Provider specific additional resources
```

View File

@ -1,30 +0,0 @@
<!--
title: Serverless Framework Getting Started Guide
menuText: Getting Started
layout: Doc
-->
# Guide
This guide will help you build your Serverless services. We'll start by giving you information on how to install Serverless. After that we create and deploy a service, invoke a service's function and add additional event sources to our function.
At the end we'll add custom provider resources to our service and remove it.
We always try to make our documentation better, so if you have feedback on the Guide please let us know in [our Forum](http://forum.serverless.com) or [open an Issue in our Github repository](https://github.com/serverless/serverless/issues/new)
## Getting started
- [Installing Serverless](./01-installing-serverless.md)
- [Creating a service](./02-creating-services.md)
- [Deploying a service](./03-deploying-services.md)
- [Invoking a function](./04-invoking-functions.md)
- [Event sources](./05-event-sources.md)
- [Custom provider resources](./06-custom-provider-resources.md)
- [Removing a service](./07-removing-services.md)
## Advanced Guides
- [Serverless Variables](./08-serverless-variables.md)
- [Installing plugins](./09-installing-plugins.md)
- [Including/Excluding files for deployment](./10-packaging.md)
- [Environment variable handling](./11-environment-variable-handling.md)
- [Serverless.yml reference](./12-serverless-yml-reference.md)

View File

@ -1,9 +0,0 @@
<!--
title: Serverless Providers
menuText: Serverless Providers
layout: Doc
-->
# Serverless Providers
* [Amazon Web Services](aws)

View File

@ -1,208 +0,0 @@
<!--
title: AWS Authentication Setup
menuText: AWS Authentication Setup
layout: Doc
-->
# Provider account setup
[Watch the video guide here](https://youtu.be/weOsx5rLWX0)
Serverless needs access to your cloud providers account so that it can create and manage resources on your behalf.
Here we'll provide setup instructions for different cloud provider accounts. Just pick the one for your
provider and follow the steps to get everything in place for Serverless.
## Amazon Web Services
### Creating an administrative IAM User
We're going to create an admin user which can access and configure the services in your AWS account.
To get you up and running quickly, we're going to create a AWS IAM User with administrative access to your AWS account.
**Note:** In a production environment we recommend reducing the permissions to the IAM User which the Framework uses.
Unfortunately, the frameworks functionality is growing so fast, we can't yet offer you a finite set of permissions it needs. In the interim, ensure that your AWS API Keys are kept in a safe, private location.
1. Create or login to your Amazon Web Services Account and go to the Identity & Access Management (IAM) Page
2. Click on **Users** and then **Create New Users**. Enter `serverless-admin` in the first field and click **Create**
3. **View and copy the API Key & Secret. You'll need it in the next step**
4. In the User record in the AWS IAM Dashboard, look for **Managed Policies** on the **Permissions** tab and click
**Attach Policy**
5. In the next screen, search for and select **AdministratorAccess** then click **Attach**
### Signing up for an AWS Subscription
Most AWS services require you to have a credit card set up, otherwise you can't deploy your resources and the following error message will appear:
>AWS Access Key Id needs a subscription for the service
If you created a new AWS account make sure that a credit card is set up for the account.
### Setting the AWS API Key & Secret
To start using Serverless and access the AWS API you need to set the AWS API Access Key & Secret.
#### Quick Setup
As a quick setup to get started you can export them as environment variables so they would be accessible to Serverless and the AWS SDK in your shell:
```bash
export AWS_ACCESS_KEY_ID=<key>
export AWS_SECRET_ACCESS_KEY=<secret>
```
OR, if you already have an AWS profile set up…
```bash
export AWS_PROFILE=<profile>
```
Continue with [creating your first service](../../01-guide/02-creating-services.md).
#### Using AWS Profiles
For a more permanent solution you can also set up credentials through AWS profiles using the `aws-cli`, or by configuring the credentials file directly.
To set them up through the `aws-cli` [install it first](http://docs.aws.amazon.com/cli/latest/userguide/installing.html) then run `aws configure` [to configure the aws-cli and credentials](http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html):
```bash
$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: ENTER
```
Credentials are stored in INI format in `~/.aws/credentials`, which you can edit directly if needed. Read more about that file in the [AWS documentation](http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#cli-config-files)
You can even set up different profiles for different accounts, which can be used by Serverless as well.
#### Specifying Credentials/Profiles to Serverless
You can specify either credentials or a profile. Each of these can be provided by altering your serverless.yml or your system's environment variables. Each can be specified for all stages or you can specify stage specific credentials. Using variables in your serverless.yml, you could implement more complex credential selection capabilities.
One set of credentials for all stages using serverless.yml
```yml
provider:
credentials:
accessKeyId: YOUR_ACCESS_KEY
secretAccessKey: YOUR_SECRET_KEY
```
A set of credentials for each stage using serverless.yml
```yml
custom:
test:
credentials:
accessKeyId: YOUR_ACCESS_KEY_FOR_TEST
secretAccessKey: YOUR_SECRET_KEY_FOR_TEST
prod:
credentials:
accessKeyId: YOUR_ACCESS_KEY_FOR_PROD
secretAccessKey: YOUR_SECRET_KEY_FOR_PROD
provider:
credentials: ${self:custom.${opt:stage}.credentials}
```
One profile for all stages using serverless.yml
```yml
provider:
profile: your-profile
```
A profile for each stage using serverless.yml
```yml
custom:
test:
profile: your-profile-for-test
prod:
profile: your-profile-for-prod
provider:
profile: ${self:custom.${opt:stage}.profile}
```
One set of credentials for all stages using environment variables
```bash
export AWS_ACCESS_KEY_ID=<key>
export AWS_SECRET_ACCESS_KEY=<secret>
export AWS_SESSION_TOKEN=<token>
serverless <…>
```
A set of credentials for each stage using environment variables
```bash
export AWS_TEST_ACCESS_KEY_ID=<key>
export AWS_TEST_SECRET_ACCESS_KEY=<secret>
export AWS_TEST_SESSION_TOKEN=<token>
export AWS_PROD_ACCESS_KEY_ID=<key>
export AWS_PROD_SECRET_ACCESS_KEY=<secret>
export AWS_PROD_SESSION_TOKEN=<token>
serverless <…>
```
A profile for all stages using environment variables
```bash
export AWS_PROFILE=<profile>
serverless <…>
```
A profile for each stage using environment variables
```bash
export AWS_TEST_PROFILE=<profile>
export AWS_PROD_PROFILE=<profile>
serverless <…>
```
#### Credential & Profile Overriding
Sometimes you want to be able to specify a default but to override that default for a special case. This is possible with credentials and profiles in Serverless. You may specify credentials and profiles in various forms. The serverless.yml has the lowest priority and environment variables used for all stages will override values set in serverless.yml. Environment variables that are specific to a stage have the highest priority and will override both broad environment variables as well as serverless.yml. Profile provided credentials will override credentials provided in piece-meal from otherwise equivalent credential sources. A priority listing follows.
severless.yml credentials < serverless.yml profile credentials < all-stages environment credentials < all stages environment profile credentials < stage-specific environment credentials < stage-specific environment profile credentials
A default set of `prod` credentials to use overriden by stage specific credentials
```bash
export AWS_ACCESS_KEY_ID=<key>
export AWS_SECRET_ACCESS_KEY=<secret>
export AWS_SESSION_TOKEN=<token>
export AWS_PROD_ACCESS_KEY_ID=<prod-key>
export AWS_PROD_SECRET_ACCESS_KEY=<prod-secret>
export AWS_PROD_SESSION_TOKEN=<prod-token>
serverless <…>
```
A default profile to use overriden by a `prod` specific profile
```bash
export AWS_PROFILE=<profile>
export AWS_PROD_PROFILE=<profile>
serverless <…>
```
A default profile declared in serverless.yml overridden by a `prod` specific environment variable profile
```yml
provider:
profile: your-profile
```
```bash
export AWS_PROD_ACCESS_KEY_ID=<prod-key>
export AWS_PROD_SECRET_ACCESS_KEY=<prod-secret>
export AWS_PROD_SESSION_TOKEN=<prod-token>
serverless <…>
```
## Conclusion
With the account setup in place Serverless is now able to create and manage resources on our behalf.
Now it's time to start with our first Serverless service.
[Next step > Creating a service](../../01-guide/02-creating-services.md)

View File

@ -1,43 +0,0 @@
<!--
title: IAM Role configuration
menuText: IAM Role configuration
layout: Doc
-->
# Adding custom IAM role statements
If you want to give permission to your functions to access certain resources on your AWS account, you can add custom IAM role statements to your service by adding the statements in the `iamRoleStatements` array in the `provider` object. As those statements will be merged into the CloudFormation template you can use Join, Ref or any other CloudFormation method or feature. You're also able to either use YAML for defining the statement (including the methods) or use embedded JSON if you prefer it. Here's an example that uses all of the above:
```yml
# serverless.yml
service: new-service
provider:
name: aws
iamRoleStatements:
- Effect: "Allow"
Action:
- "s3:ListBucket"
Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket"} ] ] }
- Effect: "Allow"
Action:
- "s3:PutObject"
Resource:
Fn::Join:
- ""
- - "arn:aws:s3:::"
- "Ref" : "ServerlessDeploymentBucket"
```
On deployment, all these statements will be added to the IAM role that is assumed by your lambda functions.
# Using existing IAM role
If you want to use an existing IAM role, you can add your IAM role ARN in the `iamRoleARN`. For example:
```yml
# serverless.yml
service: new-service
provider:
name: aws
iamRoleARN: arn:aws:iam::YourAccountNumber:role/YourIamRole
```

View File

@ -1,57 +0,0 @@
<!--
title: Serverless VPC Configuration
menuText: VPC Configuration
layout: Doc
-->
# Configuring your functions to run in a VPC
You can add VPC configuration to a specific function in `serverless.yml` by adding a `vpc` object property in the function configuration. This object should contain the `securityGroupIds` and `subnetIds` array properties needed to construct VPC for this function. Here's an example configuration:
```yml
# serverless.yml
service: service-name
provider: aws
functions:
hello:
handler: handler.hello
vpc:
securityGroupIds:
- securityGroupId1
- securityGroupId2
subnetIds:
- subnetId1
- subnetId2
```
Or if you want to apply VPC configuration to all functions in your service, you can add the configuration to the higher level `provider` object, and overwrite these service level config at the function level. For example:
```yml
# serverless.yml
service: service-name
provider:
name: aws
vpc:
securityGroupIds:
- securityGroupId1
- securityGroupId2
subnetIds:
- subnetId1
- subnetId2
functions:
hello: # this function will overwrite the service level vpc config above
handler: handler.hello
vpc:
securityGroupIds:
- securityGroupId1
- securityGroupId2
subnetIds:
- subnetId1
- subnetId2
users: # this function will inherit the service level vpc config above
handler: handler.users
```
Then, when you run `serverless deploy`, VPC configuration will be deployed along with your lambda function.

View File

@ -1,37 +0,0 @@
<!--
title: Serverless Cloudformation Resource naming Reference
menuText: Cloudformation Resource Reference
layout: Doc
-->
# Cloudformation Resource Reference
To have consistent naming in the Cloudformation Templates that get deployed we've defined a standard name:
`{Function Name}{Cloud Formation Resource Type}{ResourceName}{SequentialID or Random String}`
* `Function Name` this is optional for Resources that should be recreated when the function name gets changed. Those resources are also called *function bound*
* `Cloud Formation Resource Type` e.g. S3Bucket
* `Resource Name` an identifier for the specific resource, e.g. for an S3 Bucket the configured bucket name.
* `SequentialID or Random String` For a few resources we need to add an optional sequential id or random string to identify them
All resource names that are deployed by Serverless have to follow this naming scheme. The only exception (for backwards compatibility reasons) is the S3 Bucket that is used to upload artifacts so they can be deployed to your function.
We're also using the term `normalizedName` or similar terms in this guide. This basically just means dropping any characters that aren't allowed in resources names, e.g. special characters.
| AWS Resource | Name Template | Example |
|--- |--- | --- |
| S3::Bucket | S3Bucket{normalizedBucketName} | S3BucketMybucket |
|IAM::Role | IamRoleLambdaExecution | IamRoleLambdaExecution |
|IAM::Policy | IamPolicyLambdaExecution | IamPolicyLambdaExecution |
|Lambda::Function | {normalizedFunctionName}LambdaFunction | HelloLambdaFunction |
|Lambda::Permission | <ul><li>**Schedule**: {normalizedFunctionName}LambdaPermissionEventsRuleSchedule{index} </li><li>**S3**: {normalizedFunctionName}LambdaPermissionS3</li><li>**APIG**: {normalizedFunctionName}LambdaPermissionApiGateway</li><li>**SNS**: {normalizedFunctionName}LambdaPermission{normalizedTopicName}</li></ul> | <ul><li>**Schedule**: HelloLambdaPermissionEventsRuleSchedule1 </li><li>**S3**: HelloLambdaPermissionS3</li><li>**APIG**: HelloLambdaPermissionApiGateway</li><li>**SNS**: HelloLambdaPermissionSometopic</li></ul> |
|Events::Rule | {normalizedFuntionName}EventsRuleSchedule{SequentialID} | HelloEventsRuleSchedule1 |
|ApiGateway::RestApi | ApiGatewayRestApi | ApiGatewayRestApi |
|ApiGateway::Resource | ApiGatewayResource{normalizedPath} | <ul><li>ApiGatewayResourceUsers</li><li>ApiGatewayResourceUsers**Var** for paths containing a variable</li><li>ApiGatewayResource**Dash** if the path is just a `-`</li></ul> |
|ApiGateway::Method | ApiGatewayResource{normalizedPath}{normalizedMethod} | ApiGatewayResourceUsersGet |
|ApiGateway::Authorizer | {normalizedFunctionName}ApiGatewayAuthorizer | HelloApiGatewayAuthorizer |
|ApiGateway::Deployment | ApiGatewayDeployment{randomNumber} | ApiGatewayDeployment12356789 |
|ApiGateway::ApiKey | ApiGatewayApiKey{SequentialID} | ApiGatewayApiKey1 |
|SNS::Topic | SNSTopic{normalizedTopicName} | SNSTopicSometopic |
|AWS::Lambda::EventSourceMapping | <ul><li>**DynamoDB**: {normalizedFunctionName}EventSourceMappingDynamodb{tableName} </li><li>**Kinesis**: {normalizedFunctionName}EventSourceMappingKinesis{streamName} </li></ul> | <ul><li>**DynamoDB**: HelloLambdaEventSourceMappingDynamodbUsers </li><li>**Kinesis**: HelloLambdaEventSourceMappingKinesisMystream </li></ul> |

View File

@ -1,94 +0,0 @@
<!--
title: Serverless AWS Documentation
menuText: AWS Documentation
layout: Doc
-->
# Serverless AWS Documentation
Check out the [Getting started guide](../../01-guide/) and the [CLI reference](../../03-cli-reference/) for an introduction to Serverless.
## Setup and configuration
Please follow these [setup instructions](./01-setup.md) to start using AWS Lambda and serverless together
## Provider configuration
Following are examples and descriptions of all available AWS specific provider configuration settings.
```yaml
provider:
name: aws # Set the provider you want to use, in this case AWS
runtime: nodejs4.3 # Default runtime for functions in this provider
stage: dev # Set the default stage used. Default is dev
region: us-east-1 # Overwrite the default region used. Default is us-east-1
deploymentBucket: com.serverless.${self:provider.region}.deploys # Overwrite the default deployment bucket
stackTags: # Optional CF stack tags
key: value
stackPolicy: # Optional CF stack policy. The example below allows updates to all resources except deleting/replacing EC2 instances (use with caution!)
- Effect: Allow
Principal: "*"
Action: "Update:*"
Resource: "*"
- Effect: Deny
Principal: "*"
Action:
- Update:Replace
- Update:Delete
Condition:
StringEquals:
ResourceType:
- AWS::EC2::Instance
```
### Deployment S3 Bucket
The bucket must exist beforehand and be in the same region as the Lambda functions you want to deploy. Due to the importance and hard dependency of the deployment bucket, if you want to switch between the core and custom bucket, you have to do the following:
* **From CloudFormation Bucket to Self Provided Bucket:** You need to manually empty the CloudFormation bucket. On the next deployment the bucket will be removed and we will use the self provided bucket. Without emptying the CloudFormation bucket your next deployment will fail.
* **From Self Provided Bucket to CloudFormation Bucket:** You'll need to add the following custom resources template to `serverless.yml`:
```yml
resources:
Resources:
ServerlessDeploymentBucket:
Type: AWS::S3::Bucket
```
then deploy your service to create the CloudFormation bucket, then remove the `provider.deploymentBucket` property and deploy your service again. This syncs the framework back to the CloudFormation Bucket without conflict. After that deployment you can remove the CloudFormation bucket from the resources section in `serverless.yml` as it will be automatically added from now on.
## Additional function configuration
```yaml
functions:
hello:
name: ${self:provider.stage}-lambdaName # Deployed Lambda name
description: Description of what the lambda function does # Description to publish to AWS
handler: handler.hello # handler set in AWS Lambda
runtime: python2.7 # optional overwrite, default is provider runtime
memorySize: 512 # optional, default is 1024
timeout: 10 # optional, default is 6
```
## General Configuration
* [Configuring IAM resources](./02-iam.md)
* [VPC configuration](./03-vpc.md)
* [Cloudformation Resource naming reference](./04-resource-names-reference.md)
## AWS events
* [API Gateway](./events/01-apigateway.md)
* [S3](./events/02-s3.md)
* [Schedule](./events/03-schedule.md)
* [SNS](./events/04-sns.md)
* [Kinesis Streams](./events/05-kinesis-streams.md)
* [Dynamodb Streams](./events/06-dynamodb-streams.md)
## Examples
See the [examples folder](./examples) for all AWS serverless examples
- [hello-world](./examples/hello-world)
- [using-external-libraries](./examples/using-external-libraries)
- [web-api](./examples/web-api)
To add examples, fork this repo and submit a pull request

View File

@ -1,13 +0,0 @@
<!--
title: AWS Serverless Events
menuText: AWS Events
layout: Doc
-->
# AWS serverless events
* [API Gateway](./01-apigateway.md)
* [S3](./02-s3.md)
* [Schedule](./03-schedule.md)
* [SNS](./04-sns.md)
* [DynamoDB / Kinesis Streams](./05-streams.md)

View File

@ -1,6 +0,0 @@
module.exports = {
"rules": {
"no-console": "off",
"import/no-unresolved": "off"
}
};

View File

@ -1,11 +0,0 @@
<!--
title: AWS Lambda Example Projects
menuText: AWS Lambda Examples
description: A list of serverless AWS Lambda Example Projects
layout: Doc
-->
* [hello-world](./hello-world)
* [using-external-libraries](./using-external-libraries)
* [cron](./cron)
* [web-serving-html](./web-serving-html)

View File

@ -1,14 +0,0 @@
<!--
title: Serverless Scheduled Cron Example
menuText: Scheduled Cron Example
description: Create a serverless scheduled cron job
layout: Doc
-->
# Schedule Cron
Create a scheduled task with AWS Lambda and automate all the things!
For more information on running cron with serverless check out the [Tutorial: Serverless Scheduled Tasks](https://parall.ax/blog/view/3202/tutorial-serverless-scheduled-tasks) by parallax.
For more information on `schedule` serverless event check out [our docs](/docs/02-providers/aws/events/03-schedule.md).

View File

@ -1,18 +0,0 @@
<!--
title: Node Lambda Scheduled Cron Example
menuText: Scheduled Cron Example
description: Create a serverless scheduled cron job with nodejs and aws lambda
layout: Doc
-->
# AWS Lambda Node Cron Function
This is an example of creating a function that runs on a scheduled cron.
To see your cron running tail your logs with:
```bash
serverless logs -function cron -tail
```
[Tutorial: Serverless Scheduled Tasks](https://parall.ax/blog/view/3202/tutorial-serverless-scheduled-tasks)

View File

@ -1,16 +0,0 @@
<!--
title: Serverless Hello World Example
menuText: Hello World Example
description: Example of creating a hello world function in NodeJS and Python with the serverless framework
layout: Doc
-->
# Hello World Example
Welcome to the hello world serverless example.
We are excited for you to start your serverless journey!
* [Javascript](./node)
* [Python](./python)

View File

@ -1,30 +0,0 @@
<!--
title: Hello World AWS Lambda Node Example
menuText: Hello World Node Example
description: Create a nodeJS Lambda function on amazon web services
layout: Doc
-->
# Hello World Node.js
Make sure `serverless` is installed. [See installation guide](/docs/01-guide/01-installing-serverless.md)
## 1. Deploy
`serverless deploy` or `sls deploy`. `sls` is shorthand for the serverless CLI command
## 2. Invoke deployed function
`serverless invoke --function helloWorld` or `serverless invoke -f helloWorld`
`-f` is shorthand for `--function`
In your terminal window you should see the response from AWS Lambda
```bash
{
"message": "Hello World"
}
```
Congrats you have just deployed and ran your hello world function!

View File

@ -1,30 +0,0 @@
<!--
title: Hello World AWS Lambda Python Example
menuText: Hello World Python Example
description: Create a simple Python powered Lambda function on amazon web services
layout: Doc
-->
# Hello World in Python
Make sure `serverless` is installed. [See installation guide](/docs/01-guide/01-installing-serverless.md)
## 1. Deploy
`serverless deploy` or `sls deploy`. `sls` is shorthand for the serverless CLI command
## 2. Invoke deployed function
`serverless invoke --function helloWorld` or `serverless invoke -f helloWorld`
`-f` is shorthand for `--function`
In your terminal window you should see the response from AWS Lambda
```bash
{
"message": "Hello World"
}
```
Congrats you have just deployed and ran your hello world function!

View File

@ -1,14 +0,0 @@
<!--
title: Using External Libraries
menuText: Using External Libraries
description: Example of Using External Libraries in NodeJS and Python with the serverless framework
layout: Doc
-->
# Using External Libraries Examples
When creating serverless services you are able to use third party packages from your respective ecosystems package manager.
For node.js you can leverage the vast ecosystem of NPM and `require` in modules into your project.
For Python you can use the pip package manager

View File

@ -1,39 +0,0 @@
<!--
title: Using external libraries in Node.js service
menuText: External libraries in Node.js service
description: Create a nodeJS Lambda function on amazon web services
layout: Doc
-->
# Using external libraries in Node.js service
Make sure `serverless` is installed. [See installation guide](/docs/01-guide/01-installing-serverless.md)
## 1. Install dependencies
For this example we are going to install the `faker` module from npm.
`npm install faker --save`
## 2. Use the faker module in your `handler.js` file
Inside of `handler.js` require your module.
`const faker = require('faker');`
## 3. Deploy
`serverless deploy`
## 4. Invoke
`serverless invoke -f helloRandomName`
In your terminal window you should see the response from AWS Lambda
```bash
{
"message": "Hello Floyd"
}
```

View File

@ -1,13 +0,0 @@
'use strict';
// Import faker module from node_modules
const faker = require('faker');
module.exports.helloRandomName = function (event, context, callback) {
const name = faker.name.firstName();
const message = {
message: `Hello ${name}`,
};
callback(null, message);
};

View File

@ -1,16 +0,0 @@
<!--
title: Serving HTML through API Gateway
menuText: Serving HTML
description: Example of serving HTML page through API Gateway
layout: Doc
-->
# Serving HTML through API Gateway
These examples illustrate how to hookup an API Gateway endpoint to a Lambda function to render HTML on a `GET` request.
So instead of returning the default `json` from requests to an endpoint, you can display custom HTML.
This is useful for dynamic webpages and landing pages for marketing activities.
* [Javascript](./node)

View File

@ -1,9 +0,0 @@
<!--
title: AWS Lambda Serving Static HTML Node Example
menuText: Serving Static HTML
layout: Doc
-->
# Serving Static HTML with NodeJS + API Gateway
This is an example of serving vanilla HTML/CSS/JS through API Gateway

View File

@ -1,32 +0,0 @@
<!--
title: Serverless Install CLI Command
menuText: Install
description: Install a service from a GitHub URL in your current working directory
layout: Doc
-->
# Install
Installs a service from a GitHub URL in the current working directory.
```
serverless install --url https://github.com/some/service
```
## Options
- `--url` or `-u` The services GitHub URL. **Required**.
## Provided lifecycle events
- `install:install`
## Examples
### Installing a service from a GitHub URL
```
serverless install --url https://github.com/johndoe/authentication
```
This example will download the .zip file of the `authentication` service from GitHub,
create a new directory with the name `authentication` in the current working directory
and unzips the files in this directory.

View File

@ -1,31 +0,0 @@
<!--
title: Serverless SlStats CLI Command
menuText: Stats
description: Enable or disable framework statistics
layout: Doc
-->
# SlStats
This plugin implements a way to toggle [framework statistics](../framework-statistics.md).
```
serverless slstats --enable
```
## Options
- `--enable` or `-e`.
- `--disable` or `-d`
## Provided lifecycle events
- `slstats:slstats`
## Examples
### Disabling it
```
serverless slstats --disable
```
This example will disable framework statistics.

View File

@ -1,18 +0,0 @@
<!--
title: Serverless CLI Reference
menuText: CLI Reference
layout: Doc
-->
# Serverless CLI Reference
Here you can read through the docs of all commands that come with Serverless.
* [create](./01-create.md)
* [install](./02-install.md)
* [deploy](./03-deploy.md)
* [invoke](./04-invoke.md)
* [logs](./05-logs.md)
* [info](./06-info.md)
* [remove](./07-remove.md)
* [slstats](./08-slstats.md)

View File

@ -1,498 +0,0 @@
<!--
title: Building Serverless Plugins
menuText: Building Plugins
layout: Doc
-->
# Building Serverless plugins
The Serverless plugin System is at the core of the Serverless framework.
The main goals of the plugin system are:
- Separation of CLI configuration and plugin logic
- We want any plugin author to be able to easily create new commands within the Serverless framework and extend existing commands. To achieve this we've created a strong separation between CLI and plugins that has clear interfaces between each other.
- Separation between logic of different plugins
- Different plugins need to have an easy way to run independently and after each other without defining dependencies between each other.
- Greater Extensibility
- Plugins need to be able to easily integrate into the lifecycle of a command independent of other Plugins that are running and can extend the functionality of Serverless easily.
## Concepts
### Plugin
A plugin encapsulates commands (and corresponding lifecycle events) and hooks in a shareable way. A plugin is not forced to provide both, they can only consist of a list of commands and lifecycle events or only of hooks.
### Command
A command represents a CLI command that can be called by a user, e.g. `serverless deploy` would be the `deploy` command.
A command has no logic, but simply defines the CLI configuration (e.g. command, subcommands, parameters) and the lifecycle events for this particular command. Every command defines its own lifecycle events, so different commands can have completely different lifecycles.
The commands that come with Serverless (e.g. `deploy`, `remove`, …) are implemented in the exact same way as commands built by other users. This means that lifecycle events we define for our commands do not have any special meaning in Serverless or for other plugins. Every command is free to have its own lifecycle events, none of them are more special than others.
```javascript
'use strict';
class MyPlugin {
constructor() {
this.commands = {
deploy: {
lifecycleEvents: [
'resources',
'functions'
]
},
};
}
}
module.exports = MyPlugin;
```
We automatically put the name of the command in front of lifecycle events when they are used for hooks.
So in a hook the following syntax needs to be used.
***CommandName:LifecycleEventName***
Which would be **deploy:resources**, and **deploy:functions** in a hook definition (which we will show in more detail below).
In addition to the lifecycle events defined here we will create 2 additional events for each:
1. `before:CommandName:LifecycleEventName`
2. `after:CommandName:LifecycleEventName`
Following the above example well have these lifecycle events for our `myPlugin` plugin:
For the **deploy:resources** lifecycleEvent:
- `before:deploy:resources`
- `deploy:resources`
- `after:deploy:resources`
For the **deploy:functions** lifecycleEvent:
- `before:deploy:functions`
- `deploy:functions`
- `after:deploy:functions`
These names will be used as hooks to include plugin logic. This allows to set up lifecycle events with generic names, but still make sure they are only executed for specific commands.
You can also nest commands, e.g. if you want to provide a command `serverless deploy single` you can simply nest commands as defined in the following example. Those nested commands have their own lifecycle events and do not inherit them from their parents.
```javascript
'use strict';
class MyPlugin {
constructor() {
this.commands = {
deploy: {
lifecycleEvents: [
'resources',
'functions'
],
commands: {
single: {
lifecycleEvents: [
'resources',
'functions'
],
},
},
},
}
}
}
module.exports = MyPlugin;
```
### Hook
Hooks allow to connect specific lifecycle events to functions in a plugin. In the constructor of your class you define a `hooks` variable that the Plugin System will use once a specific command is running. Any hook can bind to any lifecycle event from any command, not just from commands that the same plugin provides.
This allows to extend any command with additional functionality.
```javascript
'use strict';
class Deploy {
constructor() {
this.commands = {
deploy: {
lifecycleEvents: [
'resources',
'functions'
]
},
};
this.hooks = {
'before:deploy:resources': this.beforeDeployResources,
'deploy:resources': this.deployResources,
'after:deploy:functions': this.afterDeployFunctions
};
}
beforeDeployResources() {
console.log('Before Deploy Resources');
}
deployResources() {
console.log('Deploy Resources');
}
afterDeployFunctions() {
console.log('After Deploy Functions');
}
}
module.exports = Deploy;
```
### Serverless instance
The `serverless` instance which enables access to the whole Serverless setup during runtime is passed in as the first parameter to the plugin constructor.
```javascript
'use strict';
class MyPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
log: {
lifecycleEvents: [
'serverless'
],
},
};
this.hooks = {
'log:serverless': this.logServerless.bind(this)
}
}
logServerless() {
console.log('Serverless instance: ', this.serverless);
}
}
module.exports = MyPlugin;
```
### Options and shortcuts
Each (sub)command can have multiple options (and corresponding shortcuts if available).
Options are passed in with a double dash (`--`) like this: `serverless function deploy --function functionName`.
Shortcuts are passed in with a single dash (`-`) like this: `serverless function deploy -f functionName`
The `options` object will be passed in as the second parameter to the constructor of your plugin.
```javascript
'use strict';
class Deploy {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
deploy: {
lifecycleEvents: [
'functions'
],
options: {
function: {
usage: 'Specify the function you want to deploy (e.g. "--function myFunction")'
}
}
},
};
this.hooks = {
'deploy:functions': this.deployFunction.bind(this)
}
}
deployFunction() {
console.log('Deploying function: ', this.options.function);
}
}
module.exports = Deploy;
```
#### Mark options as required
Options can be marked as required. This way the plugin manager will automatically raise an error if a required option
is not passed in via the CLI. You can mark options as required with the help of `required: true` inside the options
definition.
```javascript
'use strict';
class Deploy {
constructor(serverless, options) {
this.options = options;
this.commands = {
deploy: {
lifecycleEvents: [
'functions'
],
options: {
function: {
usage: 'Specify the function you want to deploy (e.g. "--function myFunction")',
required: true
}
}
},
};
this.hooks = {
'deploy:functions': this.deployFunction.bind(this)
}
}
deployFunction() {
console.log('Deploying function: ', this.options.function);
}
}
module.exports = Deploy;
```
#### Define shortcuts for options
Options can also provide shortcuts. Shortcuts make it more convenient to enter long commands. Serverless will
translate shortcuts into options under the hood which means that the option the shortcut belongs to will be replaced with the value of the shortcut (if the shortcut is given).
You can define shortcuts by setting the `shortcut` property in the options definition.
**Note:** A shortcut should be unique inside of a plugin.
```javascript
'use strict';
class Deploy {
constructor(serverless, options) {
this.options = options;
this.commands = {
deploy: {
lifecycleEvents: [
'functions'
],
options: {
function: {
usage: 'Specify the function you want to deploy (e.g. "--function myFunction" or "-f myFunction")',
required: true,
shortcut: 'f'
}
}
},
};
this.hooks = {
'deploy:functions': this.deployFunction.bind(this)
}
}
deployFunction() {
console.log('Deploying function: ', this.options.function);
}
}
module.exports = Deploy;
```
#### Custom validations for options
You can provide a custom validation rule in form of a regular expression for your option. Serverless will raise an error
you can specify if the input for the option does not match the regular expression.
In the following example we'll validate the `retries` option against a regular expression that checks if the value is a number.
```javascript
'use strict';
class Deploy {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
deploy: {
lifecycleEvents: [
'functions'
],
options: {
retries: {
usage: 'Number of retries which should be performed',
customValidation: {
regularExpression: /^[0-9]+$/,
errorMessage: 'Retries should be a number',
},
}
}
},
};
this.hooks = {
'deploy:functions': this.deployFunction.bind(this)
}
}
deployFunction() {
console.log(`Deploying function… Will retry ${this.options.retries} times`);
}
}
module.exports = Deploy;
```
## Provider specific plugins
Plugins can be provider specific which means that they are bound to a provider.
**Note:** Binding a plugin to a provider is optional. Serverless will always consider your plugin if you don't specify a `provider`.
The provider definition should be added inside the plugins constructor and can be the name of the provider (as a string) or the provider plugin instance.
### String representation
The string representation simply tells Serverless that this plugin should only be loaded if the provider defined in the service matches the one of the plugin.
```javascript
'use strict';
class ProviderDeploy {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
// set the providers name here
this.provider = 'providerName';
this.commands = {
deploy: {
lifecycleEvents: [
'functions'
],
options: {
function: {
usage: 'Specify the function you want to deploy (e.g. "--function myFunction")',
required: true
}
}
},
};
this.hooks = {
'deploy:functions': this.deployFunction.bind(this)
}
}
deployFunction() {
console.log('Deploying function: ', this.options.function);
}
}
module.exports = ProviderDeploy;
```
### The provider plugin instance
If you want to get access to provider specific utilities such as the SDK you can get the provider plugin instance with the help of the
`this.serverless.getProvider('providerName')` function and set it to the plugins `provider` property.
You can access the wrapped methods via `this.provider.<methodName>`.
The usage of the plugins `provider` property will load the plugin only if the `provider` matches the one defined in the service.
```javascript
'use strict';
class ProviderInvoke {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
// get access to the provider plugin instance here
this.provider = this.serverless.getProvider('providerName');
this.commands = {
invoke: {
lifecycleEvents: [
'function'
],
options: {
function: {
usage: 'Specify the function you want to invoke (e.g. "--function myFunction")',
required: true
}
}
},
};
this.hooks = {
'invoke:function': this.invokeFunction.bind(this)
}
}
invokeFunction() {
// use the "request" method from the provider plugin
return this.provider.request('function', 'invoke', this.options.function);
}
}
module.exports = ProviderInvoke;
```
## Plugin registration process
A user has to define the plugins they want to use in the root level of the
`serverless.yml` file:
```yml
plugins:
- custom-plugin-1
- custom-plugin-2
```
We do not auto-detect plugins from installed dependencies so users do not run into any surprises and we cut down on the startup time of the tool. Through JSON-REF users can share configuration for used plugins between
`serverless.yml` files in one repository.
After the `serverless.yml` configuration file is loaded the plugin system will load all the commands and plugins and initialize the plugin system.
## Plugin options
Sometimes your plugin needs to setup some custom options. The `serverless.yml`
file provides the `custom` section where you can add options your plugin can use.
```yml
plugins:
- my-greet-plugin
custom:
greeting: hello
```
## Plugin Order
Plugins are registered in the order they are defined through our system and the
`serverless.yml` file. By default we will load the
[core plugins](https://github.com/serverless/serverless/tree/master/lib/plugins) first, then we will load all plugins according to the order given in the
`serverless.yml` file.
This means the Serverless core plugins will always be executed first for every lifecycle event before 3rd party plugins.
If external plugins should be running before our plugins they should generally be able to hook into an earlier lifecycle
event.
## Command naming
Command names need to be unique. If we load two commands and both want to specify the same command (e.g. we have an integrated command `deploy` and an external command also wants to use `deploy`) the Serverless CLI will print an error and exit. Commands need to be unique in the current service context they are executed. So if you want to have your own `deploy` command you need to name it something different like `myCompanyDeploy` so they don't clash with existing plugins.

View File

@ -1,125 +0,0 @@
<!--
title: Building Serverless Provider Integrations
menuText: Building Provider Integrations
layout: Doc
-->
# Building provider integrations
Integrating different infrastructure providers happens through the standard plugin system.
Take a look at the ["building plugins"](./01-creating-plugins.md) documentation to understand how the plugin system works.
## Provider plugins
We'd recommend that you encapsulate provider related utilities into an own plugin and call it `<ProviderName>Provider`.
You can register this provider plugin in Serverless with the help of the `serverless.setProvider(<providerName>, <pluginInstance>)` function.
Furthermore your provider plugin needs to provide a static method which returns the providers name.
Here's a simple skeleton which shows this in detail and can be used as a boilerplate to get started:
```javascript
class MyProvider {
static getProviderName() {
return 'providerName';
}
constructor(serverless) {
this.serverless = serverless;
this.sdk = TheProvidersSDK;
this.provider = this; // only load plugin in a "providerName" service context
this.serverless.setProvider('providerName', this);
}
// this method can be easily re-used by other plugins
useSDK(command) {
return this.sdk(command);
}
}
module.exports = MyProvider;
```
After doing this other plugins can simply call `this.serverless.getProvider('providerName')` and access all the methods you've defined in your provider plugin.
## Provider specific plugins
You can add the providers name inside the constructor of your plugin. This makes it possible to only execute your plugins logic when the Serverless service uses the provider you've specified in your plugin.
## Deployment
Infrastructure provider plugins should bind to specific lifecycle events of the `deploy` command to compile the function and their events to provider specific resources.
### Deployment lifecycle
Let's take a look at the [core `deploy` plugin](https://github.com/serverless/serverless/tree/master/lib/plugins/deploy) and the different lifecycle hooks it provides.
The following lifecycle events are run in order once the user types `serverless deploy` and hits enter:
- `deploy:initialize`
- `deploy:setupProviderConfiguration`
- `deploy:compileFunctions`
- `deploy:compileEvents`
- `deploy:createDeploymentArtifacts`
- `deploy:deploy`
Plugin developers can hook into those lifecycle events to compile and deploy functions and events on your providers infrastructure.
Let's take a closer look at each lifecycle event to understand what its purpose is and what it should be used for.
#### `deploy:initialize`
This lifecycle should be used to load the basic resources the provider needs into memory (e.g. parse a basic resource
template skeleton such as a CloudFormation template).
#### `deploy:setupProviderConfiguration`
The purpose of the `deploy:setupProviderConfiguration` lifecycle is to take the basic resource template which was created in the previous lifecycle and deploy the rough skeleton on the cloud providers infrastructure (without any functions or events) for the first time.
#### `deploy:createDeploymentArtifacts`
The whole service get's zipped up into one .zip file.
Serverless will automatically exclude the following files / folders to reduce the size of the .zip file:
- .git
- .gitignore
- .serverless
- serverless.yaml
- serverless.yml
- .DS_Store
You can always include previously excluded files and folders if you want to.
#### `deploy:compileFunctions`
Next up the functions inside the `serverless.yml` file should be compiled to provider specific resources and stored into memory.
#### `deploy:compileEvents`
After that the events which are defined in the `serverless.yml` file on a per function basis should be compiled to provider specific resources and also stored into memory.
#### `deploy:deploy`
The final lifecycle is the `deploy:deploy` lifecycle which should be used to deploy the previously compiled function and event resources to the providers infrastructure.
### Amazon Web Services provider integration
Curious how this works for the Amazon Web Services (AWS) provider integration?
Here are the steps the AWS plugins take to compile and deploy the service on the AWS infrastructure in detail.
#### The steps in detail
1. The `serverless.yml` file is loaded into memory
2. A default AWS CloudFormation template is loaded and deployed to AWS (A S3 bucket for the service gets created)(`deploy:setupProviderConfiguration`)
3. The functions of the `serverless.yml`
4. Each functions events are compiled into CloudFormation resources and stored into memory (`deploy:compileEvents`)
5. Old functions (if available) are removed from the S3 bucket (`deploy:deploy`)
6. The service gets zipped up and is uploaded to S3 (`deploy:createDeploymentArtifacts` and `deploy:deploy`)
7. The compiled functions, event resources and custom provider resources are attached to the core CloudFormation template and the updated CloudFormation template gets redeployed (`deploy:deploy`)
#### The code
You may also take a closer look at the corresponding plugin code to get a deeper knowledge about what's going on behind the scenes.
The full AWS integration can be found in [`lib/plugins/aws`](https://github.com/serverless/serverless/tree/master/lib/plugins/aws).

View File

@ -1,16 +0,0 @@
<!--
title: Developing serverless plugins
menuText: Developing plugins
layout: Doc
-->
# Developing plugins
Here you can read how to develop your own Serverless plugins. We'll get into details on how to write custom plugins to
extend the functionality of Serverless. Furthermore we'll look into the way how you can use your plugin knowledge
to integrate your own provider into the Serverless framework.
## Table of contents
- [Building plugins](./01-creating-plugins.md)
- [Building provider integrations](./02-creating-provider-plugins.md)

View File

@ -4,63 +4,92 @@ menuText: Docs
layout: Doc
-->
# Serverless Documentation
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/)
<!-- DOCS-SITE-LINK:END -->
Welcome to the Serverless documentation.
# Documentation
- [Quick Start Guide](./01-guide/)
- [Core Concepts](#concepts)
- [CLI Reference](./03-cli-reference/)
- [Providers](#providers)
- [Extending Serverless](./04-extending-serverless/)
- [Contributing to Serverless](#contributing)
The Serverless Framework allows you to deploy auto-scaling, pay-per-execution, event-driven functions to any cloud. We currently support Amazon Web Service's Lambda, and are expanding to support other cloud providers.
## Providers
- [AWS Integration Docs](./02-providers/aws/)
<div class="docsSections">
<div class="docsSection">
<div class="docsSectionHeader">
<a href="./providers/aws/guide/">
<img src="https://s3-us-west-2.amazonaws.com/assets.site.serverless.com/images/docs_guide_aws5.jpg" alt="Serverless Framework AWS Lambda Guide" width="250" draggable="false"/>
</a>
</div>
<div class="test">
<ul>
<li><a href="./providers/aws/guide/intro.md">Intro</a></li>
<li><a href="./providers/aws/guide/installation.md">Installation</a></li>
<li><a href="./providers/aws/guide/credentials.md">Credentials</a></li>
<li><a href="./providers/aws/guide/services.md">Services</a></li>
<li><a href="./providers/aws/guide/functions.md">Functions</a></li>
<li><a href="./providers/aws/guide/events.md">Events</a></li>
<li><a href="./providers/aws/guide/resources.md">Resources</a></li>
<li><a href="./providers/aws/guide/deploying.md">Deploying</a></li>
<li><a href="./providers/aws/guide/testing.md">Testing</a></li>
<li><a href="./providers/aws/guide/variables.md">Variables</a></li>
<li><a href="./providers/aws/guide/packaging.md">Packaging</a></li>
<li><a href="./providers/aws/guide/plugins.md">Plugins</a></li>
<li><a href="./providers/aws/guide/workflow.md">Workflow</a></li>
</ul>
</div>
</div>
## Concepts
<div class="docsSection">
<div class="docsSectionHeader">
<a href="./providers/aws/cli-reference/">
<img src="https://s3-us-west-2.amazonaws.com/assets.site.serverless.com/images/docs_clireference_aws4.jpg" alt="Serverless Framework AWS Lambda CLI Reference" width="250" draggable="false"/>
</a>
</div>
<div>
<ul>
<li><a href="./providers/aws/cli-reference/create.md">Create</a></li>
<li><a href="./providers/aws/cli-reference/install.md">Install</a></li>
<li><a href="./providers/aws/cli-reference/deploy.md">Deploy</a></li>
<li><a href="./providers/aws/cli-reference/invoke.md">Invoke</a></li>
<li><a href="./providers/aws/cli-reference/logs.md">Logs</a></li>
<li><a href="./providers/aws/cli-reference/info.md">Info</a></li>
<li><a href="./providers/aws/cli-reference/remove.md">Remove</a></li>
<li><a href="./providers/aws/cli-reference/slstats.md">Serverless Stats</a></li>
</ul>
</div>
</div>
Before we begin, let's run through some of the main concepts behind serverless.
<div class="docsSection">
<div class="docsSectionHeader">
<a href="./providers/aws/events/">
<img src="https://s3-us-west-2.amazonaws.com/assets.site.serverless.com/images/docs_events_aws4.jpg" alt="Serverless Framework AWS Lambda Events" width="250" draggable="false"/>
</a>
</div>
<div>
<ul>
<li><a href="./providers/aws/events/apigateway.md">API Gateway</a></li>
<li><a href="./providers/aws/events/streams.md">Streams</a></li>
<li><a href="./providers/aws/events/s3.md">S3</a></li>
<li><a href="./providers/aws/events/schedule.md">Schedule</a></li>
<li><a href="./providers/aws/events/sns.md">SNS</a></li>
</ul>
</div>
</div>
* [Functions](#functions)
* [Events](#events)
* [Resources](#resources)
* [Services](#services)
* [Plugins](#plugins)
### Functions
Functions are the essential part for any serverless infrastructure. Several functions together form a service. A service typically solves one particular problem in your infrastructure.
### Events
Serverless is used to build event driven architecture. Basically everything which can trigger a function is an event.
Events could be HTTP requests, events fired from a cloud storage (like a S3 bucket), scheduled events, etc.
- [AWS Events](./02-providers/aws/events/)
### Resources
Resources are the different pieces that comprise your infrastructure like databases, storage buckets, API Gateways or other resources your provider lets you configure.
### Services
A *Serverless service* is a group of one or multiple functions and any resources they require. By grouping related functions together, it's easier to share code and resources between those functions. Services are also designed to be completely independent, which helps teams develop more quickly without waiting for others.
### Plugins
Here you can read how to develop your own Serverless plugins. We'll get into details on how to write custom plugins to extend the functionality of Serverless. Furthermore we'll look into the way how you can use your plugin knowledge to integrate your own provider into the Serverless framework.
- [Building plugins](./04-extending-serverless/)
Connect with the community on [gitter](https://gitter.im/serverless/serverless) or in the [Forum](http://forum.serverless.com)
## Contributing
We love our contributors! Please read our [Contributing Document](../CONTRIBUTING.md) to learn how you can start working on the Framework yourself.
Check out our [help-wanted](https://github.com/serverless/serverless/labels/help-wanted) or [help-wanted-easy](https://github.com/serverless/serverless/labels/help-wanted-easy) labels to find issues we want to move forward on with your help.
## Framework statistics
[Framework statistics](./framework-statistics.md)
<div class="docsSection">
<div class="docsSectionHeader">
<a href="./providers/aws/examples/">
<img src="https://s3-us-west-2.amazonaws.com/assets.site.serverless.com/images/docs_examples_aws4.jpg" alt="Serverless Framework AWS Lambdxxxxa Examples" width="250" draggable="false"/>
</a>
</div>
<div>
<div>
<ul>
<li><a href="./providers/aws/examples/hello-world">Hello World</a></li>
<li><a href="./providers/aws/examples/cron">Cron</a></li>
<li><a href="./providers/aws/examples/using-external-libraries">Using External Libraries</a></li>
<li><a href="./providers/aws/examples/web-serving-html">Serving HTML page</a></li>
</ul>
</div>
</div>
</div>
</div>

View File

@ -1,30 +0,0 @@
<!--
title: Serverless framework statistics
menuText: Framework statistics
layout: Doc
-->
# Framework statistics
Serverless will automatically collect anonymous framework statistics. This is done so that we better understand the usage and needs
of our users to improve Serverless in future releases. However you can always [disable it](#how-to-disable-it).
## What we collect
Our main goal is anonymity. All the data is anonymized and won't reveal who you are or what the project you're working on is / looks like.
Please take a look at the [`logStat()` method](https://github.com/serverless/serverless/blob/master/lib/classes/Utils.js) in the `Utils` class to see what (and how) we collect statistics.
## How it's implemented
We encourage you to look into the source to see more details about the actual implementation.
The whole implementation consists of two parts:
1. The [slstats plugin](https://github.com/serverless/serverless/tree/master/lib/plugins/slstats)
2. The `logStat()` method you can find in the [Utils class](https://github.com/serverless/serverless/blob/master/lib/classes/Utils.js)
## How to disable it
You can disable it by running the following command: `serverless slstats --disable`.
You can always run `serverless slstats --enable` to enable it again.

19
docs/providers/README.md Normal file
View File

@ -0,0 +1,19 @@
<!--
title: Serverless - Infrastructure Providers
menuText: Providers
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/)
<!-- DOCS-SITE-LINK:END -->
# Serverless Infrastructure Providers
Providers are where your serverless functions run in the cloud.
Under the hood, the serverless framework is deploying your code to a cloud provider like Amazon web services or Google Cloud functions.
You specify your provider in your services `serverless.yml` file.
* [Back to main documentation](../README.md)

View File

@ -0,0 +1,17 @@
<!--
title: Serverless - AWS Documentation
menuText: AWS
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/)
<!-- DOCS-SITE-LINK:END -->
# Serverless AWS Provider Documentation
Welcome to the Serverless Amazon Web Services documentation! Please select a section on the left to get started.
**Note:** Before continuing [AWS system credentials](./guide/credentials/) are required for using the CLI.
If you have questions, join the [chat in gitter](https://gitter.im/serverless/serverless) or [post over on the forums](https://gitter.im/serverless/serverless)

View File

@ -0,0 +1,17 @@
<!--
title: Serverless - AWS Lambda - CLI Reference
menuText: AWS
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/cli-reference/)
<!-- DOCS-SITE-LINK:END -->
# Serverless AWS Lambda CLI Reference
Welcome to the Serverless AWS Lambda CLI Reference! Please select a section on the left to get started.
**Note:** Before continuing [AWS system credentials](https://serverless.com/framework/docs/providers/aws/guide/credentials/) are required for using the CLI.
If you have questions, join the [chat in gitter](https://gitter.im/serverless/serverless) or [post over on the forums](https://gitter.im/serverless/serverless)

View File

@ -1,15 +1,20 @@
<!--
title: Serverless Create CLI Command
title: Serverless Framework Commands - AWS Lambda - Create
menuText: Create
description: Create a new service in your current working directory
menuOrder: 1
description: Creates a new Service in your current working directory
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/cli-reference/create)
<!-- DOCS-SITE-LINK:END -->
# Create
Creates a new service in the current working directory based on the provided template.
```
```bash
serverless create --template aws-nodejs
```
@ -37,7 +42,7 @@ Most commonly used templates:
### Creating a new service
```
```bash
serverless create --template aws-nodejs --name my-special-service
```
@ -49,7 +54,7 @@ The provider which is used for deployment later on is AWS (Amazon web services).
### Creating a named service in a (new) directory
```
```bash
serverless create --template aws-nodejs --path my-new-service
```
@ -58,4 +63,4 @@ will be generated in the `my-new-service` directory. This directory will be crea
will use the already present directory.
Additionally Serverless will rename the service according to the path you provide. In this example the service will be
renamed to `my-new-service`.
renamed to `my-new-service`.

View File

@ -1,16 +1,21 @@
<!--
title: Serverless Deploy CLI Command
title: Serverless Framework Commands - AWS Lambda - Deploy
menuText: Deploy
menuOrder: 3
description: Deploy your service to the specified provider
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/cli-reference/deploy)
<!-- DOCS-SITE-LINK:END -->
# Deploy
Deploys your service. You can access all created deployment artifacts in the `.serverless` folder.
```
serverless deploy [function|list]
```bash
serverless deploy [function]
```
## Options
@ -25,7 +30,7 @@ serverless deploy [function|list]
### Deployment without stage and region options
```
```bash
serverless deploy
```
@ -34,22 +39,13 @@ provider in the default stage (`dev`) to the default region (`us-east-1`).
### Deployment with stage and region options
```
```bash
serverless deploy --stage production --region eu-central-1
```
With this example we've defined that we want our service to be deployed to the `production` stage in the region
`eu-central-1`.
## List existing deploys
```
serverless deploy list
```
Running this command will list your recent deployments available in your S3 deployment bucket. It will use
stage and region from the provider config.
## Provided lifecycle events
- `deploy:cleanup`
- `deploy:initialize`
@ -58,5 +54,4 @@ stage and region from the provider config.
- `deploy:compileFunctions`
- `deploy:compileEvents`
- `deploy:deploy`
- `deploy:function:deploy`
- `deploy:list:log`
- `deploy:function:deploy`

View File

@ -1,10 +1,15 @@
<!--
title: Serverless Info CLI Command
title: Serverless Framework Commands - AWS Lambda - Info
menuText: Info
description: Display information about your deployed service
menuOrder: 6
description: Display information about your deployed service and the AWS Lambda Functions, Events and AWS Resources it contains.
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/cli-reference/info)
<!-- DOCS-SITE-LINK:END -->
# Info
Displays information about the deployed service.
@ -30,7 +35,7 @@ See the example below for an example output.
**Example:**
```
```bash
$ serverless info
Service Information
@ -46,8 +51,10 @@ functions:
```
#### Verbose
When using the `--verbose` flag, the `info` command will also append all Stack Outputs to the output:
```
```bash
$ serverless info --verbose
Service Information
@ -69,4 +76,4 @@ CreateThumbnailsLambdaFunctionArn: arn:aws:lambda:us-east-1:377024778620:functio
TakeScreenshotLambdaFunctionArn: arn:aws:lambda:us-east-1:377024778620:function:lambda-screenshots-dev-takeScreenshot
ServiceEndpoint: https://12341jc801.execute-api.us-east-1.amazonaws.com/dev
ServerlessDeploymentBucketName: lambda-screenshots-dev-serverlessdeploymentbucket-15b7pkc04f98a
```
```

View File

@ -0,0 +1,35 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Install
menuText: Install
menuOrder: 2
description: Install pre-written AWS Lambda Functions, Events and Resources with the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/cli-reference/install)
<!-- DOCS-SITE-LINK:END -->
# Install
Installs a service from a GitHub URL in the current working directory.
```bash
serverless install --url https://github.com/some/service
```
## Options
- `--url` or `-u` The services GitHub URL. **Required**.
## Provided lifecycle events
- `install:install`
## Examples
### Installing a service from a GitHub URL
```bash
serverless install --url https://github.com/johndoe/authentication
```
This example will download the .zip file of the `authentication` service from GitHub, create a new directory with the name `authentication` in the current working directory and unzips the files in this directory.

View File

@ -1,10 +1,15 @@
<!--
title: Serverless Invoke CLI Command
title: Serverless Framework Commands - AWS Lambda - Invoke
menuText: Invoke
description: Invoke a function in your deployed service
menuOrder: 4
description: Invoke an AWS Lambda Function using the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/cli-reference/invoke)
<!-- DOCS-SITE-LINK:END -->
# Invoke
Invokes a previously deployed function. It allows to send event data to the function and read logs and display other important information of the function invoke.
@ -17,11 +22,11 @@ serverless invoke --function functionName
- `--function` or `-f` The name of the function in your service that you want to invoke. **Required**.
- `--stage` or `-s` The stage in your service you want to invoke your function in.
- `--region` or `-r` The region in your stage that you want to invoke your function in.
- `--path` or `-p` The path to a json file holding input data to be passed to the invoked function. Either an absolute or
relative (to the root directory of your service) may be given.
- `--path` or `-p` The path to a json file holding input data to be passed to the invoked function. This path is relative to the
root directory of the service.
- `--type` or `-t` The type of invocation. Either `RequestResponse`, `Event` or `DryRun`. Default is `RequestResponse`.
- `--log` or `-l` If set to `true` and invocation type is `RequestResponse`, it will output logging data of the invocation.
Default is `false`.
Default is `false`.
## Provided lifecycle events
- `invoke:invoke`
@ -30,7 +35,7 @@ serverless invoke --function functionName
### AWS
```
```bash
serverless invoke --function functionName --stage dev --region us-east-1
```
@ -39,7 +44,7 @@ output the result of the invocation in your terminal.
#### Function invocation with logging
```
```bash
serverless invoke --function functionName --stage dev --region us-east-1 --log
```
@ -47,15 +52,9 @@ Just like the first example, but will also outputs logging information about you
#### Function invocation with data passing
```
```bash
serverless invoke --function functionName --stage dev --region us-east-1 --path lib/data.json
```
This example will pass the json data in the `lib/data.json` file (relative to the root of the service) while invoking
the specified/deployed function.
```
serverless invoke --function functionName --stage dev --region us-east-1 --path /tmp/data.json
```
This example will pass the json data in the `/tmp/data.json` file while invoking the specified/deployed function.
the specified/deployed function.

View File

@ -1,10 +1,15 @@
<!--
title: Serverless Logs CLI Command
title: Serverless Framework Commands - AWS Lambda - Logs
menuText: Logs
description: View logs of your deployed Service
menuOrder: 5
description: View logs of your AWS Lambda Function within your terminal using the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/cli-reference/logs)
<!-- DOCS-SITE-LINK:END -->
# Logs
Lets you watch the logs of a specific function.
@ -18,9 +23,9 @@ serverless logs -f hello
- `--function` or `-f` The function you want to fetch the logs for. **Required**
- `--stage` or `-s` The stage you want to view the function logs for. If not provided, the plugin will use the default stage listed in `serverless.yml`. If that doesn't exist either it'll just fetch the logs from the `dev` stage.
- `--region` or `-r` The region you want to view the function logs for. If not provided, the plugin will use the default region listed in `serverless.yml`. If that doesn't exist either it'll just fetch the logs from the `us-east-1` region.
- `--startTime` A specific unit in time to start fetching logs from (ie: `2010-10-20` or `1469705761`). All absolute dates/datetimes .e.g `2010-10-20` are parsed as UTC. Here's a list of the supported string formats:
- `--startTime` A specific unit in time to start fetching logs from (ie: `2010-10-20` or `1469705761`). Here's a list of the supported string formats:
```
```bash
30m # since 30 minutes ago
2h # since 2 hours ago
3d # since 3 days ago
@ -71,4 +76,4 @@ Serverless will tail the CloudWatch log output and print new log messages coming
```bash
serverless logs -f hello --filter serverless
```
This will fetch only the logs that contain the string `serverless`
This will fetch only the logs that contain the string `serverless`

View File

@ -1,15 +1,20 @@
<!--
title: Serverless Remove CLI Command
title: Serverless Framework Commands - AWS Lambda - Remove
menuText: Remove
description: Remove a deployed service with the Serverless CLI
menuOrder: 7
description: Remove a deployed Service and all of its AWS Lambda Functions, Events and Resources
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/cli-reference/remove)
<!-- DOCS-SITE-LINK:END -->
# Remove
Removes the deployed service which is defined in your current working directory.
```
```bash
serverless remove
```
@ -25,8 +30,8 @@ serverless remove
### Removal of service in specific stage and region
```
```bash
serverless remove --stage dev --region us-east-1
```
This example will remove the deployed service of your current working directory with the stage `dev` and the region `us-east-1`.
This example will remove the deployed service of your current working directory with the stage `dev` and the region `us-east-1`.

View File

@ -0,0 +1,36 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Serverless Stats
menuText: Serverless Stats
menuOrder: 8
description: Enables or disables Serverless Statistic logging within the Serverless Framework.
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/cli-reference/slstats)
<!-- DOCS-SITE-LINK:END -->
# Serverless Statistics
This plugin implements a way to toggle framework statistics.
```bash
serverless slstats --enable
```
## Options
- `--enable` or `-e`.
- `--disable` or `-d`
## Provided lifecycle events
- `slstats:slstats`
## Examples
### Disabling it
```bash
serverless slstats --disable
```
This example will disable framework statistics.

View File

@ -0,0 +1,17 @@
<!--
title: Serverless - AWS Lambda - Events
menuText: AWS
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/events/)
<!-- DOCS-SITE-LINK:END -->
# Serverless AWS Lambda Events
Welcome to the Serverless AWS Lambda Events Glossary! Please select a section on the left to get started.
**Note:** Before continuing [AWS system credentials](https://serverless.com/framework/docs/providers/aws/guide/credentials/) are required for using the CLI.
If you have questions, join the [chat in gitter](https://gitter.im/serverless/serverless) or [post over on the forums](https://gitter.im/serverless/serverless)

View File

@ -1,16 +1,36 @@
<!--
title: API Gateway Event configuration
menuText: API Gateway Event config
title: Serverless Framework - AWS Lambda Events - API Gateway
menuText: API Gateway
menuOrder: 1
description: Setting up AWS API Gateway Events with AWS Lambda via the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/events/apigateway)
<!-- DOCS-SITE-LINK:END -->
# API Gateway
## Simple http setup
To create HTTP endpoints as Event sources for your AWS Lambda Functions, use the Serverless Framework's easy AWS API Gateway Events syntax.
There are two ways you can configure your HTTP endpoints to integrate with your AWS Lambda Functions:
* lambda-proxy (Recommended)
* lambda
The difference between these is `lambda-proxy` automatically passes the content of the HTTP request into your AWS Lambda function (headers, body, etc.) and allows you to configure your response (headers, status code, body) in the code of your AWS Lambda Function. Whereas, the `lambda` method makes you explicitly define headers, status codes, and more in the configuration of each API Gateway Endpoint (not in code). We highly recommend using the `lambda-proxy` method if it supports your use-case, since the `lambda` method is highly tedious.
By default, the Framework uses the `lambda-proxy` method (i.e., everything is passed into your Lambda), and nothing is required by you to enable it.
## Lambda Proxy Integration
### Simple HTTP Endpoint
This setup specifies that the `index` function should be run when someone accesses the API gateway at `users/index` via
a `GET` request.
Here's an example:
```yml
# serverless.yml
functions:
@ -20,7 +40,33 @@ functions:
- http: GET users/index
```
## Http setup with extended event options
```javascript
// users.js
'use strict';
exports.handler = function(event, context, callback) {
console.log(event); // Contains incoming request data (e.g., query params, headers and more)
const response = {
statusCode: 200,
headers: {
"x-custom-header" : "My Header Value"
},
body: JSON.stringify({ "message": "Hello World!" })
};
callback(null, response);
};
```
**Note:** When the body is a JSON-Document, you must parse it yourself:
```
JSON.parse(event.body);
```
### HTTP Endpoint with Extended Options
Here we've defined an POST endpoint for the path `posts/create`.
@ -35,9 +81,155 @@ functions:
method: post
```
## Request parameters
### Enabling CORS
To set CORS configurations for your HTTP endpoints, simply modify your event configurations as follows:
You can pass optional and required parameters to your functions, so you can use them in for example Api Gateway tests and SDK generation. Marking them as `true` will make them required, `false` will make them optional.
```yml
functions:
hello:
handler: handler.hello
events:
- http:
path: user/create
method: get
cors: true
```
If you want to use CORS with the lambda-proxy integration, remember to include `Access-Control-Allow-Origin` in your returned headers object, like this:
```javascript
// users.js
'use strict';
exports.handler = function(event, context, callback) {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*" // Required for CORS support to work
},
body: JSON.stringify({ "message": "Hello World!" })
};
callback(null, response);
};
```
### HTTP Endpoints with Custom Authorizers
Custom Authorizers allow you to run an AWS Lambda Function before your targeted AWS Lambda Function. This is useful for Microservice Architectures or when you simply want to do some Authorization before running your business logic.
You can enable Custom Authorizers for your HTTP endpoint by setting the Authorizer in your `http` event to another function
in the same service, as shown in the following example:
```yml
# serverless.yml
functions:
create:
handler: posts.create
events:
- http:
path: posts/create
method: post
authorizer: authorizerFunc
authorizerFunc:
handler: handlers.authorizerFunc
```
Or, if you want to configure the Authorizer with more options, you can turn the `authorizer` property into an object as
shown in the following example:
```yml
# serverless.yml
functions:
create:
handler: posts.create
events:
- http:
path: posts/create
method: post
authorizer:
name: authorizerFunc
resultTtlInSeconds: 0
identitySource: method.request.header.Authorization
identityValidationExpression: someRegex
authorizerFunc:
handler: handlers.authorizerFunc
```
If the Authorizer function does not exist in your service but exists in AWS, you can provide the ARN of the Lambda
function instead of the function name, as shown in the following example:
```yml
# serverless.yml
functions:
create:
handler: posts.create
events:
- http:
path: posts/create
method: post
authorizer: xxx:xxx:Lambda-Name
```
Or, if you want to configure the Authorizer with more options, you can turn the `authorizer` property into an object as
shown in the following example:
```yml
# serverless.yml
functions:
create:
handler: posts.create
events:
- http:
path: posts/create
method: post
authorizer:
arn: xxx:xxx:Lambda-Name
resultTtlInSeconds: 0
identitySource: method.request.header.Authorization
identityValidationExpression: someRegex
```
### Catching Exceptions In Your Lambda Function
In case an exception is thrown in your lambda function AWS will send an error message with `Process exited before completing request`. This will be caught by the regular expression for the 500 HTTP status and the 500 status will be returned.
### Setting API keys for your Rest API
You can specify a list of API keys to be used by your service Rest API by adding an `apiKeys` array property to the
`provider` object in `serverless.yml`. You'll also need to explicitly specify which endpoints are `private` and require
one of the api keys to be included in the request by adding a `private` boolean property to the `http` event object you
want to set as private.
Here's an example configuration for setting API keys for your service Rest API:
```yml
service: my-service
provider:
name: aws
apiKeys:
- myFirstKey
- ${env:MY_API_KEY} # you can hide it in a serverless variable
functions:
hello:
events:
- http:
path: user/create
method: get
private: true
```
Please note that those are the API keys names, not the actual values. Once you deploy your service, the value of those API keys will be auto generated by AWS and printed on the screen for you to use.
Clients connecting to this Rest API will then need to set any of these API keys values in the `x-api-key` header of their request. This is only necessary for functions where the `private` property is set to true.
## Lambda Integration
This method is more complicated and involves a lot more configuration of the `http` event syntax.
### Request Parameters
To pass optional and required parameters to your functions, so you can use them in API Gateway tests and SDK generation, marking them as `true` will make them required, `false` will make them optional.
```yml
# serverless.yml
@ -60,7 +252,7 @@ functions:
bar: false
```
In order for path variables to work, ApiGateway also needs them in the method path itself, like so:
In order for path variables to work, API Gateway also needs them in the method path itself, like so:
```yml
# serverless.yml
@ -78,78 +270,9 @@ functions:
id: true
```
## Integration types
### Request templates
Serverless supports the following integration types:
- `lambda`
- `lambda-proxy`
Here's a simple example which demonstrates how you can set the `integration` type for your `http` event:
```yml
# serverless.yml
functions:
get:
handler: users.get
events:
- http:
path: users
method: get
integration: lambda
```
### `lambda-proxy`
**Important:** Serverless defaults to this integration type if you don't setup another one.
Furthermore any `request` or `response` configuration will be ignored if this `integration` type is used.
`lambda-proxy` simply passes the whole request as is (regardless of the content type, the headers, etc.) directly to the
Lambda function. This means that you don't have to setup custom request / response configuration (such as templates, the
passthrough behavior, etc.).
Your function needs to return corresponding response information.
Here's an example for a JavaScript / Node.js function which shows how this might look like:
```javascript
'use strict';
exports.handler = function(event, context, callback) {
const responseBody = {
message: "Hello World!",
input: event
};
const response = {
statusCode: 200,
headers: {
"x-custom-header" : "My Header Value"
},
body: JSON.stringify(responseBody)
};
callback(null, response);
};
```
**Note:** If you want to use CORS with the lambda-proxy integration, remember to include `Access-Control-Allow-Origin` in your returned headers object.
Take a look at the [AWS documentation](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html)
for more information about this.
### `lambda`
The `lambda` integration type should be used if you want more control over the `request` and `response` configurations.
Serverless ships with defaults for the request / response configuration (such as request templates, error code mappings,
default passthrough behaviour) but you can always configure those accordingly when you set the `integration` type to `lambda`.
## Request templates
**Note:** The request configuration can only be used when the integration type is set to `lambda`.
### Default request templates
#### Default Request Templates
Serverless ships with the following default request templates you can use out of the box:
@ -168,7 +291,7 @@ Both templates give you access to the following properties you can access with t
- identity
- stageVariables
### Using custom request templates
#### Custom Request Templates
However you can define and use your own request templates as follows (you can even overwrite the default request templates
by defining a new request template for an existing content type):
@ -210,8 +333,7 @@ functions:
You can then access the query string `https://example.com/dev/whatever?bar=123` by `event.foo` in the lambda function.
If you want to spread a string into multiple lines, you can use the `>` or `|` syntax, but the following strings have to be all indented with the same amount, [read more about `>` syntax](http://stackoverflow.com/questions/3790454/in-yaml-how-do-i-break-a-string-over-multiple-lines).
### Pass Through Behavior
#### Pass Through Behavior
API Gateway provides multiple ways to handle requests where the Content-Type header does not match any of the specified mapping templates. When this happens, the request payload will either be passed through the integration request *without transformation* or rejected with a `415 - Unsupported Media Type`, depending on the configuration.
You can define this behavior as follows (if not specified, a value of **NEVER** will be used):
@ -243,13 +365,11 @@ See the [api gateway documentation](https://docs.aws.amazon.com/apigateway/lates
- A missing/empty request Content-Type is considered to be the API Gateway default (`application/json`)
- API Gateway docs refer to "WHEN_NO_TEMPLATE" (singular), but this will fail during creation as the actual value should be "WHEN_NO_TEMPLATES" (plural)
## Responses
**Note:** The response configuration can only be used when the integration type is set to `lambda`.
### Responses
Serverless lets you setup custom headers and a response template for your `http` event.
### Using custom response headers
#### Custom Response Headers
Here's an example which shows you how you can setup a custom response header:
@ -271,7 +391,7 @@ functions:
for your header values. Headers are passed to API Gateway exactly like you define them. Passing the `Cache-Control` header
as `"'max-age=120'"` means API Gateway will receive the value as `'max-age=120'` (enclosed with single quotes).
### Using a custom response template
### Custom Response Templates
Sometimes you'll want to define a custom response template API Gateway should use to transform your lambdas output.
Here's an example which will transform the return value of your lambda so that the browser renders it as HTML:
@ -298,7 +418,7 @@ the `${file(templatefile)}` syntax.
Serverless ships with default status codes you can use to e.g. signal that a resource could not be found (404) or that
the user is not authorized to perform the action (401). Those status codes are regex definitions that will be added to your API Gateway configuration.
#### Overview of available status codes
#### Available Status Codes
| Status Code | Meaning |
| --- | --- |
@ -311,7 +431,7 @@ the user is not authorized to perform the action (401). Those status codes are r
| 502 | Bad Gateway |
| 504 | Gateway Timeout |
#### Using status codes
#### Using Status Codes
To return a given status code you simply need to add square brackets with the status code of your choice to your
returned message like this: `[401] You are not authorized to access this resource!`.
@ -324,7 +444,7 @@ module.exports.hello = (event, context, cb) => {
}
```
#### Custom status codes
#### Custom Status Codes
You can override the defaults status codes supplied by Serverless. You can use this to change the default status code, add/remove status codes, or change the templates and headers used for each status code. Use the pattern key to change the selection process that dictates what code is returned.
@ -380,114 +500,7 @@ functions:
Content-Type: "'application/json+hal'"
```
### Catching exceptions in your Lambda function
In case an exception is thrown in your lambda function AWS will send an error message with `Process exited before completing request`. This will be caught by the regular expression for the 500 HTTP status and the 500 status will be returned.
### Http setup with custom authorizer
You can enable custom authorizers for your HTTP endpoint by setting the authorizer in your http event to another function
in the same service, as shown in the following example
```yml
# serverless.yml
functions:
create:
handler: posts.create
events:
- http:
path: posts/create
method: post
authorizer: authorizerFunc
authorizerFunc:
handler: handlers.authorizerFunc
```
Or, if you want to configure the authorizer with more options, you can turn the `authorizer` property into an object as
shown in the following example:
```yml
# serverless.yml
functions:
create:
handler: posts.create
events:
- http:
path: posts/create
method: post
authorizer:
name: authorizerFunc
resultTtlInSeconds: 0
identitySource: method.request.header.Authorization
identityValidationExpression: someRegex
authorizerFunc:
handler: handlers.authorizerFunc
```
### Http setup with custom authorizer (via ARN)
If the authorizer function does not exist in your service but exists in AWS, you can provide the ARN of the Lambda
function instead of the function name, as shown in the following example:
```yml
# serverless.yml
functions:
create:
handler: posts.create
events:
- http:
path: posts/create
method: post
authorizer: xxx:xxx:Lambda-Name
```
Or, if you want to configure the authorizer with more options, you can turn the `authorizer` property into an object as
shown in the following example:
```yml
# serverless.yml
functions:
create:
handler: posts.create
events:
- http:
path: posts/create
method: post
authorizer:
arn: xxx:xxx:Lambda-Name
resultTtlInSeconds: 0
identitySource: method.request.header.Authorization
identityValidationExpression: someRegex
```
## Setting API keys for your Rest API
You can specify a list of API keys to be used by your service Rest API by adding an `apiKeys` array property to the
`provider` object in `serverless.yml`. You'll also need to explicitly specify which endpoints are `private` and require
one of the api keys to be included in the request by adding a `private` boolean property to the `http` event object you
want to set as private.
Here's an example configuration for setting API keys for your service Rest API:
```yml
service: my-service
provider:
name: aws
apiKeys:
- myFirstKey
- ${env:MY_API_KEY} # you can hide it in a serverless variable
functions:
hello:
events:
- http:
path: user/create
method: get
private: true
```
Please note that those are the API keys names, not the actual values. Once you deploy your service, the value of those API keys will be auto generated by AWS and printed on the screen for you to use.
Clients connecting to this Rest API will then need to set any of these API keys values in the `x-api-key` header of their request. This is only necessary for functions where the `private` property is set to true.
## Enabling CORS for your endpoints
To set CORS configurations for your HTTP endpoints, simply modify your event configurations as follows:
## Enabling CORS with the Lambda Integration Method
```yml
functions:
@ -537,7 +550,7 @@ module.exports.hello = (event, context, cb) => {
}
```
## Setting an HTTP proxy on API Gateway
## Setting an HTTP Proxy on API Gateway
To set up an HTTP proxy, you'll need two CloudFormation templates, one for the endpoint (known as resource in CF), and
one for method. These two templates will work together to construct your proxy. So if you want to set `your-app.com/serverless` as a proxy for `serverless.com`, you'll need the following two templates in your `serverless.yml`:

View File

@ -1,16 +1,22 @@
<!--
title: AWS S3 Event configuration
menuText: S3 Event config
title: Serverless Framework - AWS Lambda Events - S3
menuText: S3
menuOrder: 3
description: Setting up AWS S3 Events with AWS Lambda via the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/events/s3)
<!-- DOCS-SITE-LINK:END -->
# S3
## Simple event definition
This will create a `photos` bucket which fires the `resize` function when an object is added or modified inside the bucket. A hardcoded bucket name can lead to issues as a bucket name can only be used once in S3. For that you can use the [Serverless Variable syntax](../../../01-guide/08-serverless-variables.md) and add dynamic elements to the bucket name.
```yml
```yaml
functions:
resize:
handler: resize.handler
@ -22,7 +28,7 @@ functions:
This will create a bucket `photos`. The `users` function is called whenever an object is removed from the bucket. Check out the [AWS documentation](http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html#notification-how-to-event-types-and-destinations) to learn more about all the different event types that can be configured.
```yml
```yaml
functions:
users:
handler: users.handler
@ -36,11 +42,11 @@ functions:
This will create a bucket `photos`. The `users` function is called whenever an image with `.jpg` extension is uploaded to folder `uploads` in the bucket. Check out the [AWS documentation](http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html#notification-how-to-filtering) to learn more about all the different filter types that can be configured.
```yml
```yaml
functions:
users:
handler: users.handler
rules:
events:
- s3:
bucket: photos
event: s3:ObjectCreated:*

View File

@ -1,14 +1,20 @@
<!--
title: AWS Schedule
menuText: AWS Schedule config
title: Serverless Framework - AWS Lambda Events - Scheduled & Recurring
menuText: Schedule
menuOrder: 4
description: Setting up Scheduled, Recurring, CRON Task Events with AWS Lambda via the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/events/schedule)
<!-- DOCS-SITE-LINK:END -->
# Schedule
The following config will attach a schedule event and causes the function `crawl` to be called every 2 hours. The configuration allows you to attach multiple schedules to the same function. You can either use the `rate` or `cron` syntax. Take a look at the [AWS schedule syntax documentation](http://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html) for more details.
```yml
```yaml
functions:
crawl:
handler: crawl
@ -22,7 +28,7 @@ functions:
This will create and attach a schedule event for the `aggregate` function which is disabled. If enabled it will call
the `aggregate` function every 10 minutes.
```yml
```yaml
functions:
aggregate:
handler: statistics.handler
@ -30,4 +36,7 @@ functions:
- schedule:
rate: rate(10 minutes)
enabled: false
- schedule:
rate: cron(0 12 * * ? *)
enabled: false
```

View File

@ -1,9 +1,15 @@
<!--
title: SNS Event configuration docs
menuText: SNS Event config
title: Serverless Framework - AWS Lambda Events - SNS
menuText: SNS
menuOrder: 5
description: Setting up AWS SNS Events with AWS Lambda via the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/events/sns)
<!-- DOCS-SITE-LINK:END -->
# SNS
In the following example we create a new SNS topic with the name `dispatch` which is bound to the `dispatcher` function. The function will be called every time a message is sent to the `dispatch` topic.

View File

@ -1,9 +1,15 @@
<!--
title: DynamoDB / Kinesis Streams configuration docs
menuText: DynamoDB / Kinesis Streams config
title: Serverless Framework - AWS Lambda Events - Kinesis & DynamoDB Streams
menuText: Kinesis & DynamoDB
menuOrder: 2
description: Setting up AWS Kinesis Streams and AWS DynamoDB Streams Events with AWS Lambda via the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/events/streams)
<!-- DOCS-SITE-LINK:END -->
# DynamoDB / Kinesis Streams
This setup specifies that the `compute` function should be triggered whenever the corresponding DynamoDB table is modified (e.g. a new entry is added).

View File

@ -0,0 +1,20 @@
<!--
title: Serverless - AWS Lambda - Examples
menuText: AWS
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/examples/)
<!-- DOCS-SITE-LINK:END -->
# Serverless AWS Lambda Examples
Welcome to the Serverless Amazon Web Services Examples! Please select an example below:
* [Hello World](./hello-world)
* [Using External Libraries](./using-external-libraries)
* [Cron](./cron)
* [Serving HTML page](./web-serving-html)
If you have questions, join the [chat in gitter](https://gitter.im/serverless/serverless) or [post over on the forums](https://gitter.im/serverless/serverless)

View File

@ -0,0 +1,20 @@
<!--
title: Cron Example
menuText: Cron Example
description: Create a Serverless cron job
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/examples/cron/)
<!-- DOCS-SITE-LINK:END -->
# Cron Example
Create a scheduled task with AWS Lambda and automate all the things! Examples:
* [JavaScript](./node)
For more information on running cron with Serverless check out the [Tutorial: Serverless Scheduled Tasks](https://parall.ax/blog/view/3202/tutorial-serverless-scheduled-tasks) by parallax.
For more information on `schedule` event check out [our docs](../../events/schedule.md).

View File

@ -0,0 +1,20 @@
<!--
title: JavaScript Cron Example
menuText: JavaScript Cron Example
description: Create a Serverless scheduled cron job with Node.js
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/examples/cron/node)
<!-- DOCS-SITE-LINK:END -->
# JavaScript Cron Example
This is an example of creating a function that runs as a cron job.
To see your job running tail your logs with:
```bash
serverless logs -function cron -tail
```

View File

@ -2,5 +2,5 @@
module.exports.run = () => {
const time = new Date();
console.log(`Your cron ran ${time}`);
console.log(`Your cron ran ${time}`); // eslint-disable-line no-console
};

View File

@ -8,4 +8,4 @@ functions:
cron:
handler: handler.run
events:
- schedule: rate(1 minute)
- schedule: rate(1 minute)

View File

@ -0,0 +1,19 @@
<!--
title: Hello World Example
menuText: Hello World Example
description: Example of creating a Hello World function in Node.js and Python with the Serverless framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/examples/hello-world/)
<!-- DOCS-SITE-LINK:END -->
# Hello World Example
Welcome to the Hello World example.
We are excited for you to start your Serverless journey!
* [JavaScript](./node)
* [Python](./python)

View File

@ -0,0 +1,35 @@
<!--
title: Hello World Node.js Example
menuText: Hello World Node.js Example
description: Create a Node.js Hello World Lambda function
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/examples/hello-world/node/)
<!-- DOCS-SITE-LINK:END -->
# Hello World Node.js Example
Make sure `serverless` is installed. [See installation guide](../../../guide/installation.md).
## 1. Deploy
`serverless deploy` or `sls deploy`. `sls` is shorthand for the Serverless CLI command
## 2. Invoke deployed function
`serverless invoke --function helloWorld` or `serverless invoke -f helloWorld`
`-f` is shorthand for `--function`
In your terminal window you should see the response from AWS Lambda
```bash
{
"message": "Hello World",
"event": {}
}
```
Congrats you have just deployed and ran your Hello World function!

View File

@ -4,6 +4,7 @@
module.exports.helloWorldHandler = function (event, context, callback) {
const message = {
message: 'Hello World',
event,
};
// callback will send message object back
callback(null, message);

View File

@ -0,0 +1,34 @@
<!--
title: Hello World Python Example
menuText: Hello World Python Example
description: Create a simple Python powered Lambda function
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/examples/hello-world/python/)
<!-- DOCS-SITE-LINK:END -->
# Hello World Python Example
Make sure `serverless` is installed. [See installation guide](../../../guide/installation.md).
## 1. Deploy
`serverless deploy` or `sls deploy`. `sls` is shorthand for the serverless CLI command
## 2. Invoke deployed function
`serverless invoke --function helloWorld` or `serverless invoke -f helloWorld`
`-f` is shorthand for `--function`
In your terminal window you should see the response from AWS Lambda
```bash
{
"message": "Hello World"
}
```
Congrats you have just deployed and ran your Hello World function!

View File

@ -3,4 +3,4 @@ def helloWorldHandler(event, context):
'message': 'Hello World'
}
return message
return message

View File

@ -0,0 +1,20 @@
<!--
title: Using External Libraries
menuText: Using External Libraries
description: Example of Using External Libraries in NodeJS and Python with the serverless framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/examples/using-external-libraries/)
<!-- DOCS-SITE-LINK:END -->
# Using External Libraries Examples
When creating Serverless services you are able to use third party packages from your respective ecosystems package manager. Examples:
* [JavaScript](./node)
For Node.js you can leverage the vast ecosystem of NPM and `require` in modules into your project.
For Python you can use the `pip` package manager.

View File

@ -0,0 +1,36 @@
<!--
title: Using External libraries in Node.js Example
menuText: External libraries in Node.js
description: Create a Node.js using external libraries Lambda function
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/examples/using-external-libraries/node/)
<!-- DOCS-SITE-LINK:END -->
# Using External libraries in Node.js Example
Make sure `serverless` is installed. [See installation guide](../../../guide/installation.md).
## 1. Install dependencies
For this example we are going to install the `faker` module from npm.
`npm install faker --save`
## 2. Install the faker module in your `handler.js` file
Inside of `handler.js` require your module:
`const faker = require('faker');`
## 3. Deploy
Run `serverless deploy`.
Alternatively, you can run `npm run deploy` and deploy via NPM script defined in the `package.json` file
## 4. Invoke
`serverless invoke --function helloRandomName`

View File

@ -0,0 +1,5 @@
{
"key3": "value3",
"key2": "value2",
"key1": "value1"
}

View File

@ -0,0 +1,13 @@
// 'use strict';
// // Import faker module from node_modules
// const faker = require('faker');
//
// // Your function handler
// module.exports.helloRandomNameHandler = function (event, context, callback) {
// const randomName = faker.name.firstName();
// const message = {
// message: 'Hello ' + randomName,
// event: event
// };
// callback(null, message);
// };

View File

@ -1,7 +1,10 @@
{
"name": "external-library",
"description": "Serverless using external libraries example with Node.js",
"name": "hello-world",
"description": "Serverless using external libraries example with node",
"private": true,
"scripts": {
"deploy": "serverless deploy"
},
"dependencies": {
"faker": "^3.1.0"
}

View File

@ -1,5 +1,5 @@
# Hello Random Name for AWS Lambda
service: external-lib # Service Name
service: hello-random-name # Service Name
provider:
name: aws
@ -7,4 +7,4 @@ provider:
functions:
helloRandomName:
handler: handler.helloRandomName
handler: handler.helloRandomNameHandler

View File

@ -0,0 +1,18 @@
<!--
title: Serving HTML through API Gateway Example
menuText: Serving HTML Example
description: Example of serving HTML page through API Gateway
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/examples/web-serving-html/)
<!-- DOCS-SITE-LINK:END -->
# Serving HTML through API Gateway Example
These examples illustrate how to hookup an API Gateway endpoint to a Lambda function to render HTML on a `GET` request. So instead of returning the default `json` from requests to an endpoint, you can display custom HTML.
This is useful for dynamic webpages and landing pages for marketing activities.
* [JavaScript](./node)

View File

@ -0,0 +1,13 @@
<!--
title: Serving HTML in Node.js through API Gateway Example
menuText: Serving HTML in Node.js Example
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/examples/web-serving-html/node/)
<!-- DOCS-SITE-LINK:END -->
# Serving HTML in Node.js through API Gateway Example
[This is an example](https://github.com/serverless/serverless/tree/master/docs/providers/aws/examples/web-serving-html/node) of serving vanilla HTML/CSS/JS through API Gateway.

View File

@ -1,7 +1,7 @@
'use strict';
// Your function handler
module.exports.staticHtml = function (event, context, callback) {
module.exports.html = function (event, context, callback) {
let dynamicHtml;
/* check for GET params and use if available */
if (event.queryStringParameters && event.queryStringParameters.name) {

View File

@ -1,5 +1,4 @@
# Serving HTML through API Gateway for AWS Lambda
service: serve-html
provider:
@ -8,7 +7,7 @@ provider:
functions:
staticHtml:
handler: handler.staticHtml
handler: handler.html
events:
- http:
method: get

View File

@ -0,0 +1,17 @@
<!--
title: Serverless - AWS Guide
menuText: AWS
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/)
<!-- DOCS-SITE-LINK:END -->
# Serverless AWS Lambda Guide
Welcome to the Serverless AWS Lambda Guide! Please select a section on the left to get started.
**Note:** Before continuing [AWS system credentials](https://serverless.com/framework/docs/providers/aws/guide/credentials/) are required for using the CLI.
If you have questions, join the [chat in gitter](https://gitter.im/serverless/serverless) or [post over on the forums](https://gitter.im/serverless/serverless)

View File

@ -0,0 +1,112 @@
<!--
title: Serverless Framework - AWS Lambda Guide - Credentials
menuText: Credentials
menuOrder: 3
description: How to set up the Serverless Framework with your Amazon Web Services credentials
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/credentials)
<!-- DOCS-SITE-LINK:END -->
# Credentials
The Serverless Framework needs access to your cloud providers account so that it can create and manage resources on your behalf.
Here we'll provide setup instructions for different cloud provider accounts. Just pick the one for your provider and follow the steps to get everything in place for Serverless.
At this time, the Serverless Framework supports only Amazon Web Services, but support for other providers is in the works.
## Amazon Web Services
**[Video Guide Available Here](https://www.youtube.com/watch?v=bFHmgqbAh4M)**
Here's how to set up the Serverless Framework with your Amazon Web Services account.
If you're new to Amazon Web Services, make sure you put in a credit card. If you don't have a credit card set up, you may not be able to deploy your resources and you may run into this error:
```bash
AWS Access Key Id needs a subscription for the service
```
Don't worry, you won't be charged for signing up. New AWS users get access to the [AWS Free Tier](https://aws.amazon.com/free/), which let's you use many AWS resources for free for 1 year, like [AWS Lambda](https://aws.amazon.com/lambda/pricing/).
While in the AWS Free Tier, you can build an entire application on AWS Lambda, AWS API Gateway, and more, without getting charged for 1 year... As long as you don't exceed the resources in the Free Tier.
### Creating AWS Access Keys
To let the Serverless Framework access your AWS account, we're going to create an IAM User with Admin access, which can configure the services in your AWS account. This IAM User will have its own set of AWS Access Keys.
**Note:** In a production environment, we recommend reducing the permissions to the IAM User which the Framework uses. Unfortunately, the Framework's functionality is growing so fast, we can't yet offer you a finite set of permissions it needs (we're working on this). Consider using a separate AWS account in the interim, if you cannot get permission to your organization's primary AWS accounts.
1. Create or login to your Amazon Web Services Account and go to the Identity & Access Management (IAM) page.
2. Click on **Users** and then **Create New Users**. Enter a name in the first field to remind you this User is the Framework, like `serverless-admin`. Then click **Create**. Later, you can create different IAM Users for different apps and different stages of those apps. That is, if you don't use separate AWS accounts for stages/apps, which is most common.
3. View and copy the **API Key** & **Secret** to a temporary place. You'll need it in the next step.
4. In the User record in the AWS IAM Dashboard, look for **Managed Policies** on the **Permissions** tab and click **Attach Policy**.
5. In the next screen, search for and select **AdministratorAccess** then click **Attach**.
### Using AWS Access Keys
You can configure the Serverless Framework to use your AWS **API Key** & **Secret** two ways:
#### Quick Setup
As a quick setup to get started you can export them as environment variables so they would be accessible to Serverless and the AWS SDK in your shell:
```bash
export AWS_ACCESS_KEY_ID=<key>
export AWS_SECRET_ACCESS_KEY=<secret>
serverless deploy
```
#### Using AWS Profiles
For a more permanent solution you can also set up credentials through AWS profiles using the `aws-cli`, or by configuring the credentials file directly.
To set them up through the `aws-cli` [install it first](http://docs.aws.amazon.com/cli/latest/userguide/installing.html) then run `aws configure` [to configure the aws-cli and credentials](http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html):
```bash
$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: ENTER
```
Credentials are stored in INI format in `~/.aws/credentials`, which you can edit directly if needed. Read more about that file in the [AWS documentation](http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#cli-config-files)
You can even set up different profiles for different accounts, which can be used by Serverless as well. To specify a default profile to use, you can add a `profile` setting to your `provider` configuration in `serverless.yml`:
```yml
service: new-service
provider:
name: aws
runtime: nodejs4.3
stage: dev
profile: devProfile
```
##### Per Stage Profiles
As an advanced use-case, you can deploy different stages to different accounts by using different profiles per stage. In order to use different profiles per stage, you must leverage [variables](https://serverless.com/framework/docs/providers/aws/guide/variables) and the provider profile setting.
This example `serverless.yml` snippet will load the profile depending upon the stage specified in the command line options (or default to 'dev' if unspecified);
```yml
service: new-service
provider:
name: aws
runtime: nodejs4.3
stage: ${opt:stage, self:custom.defaultStage}
profile: ${self:custom.profiles.${self:provider.stage}}
custom:
defaultStage: dev
profiles:
dev: devProfile
prod: prodProfile
```

View File

@ -0,0 +1,83 @@
<!--
title: Serverless Framework - AWS Lambda Guide - Deploying
menuText: Deploying
menuOrder: 8
description: How to deploy your AWS Lambda functions and their required infrastructure
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/deploying)
<!-- DOCS-SITE-LINK:END -->
# Deploying
The Serverless Framework was designed to provision your AWS Lambda Functions, Events and infrastructure Resources safely and quickly. It does this via a couple of methods designed for different types of deployments.
## Deploy All
This is the main method for doing deployments with the Serverless Framework:
```bash
serverless deploy
```
Use this method when you have updated your Function, Event or Resource configuration in `serverless.yml` and you want to deploy that change (or multiple changes at the same time) to Amazon Web Services.
### How It Works
The Serverless Framework translates all syntax in `serverless.yml` to a single AWS CloudFormation template. By depending on CloudFormation for deployments, users of the Serverless Framework get the safety and reliability of CloudFormation.
* An AWS CloudFormation template is created from your `serverless.yml`.
* If a Stack has not yet been created, then it is created with no resources except for an S3 Bucket, which will store zip files of your Function code.
* The code of your Functions is then packaged into zip files.
* Zip files of your Functions' code are uploaded to your Code S3 Bucket.
* Any IAM Roles, Functions, Events and Resources are added to the AWS CloudFormation template.
* The CloudFormation Stack is updated with the new CloudFormation template.
### Tips
* Use this in your CI/CD systems, as it is the safest method of deployment.
* You can print the progress during the deployment if you use `verbose` mode, like this:
```
serverless deploy --verbose
```
* This method uses the AWS CloudFormation Stack Update method. CloudFormation is slow, so this method is slower. If you want to develop more quickly, use the `serverless deploy function` command (described below)
* This method defaults to `dev` stage and `us-east-1` region. You can change the default stage and region in your `serverless.yml` file by setting the `stage` and `region` properties inside a `provider` object as the following example shows:
```yml
# serverless.yml
service: service-name
provider:
name: aws
stage: beta
region: us-west-2
```
* You can also deploy to different stages and regions by passing in flags to the command:
```
serverless deploy --stage production --region eu-central-1
```
Check out the [deploy command docs](../cli-reference/deploy) for all details and options.
## Deploy Function
This deployment method does not touch your AWS CloudFormation Stack. Instead, it simply overwrites the zip file of the current function on AWS. This method is much faster, since it does not rely on CloudFormation.
```bash
serverless deploy function --function myFunction
```
### How It Works
* The Framework packages up the targeted AWS Lambda Function into a zip file.
* That zip file is uplaoded to your S3 bucket using the same name as the previous function, which the CloudFormation stack is pointing to.
### Tips
* Use this when you are developing and want to test on AWS because it's much faster.
* During development, people will often run this command several times, as opposed to `serverless deploy` which is only run when larger infrastructure provisioning is required.
Check out the [deploy command docs](../cli-reference/deploy.md) for all details and options.

View File

@ -0,0 +1,59 @@
<!--
title: Serverless Framework - AWS Lambda Guide - Events
menuText: Events
menuOrder: 6
description: Configuring AWS Lambda function events in the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/events)
<!-- DOCS-SITE-LINK:END -->
# Events
If you are using AWS as a provider for your Service, all *Events* are anything in AWS that can trigger an AWS Lambda function, like an S3 bucket upload, an SNS topic, and HTTP endpoints created via API Gateway.
Upon deployment, the Serverless Framework will deploy any infrastructure required for an event (e.g., an API Gateway endpoint) and configure your Function to listen to it.
## Configuration
Events belong to each Function and can be found in the `events` property, which is an array:
```yml
functions:
createUser: # A function
handler: handler.createUser
events: # All events are here
- http:
path: users/create
method: post
```
Events are objects, which can contain event-specific information.
You can set multiple Events per Function, as long as that is supported by AWS.
```yml
functions:
createUser: # A function
handler: handler.users
events: # All events are here
- http:
path: users/create
method: post
- http:
path: users/update
method: put
- http:
path: users/delete
method: delete
```
## Types
The Serverless Framework supports all of the AWS Lambda events and more. Instead of listing them here, we've put them in a separate section, since they have a lot of configurations and functionality. [Check out the events section for more information.](../events)
## Deploying
To deploy or update your Functions, Events and Infrastructure, run `serverless deploy`.

View File

@ -0,0 +1,248 @@
<!--
title: Serverless Framework - AWS Lambda Guide - Functions
menuText: Functions
menuOrder: 5
description: How to configure AWS Lambda functions in the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/functions)
<!-- DOCS-SITE-LINK:END -->
# Functions
If you are using AWS as a provider for your *Service*, all *Functions* are AWS Lambda functions.
## Configuration
All of the AWS Lambda functions in your serverless service can be found in `serverless.yml` under the `functions` property.
```yml
# serverless.yml
service: myService
provider:
name: aws
runtime: nodejs4.3
functions:
functionOne:
handler: handler.functionOne
```
The `handler` property points to the file and module containing the code you want to run in your function.
```javascript
// handler.js
module.exports.functionOne = function(event, context, callback) {}
```
You can add as many functions as you want within this property.
```yml
# serverless.yml
service: myService
provider:
name: aws
runtime: nodejs4.3
functions:
functionOne:
handler: handler.functionOne
description: optional description for your Lambda
functionTwo:
handler: handler.functionTwo
functionThree:
handler: handler.functionThree
```
Your functions can either inherit their settings from the `provider` property.
```yml
# serverless.yml
service: myService
provider:
name: aws
runtime: nodejs4.3
memorySize: 512 # inherited value
functions:
functionOne:
handler: handler.functionOne
```
Or you can specify properties at the function level.
```yml
# serverless.yml
service: myService
provider:
name: aws
runtime: nodejs4.3
functions:
functionOne:
handler: handler.functionOne
memorySize: 512 # function specific
```
## Permissions
Every AWS Lambda function needs permission to interact with other AWS infrastructure resources within your account. These permissions are set via an AWS IAM Role. You can set permission policy statements within this role via the `provider.iamRoleStatements` property.
```yml
# serverless.yml
service: myService
provider:
name: aws
runtime: nodejs4.3
iamRoleStatements: # permissions for all of your functions can be set here
- Effect: Allow
Action: # Gives permission to DynamoDB tables in a specific region
- dynamodb:DescribeTable
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: "arn:aws:dynamodb:us-east-1:*:*"
functions:
functionOne:
handler: handler.functionOne
memorySize: 512
```
Another example:
```yml
# serverless.yml
service: myService
provider:
name: aws
iamRoleStatements:
- Effect: "Allow"
Action:
- "s3:ListBucket"
Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket"} ] ] } # You can put CloudFormation syntax in here. No one will judge you. Remember, this all gets translated to CloudFormation.
- Effect: "Allow"
Action:
- "s3:PutObject"
Resource:
Fn::Join:
- ""
- - "arn:aws:s3:::"
- "Ref" : "ServerlessDeploymentBucket"
functions:
functionOne:
handler: handler.functionOne
memorySize: 512
```
You can also use an existing IAM role by adding your IAM Role ARN in the `iamRoleARN` property. For example:
```yml
# serverless.yml
service: new-service
provider:
name: aws
iamRoleARN: arn:aws:iam::YourAccountNumber:role/YourIamRole
```
Support for separate IAM Roles per function is coming soon.
## VPC Configuration
You can add VPC configuration to a specific function in `serverless.yml` by adding a `vpc` object property in the function configuration. This object should contain the `securityGroupIds` and `subnetIds` array properties needed to construct VPC for this function. Here's an example configuration:
```yml
# serverless.yml
service: service-name
provider: aws
functions:
hello:
handler: handler.hello
vpc:
securityGroupIds:
- securityGroupId1
- securityGroupId2
subnetIds:
- subnetId1
- subnetId2
```
Or if you want to apply VPC configuration to all functions in your service, you can add the configuration to the higher level `provider` object, and overwrite these service level config at the function level. For example:
```yml
# serverless.yml
service: service-name
provider:
name: aws
vpc:
securityGroupIds:
- securityGroupId1
- securityGroupId2
subnetIds:
- subnetId1
- subnetId2
functions:
hello: # this function will overwrite the service level vpc config above
handler: handler.hello
vpc:
securityGroupIds:
- securityGroupId1
- securityGroupId2
subnetIds:
- subnetId1
- subnetId2
users: # this function will inherit the service level vpc config above
handler: handler.users
```
Then, when you run `serverless deploy`, VPC configuration will be deployed along with your lambda function.
## Environment Variables
We're working on great Environment Variable support. Until then, you'll be able to use the following tools for different languages to set environment variables and make them available to your code.
## Javascript
You can use [dotenv](https://www.npmjs.com/package/dotenv) to load files with environment variables. Those variables can be set during your CI process or locally and then packaged and deployed together with your function code.
## Python
You can use [python-dotenv](https://github.com/theskumar/python-dotenv) to load files with environment variables. Those variables can be set during your CI process or locally and then packaged and deployed together with your function code.
## Java
For Java the easiest way to set up environment like configuration is through [property files](https://docs.oracle.com/javase/tutorial/essential/environment/properties.html). While those will not be available as environment variables they are very commonly used configuration mechanisms throughout Java.
## Log Group Resources
By default, the framework does not create LogGroups for your Lambdas. However this behavior will be deprecated soon and we'll be adding CloudFormation LogGroups resources as part of the stack. This makes it easy to clean up your log groups in the case you remove your service, and make the lambda IAM permissions much more specific and secure.
To opt in for this feature now to avoid breaking changes later, add the following to your provider config in serverless.yml:
```
provider:
cfLogs: true
```
If you get a CloudFormation error saying that log group already exists, you have to remove it first from AWS console, then deploy, otherwise for new services this should work out of the box.

View File

@ -0,0 +1,35 @@
<!--
title: Serverless Framework - AWS Lambda Guide - Installing The Serverless Framework
menuText: Installation
menuOrder: 2
description: How to install the Serverless Framework and start using AWS Lambda
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/installation)
<!-- DOCS-SITE-LINK:END -->
# Installation
### Installing Node.js
Serverless is a [Node.js](https://nodejs.org) CLI tool so the first thing you need to do is to install Node.js on your machine.
Go to the official [Node.js website](https://nodejs.org), download and follow the [installation instructions](https://nodejs.org/en/download/) to install Node.js on your local machine.
**Note:** Serverless runs on Node v4 or higher. So make sure that you pick a recent Node version.
You can verify that Node.js is installed successfully by runnning `node --version` in your terminal. You should see the corresponding Node version number printed out.
### Installing the Serverless Framework
Next, install the Serverless Framework via [npm](https://npmjs.org) which was already installed when you installed Node.js.
Open up a terminal and type `npm install -g serverless` to install Serverless.
Once the installation process is done you can verify that Serverless is installed successfully by running `serverless`.
### Installing AWS
AWS ships with the core of the Serverless Framework, so no additional installation is required.

View File

@ -0,0 +1,90 @@
<!--
title: Serverless Framework - AWS Lambda Guide - Introduction
menuText: Intro
menuOrder: 1
description: An introduction to using AWS and AWS Lambda with the Serverless Framework.
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/intro)
<!-- DOCS-SITE-LINK:END -->
# Introduction
The Serverless Framework helps you develop and deploy your AWS Lambda functions, along with the AWS infrastructure resources they require. It's a CLI that offers structure, automation and best practices out-of-the-box, allowing you to focus on building sophisticated, event-driven, serverless architectures, comprised of Functions and Events.
A few things the Serverless Framework does differently than a normal application Framework are:
* It manages your code as well as your infrastructure
* It supports multiple languages (Node.js, Python, Java, and more)
Here are the Framework's main concepts and how they pertain to AWS and Lambda...
## Concepts
### Functions
A Function is an AWS Lambda function. It's an independent unit of deployment, like a microservice. It's merely code, deployed in the cloud, that is most often written to perform a single job such as:
* *Saving a user to the database*
* *Processing a file in a database*
* *Performing a scheduled task*
You can perform multiple jobs in your code, but we don't recommend doing that without good reason. Separation of concerns is best and the Framework is designed to help you easily develop and deploy Functions, as well as manage lots of them.
### Events
Anything that triggers an AWS Lambda Function to execute is regarded by the Framework as an **Event**. Events are infrastructure events on AWS such as:
* *An AWS API Gateway HTTP endpoint (e.g., for a REST API)*
* *An AWS S3 bucket upload (e.g., for an image)*
* *A CloudWatch timer (e.g., run every 5 minutes)*
* *An AWS SNS topic (e.g., a message)*
* *A CloudWatch Alert (e.g., something happened)*
* *And more...*
When you define an event for your AWS Lambda functions in the Serverless Framework, the Framework will automatically create any infrastructure necessary for that event (e.g., an API Gateway endpoint) and configure your AWS Lambda Functions to listen to it.
### Resources
**Resources** are AWS infrastructure components which your Functions use such as:
* *An AWS DynamoDB Table (e.g., for saving Users/Posts/Comments data)*
* *An AWS S3 Bucket (e.g., for saving images or files)*
* *An AWS SNS Topic (e.g., for sending messages asynchronously)*
* *Anything that can be defined in CloudFormation is supported by the Serverless Framework*
The Serverless Framework not only deploys your Functions and the Events that trigger them, but it also deploys the AWS infrastructure components your Functions depend upon.
### Services
A **Service** is the Framework's unit of organization. You can think of it as a project file, though you can have multiple services for a single application. It's where you define your Functions, the Events that trigger them, and the Resources your Functions use, all in one file entitled `serverless.yml`. It looks like this:
```yml
// serverless.yml
service: users
functions: // Your "Functions"
usersCreate:
events: // The "Events" that trigger this function
- http: post users/create
usersCreate:
events:
- http: delete users/delete
resources: // The "Resources" your "Functions" use. Raw AWS CloudFormation goes in here.
```
When you deploy with the Framework by running `serverless deploy`, everything in `serverless.yml` is deployed at once.
### Plugins
You can overwrite or extend the functionality of the Framework using **Plugins**. Every `serverless.yml` can contain a `plugins:` property, which features multiple plugins.
```yml
# serverless.yml
plugins:
- serverless-offline
- serverless-secrets
```

View File

@ -0,0 +1,82 @@
<!--
title: Serverless Framework Guide - AWS Lambda Guide - Packaging
menuText: Packaging
menuOrder: 11
description: How the Serverless Framework packages your AWS Lambda functions and other available options
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/packaging)
<!-- DOCS-SITE-LINK:END -->
# Packaging
Sometimes you might like to have more control over your function artifacts and how they are packaged.
You can use the `package` and `exclude` configuration for more control over the packaging process.
## Exclude / include
Exclude allows you to define globs that will be excluded from the resulting artifact. If you wish to
include files you can use a glob pattern prefixed with `!` such as `!re-include-me/**`. Serverless will run the glob patterns in order.
## Example
Exclude all node_modules but then re-include a specific modules (in this case node-fetch)
``` yaml
package:
exclude:
- node_modules/**
- "!node_modules/node-fetch/**"
```
```
exclude:
- tmp/**
- .git
```
## Artifact
For complete control over the packaging process you can specify your own zip file for your service. Serverless won't zip your service if this is configured so `include` and `exclude` will be ignored.
## Example
```yaml
service: my-service
package:
include:
- lib
- functions
exclude:
- tmp
- .git
artifact: path/to/my-artifact.zip
```
## Packaging functions separately
If you want even more controls over your functions for deployment you can configure them to be packaged independently. This allows you more control for optimizing your deployment. To enable individual packaging set `individually` to true in the service wide packaging settings.
Then for every function you can use the same `include/exclude/artifact` config options as you can service wide. The `include/exclude` options will be merged with the service wide options to create one `include/exclude` config per function during packaging.
```yaml
service: my-service
package:
individually: true
exclude:
- excluded-by-default.json
functions:
hello:
handler: handler.hello
package:
include:
# We're including this file so it will be in the final package of this function only
- excluded-by-default.json
world:
handler: handler.hello
package:
exclude:
- event.json
```

View File

@ -0,0 +1,314 @@
<!--
title: Serverless Framework - AWS Lambda Guide - Plugins
menuText: Plugins
menuOrder: 12
description: How to install and create Plugins to extend or overwrite the functionality of the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/plugins)
<!-- DOCS-SITE-LINK:END -->
# Plugins
A Plugin is custom Javascript code that creates new or extends existing commands within the Serverless Framework. The Serverless Framework is merely a group of Plugins that are provided in the core. If you or your organization have a specific workflow, install a pre-written Plugin or write a plugin to customize the Framework to your needs. External Plugins are written exactly the same way as the core Plugins.
If you or your organization have a specific workflow, install a pre-written Plugin or write a plugin to customize the Framework to your needs. External Plugins are written exactly the same way as the core Plugins.
## Installing Plugins
External Plugins are added on a per service basis and are not applied globally. Make sure you are in your Service's root directory, then install the corresponding Plugin with the help of NPM:
```
npm install --save custom-serverless-plugin
```
We need to tell Serverless that we want to use the plugin inside our service. We do this by adding the name of the Plugin to the `plugins` section in the `serverless.yml` file.
```yml
# serverless.yml file
plugins:
- custom-serverless-plugin
```
Plugins might want to add extra information which should be accessible to Serverless. The `custom` section in the `serverless.yml` file is the place where you can add necessary
configurations for your plugins (the plugins author / documentation will tell you if you need to add anything there):
```yml
plugins:
- custom-serverless-plugin
custom:
customkey: customvalue
```
### Load Order
Keep in mind that the order you define your plugins matters. When Serverless loads all the core plugins and then the custom plugins in the order you've defined them.
```yml
# serverless.yml
plugins:
- plugin1
- plugin2
```
In this case `plugin1` is loaded before `plugin2`.
## Writing Plugins
### Concepts
#### Plugin
Code which defines *Commands*, any *Events* within a *Command*, and any *Hooks* assigned to an *Lifecycle Event*.
* Command // CLI configuration, commands, subcommands, options
* LifecycleEvent(s) // Events that happen sequentially when the command is run
* Hook(s) // Code that runs when a Lifecycle Event happens during a Command
#### Command
A CLI *Command* that can be called by a user, e.g. `serverless deploy`. A Command has no logic, but simply defines the CLI configuration (e.g. command, subcommands, parameters) and the *Lifecycle Events* for the command. Every command defines its own lifecycle events.
```javascript
'use strict';
class MyPlugin {
constructor() {
this.commands = {
deploy: {
lifecycleEvents: [
'resources',
'functions'
]
},
};
}
}
module.exports = MyPlugin;
```
#### Lifecycle Events
Events that fire sequentially during a Command. The above example list two Events. However, for each Event, and additional `before` and `after` event is created. Therefore, six Events exist in the above example:
- `before:deploy:resources`
- `deploy:resources`
- `after:deploy:resources`
- `before:deploy:functions`
- `deploy:functions`
- `after:deploy:functions`
The name of the command in front of lifecycle events when they are used for Hooks.
#### Hooks
A Hook binds code to any lifecycle event from any command.
```javascript
'use strict';
class Deploy {
constructor() {
this.commands = {
deploy: {
lifecycleEvents: [
'resources',
'functions'
]
},
};
this.hooks = {
'before:deploy:resources': this.beforeDeployResources,
'deploy:resources': this.deployResources,
'after:deploy:functions': this.afterDeployFunctions
};
}
beforeDeployResources() {
console.log('Before Deploy Resources');
}
deployResources() {
console.log('Deploy Resources');
}
afterDeployFunctions() {
console.log('After Deploy Functions');
}
}
module.exports = Deploy;
```
### Nesting Commands
You can also nest commands, e.g. if you want to provide a command `serverless deploy single`. Those nested commands have their own lifecycle events and do not inherit them from their parents.
```javascript
'use strict';
class MyPlugin {
constructor() {
this.commands = {
deploy: {
lifecycleEvents: [
'resources',
'functions'
],
commands: {
function: {
lifecycleEvents: [
'package',
'deploy'
],
},
},
},
}
}
}
module.exports = MyPlugin;
```
### Defining Options
Each (sub)command can have multiple Options.
Options are passed in with a double dash (`--`) like this: `serverless function deploy --function functionName`.
Option Shortcuts are passed in with a single dash (`-`) like this: `serverless function deploy -f functionName`.
The `options` object will be passed in as the second parameter to the constructor of your plugin.
In it, you can optionally add a `shortcut` property, as well as a `required` property. The Framework will return an error if a `required` Option is not included.
**Note:** At this time, the Serverless Framework does not use parameters.
```javascript
'use strict';
class Deploy {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
deploy: {
lifecycleEvents: [
'functions'
],
options: {
function: {
usage: 'Specify the function you want to deploy (e.g. "--function myFunction")',
shortcut: 'f',
required: true
}
}
},
};
this.hooks = {
'deploy:functions': this.deployFunction.bind(this)
}
}
deployFunction() {
console.log('Deploying function: ', this.options.function);
}
}
module.exports = Deploy;
```
### Provider Specific Plugins
Plugins can be provider specific which means that they are bound to a provider.
**Note:** Binding a plugin to a provider is optional. Serverless will always consider your plugin if you don't specify a `provider`.
The provider definition should be added inside the plugins constructor:
```javascript
'use strict';
class ProviderDeploy {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
// set the providers name here
this.provider = 'providerName';
this.commands = {
deploy: {
lifecycleEvents: [
'functions'
],
options: {
function: {
usage: 'Specify the function you want to deploy (e.g. "--function myFunction")',
required: true
}
}
},
};
this.hooks = {
'deploy:functions': this.deployFunction.bind(this)
}
}
deployFunction() {
console.log('Deploying function: ', this.options.function);
}
}
module.exports = ProviderDeploy;
```
The Plugin's functionality will now only be executed when the Serverless Service's provider matches the provider name which is defined inside the plugins constructor.
### Serverless Instance
The `serverless` instance which enables access to global service config during runtime is passed in as the first parameter to the plugin constructor.
```javascript
'use strict';
class MyPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
log: {
lifecycleEvents: [
'serverless'
],
},
};
this.hooks = {
'log:serverless': this.logServerless.bind(this)
}
}
logServerless() {
console.log('Serverless instance: ', this.serverless);
}
}
module.exports = MyPlugin;
```
### Command Naming
Command names need to be unique. If we load two commands and both want to specify the same command (e.g. we have an integrated command `deploy` and an external command also wants to use `deploy`) the Serverless CLI will print an error and exit. If you want to have your own `deploy` command you need to name it something different like `myCompanyDeploy` so they don't clash with existing plugins.

View File

@ -0,0 +1,81 @@
<!--
title: Serverless Framework - AWS Lambda Guide - AWS Infrastructure Resources
menuText: Resources
menuOrder: 7
description: How to deploy and manage AWS infrastructure to use with your AWS Lambda functions with the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/resources)
<!-- DOCS-SITE-LINK:END -->
# Resources
If you are using AWS as a provider for your Service, all *Resources* are other AWS infrastructure resources which the AWS Lambda functions in your *Service* depend on, like AWS DynamoDB or AWS S3.
Using the Serverless Framework, you can define the infrastructure resources you need in `serverless.yml`, and easily deploy them.
## Configuration
Every `serverless.yml` using the `aws` provider is a single AWS CloudFormation stack. This is where your AWS Lambda functions and their event configurations are defined and it's how they are deployed. When you add `resources` those resources are added into your CloudFormation stack upon `serverless deploy`.
Define your AWS resources in a property titled `resources`. What goes in this property is raw CloudFormation template syntax, in YAML, like this:
```yml
# serverless.yml
service: usersCrud
provider: aws
functions:
resources: // CloudFormation template syntax
Resources:
usersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: usersTable
AttributeDefinitions:
- AttributeName: email
AttributeType: S
KeySchema:
- AttributeName: email
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
```
You can overwrite/attach any kind of resource to your CloudFormation stack. You can add `Resources`, `Outputs` or even overwrite the `Description`. You can also use [Serverless Variables](./variables.md) for sensitive data or reusable configuration in your resources templates. Please be cautious as overwriting existing parts of your CloudFormation stack might introduce unexpected behavior.
## AWS CloudFormation Resource Reference
To have consistent naming in the Cloudformation Templates that get deployed we use a standard pattern:
`{Function Name}{Cloud Formation Resource Type}{ResourceName}{SequentialID or Random String}`
* `Function Name` - This is optional for Resources that should be recreated when the function name gets changed. Those resources are also called *function bound*
* `Cloud Formation Resource Type` - E.g., S3Bucket
* `Resource Name` - An identifier for the specific resource, e.g. for an S3 Bucket the configured bucket name.
* `SequentialID or Random String` - For a few resources we need to add an optional sequential id or random string to identify them
All resource names that are deployed by Serverless have to follow this naming scheme. The only exception (for backwards compatibility reasons) is the S3 Bucket that is used to upload artifacts so they can be deployed to your function.
We're also using the term `normalizedName` or similar terms in this guide. This means dropping any characters that aren't allowed in resources names, e.g. special characters.
| AWS Resource | Name Template | Example |
|--- |--- | --- |
| S3::Bucket | S3Bucket{normalizedBucketName} | S3BucketMybucket |
|IAM::Role | IamRoleLambdaExecution | IamRoleLambdaExecution |
|IAM::Policy | IamPolicyLambdaExecution | IamPolicyLambdaExecution |
|Lambda::Function | {normalizedFunctionName}LambdaFunction | HelloLambdaFunction |
|Lambda::Permission | <ul><li>**Schedule**: {normalizedFunctionName}LambdaPermissionEventsRuleSchedule{index} </li><li>**S3**: {normalizedFunctionName}LambdaPermissionS3</li><li>**APIG**: {normalizedFunctionName}LambdaPermissionApiGateway</li><li>**SNS**: {normalizedFunctionName}LambdaPermission{normalizedTopicName}</li> | <ul><li>**Schedule**: HelloLambdaPermissionEventsRuleSchedule1 </li><li>**S3**: HelloLambdaPermissionS3</li><li>**APIG**: HelloLambdaPermissionApiGateway</li><li>**SNS**: HelloLambdaPermissionSometopic</li> |
|Events::Rule | {normalizedFuntionName}EventsRuleSchedule{SequentialID} | HelloEventsRuleSchedule1 |
|ApiGateway::RestApi | ApiGatewayRestApi | ApiGatewayRestApi |
|ApiGateway::Resource | ApiGatewayResource{normalizedPath} | ApiGatewayResourceUsers |
|ApiGateway::Method | ApiGatewayResource{normalizedPath}{normalizedMethod} | ApiGatewayResourceUsersGet |
|ApiGateway::Authorizer | {normalizedFunctionName}ApiGatewayAuthorizer | HelloApiGatewayAuthorizer |
|ApiGateway::Deployment | ApiGatewayDeployment{randomNumber} | ApiGatewayDeployment12356789 |
|ApiGateway::ApiKey | ApiGatewayApiKey{SequentialID} | ApiGatewayApiKey1 |
|SNS::Topic | SNSTopic{normalizedTopicName} | SNSTopicSometopic |
|AWS::Lambda::EventSourceMapping | <ul><li>**DynamoDB:** {normalizedFunctionName}EventSourceMappingDynamodb{tableName}</li><li>**Kinesis:** {normalizedFunctionName}EventSourceMappingKinesis{streamName}</li></ul> | <ul><li>**DynamoDB:** HelloLambdaEventSourceMappingDynamodbUsers</li><li>**Kinesis:** HelloLambdaEventSourceMappingKinesisMystream</li></ul> |

View File

@ -0,0 +1,154 @@
<!--
title: Serverless Framework - AWS Lambda Guide - Services
menuText: Services
menuOrder: 4
description: How to manage and configure serverless services, which contain your AWS Lambda functions, their events and infrastructure resources.
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/services)
<!-- DOCS-SITE-LINK:END -->
# Services
A *Service* is like a Project. It's where you define your AWS Lambda Functions, the Events that trigger them and any AWS infrastructure Resources they require, all in a file called `serverless.yml`.
To get started building your first Serverless Framework project, create a *Service*.
## Organization
In the beginning of an application, many people use a single Service to define all of the Functions, Events and Resources for that project. This is what we recommend in the beginning.
```bash
myApp/
serverless.yml # Contains all functions and infrastructure resources
```
However, as your application grows, you can break it out into multiple services. A lot of people organize their services by workflows or data models, and group the functions related to those workflows and data models together in the service.
```bash
users/
serverless.yml # Contains 4 functions that do Users CRUD operations and the Users database
posts/
serverless.yml # Contains 4 functions that do Posts CRUD operations and the Posts database
comments/
serverless.yml # Contains 4 functions that do Comments CRUD operations and the Comments database
```
This makes sense since related functions usually use common infrastructure resources, and you want to keep those functions and resources together as a single unit of deployment, for better organization and separation of concerns.
**Note:** Currently, every service will create a separate REST API on AWS API Gateway. Due to a limitation with AWS API Gateway, you can only have a custom domain per one REST API. If you plan on making a large REST API, please make note of this limitation. Also, a fix is in the works and is a top priority.
## Creation
To create a service, use the `create` command. You must also pass in a runtime (e.g., node.js, python etc.) you would like to write the service in. You can also pass in a path to create a directory and auto-name your service:
```bash
serverless create --template aws-nodejs --path myService
```
Here are the available runtimes for AWS Lambda:
* aws-nodejs
* aws-python
* aws-java-gradle
* aws-java-maven
* aws-scala-sbt
Check out the [create command docs](../cli-reference/create) for all the details and options.
## Contents
You'll see the following files in your working directory:
- `serverless.yml`
- `handler.js`
- `event.json`
### serverless.yml
Each *Serverless service* configuration is managed in the `serverless.yml` file. The main responsibilities of this file are:
- Declare a Serverless service
- Define one or multiple functions in the service
- Define the provider the service will be deployed to (and the runtime if provided)
- Define custom plugins to be used
- Define events that trigger each function to execute (e.g. HTTP requests)
- Define a set of resources (e.g. 1 AWS CloudFormation stack) required by the functions in this service
- Allow events listed in the `events` section to automatically create the resources required for the event upon deployment
- Allow flexible configuration using Serverless Variables
You can see the name of the service, the provider configuration and the first function inside the `functions` definition which points to the `handler.js` file. Any further service configuration will be done in this file.
```yml
# serverless.yml
service: users
provider:
name: aws
runtime: nodejs4.3
memorySize: 512
functions:
usersCreate: # A Function
events: # The Events that trigger this Function
- http: post users/create
usersDelete: # A Function
events: # The Events that trigger this Function
- http: delete users/delete
# The "Resources" your "Functions" use. Raw AWS CloudFormation goes in here.
resources:
Resources:
usersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: usersTable
AttributeDefinitions:
- AttributeName: email
AttributeType: S
KeySchema:
- AttributeName: email
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
```
Every `serverless.yml` translates to a single AWS CloudFormation template and a CloudFormation stack is created from that resulting CloudFormation template.
### handler.js
The `handler.js` file contains your function code. The function definition in `serverless.yml` will point to this `handler.js` file and the function exported here.
### event.json
This file contains event data you can use to invoke your function with via `serverless invoke -p event.json`
## Deployment
When you deploy a Service, all of the Functions, Events and Resources in your `serverless.yml` are translated to an AWS CloudFormation template and deployed as a single CloudFormation stack.
To deploy a service, use the `deploy` command:
```bash
serverless deploy
```
Deployment defaults to `dev` stage and `us-east-1` region on AWS, unless you specified these elsewhere, or add them in as options:
```bash
serverless deploy --stage prod --region us-east-1
```
Check out the [deployment guide](https://serverless.com/framework/docs/providers/aws/guide/deploying/) to learn more about deployments and how they work. Or, check out the [deploy command docs](../cli-reference/deploy) for all the details and options.
## Removal
To easily remove your Service from your AWS account, you can use the `remove` command.
Run `serverless remove -v` to trigger the removal process. As in the deploy step we're also running in the `verbose` mode so you can see all details of the remove process.
Serverless will start the removal and informs you about it's process on the console. A success message is printed once the whole service is removed.
The removal process will only remove the service on your provider's infrastructure. The service directory will still remain on your local machine so you can still modify and (re)deploy it to another stage, region or provider later on.

View File

@ -0,0 +1,98 @@
<!--
title: Serverless Framework - AWS Lambda Guide - Testing
menuText: Testing
menuOrder: 9
description: Recommendations and best practices for testing AWS Lambda Functions with the Serverless Framework
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/testing)
<!-- DOCS-SITE-LINK:END -->
# Testing
Serverless introduces a lot of simplifications when it comes to serving business logic. We only need to provide handler function that almost entirely implements business logic. The only thing that we need to apply to are handler function arguments that are passed by FaaS provider. E.g. AWS Lambda passes 3 arguments `event`, `context` and `callback` to Node.js functions. Of course list of arguments differs between languages and, what is more important, between FaaS providers.
Another important factor is a cloud environment. Basically, it's impossible to emulate AWS locally. Of course projects like [dynamodb-local](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html) or [kinesalite](https://github.com/mhart/kinesalite) may help but AWS (and other providers) provide much more services. We shouldn't rely on local implementations if we want to be 100% sure that our service won't fail after deploying to production environment.
Because of those issues (and having [test pyramid](http://martinfowler.com/bliki/TestPyramid.html) in mind) we suggest following testing strategy:
- business logic should be independent from FaaS provider,
- unit testing should be used as a main tool for verifying business logic,
- integration tests should be used for verifying integration with other services.
Let's take simple Node.js function as an example. The responsibility of this function is to save user into DB and send welcome email:
```javascript
const db = require('db').connect();
const mailer = require('mailer');
module.exports.saveUser = (event, context, callback) => {
const user = {
email: event.email,
created_at: Date.now()
}
db.saveUser(user, function (err) {
if (err) {
callback(err);
} else {
mailer.sendWelcomeEmail(event.email);
callback();
}
});
};
```
There are two main problems with this functions:
- code is bounded to how AWS Lambda passes incoming data (`event` object),
- testing this function require running DB instance and mail server.
## Unit testing
Business logic should be implemented in a way that allows using it in a different environment, no matter if it's AWS Lambda, Google Cloud Functions or HTTP server. Instead of writing complicated handler functions we should extract what is the core of our business. Let's extract it from above example
```javascript
class Users {
constructor(db, mailer) {
this.db = db;
this.mailer = mailer;
}
save(email, callback) {
const user = {
email: email,
created_at: Date.now()
}
this.db.saveUser(user, function (err) {
if (err) {
callback(err);
} else {
this.mailer.sendWelcomeEmail(email);
callback();
}
});
}
}
```
This class is testable and doesn't require running any of the external services. Instead of real `db` and `mailer` objects we can pass mocks and assert if `saveUser` and `sendWelcomeEmail` has been called with proper arguments. We should have as much unit-test as possible and run them every code change. Of course passing unit-tests doesn't mean that our function is working as expected. That's why we also need integration test.
## Integration tests
After extracting business logic to separate module handler function looks like this:
```javascript
const db = require('db').connect();
const mailer = require('mailer');
const users = require('users')(db, mailer);
module.exports.saveUser = (event, context, callback) => {
users.save(event.email, callback);
};
```
It's responsible for setting up dependencies, injecting them and calling business logic functions. This code will be changed less often. To make sure that function is working as expected integration tests should be ran against deployed function. They should invoke function (`serverless invoke`) with fixture email address, check if user is actually saved to DB and check if email was received.

View File

@ -1,12 +1,19 @@
<!--
title: Version 0 to Version 1 comparison
menuText: Comparison between 0.x and 1.x
title: Serverless Framework - AWS Lambda Guide - Comparison Of Serverless Framework V.1 & V.0
menuText: V.0 & V.1
menuOrder: 14
description: A comparison of Serverless Framework V.1 and Serverless Framework V.0
layout: Doc
-->
# Comparison between 0.x and 1.x of Serverless
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/v0_to_v1)
<!-- DOCS-SITE-LINK:END -->
# Comparison Of Serverless Framework V.1 & V.0
After the 0.5.6 release of Serverless we sat down with many contributors and users of the Framework to discuss the next steps to improve Serverless.
Those discussions lead to our decision to completely rewrite Serverless. The configuration is in no way backwards compatible and can basically be seen as a completely new tool.
We've decided to make this step so in the future we have a stronger base to work from and make sure we don't have to do major breaking changes like this anymore.
@ -19,7 +26,7 @@ As 1.x is a complete reimplementation without backwards compatibility pretty muc
### Central configuration file
In the past configuration was spread out over several configuration files. It was hard for users to have a good overview over all the different configuration values set for different functions. This was now moved into a central [serverless.yml file](./01-guide/12-serverless-yml-reference.md) that stores all configuration for one service. This also means there is no specific folder setup that you have to follow any more. By default Serverless simply zips up the folder your serverless.yml is in and deploys it to any functions defined in that config file (although you can [change the packaging behavior](./01-guide/10-packaging.md)).
In the past configuration was spread out over several configuration files. It was hard for users to have a good overview over all the different configuration values set for different functions. This was now moved into a central serverless.yml file that stores all configuration for one service. This also means there is no specific folder setup that you have to follow any more. By default Serverless simply zips up the folder your serverless.yml is in and deploys it to any functions defined in that config file (although you can [change the packaging behavior](https://serverless.com/framework/docs/providers/aws/guide/packaging/)).
### Services are the main unit of deployment
@ -27,16 +34,16 @@ In the past Serverless didn't create a strong connection between functions that
### Built on CloudFormation
With the move to a more service oriented style came the decision to move all configuration into CloudFormation. Every resource we create gets created through a central CloudFormation template. Each service gets its own CloudFormation stack, we even deploy new CF stacks if you create a service in a different stage. A very important feature that came with this move to CF was that you can now easily create any other kind of resource in AWS and connect it with your functions. You can read more about custom resources in [our guide](./01-guide/06-custom-provider-resources.md)
With the move to a more service oriented style came the decision to move all configuration into CloudFormation. Every resource we create gets created through a central CloudFormation template. Each service gets its own CloudFormation stack, we even deploy new CF stacks if you create a service in a different stage. A very important feature that came with this move to CF was that you can now easily create any other kind of resource in AWS and connect it with your functions. You can read more about resources in [our guide](https://serverless.com/framework/docs/providers/aws/guide/resources/)
### New plugin system
While our old plugin system allowed for a powerful setup we felt we could push it a lot further and went back to the drawing board. We came up with a completely new way to build plugins for Serverless through hooks and lifecycle events. This is a breaking change for any existing plugin. You can read more about our Plugin system in our [extending serverless docs](./04-extending-serverless).
While our old plugin system allowed for a powerful setup we felt we could push it a lot further and went back to the drawing board. We came up with a completely new way to build plugins for Serverless through hooks and lifecycle events. This is a breaking change for any existing plugin. You can read more about our Plugin system in our [extending serverless docs](https://serverless.com/framework/docs/providers/aws/guide/plugins/).
### Endpoints are now events
In 0.x APIG was treated as a separate resource and you could deploy endpoints separately. In 1.x APIG is just another event source that can be configured to trigger Lambda functions. We create one APIG per CloudFormation stack, so if you deploy to different stages we're creating separate API Gateways. You can read all about our [APIG integration in our event docs](./02-providers/aws/events/01-apigateway.md).
In 0.x APIG was treated as a separate resource and you could deploy endpoints separately. In 1.x APIG is just another event source that can be configured to trigger Lambda functions. We create one APIG per CloudFormation stack, so if you deploy to different stages we're creating separate API Gateways. You can read all about our [APIG integration in our event docs](https://serverless.com/framework/docs/providers/aws/events/apigateway/).
## How to upgrade from 0.x to 1.x
As Serverless 1.x is a complete reimplementation and does not implement all the features that were in 0.x (but has a lot more features in general) there is no direct update path. Basically the best way for users to move from 0.x to 1.x is to go through [our guide](./01-guide) and the [AWS provider documentation](./02-providers/aws) that will teach you all the details of Serverless 1.x. This should make it pretty easy to understand how to set up a service for 1.x and move your code over. We've worked with different teams during the Beta phase of Serverless 1.x and they were able to move their services into the new release pretty quickly.
As Serverless 1.x is a complete reimplementation and does not implement all the features that were in 0.x (but has a lot more features in general) there is no direct update path. Basically the best way for users to move from 0.x to 1.x is to go through [our guide](https://serverless.com/framework/docs/providers/aws/guide/) and the [AWS provider documentation](https://serverless.com/framework/docs/providers/aws/) that will teach you all the details of Serverless 1.x. This should make it pretty easy to understand how to set up a service for 1.x and move your code over. We've worked with different teams during the Beta phase of Serverless 1.x and they were able to move their services into the new release pretty quickly.

View File

@ -1,13 +1,18 @@
<!--
title: Serverless Variables
menuText: Using Variables
description: How to use variables to make your serverless.yml more dynamic
menuText: Variables
menuOrder: 10
description: How to use Serverless Variables to insert dynamic configuration info into your serverless.yml
layout: Doc
-->
# Serverless Variables
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/variables)
<!-- DOCS-SITE-LINK:END -->
The Serverless framework provides a powerful variable system to give your `serverless.yml` configuration file extra flexibility. With Serverless Variables, you'll be able to do the following:
# Variables
The Serverless framework provides a powerful variable system which allows you to add dynamic data into your `serverless.yml`. With Serverless Variables, you'll be able to do the following:
- Reference & load variables from environment variables
- Reference & load variables from CLI options
@ -16,44 +21,8 @@ The Serverless framework provides a powerful variable system to give your `serve
- Recursively nest variable references within each other for ultimate flexibility
- Combine multiple variable references to overwrite each other
## Referencing Environment Variables
To reference environment variables, you'll need to use the `${env:SOME_VAR}` syntax in your `serverless.yml` configuration file. Here's an example:
```yml
service: new-service
provider: aws
functions:
hello:
name: ${env:FUNC_PREFIX}-hello
handler: handler.hello
world:
name: ${env:FUNC_PREFIX}-world
handler: handler.world
```
In the previous example you're dynamically adding a prefix to the function names by referencing the `FUNC_PREFIX` env var. So you can easily change that prefix for all functions by changing the `FUNC_PREFIX` env var.
## Referencing CLI Options
To reference CLI options that you passed, you'll need to use the `${opt:some_option}` syntax in your `serverless.yml` configuration file. Here's an example:
```yml
service: new-service
provider: aws
functions:
hello:
name: ${opt:stage}-hello
handler: handler.hello
world:
name: ${opt:stage}-world
handler: handler.world
```
In the previous example you're dynamically adding a prefix to the function names by referencing the `stage` option that you pass in the CLI when you run `serverless deploy --stage dev`. So when you deploy, the function name will always include the stage you're deploying to.
## Recursively Self-Reference serverless.yml Properties
To self-reference properties in `serverless.yml`, you'll need to use the `${self:someProperty}` syntax in your `serverless.yml` configuration file. This functionality is recursive, so you can go as deep in the object tree as you want. Here's an example:
## Reference Properties In serverless.yml
To self-reference properties in `serverless.yml`, use the `${self:someProperty}` syntax in your `serverless.yml`. This functionality is recursive, so you can go as deep in the object tree as you want.
```yml
service: new-service
@ -70,22 +39,51 @@ functions:
handler: handler.world
events:
- schedule: ${self:custom.globalSchedule}
```
In the previous example you're setting a global schedule for all functions by referencing the `globalSchedule` property in the same `serverless.yml` file. This way, you can easily change the schedule for all functions whenever you like.
In the above example you're setting a global schedule for all functions by referencing the `globalSchedule` property in the same `serverless.yml` file. This way, you can easily change the schedule for all functions whenever you like.
## Recursively Reference Variables in Other Files
To reference variables in other YAML or JSON files, you'll need to use the `${file(./myFile.yml):someProperty}` syntax in your `serverless.yml` configuration file. This functionality is recursive, so you can go as deep in that file as you want. Here's an example:
## Referencing Environment Variables
To reference environment variables, use the `${env:SOME_VAR}` syntax in your `serverless.yml` configuration file.
```yml
# myCustomFile.yml
globalSchedule: rate(10 minutes)
service: new-service
provider: aws
functions:
hello:
name: ${env:FUNC_PREFIX}-hello
handler: handler.hello
world:
name: ${env:FUNC_PREFIX}-world
handler: handler.world
```
In the above example you're dynamically adding a prefix to the function names by referencing the `FUNC_PREFIX` env var. So you can easily change that prefix for all functions by changing the `FUNC_PREFIX` env var.
## Referencing CLI Options
To reference CLI options that you passed, use the `${opt:some_option}` syntax in your `serverless.yml` configuration file.
```yml
service: new-service
provider: aws
functions:
hello:
name: ${opt:stage}-hello
handler: handler.hello
world:
name: ${opt:stage}-world
handler: handler.world
```
In the above example, you're dynamically adding a prefix to the function names by referencing the `stage` option that you pass in the CLI when you run `serverless deploy --stage dev`. So when you deploy, the function name will always include the stage you're deploying to.
## Reference Variables in Other Files
To reference variables in other YAML or JSON files, use the `${file(./myFile.yml):someProperty}` syntax in your `serverless.yml` configuration file. This functionality is recursive, so you can go as deep in that file as you want. Here's an example:
```yml
# myCustomFile.yml
globalSchedule: rate(10 minutes)
```
```yml
# serverless.yml
@ -101,12 +99,11 @@ functions:
handler: handler.world
events:
- schedule: ${self:custom.globalSchedule} # This would also work in this case
```
In the previous example you're referencing the entire `myCustomFile.yml` file in the `custom` property. You just need to pass the path relative to your service directory. You can also request specific properties in that file as shown in the `schedule` property. It's completely recursive and you can go as deep as you want.
In the above example, you're referencing the entire `myCustomFile.yml` file in the `custom` property. You need to pass the path relative to your service directory. You can also request specific properties in that file as shown in the `schedule` property. It's completely recursive and you can go as deep as you want.
### Referencing other
## Multiple Configuration Files
Adding many custom resources to your `serverless.yml` file could bloat the whole file, so you can use the Serverless Variable syntax to split this up.
@ -115,8 +112,7 @@ resources:
Resources: ${file(cloudformation-resources.json)}
```
The corresponding resources which are defined inside the `cloudformation-resources.json` file will be resolved and loaded
into the `Resources` section.
The corresponding resources which are defined inside the `cloudformation-resources.json` file will be resolved and loaded into the `Resources` section.
## Nesting Variable References
The Serverless variable system allows you to nest variable references within each other for ultimate flexibility. So you can reference certain variables based on other variables. Here's an example:
@ -130,17 +126,15 @@ custom:
functions:
hello:
handler: handler.hello
```
In the previous example, if you pass `dev` as a stage option, the framework will look for the `dev_arn` environment variable. If you pass `production`, the framework will look for `production_arn`, and so on. This allows you to creatively use multiple variables by using a certain naming pattern without having to update the values of these variables constantly. You can go as deep as you want in your nesting, and can reference variables at any level of nesting from any source (env, opt, self or file).
In the above example, if you pass `dev` as a stage option, the framework will look for the `dev_arn` environment variable. If you pass `production`, the framework will look for `production_arn`, and so on. This allows you to creatively use multiple variables by using a certain naming pattern without having to update the values of these variables constantly. You can go as deep as you want in your nesting, and can reference variables at any level of nesting from any source (env, opt, self or file).
## Overwriting Variables
The Serverless framework gives you an intuitive way to reference multiple variables as a fallback strategy in case one of the variables is missing. This way you'll be able to use a default value from a certain source, if the variable from another source is missing.
For example, if you want to reference the stage you're deploying to, but you don't want to keep on providing the `stage` option in the CLI. What you can do in `serverless.yml` is:
```yml
service: new-service
provider:
@ -156,21 +150,9 @@ functions:
What this says is to use the `stage` CLI option if it exists, if not, use the default stage (which lives in `provider.stage`). So during development you can safely deploy with `serverless deploy`, but during production you can do `serverless deploy --stage production` and the stage will be picked up for you without having to make any changes to `serverless.yml`.
This overwrite functionality is super powerful. You can have as many variable references as you want, from any source you want, and each of them can be of different type and different name.
You can have as many variable references as you want, from any source you want, and each of them can be of different type and different name.
## Setting the variable syntax
You can overwrite the variable syntax in case you want to use a text for a config parameter that would clash with the variable syntax.
```yml
service: aws-nodejs # Name of the Service
defaults:
variableSyntax: '\${{([\s\S]+?)}}' # Overwrite the default "${}" variable syntax to be "${{}}" instead. This can be helpful if you want to use "${}" as a string without using it as a variable.
```
# Migrating serverless.env.yml
## Migrating serverless.env.yml
Previously we used the `serverless.env.yml` file to track Serverless Variables. It was a completely different system with different concepts. To migrate your variables from `serverless.env.yml`, you'll need to decide where you want to store your variables.
* Using a config file: You can still use `serverless.env.yml`, but the difference now is that you can structure the file however you want, and you'll need to reference each variable/property correctly in `serverless.yml`. For more info, you can check the file reference section above.
@ -178,4 +160,4 @@ Previously we used the `serverless.env.yml` file to track Serverless Variables.
* Using environment variables: You can instead store your variables in environment variables and reference them with `env.someEnvVar`. For more info, you can check the environment variable reference section above.
* Making your variables stage/region specific: `serverless.env.yml` allowed you to have different values for the same variable based on the stage/region you're deploying to. You can achieve the same result by using the nesting functionality of the new variable system. For example, if you have two different ARNs, one for `dev` stage and the other for `prod` stage, you can do the following: `${env:${opt:stage}_arn}`. This will make sure the correct env var is referenced based on the stage provided as an option. Of course you'll need to export both `dev_arn` and `prod_arn` env vars on your local system.
Now you don't need `serverless.env.yml` at all, but you can still use it if you want. It's just not required anymore. Migrating to the new variable system is easy and you just need to know how the new system works and make small adjustments to how you store & reference your variables.
Now you don't need `serverless.env.yml` at all, but you can still use it if you want. It's just not required anymore. Migrating to the new variable system is easy and you just need to know how the new system works and make small adjustments to how you store & reference your variables.

View File

@ -0,0 +1,70 @@
<!--
title: Serverless Framework Guide - AWS Lambda - Workflow
menuText: Workflow
menuOrder: 13
description: A guide and cheatsheet containing CLI commands and workflow recommendations.
layout: Doc
-->
<!-- DOCS-SITE-LINK:START automatically generated -->
### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/guide/workflow)
<!-- DOCS-SITE-LINK:END -->
# Workflow
## Process
Quick recommendations and tips for various processes.
### Development
* Write your functions
* Use `serverless deploy` only when you've made changes to `serverless.yml` and in CI/CD systems.
* Use `serverless deploy function -f myFunction -l` to rapidly deploy changes when you are working on a specific AWS Lambda Function.
* Use `serverless invoke -f myFunction -l` to test your AWS Lambda Functions on AWS.
* Open up a separate tab in your console and stream logs in there via `serverless logs -f myFunction -t`.
* Write tests to run locally.
### Stages
* At the very least, use a `dev` and `production` stage.
* Use different AWS accounts for stages.
* In larger teams, each member should use a separate AWS account and their own stage for development.
### Larger Projects
* Break your application/project into multiple Serverless Services.
* Model your Serverless Services around Data Models or Workflows.
* Keep the Functions and Resources in your Serverless Services to a minimum.
## Cheat Sheet
A handy list of commands to use when developing with the Serverless Framework.
##### Create A Service:
Creates a new Service
```
serverless create -p [SERVICE NAME] -t aws-nodejs
```
##### Install A Service
This is a convenience method to install a pre-made Serverless Service locally by downloading the Github repo and unzipping it.
```
serverless install -u [GITHUB URL OF SERVICE]
```
##### Deploy All
Use this when you have made changes to your Functions, Events or Resources in `serverless.yml` or you simply want to deploy all changes within your Service at the same time.
```
serverless deploy -s [STAGE NAME] -r [REGION NAME] -v
```
##### Deploy Function
Use this to quickly overwrite your AWS Lambda code on AWS, allowing you to develop faster.
```
serverless deploy function -f [FUNCTION NAME] -s [STAGE NAME] -r [REGION NAME]
```
##### Invoke Function
Invokes an AWS Lambda Function on AWS and returns logs.
```
serverless deploy function -f [FUNCTION NAME] -s [STAGE NAME] -r [REGION NAME] -l
```
##### Streaming Logs
Open up a separate tab in your console and stream all logs for a specific Function using this command.
```
serverless logs -f [FUNCTION NAME] -s [STAGE NAME] -r [REGION NAME]
```

View File

@ -70,7 +70,7 @@ module.exports.logError = (e) => {
}
consoleLog(' ');
consoleLog(chalk.yellow(' Your Environment Infomation -----------------------------'));
consoleLog(chalk.yellow(' Your Environment Information -----------------------------'));
consoleLog(chalk.yellow(` OS: ${process.platform}`));
consoleLog(chalk.yellow(` Node Version: ${process.version.replace(/^[v|V]/, '')}`));
consoleLog(chalk.yellow(` Serverless Version: ${version}`));

View File

@ -65,9 +65,6 @@ class Service {
if (!serverlessFile.provider) {
throw new SError('"provider" property is missing in serverless.yml');
}
if (!serverlessFile.functions) {
throw new SError('"functions" property is missing in serverless.yml');
}
if (typeof serverlessFile.provider !== 'object') {
const providerName = serverlessFile.provider;
@ -91,7 +88,7 @@ class Service {
that.custom = serverlessFile.custom;
that.plugins = serverlessFile.plugins;
that.resources = serverlessFile.resources;
that.functions = serverlessFile.functions;
that.functions = serverlessFile.functions || {};
if (serverlessFile.package) {
that.package.individually = serverlessFile.package.individually;

View File

@ -334,7 +334,7 @@ describe('Service', () => {
});
});
it('should throw error if functions property is missing', () => {
it('should not throw error if functions property is missing', () => {
const SUtils = new Utils();
const serverlessYml = {
service: 'service-name',
@ -347,11 +347,7 @@ describe('Service', () => {
serviceInstance = new Service(serverless);
return serviceInstance.load().then(() => {
// if we reach this, then no error was thrown as expected
// so make assertion fail intentionally to let us know something is wrong
expect(1).to.equal(2);
}).catch(e => {
expect(e.name).to.be.equal('ServerlessError');
expect(serverless.service.functions).to.deep.equal({});
});
});

View File

@ -291,7 +291,7 @@ class Utils {
general: {
userId,
timestamp: (new Date()).getTime(),
timezone: (new Date()).toString().match(/([A-Z]+[\+-][0-9]+)/)[1],
timezone: (new Date()).toString().match(/([A-Z]+[+-][0-9]+)/)[1],
operatingSystem: process.platform,
serverlessVersion: serverless.version,
nodeJsVersion: process.version,

View File

@ -12,7 +12,7 @@ class Variables {
this.service = this.serverless.service;
this.overwriteSyntax = RegExp(/,/g);
this.fileRefSyntax = RegExp(/^file\(([a-zA-Z0-9._\-\/]+?)\)/g);
this.fileRefSyntax = RegExp(/^file\(([a-zA-Z0-9._\-/]+?)\)/g);
this.envRefSyntax = RegExp(/^env:./g);
this.optRefSyntax = RegExp(/^opt:./g);
this.selfRefSyntax = RegExp(/^self:./g);
@ -75,18 +75,22 @@ class Variables {
populateVariable(propertyParam, matchedString, valueToPopulate) {
let property = propertyParam;
if (typeof valueToPopulate === 'string') {
property = replaceall(matchedString, valueToPopulate, property);
} else {
if (property !== matchedString) {
const errorMessage = [
'Trying to populate non string value into',
` a string for variable ${matchedString}.`,
' Please make sure the value of the property is a string.',
].join('');
throw new this.serverless.classes
.Error(errorMessage);
if (typeof valueToPopulate === 'number') {
property = replaceall(matchedString, String(valueToPopulate), property);
} else {
const errorMessage = [
'Trying to populate non string value into',
` a string for variable ${matchedString}.`,
' Please make sure the value of the property is a string.',
].join('');
throw new this.serverless.classes
.Error(errorMessage);
}
return property;
}
property = valueToPopulate;
}
@ -98,7 +102,8 @@ class Variables {
const variableStringsArray = variableStringsString.split(',');
variableStringsArray.find(variableString => {
finalValue = this.getValueFromSource(variableString);
return (typeof finalValue !== 'undefined' && finalValue !== null);
return (finalValue !== null && typeof finalValue !== 'undefined') &&
!(typeof finalValue === 'object' && _.isEmpty(finalValue));
});
return finalValue;
@ -151,6 +156,10 @@ class Variables {
const referencedFileFullPath = path.join(this.serverless.config.servicePath,
referencedFileRelativePath);
if (!this.serverless.utils.fileExistsSync(referencedFileFullPath)) {
return undefined;
}
let valueToPopulate = this.serverless.utils.readFileSync(referencedFileFullPath);
if (matchedFileRefString !== variableString) {
let deepProperties = variableString

View File

@ -155,6 +155,17 @@ describe('Variables', () => {
expect(newProperty).to.equal('my stage is dev');
});
it('should populate number variables as sub string', () => {
const serverless = new Serverless();
const valueToPopulate = 5;
const matchedString = '${opt:number}';
const property = 'your account number is ${opt:number}';
const newProperty = serverless.variables
.populateVariable(property, matchedString, valueToPopulate);
expect(newProperty).to.equal('your account number is 5');
});
it('should populate non string variables', () => {
const serverless = new Serverless();
const valueToPopulate = 5;
@ -166,11 +177,11 @@ describe('Variables', () => {
expect(newProperty).to.equal(5);
});
it('should throw error if populating non string variable as sub string', () => {
it('should throw error if populating non string or non number variable as sub string', () => {
const serverless = new Serverless();
const valueToPopulate = 5;
const matchedString = '${opt:number}';
const property = 'hello ${opt:number}';
const valueToPopulate = {};
const matchedString = '${opt:object}';
const property = 'your account number is ${opt:object}';
expect(() => serverless.variables
.populateVariable(property, matchedString, valueToPopulate))
.to.throw(Error);
@ -194,6 +205,21 @@ describe('Variables', () => {
serverless.variables.getValueFromSource.restore();
});
it('should overwrite empty object values', () => {
const serverless = new Serverless();
const getValueFromSourceStub = sinon
.stub(serverless.variables, 'getValueFromSource');
getValueFromSourceStub.onCall(0).returns({});
getValueFromSourceStub.onCall(1).returns('variableValue');
const valueToPopulate = serverless.variables
.overwrite('opt:stage,env:stage');
expect(valueToPopulate).to.equal('variableValue');
expect(getValueFromSourceStub.callCount).to.equal(2);
serverless.variables.getValueFromSource.restore();
});
it('should not overwrite 0 values', () => {
const serverless = new Serverless();
const getValueFromSourceStub = sinon
@ -359,6 +385,16 @@ describe('Variables', () => {
expect(valueToPopulate).to.deep.equal(configYml);
});
it('should get undefined if non existing file and the second argument is true', () => {
const serverless = new Serverless();
const tmpDirPath = testUtils.getTmpDirPath();
serverless.config.update({ servicePath: tmpDirPath });
const valueToPopulate = serverless.variables.getValueFromFile('file(./config.yml)');
expect(valueToPopulate).to.be.equal(undefined);
});
it('should populate non json/yml files', () => {
const serverless = new Serverless();
const SUtils = new Utils();

Some files were not shown because too many files have changed in this diff Show More