Add OpenWhisk docs

This commit is contained in:
James Thomas 2017-01-24 13:29:13 +00:00
parent 0b49aae3c3
commit a01d080fe4
51 changed files with 3812 additions and 0 deletions

View File

@ -0,0 +1,19 @@
<!--
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.
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)
**Note:** Before continuing [AWS system credentials](./guide/credentials.md) are required for using the CLI.

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](../guide/credentials.md) 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,46 @@
<!--
title: Serverless Framework Commands - Apache OpenWhisk - Config Credentials
menuText: Config Credentials
menuOrder: 1
description: Configure Serverless 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/cli-reference/config-credentials)
<!-- DOCS-SITE-LINK:END -->
# Config Credentials
```bash
serverless config credentials --provider provider --key key --secret secret
```
## Options
- `--provider` or `-p` The provider (in this case `aws`). **Required**.
- `--key` or `-k` The `aws_access_key_id`. **Required**.
- `--secret` or `-s` The `aws_secret_access_key`. **Required**.
- `--profile` or `-n` The name of the profile which should be created.
## Provided lifecycle events
- `config:credentials:config`
## Examples
### Configure the `default` profile
```bash
serverless config credentials --provider aws --key 1234 --secret 5678
```
This example will configure the `default` profile with the `aws_access_key_id` of `1234` and the `aws_secret_access_key` of `5678`.
### Configure a custom profile
```bash
serverless config credentials --provider aws --key 1234 --secret 5678 --profile custom-profile
```
This example create and configure a `custom-profile` profile with the `aws_access_key_id` of `1234` and the `aws_secret_access_key` of `5678`.

View File

@ -0,0 +1,84 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Create
menuText: Create
menuOrder: 2
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.
**Create service in current working directory:**
```bash
serverless create --template aws-nodejs
```
**Create service in new folder:**
```bash
serverless create --template aws-nodejs --path myService
```
## Options
- `--template` or `-t` The name of one of the available templates. **Required**.
- `--path` or `-p` The path where the service should be created.
- `--name` or `-n` the name of the service in `serverless.yml`.
## Provided lifecycle events
- `create:create`
## Available Templates
To see a list of available templates run `serverless create --help`
Most commonly used templates:
- aws-nodejs
- aws-python
- aws-java-maven
- aws-java-gradle
- aws-scala-sbt
- aws-csharp
- plugin
## Examples
### Creating a new service
```bash
serverless create --template aws-nodejs --name my-special-service
```
This example will generate scaffolding for a service with `AWS` as a provider and `nodejs` as runtime. The scaffolding
will be generated in the current working directory.
Your new service will have a default stage called `dev` and a default region inside that stage called `us-east-1`.
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
```
This example will generate scaffolding for a service with `AWS` as a provider and `nodejs` as runtime. The scaffolding
will be generated in the `my-new-service` directory. This directory will be created if not present. Otherwise Serverless
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`.
### Creating a new plugin
```
serverless create --template plugin
```
This example will generate scaffolding for a hello world plugin that demonstrates how to create a new command and how to listen to the various events available.

View File

@ -0,0 +1,38 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Deploy Function
menuText: Deploy Function
menuOrder: 5
description: Deploy your AWS Lambda functions quickly without cloudformation
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-function)
<!-- DOCS-SITE-LINK:END -->
# Deploy Function
The `sls deploy function` command deploys an individual function without AWS CloudFormation. This command simply swaps out the zip file that your CloudFormation stack is pointing toward. This is a much faster way of deploying changes in code.
```bash
serverless deploy function -f functionName
```
## Options
- `--function` or `-f` The name of the function which should be deployed
- `--stage` or `-s` The stage in your service that you want to deploy to.
- `--region` or `-r` The region in that stage that you want to deploy to.
## Examples
### Deployment without stage and region options
```bash
serverless deploy function --function helloWorld
```
### Deployment with stage and region options
```bash
serverless deploy function --function helloWorld --stage dev --region us-east-1
```

View File

@ -0,0 +1,32 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Deploy List
menuText: Deploy List
menuOrder: 6
description: List your previous CloudFormation deployments
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-list)
<!-- DOCS-SITE-LINK:END -->
# Deploy List
The `sls deploy list` command will list your recent deployments available in your S3 deployment bucket. It will use stage and region from the provider config and show the timestamp of each deployment so you can roll back if necessary using `sls rollback`.
## Options
- `--stage` or `-s` The stage in your service that you want to deploy to.
- `--region` or `-r` The region in that stage that you want to deploy to.
## Artifacts
After the `serverless deploy` command runs all created deployment artifacts are placed in the `.serverless` folder of the service.
## Examples
### List existing deploys
```bash
serverless deploy list --stage dev --region us-east-1
```

View File

@ -0,0 +1,59 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Deploy
menuText: Deploy
menuOrder: 4
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
The `sls deploy` command deploys your entire service via CloudFormation. Run this command when you have made infrastructure changes (i.e., you edited `serverless.yml`). Use `serverless deploy function -f myFunction` when you have made code changes and you want to quickly upload your updated code to AWS Lambda.
```bash
serverless deploy
```
## Options
- `--stage` or `-s` The stage in your service that you want to deploy to.
- `--region` or `-r` The region in that stage that you want to deploy to.
- `--noDeploy` or `-n` Skips the deployment steps and leaves artifacts in the `.serverless` directory
- `--verbose` or `-v` Shows all stack events during deployment, and display any Stack Output.
## Artifacts
After the `serverless deploy` command runs all created deployment artifacts are placed in the `.serverless` folder of the service.
## Examples
### Deployment without stage and region options
```bash
serverless deploy
```
This is the simplest deployment usage possible. With this command Serverless will deploy your service to the defined
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`.
## Provided lifecycle events
- `deploy:cleanup`
- `deploy:initialize`
- `deploy:setupProviderConfiguration`
- `deploy:createDeploymentArtifacts`
- `deploy:compileFunctions`
- `deploy:compileEvents`
- `deploy:deploy`
- `deploy:function:deploy`

View File

@ -0,0 +1,79 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Info
menuText: Info
menuOrder: 11
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.
```bash
serverless info
```
## Options
- `--stage` or `-s` The stage in your service you want to display information about.
- `--region` or `-r` The region in your stage that you want to display information about.
- `--verbose` or `-v` Shows displays any Stack Output.
## Provided lifecycle events
- `info:info`
## Examples
### AWS
On AWS the info plugin uses the `Outputs` section of the CloudFormation stack and the AWS SDK to gather the necessary information.
See the example below for an example output.
**Example:**
```bash
$ serverless info
Service Information
service: my-serverless-service
stage: dev
region: us-east-1
api keys:
myKey: some123valid456api789key1011for1213api1415gateway
endpoints:
GET - https://dxaynpuzd4.execute-api.us-east-1.amazonaws.com/dev/users
functions:
my-serverless-service-dev-hello: arn:aws:lambda:us-east-1:377024778620:function:my-serverless-service-dev-hello
```
#### Verbose
When using the `--verbose` flag, the `info` command will also append all Stack Outputs to the output:
```bash
$ serverless info --verbose
Service Information
service: my-serverless-service
stage: dev
region: us-east-1
api keys:
myKey: some123valid456api789key1011for1213api1415gateway
endpoints:
GET - https://dxaynpuzd4.execute-api.us-east-1.amazonaws.com/dev/users
functions:
my-serverless-service-dev-hello: arn:aws:lambda:us-east-1:377024778620:function:my-serverless-service-dev-hello
Stack Outputs
CloudFrontUrl: d2d10e2tyk1pei.cloudfront.net
ListScreenshotsLambdaFunctionArn: arn:aws:lambda:us-east-1:377024778620:function:lambda-screenshots-dev-listScreenshots
ScreenshotBucket: dev-svdgraaf-screenshots
CreateThumbnailsLambdaFunctionArn: arn:aws:lambda:us-east-1:377024778620:function:lambda-screenshots-dev-createThumbnails
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,52 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Install
menuText: Install
menuOrder: 3
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**.
- `--name` or `-n` Name for the service.
## Provided lifecycle events
- `install:install`
## Examples
### Installing a service from a GitHub URL
```bash
serverless install --url https://github.com/pmuens/serverless-crud
```
This example will download the .zip file of the `serverless-crud` service from GitHub, create a new directory with the name `serverless-crud` in the current working directory and unzips the files in this directory.
### Installing a service from a GitHub URL with a new service name
```bash
serverless install --url https://github.com/pmuens/serverless-crud --name my-crud
```
This example will download the .zip file of the `serverless-crud` service from GitHub, create a new directory with the name `my-crud` in the current working directory and unzips the files in this directory and renames the service to `my-crud` if `serverless.yml` exists in the service root.
### Installing a service from a directory in a GitHub URL
```bash
serverless install --url https://github.com/serverless/examples/tree/master/rest-api-with-dynamodb
```
This example will download the `rest-api-with-dynamodb` service from GitHub.

View File

@ -0,0 +1,63 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Invoke Local
menuText: Invoke Local
menuOrder: 8
description: Emulate an invocation of your AWS Lambda function locally 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-local)
<!-- DOCS-SITE-LINK:END -->
# Invoke Local
This runs your code locally by emulating the AWS Lambda environment. Please keep in mind, it's not a 100% perfect emulation, there may be some differences, but it works for the vast majority of users. We mock the `context` with simple mock data.
```bash
serverless invoke local --function functionName
```
## Options
- `--function` or `-f` The name of the function in your service that you want to invoke locally. **Required**.
- `--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. The json file should have event and context properties to hold your mocked event and context data.
- `--data` or `-d` String data to be passed as an event to your function. Keep in mind that if you pass both `--path` and `--data`, the data included in the `--path` file will overwrite the data you passed with the `--data` flag.
## Examples
### Local function invocation
```bash
serverless invoke local --function functionName
```
This example will locally invoke your function.
### Local function invocation with data
```bash
serverless invoke --function functionName --data "hello world"
```
```bash
serverless invoke --function functionName --data '{"a":"bar"}'
```
### Local function invocation with data from standard input
```bash
node dataGenerator.js | serverless invoke local --function functionName
```
### Local function invocation with data passing
```bash
serverless invoke local --function functionName --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.
### Limitations
Currently, `invoke local` only supports the NodeJs and Python runtimes.

View File

@ -0,0 +1,86 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Invoke
menuText: Invoke
menuOrder: 7
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 deployed function. It allows to send event data to the function, read logs and display other important information of the function invocation.
```bash
serverless invoke [local] --function functionName
```
## Options
- `--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.
- `--data` or `-d` String data to be passed as an event to your function. By default data is read from standard input.
- `--path` or `-p` The path to a json file with 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`.
## Provided lifecycle events
- `invoke:invoke`
# Invoke Local
Invokes a function locally for testing and logs the output. You can only invoke Node.js runtime locally at the moment. Keep in mind that we mock the `context` with simple mock data.
```bash
serverless invoke local --function functionName
```
## Options
- `--function` or `-f` The name of the function in your service that you want to invoke locally. **Required**.
- `--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. The json file should have event and context properties to hold your mocked event and context data.
- `--data` or `-d` String data to be passed as an event to your function. Keep in mind that if you pass both `--path` and `--data`, the data included in the `--path` file will overwrite the data you passed with the `--data` flag.
## Examples
### AWS
```bash
serverless invoke --function functionName --stage dev --region us-east-1
```
This example will invoke your deployed function named `functionName` in region `us-east-1` in stage `dev`. This will
output the result of the invocation in your terminal.
#### Function invocation with data
```bash
serverless invoke --function functionName --stage dev --region us-east-1 --data "hello world"
```
#### Function invocation with data from standard input
```bash
node dataGenerator.js | serverless invoke --function functionName --stage dev --region us-east-1
```
#### Function invocation with logging
```bash
serverless invoke --function functionName --stage dev --region us-east-1 --log
```
Just like the first example, but will also outputs logging information about your invocation.
#### 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.

View File

@ -0,0 +1,79 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Logs
menuText: Logs
menuOrder: 9
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.
```bash
serverless logs -f hello
```
## Options
- `--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`). 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
2013-02-08 # A calendar date part
2013-W06-5 # A week date part
2013-039 # An ordinal date part
20130208 # Basic (short) full date
2013W065 # Basic (short) week, weekday
2013W06 # Basic (short) week only
2013050 # Basic (short) ordinal date
2013-02-08T09 # An hour time part separated by a T
20130208T080910,123 # Short date and time up to ms, separated by comma
20130208T080910.123 # Short date and time up to ms
20130208T080910 # Short date and time up to seconds
20130208T0809 # Short date and time up to minutes
20130208T08 # Short date and time, hours only
```
- `--filter` You can specify a filter string to filter the log output. This is useful if you want to to get the `error` logs for example.
- `--tail` or `-t` You can optionally tail the logs and keep listening for new logs in your terminal session by passing this option.
- `--interval` or `-i` If you choose to tail the output, you can control the interval at which the framework polls the logs with this option. The default is `1000`ms.
## Examples
### AWS
**Note:** There's a small lag between invoking the function and actually having the log event registered in CloudWatch. So it takes a few seconds for the logs to show up right after invoking the function.
```bash
serverless logs -f hello --startTime 5h
```
This will fetch the logs that happened in the past 5 hours.
```bash
serverless logs -f hello --startTime 1469694264
```
This will fetch the logs that happened starting at epoch `1469694264`.
```bash
serverless logs -f hello -t
```
Serverless will tail the CloudWatch log output and print new log messages coming in.
```bash
serverless logs -f hello --filter serverless
```
This will fetch only the logs that contain the string `serverless`

View File

@ -0,0 +1,63 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Metrics
menuText: Metrics
menuOrder: 10
description: View metrics 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/metrics)
<!-- DOCS-SITE-LINK:END -->
# Metrics
Lets you watch the metrics of a specific function.
```bash
serverless metrics
```
## Options
- `--function` or `-f` The function you want to fetch the metrics for.
- `--stage` or `-s` The stage you want to view the function metrics 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 metrics from the `dev` stage.
- `--region` or `-r` The region you want to view the function metrics 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 metrics from the `us-east-1` region.
- `--startTime` A specific unit in time to start fetching metrics from (ie: `2010-10-20`, `1469705761`, `30m` (30 minutes ago), `2h` (2 days ago) or `3d` (3 days ago)). Date formats should be written in ISO 8601. Defaults to 24h ago.
- `--endTime` A specific unit in time to end fetching metrics from (ie: `2010-10-21` or `1469705761`). Date formats should be written in ISO 8601. Defaults to now.
## Examples
**Note:** There's a small lag between invoking the function and actually having access to the metrics. It takes a few seconds for the metrics to show up right after invoking the function.
### See service wide metrics for the last 24h
```bash
serverless metrics
```
Displays service wide metrics for the last 24h.
### See service wide metrics for a specific timespan
```bash
serverless metrics --startTime 2016-01-01 --endTime 2016-01-02
```
Displays service wide metrics for the time between January 1, 2016 and January 2, 2016.
### See all metrics for the function `hello` of the last 24h
```bash
serverless metrics --function hello
```
Displays all `hello` function metrics for the last 24h.
### See metrics for the function `hello` of a specific timespan
```bash
serverless metrics --function hello --startTime 2016-01-01 --endTime 2016-01-02
```
Displays all `hello` function metrics for the time between January 1, 2016 and January 2, 2016.

View File

@ -0,0 +1,37 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Remove
menuText: Remove
menuOrder: 13
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
The `sls remove` command will remove the deployed service, defined in your current working directory, from the provider.
```bash
serverless remove
```
## Options
- `--stage` or `-s` The name of the stage in service.
- `--region` or `-r` The name of the region in stage.
- `--verbose` or `-v` Shows all stack events during deployment.
## Provided lifecycle events
- `remove:remove`
## Examples
### 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`.

View File

@ -0,0 +1,77 @@
<!--
title: Serverless Rollback CLI Command
menuText: Rollback
menuOrder: 12
description: Rollback the Serverless service to a specific deployment
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/rollback)
<!-- DOCS-SITE-LINK:END -->
# Rollback
Rollback the Serverless service to a specific deployment.
```bash
serverless rollback --timestamp timestamp
```
## Options
- `--timestamp` or `-t` The deployment you want to rollback to.
- `--verbose` or `-v` Shows any Stack Output.
## Provided lifecycle events
- `rollback:initialize`
- `rollback:rollback`
## Examples
### AWS
At first you want to run `serverless deploy list` to show your existing deployments. This will provide you with a list of the deployments stored in your S3 bucket. You can then use the timestamp of one of these deployments to set your infrastructure stack to this specific deployment.
**Example:**
```
$ serverless deploy list
Serverless: Listing deployments:
Serverless: -------------
Serverless: Timestamp: 1476790110568
Serverless: Datetime: 2016-10-18T11:28:30.568Z
Serverless: Files:
Serverless: - compiled-cloudformation-template.json
Serverless: - mail-service.zip
Serverless: -------------
Serverless: Timestamp: 1476889476243
Serverless: Datetime: 2016-10-19T15:04:36.243Z
Serverless: Files:
Serverless: - compiled-cloudformation-template.json
Serverless: - mail-service.zip
Serverless: -------------
Serverless: Timestamp: 1476893957131
Serverless: Datetime: 2016-10-19T16:19:17.131Z
Serverless: Files:
Serverless: - compiled-cloudformation-template.json
Serverless: - mail-service.zip
Serverless: -------------
Serverless: Timestamp: 1476895175540
Serverless: Datetime: 2016-10-19T16:39:35.540Z
Serverless: Files:
Serverless: - compiled-cloudformation-template.json
Serverless: - mail-service.zip
Serverless: -------------
Serverless: Timestamp: 1476993293402
Serverless: Datetime: 2016-10-20T19:54:53.402Z
Serverless: Files:
Serverless: - compiled-cloudformation-template.json
Serverless: - mail-service.zip
$ serverless rollback -t 1476893957131
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
.....
Serverless: Stack update finished...
```

View File

@ -0,0 +1,36 @@
<!--
title: Serverless Framework Commands - AWS Lambda - Serverless Stats
menuText: Serverless Stats
menuOrder: 14
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,19 @@
<!--
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.
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)
**Note:** Before continuing [AWS system credentials](../guide/credentials.md) are required for using the CLI.

View File

@ -0,0 +1,27 @@
<!--
title: Serverless Framework - AWS Lambda Events - Alexa Skill
menuText: Alexa Skill
menuOrder: 6
description: Setting up AWS Alexa Skill 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/alexa-skill)
<!-- DOCS-SITE-LINK:END -->
# Alexa Skill
## Event definition
This will enable your Lambda function to be called by an Alexa skill kit.
```yml
functions:
mySkill:
handler: mySkill.handler
events:
- alexaSkill
```
You can find detailed guides on how to create an Alexa Skill with Serverless using NodeJS [here](https://github.com/serverless/examples/tree/master/aws-node-alexa-skill) as well as in combination with Python [here](https://github.com/serverless/examples/tree/master/aws-python-alexa-skill).

View File

@ -0,0 +1,645 @@
<!--
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
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 `hello` function should be run when someone accesses the API gateway at `hello` via
a `GET` request.
Here's an example:
```yml
# serverless.yml
functions:
index:
handler: handler.hello
events:
- http: GET hello
```
```javascript
// handler.js
'use strict';
module.exports.hello = 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`.
```yml
# serverless.yml
functions:
create:
handler: posts.create
events:
- http:
path: posts/create
method: post
```
### Enabling CORS
To set CORS configurations for your HTTP endpoints, simply modify your event configurations as follows:
```yml
# serverless.yml
functions:
hello:
handler: handler.hello
events:
- http:
path: hello
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
// handler.js
'use strict';
module.exports.hello = 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
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
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
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
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
```
You can also configure an existing Cognito User Pool as the authorizer, as shown
in the following example:
```yml
functions:
create:
handler: posts.create
events:
- http:
path: posts/create
method: post
authorizer:
arn: arn:aws:cognito-idp:us-east-1:xxx:userpool/us-east-1_ZZZ
```
By default the `sub` claim will be exposed in `events.cognitoPoolClaims`, you can add extra claims like so:
```yml
functions:
create:
handler: posts.create
events:
- http:
path: posts/create
method: post
integration: lambda
authorizer:
arn: arn:aws:cognito-idp:us-east-1:xxx:userpool/us-east-1_ZZZ
claims:
- email
- nickname
```
Note: Since claims must be explicitly listed to be exposed, you must use `integration: lambda` integration type to access any claims.
### 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
**Note:** Due to a CloudFormation restriction you need to wire up API Keys and usage plans manually in the AWS console.
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. API Keys are created globally, so if you want to deploy your service to different stages make sure
your API key contains a stage variable as defined below.
Here's an example configuration for setting API keys for your service Rest API:
```yml
service: my-service
provider:
name: aws
apiKeys:
- myFirstKey
- ${opt:stage}-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
functions:
create:
handler: posts.create
events:
- http:
path: posts/create
method: post
integration: lambda
request:
parameters:
querystrings:
url: true
headers:
foo: false
bar: true
paths:
bar: false
```
In order for path variables to work, API Gateway also needs them in the method path itself, like so:
```yml
functions:
create:
handler: posts.post_detail
events:
- http:
path: posts/{id}
method: get
integration: lambda
request:
parameters:
paths:
id: true
```
### Request templates
#### Default Request Templates
Serverless ships with the following default request templates you can use out of the box:
1. `application/json`
2. `application/x-www-form-urlencoded`
Both templates give you access to the following properties you can access with the help of the `event` object:
- body
- method
- principalId
- stage
- headers
- query
- path
- identity
- stageVariables
#### 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):
```yml
functions:
create:
handler: posts.create
events:
- http:
method: get
path: whatever
integration: lambda
request:
template:
text/xhtml: '{ "stage" : "$context.stage" }'
application/json: '{ "httpMethod" : "$context.httpMethod" }'
```
**Note:** The templates are defined as plain text here. However you can also reference an external file with the help of the `${file(templatefile)}` syntax.
**Note 2:** In .yml, strings containing `:`, `{`, `}`, `[`, `]`, `,`, `&`, `*`, `#`, `?`, `|`, `-`, `<`, `>`, `=`, `!`, `%`, `@`, `` ` `` must be quoted.
If you want to map querystrings to the event object, you can use the `$input.params('hub.challenge')` syntax from API Gateway, as follows:
```yml
functions:
create:
handler: posts.create
events:
- http:
method: get
path: whatever
integration: lambda
request:
template:
application/json: '{ "foo" : "$input.params(''bar'')" }'
```
**Note:** Notice when using single-quoted strings, any single quote `'` inside its contents must be doubled (`''`) to escape it.
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
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):
```yml
functions:
create:
handler: posts.create
events:
- http:
method: get
path: whatever
integration: lambda
request:
passThrough: NEVER
```
There are 3 available options:
|Value | Passed Through When | Rejected When |
|----------------- | --------------------------------------------- | ----------------------------------------------------------------------- |
|NEVER | Never | No templates defined or Content-Type does not match a defined template |
|WHEN_NO_MATCH | Content-Type does not match defined template | Never |
|WHEN_NO_TEMPLATES | No templates were defined | One or more templates defined, but Content-Type does not match |
See the [api gateway documentation](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#integration-passthrough-behaviors) for detailed descriptions of these options.
**Notes:**
- 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
Serverless lets you setup custom headers and a response template for your `http` event.
#### Custom Response Headers
Here's an example which shows you how you can setup a custom response header:
```yml
functions:
create:
handler: posts.create
events:
- http:
method: get
path: whatever
integration: lambda
response:
headers:
Content-Type: integration.response.header.Content-Type
Cache-Control: "'max-age=120'"
```
**Note:** You're able to use the [integration response variables](http://docs.aws.amazon.com/apigateway/latest/developerguide/request-response-data-mappings.html#mapping-response-parameters)
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).
### 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:
```yml
functions:
create:
handler: posts.create
events:
- http:
method: get
path: whatever
integration: lambda
response:
headers:
Content-Type: "'text/html'"
template: $input.path('$')
```
**Note:** The template is defined as plain text here. However you can also reference an external file with the help of
the `${file(templatefile)}` syntax.
### Status codes
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.
#### Available Status Codes
| Status Code | Meaning |
| --- | --- |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 422 | Unprocessable Entity |
| 500 | Internal Server Error |
| 502 | Bad Gateway |
| 504 | Gateway Timeout |
#### 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!`.
Here's an example which shows you how you can raise a 404 HTTP status from within your lambda function.
```javascript
module.exports.hello = (event, context, callback) => {
callback(new Error('[404] Not found'));
}
```
#### 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.
If you specify a status code with a pattern of '' that will become the default response code. See below on how to change the default to 201 for post requests.
If you omit any default status code. A standard default 200 status code will be generated for you.
```yml
functions:
create:
handler: posts.create
events:
- http:
method: post
path: whatever
integration: lambda
response:
headers:
Content-Type: "'text/html'"
template: $input.path('$')
statusCodes:
201:
pattern: '' # Default response method
409:
pattern: '.*"statusCode":409,.*' # JSON response
template: $input.path("$.errorMessage") # JSON return object
headers:
Content-Type: "'application/json+hal'"
```
You can also create varying response templates for each code and content type by creating an object with the key as the content type
```yml
functions:
create:
handler: posts.create
events:
- http:
method: post
path: whatever
integration: lambda
response:
headers:
Content-Type: "'text/html'"
template: $input.path('$')
statusCodes:
201:
pattern: '' # Default response method
409:
pattern: '.*"statusCode":409,.*' # JSON response
template:
application/json: $input.path("$.errorMessage") # JSON return object
application/xml: $input.path("$.body.errorMessage") # XML return object
headers:
Content-Type: "'application/json+hal'"
```
## Enabling CORS with the Lambda Integration Method
```yml
functions:
hello:
handler: handler.hello
events:
- http:
path: user/create
method: get
integration: lambda
cors: true
```
You can equally set your own attributes:
```yml
functions:
hello:
handler: handler.hello
events:
- http:
path: user/create
method: get
integration: lambda
cors:
origins:
- '*'
headers:
- Content-Type
- X-Amz-Date
- Authorization
- X-Api-Key
- X-Amz-Security-Token
```
This example is the default setting and is exactly the same as the previous example. The `Access-Control-Allow-Methods` header is set automatically, based on the endpoints specified in your service configuration with CORS enabled.
**Note:** If you are using the default lambda proxy integration, remember to include `Access-Control-Allow-Origin` in your returned headers object otherwise CORS will fail.
```
module.exports.hello = (event, context, callback) => {
return callback(null, {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*'
},
body: 'Hello World!'
});
}
```
## 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`:
```yml
service: service-name
provider: aws
functions:
...
resources:
Resources:
ProxyResource:
Type: AWS::ApiGateway::Resource
Properties:
ParentId:
Fn::GetAtt:
- ApiGatewayRestApi # our default Rest API logical ID
- RootResourceId
PathPart: serverless # the endpoint in your API that is set as proxy
RestApiId:
Ref: ApiGatewayRestApi
ProxyMethod:
Type: AWS::ApiGateway::Method
Properties:
ResourceId:
Ref: ProxyResource
RestApiId:
Ref: ApiGatewayRestApi
HttpMethod: GET # the method of your proxy. Is it GET or POST or ... ?
MethodResponses:
- StatusCode: 200
Integration:
IntegrationHttpMethod: POST
Type: HTTP
Uri: http://serverless.com # the URL you want to set a proxy to
IntegrationResponses:
- StatusCode: 200
```
There's a lot going on in these two templates, but all you need to know to set up a simple proxy is setting the method &
endpoint of your proxy, and the URI you want to set a proxy to.
Now that you have these two CloudFormation templates 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 a proxy on your Rest API.

View File

@ -0,0 +1,71 @@
<!--
title: Serverless Framework - AWS Lambda Events - IoT
menuText: IoT
menuOrder: 7
description: Setting up AWS IoT 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/iot)
<!-- DOCS-SITE-LINK:END -->
# IoT
## Simple event definition
This will enable your Lambda function to be called by an AWS IoT rule.
```yml
functions:
myIoT:
handler: myIoT.handler
events:
- iot:
sql: "SELECT * FROM 'some_topic'"
```
## Enabling / Disabling
**Note:** `iot` events are enabled by default.
This will create and attach a disabled `iot` event for the `myIoT` function.
```yml
functions:
myIoT:
handler: myIoT.handler
events:
- iot:
sql: "SELECT * FROM 'some_topic'"
enabled: false
```
## Specify Name and Description
Name and Description can be specified with the help of the `name` and `description` properties.
```yml
functions:
myIoT:
handler: myIoT.handler
events:
- iot:
name: "myIotEvent"
sql: "SELECT * FROM 'some_topic'"
description: "My IoT Event Description"
```
## Specify SQL Versions
[SQL Versions](http://docs.aws.amazon.com/iot/latest/developerguide/iot-rule-sql-version.html) can be specified for an `iot` event. However the `sqlVersion` is not a required property.
```yml
functions:
myIoT:
handler: myIoT.handler
events:
- iot:
sql: "SELECT * FROM 'some_topic'"
sqlVersion: "beta"
```

View File

@ -0,0 +1,75 @@
<!--
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](../guide/variables.md) and add dynamic elements to the bucket name.
```yaml
functions:
resize:
handler: resize.handler
events:
- s3: photos
```
## Setting the specific trigger event
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.
```yaml
functions:
users:
handler: users.handler
events:
- s3:
bucket: photos
event: s3:ObjectRemoved:*
```
## Setting filter rules
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.
```yaml
functions:
users:
handler: users.handler
events:
- s3:
bucket: photos
event: s3:ObjectCreated:*
rules:
- prefix: uploads/
- suffix: .jpg
```
## Triggering separate functions from the same bucket
You're able to repeat the S3 event configuration in the same or separate functions so one bucket can call these functions. One caveat though is that you can't repeat the same configuration in both functions, e.g. the event type has to be different.
The following example will work:
```yaml
functions:
users:
handler: users.handler
events:
- s3:
bucket: photos
event: s3:ObjectCreated:*
- s3:
bucket: photos
event: s3:ObjectRemoved:*
```

View File

@ -0,0 +1,62 @@
<!--
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.
```yaml
functions:
crawl:
handler: crawl
events:
- schedule: rate(2 hours)
- schedule: cron(0 12 * * ? *)
```
## Enabling / Disabling
**Note:** `schedule` events are enabled by default.
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.
```yaml
functions:
aggregate:
handler: statistics.handler
events:
- schedule:
rate: rate(10 minutes)
enabled: false
input:
key1: value1
key2: value2
stageParams:
stage: dev
- schedule:
rate: cron(0 12 * * ? *)
enabled: false
inputPath: '$.stageVariables'
```
## Specify Name and Description
Name and Description can be specified for a schedule event. These are not required properties.
```yaml
events:
- schedule:
name: your-scheduled-rate-event-name
description: 'your scheduled rate event description'
rate: rate(2 hours)
```

View File

@ -0,0 +1,69 @@
<!--
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.
```yml
functions:
dispatcher:
handler: dispatcher.dispatch
events:
- sns: dispatch
```
You're also able to add the same SNS topic to multiple functions:
```yml
functions:
dispatcher:
handler: dispatcher.dispatch
events:
- sns: dispatch
dispatcher2:
handler: dispatcher2.dispatch
events:
- sns: dispatch
```
This will run both functions for a message sent to the dispatch topic.
## Creating the permission for a pre-existing topic
If you want to run a function from a preexisting SNS topic you need to connect the topic to a Lambda function yourself. By defining a topic arn inside of the SNS topic we're able to set up the Lambda Permission so SNS is allowed to call this function.
```yml
functions:
dispatcher:
handler: dispatcher.dispatch
events:
- sns: arn:xxx
```
Just make sure your function is already subscribed to the topic, as there's no way to add subscriptions to pre-existing topics in CF. The framework will just give permission to SNS to invoke the function.
## Setting a display name
This event definition ensures that the `aggregator` function get's called every time a message is sent to the
`aggregate` topic. `Data aggregation pipeline` will be shown in the AWS console so that the user can understand what the
SNS topic is used for.
```yml
functions:
aggregator:
handler: aggregator.handler
events:
- sns:
topicName: aggregate
displayName: Data aggregation pipeline
```

View File

@ -0,0 +1,44 @@
<!--
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).
**Note:** The `stream` event will hook up your existing streams to a Lambda function. Serverless won't create a new stream for you.
```yml
functions:
compute:
handler: handler.compute
events:
- stream: arn:aws:dynamodb:region:XXXXXX:table/foo/stream/1970-01-01T00:00:00.000
```
## Setting the BatchSize and StartingPosition
This configuration sets up a disabled Kinesis stream event for the `preprocess` function which has a batch size of `100`. The starting position is
`LATEST`.
**Note:** The `stream` event will hook up your existing streams to a Lambda function. Serverless won't create a new stream for you.
```yml
functions:
preprocess:
handler: handler.preprocess
events:
- stream:
arn: arn:aws:kinesis:region:XXXXXX:stream/foo
batchSize: 100
startingPosition: LATEST
enabled: false
```

View File

@ -0,0 +1,31 @@
<!--
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
Have an example? Submit a PR or [open an issue](https://github.com/serverless/examples/issues). ⚡️
| Example | Runtime |
|:--------------------------- |:-----|
| [Aws Auth0 Api Gateway](https://github.com/serverless/examples/tree/master/aws-node-auth0-custom-authorizers-api) <br/> Demonstration of protecting API gateway endpoints with auth0 | nodeJS |
| [Env Variables Encrypted In A File](https://github.com/serverless/examples/tree/master/aws-node-env-variables-encrypted-in-a-file) <br/> Serverless example managing secrets in an encrypted file | nodeJS |
| [Serverless Node Env Variables](https://github.com/serverless/examples/tree/master/aws-node-env-variables) <br/> This example demonstrates how to use environment variables for AWS Lambdas. | nodeJS |
| [Fetch File And Store In S3](https://github.com/serverless/examples/tree/master/aws-node-fetch-file-and-store-in-s3) <br/> Fetch an image from remote source (URL) and then upload the image to a S3 bucket. | nodeJS |
| [Function Compiled With Babel](https://github.com/serverless/examples/tree/master/aws-node-function-compiled-with-babel) <br/> Demonstrating how to compile all your code with Babel | nodeJS |
| [Serverless Rest With Dynamodb](https://github.com/serverless/examples/tree/master/aws-node-rest-api-with-dynamodb) <br/> Serverless CRUD service exposing a REST HTTP interface | nodeJS |
| [Serverless Aws Cron Job Example](https://github.com/serverless/examples/tree/master/aws-node-scheduled-cron) <br/> Example of creating a function that runs as a cron job using the serverless `schedule` event | nodeJS |
| [Aws Node Serve Dynamic Html Via Http Endpoint](https://github.com/serverless/examples/tree/master/aws-node-serve-dynamic-html-via-http-endpoint) <br/> Hookup an AWS API Gateway endpoint to a Lambda function to render HTML on a `GET` request | nodeJS |
| [Aws Node Serve Dynamic Html Via Http Endpoint](https://github.com/serverless/examples/tree/master/aws-node-simple-http-endpoint) <br/> Example demonstrates how to setup a simple HTTP GET endpoint | nodeJS |
| [Single Page App Via Cloudfront](https://github.com/serverless/examples/tree/master/aws-node-single-page-app-via-cloudfront) <br/> Demonstrating how to deploy a Single Page Application with Serverless | nodeJS |
| [Serverless Single Page App Plugin](https://github.com/serverless/examples/tree/master/aws-node-single-page-app-via-cloudfront/serverless-single-page-app-plugin) <br/> A plugin to simplify deploying Single Page Application using S3 and CloudFront | nodeJS |
| [Serverless Data Pipeline](https://github.com/serverless/examples/tree/master/aws-node-text-analysis-via-sns-post-processing) <br/> Example demonstrates how to setup a simple data processing pipeline | nodeJS |
| [Aws Python Simple Http Endpoint](https://github.com/serverless/examples/tree/master/aws-python-simple-http-endpoint) <br/> Example demonstrates how to setup a simple HTTP GET endpoint with python | python |
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,22 @@
<!--
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 Serverless Example 🌍
Welcome to the Hello World example.
Pick your language of choice:
* [JavaScript](./node)
* [Python](./python)
* [csharp](./csharp)
[View all examples](https://www.serverless.com/framework/docs/providers/aws/examples/)

View File

@ -0,0 +1,3 @@
using Amazon.Lambda.Core;
[assembly:LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

View File

@ -0,0 +1,36 @@
using System;
namespace AwsDotnetCsharp
{
public class Handler
{
public Response Hello(Request request)
{
return new Response("Go Serverless v1.0! Your function executed successfully!", request);
}
}
public class Response
{
public string Message {get; set;}
public Request Request {get; set;}
public Response(string message, Request request){
Message = message;
Request = request;
}
}
public class Request
{
public string Key1 {get; set;}
public string Key2 {get; set;}
public string Key3 {get; set;}
public Request(string key1, string key2, string key3){
Key1 = key1;
Key2 = key2;
Key3 = key3;
}
}
}

View File

@ -0,0 +1,52 @@
<!--
title: Hello World C# Example
menuText: Hello World C# Example
description: Create a C# 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/csharp/)
<!-- DOCS-SITE-LINK:END -->
# Hello World C# Example
Make sure `serverless` is installed. [See installation guide](../../../guide/installation.md).
## 1. Create a service
`serverless create --template aws-csharp --path myService` or `sls create --template aws-csharp --path myService`, where 'myService' is a new folder to be created with template service files. Change directories into this new folder.
## 2. Build using .NET CLI tools and create zip package
```
# Linux or OSX
./build.sh
```
```
# Windows PowerShell
./build.ps1
```
## 3. Deploy
`serverless deploy` or `sls deploy`. `sls` is shorthand for the Serverless CLI command
## 4. Invoke deployed function
`serverless invoke --function hello` or `serverless invoke -f hello`
`-f` is shorthand for `--function`
In your terminal window you should see the response from AWS Lambda
```bash
{
"Message": "Go Serverless v1.0! Your function executed successfully!",
"Request": {
"Key1": null,
"Key2": null,
"Key3": null
}
}
```
Congrats you have just deployed and run your Hello World function!

View File

@ -0,0 +1,33 @@
{
"version": "1.0.0-*",
"buildOptions": {
"outputName": "CsharpHandlers"
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
},
"Newtonsoft.Json": "9.0.1",
"Amazon.Lambda.Core": "1.0.0*",
"Amazon.Lambda.Serialization.Json": "1.0.0",
"Amazon.Lambda.Tools" : {
"type" :"build",
"version":"0.9.0-preview1"
}
},
"tools": {
"Amazon.Lambda.Tools" : "0.9.0-preview1"
},
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50"
}
}
}

View File

@ -0,0 +1,84 @@
# Welcome to Serverless!
#
# This file is the main config file for your service.
# It's very minimal at this point and uses default values.
# You can always add more config options for more control.
# We've included some commented out config examples here.
# Just uncomment any of them to get that config option.
#
# For full config options, check the docs:
# docs.serverless.com
#
# Happy Coding!
service: aws-csharp # NOTE: update this with your service name
# You can pin your service to only deploy with a specific Serverless version
# Check out our docs for more details
# frameworkVersion: "=X.X.X"
provider:
name: aws
runtime: dotnetcore1.0
# you can overwrite defaults here
# stage: dev
# region: us-east-1
# you can add statements to the Lambda function's IAM Role here
# 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"
# you can define service wide environment variables here
# environment:
# variable1: value1
# you can add packaging information here
package:
artifact: bin/release/netcoreapp1.0/publish/deploy-package.zip
# exclude:
# - exclude-me.js
# - exclude-me-dir/**
functions:
hello:
handler: CsharpHandlers::AwsDotnetCsharp.Handler::Hello
# The following are a few example events you can configure
# NOTE: Please make sure to change your handler code to work with those events
# Check the event documentation for details
# events:
# - http:
# path: users/create
# method: get
# - s3: ${env:BUCKET}
# - schedule: rate(10 minutes)
# - sns: greeter-topic
# - stream: arn:aws:dynamodb:region:XXXXXX:table/foo/stream/1970-01-01T00:00:00.000
# Define function environment variables here
# environment:
# variable2: value2
# you can add CloudFormation resource templates here
#resources:
# Resources:
# NewResource:
# Type: AWS::S3::Bucket
# Properties:
# BucketName: my-new-bucket
# Outputs:
# NewOutput:
# Description: "Description for the output"
# Value: "Some output value"

View File

@ -0,0 +1,36 @@
<!--
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. Create a service
`serverless create --template aws-nodejs --path myService` or `sls create --template aws-nodejs --path myService`, where 'myService' is a new folder to be created with template service files. Change directories into this new folder.
## 2. Deploy
`serverless deploy` or `sls deploy`. `sls` is shorthand for the Serverless CLI command
## 3. Invoke deployed function
`serverless invoke --function hello` or `serverless invoke -f hello`
`-f` is shorthand for `--function`
In your terminal window you should see the response from AWS Lambda
```bash
{
"statusCode": 200,
"body": "{\"message\":\"Go Serverless v1.0! Your function executed successfully!\",\"input\":{}}"
}
```
Congrats you have just deployed and run your Hello World function!

View File

@ -0,0 +1,11 @@
'use strict';
// Your function handler
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,10 @@
# Hello World for AWS Lambda
service: hello-world # Service Name
provider:
name: aws
runtime: nodejs4.3
functions:
helloWorld:
handler: handler.helloWorldHandler

View File

@ -0,0 +1,36 @@
<!--
title: Hello World Python Example
menuText: Hello World Python Example
description: Create a Python 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/python/)
<!-- DOCS-SITE-LINK:END -->
# Hello World Python Example
Make sure `serverless` is installed. [See installation guide](../../../guide/installation.md).
## 1. Create a service
`serverless create --template aws-python --path myService` or `sls create --template aws-python --path myService`, where 'myService' is a new folder to be created with template service files. Change directories into this new folder.
## 2. Deploy
`serverless deploy` or `sls deploy`. `sls` is shorthand for the serverless CLI command
## 3. Invoke deployed function
`serverless invoke --function hello` or `serverless invoke -f hello`
`-f` is shorthand for `--function`
In your terminal window you should see the response from AWS Lambda
```bash
{
"statusCode": 200,
"body": "{\"message\":\"Go Serverless v1.0! Your function executed successfully!\",\"input\":{}}"
}
```
Congrats you have just deployed and ran your Hello World function!

View File

@ -0,0 +1,6 @@
def helloWorldHandler(event, context):
message = {
'message': 'Hello World'
}
return message

View File

@ -0,0 +1,10 @@
# Hello World for AWS Lambda
service: hello-world # Service Name
provider:
name: aws
runtime: python2.7
functions:
helloWorld:
handler: handler.helloWorldHandler

View File

@ -0,0 +1,19 @@
<!--
title: Serverless - Apache OpenWhisk
menuText: OpenWhisk
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 Apache OpenWhisk Guide
Welcome to the Serverless Apache OpenWhisk Guide!
Get started with the **[Introduction to the framework](./intro.md)**
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)
**Note:** Before continuing [Apache OpenWhisk user credentials](./credentials.md) are required for using the CLI.

View File

@ -0,0 +1,138 @@
<!--
title: Serverless Framework - Apache OpenWhisk Guide - Credentials
menuText: Credentials
menuOrder: 3
description: How to set up the Serverless Framework with your Apache OpenWhisk 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 account credentials for your OpenWhisk provider so that it can create and manage resources on your behalf.
OpenWhisk is an open-source serverless platform. This means you can either choose to run the platform yourself or choose to use a hosted provider's instance.
Here we'll provide setup instructions for both options, just pick the one that you're using.
## Register with OpenWhisk platform (IBM Bluemix)
IBM's Bluemix cloud platform provides a hosted serverless solution based upon Apache OpenWhisk.
Here's how to get started…
- Sign up for a free account @ [https://bluemix.net](https://console.ng.bluemix.net/registration/)
IBM Bluemix comes with a [free trial](https://www.ibm.com/cloud-computing/bluemix/pricing?cm_mc_uid=22424350960514851832143&cm_mc_sid_50200000=1485183214) that doesn't need credit card details for the first 30 days. Following the trial, developers have to enrol using a credit card but get a free tier for the platform and services.
**All IBM Bluemix users get access to the [Free Tier for OpenWhisk](https://console.ng.bluemix.net/openwhisk/learn/pricing). This includes 400,000 GB-seconds of serverless function compute time per month.**
Additional execution time is charged at $0.000017 per GB-second of execution, rounded to the nearest 100ms.
### Access Account Credentials
Once you have signed up for IBM Bluemix, we need to retrieve your account credentials. These are available on [the page](https://console.ng.bluemix.net/openwhisk/learn/cli) about installing the command-line tool from the [service homepage](https://console.ng.bluemix.net/openwhisk/).
The second point in the instructions contains a command-line which includes the platform endpoint and authentication keys.
```
wsk property set --apihost openwhisk.ng.bluemix.net --auth XXX:YYY
```
**Make a note of the `apihost` and `auth` command flag values.**
### (optional) Install command-line utility
The command-line utility is linked from [the previous page](https://console.ng.bluemix.net/openwhisk/learn/cli). Download and install the binary into a location in your [shell path](http://unix.stackexchange.com/questions/26047/how-to-correctly-add-a-path-to-path).
## Register with OpenWhisk platform (Self-Hosted)
Following the [Quick Start guide](https://github.com/openwhisk/openwhisk#quick-start) will let you run the platform locally using a Virtual Machine.
- Download and install [Vagrant](https://www.vagrantup.com/) for your platform.
- Run the following commands to retrieve, build and start an instance of the platform.
```
# Clone openwhisk
git clone --depth=1 https://github.com/openwhisk/openwhisk.git
# Change directory to tools/vagrant
cd openwhisk/tools/vagrant
# Run script to create vm and run hello action
./hello
```
This platform will now be running inside a virtual machine at the following IP address: `192.168.33.13`
### Access Account Credentials
The default environment has a guest account configured with the authentication key available here: https://github.com/openwhisk/openwhisk/blob/master/ansible/files/auth.guest
Use the `192.168.33.13` address as the `apihost` value needed below.
### (optional) Install command-line utility
Building OpenWhisk from a cloned repository will result in the generation of the command line interface in `openwhisk/bin/go-cli/`. The default executable in this location will run on the operating system and CPU architecture on which it was built.
Executables for other operating system, and CPU architectures are located in the following directories: `openwhisk/bin/go-cli/mac`, `openwhisk/bin/go-cli/linux`, `openwhisk/bin/go-cli/windows`.
Download and install the correct binary into a location in your [shell path](http://unix.stackexchange.com/questions/26047/how-to-correctly-add-a-path-to-path).
## Using Account Credentials
You can configure the Serverless Framework to use your OpenWhisk credentials in 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 Framework:
```bash
export OW_AUTH=<your-key-here>
export OW_APIHOST=<your-api-host>
# OW_AUTH and OW_APIHOST are now available for serverless to use
serverless deploy
```
#### Using Configuration File
For a more permanent solution you can also set up credentials through a configuration file. Here are different methods you can use to do so.
##### Setup with `serverless config credentials` command
Serverless provides a convenient way to configure OpenWhisk credentials with the help of the `serverless config credentials` command.
Here's an example how you can configure the `default` AWS profile:
```bash
serverless config credentials --provider openwhisk --auth USER_AUTH_KEY --apihost PLATFORM_API_HOST
```
Take a look at the [`config` CLI reference](../cli-reference/config-credentials.md) for more information about credential configuration.
##### Setup with the `wsk` cli
If you have followed the instructions above to install the `wsk` command-line utility, run the following command to create the configuration file.
```bash
$ wsk property set --apihost PLATFORM_API_HOST --auth USER_AUTH_KEY
```
Credentials are stored in `~/.wskprops`, which you can edit directly if needed.
##### Edit file manually
The following configuration values should be stored in a new file (`.wskprops`) in your home directory. Replace the `PLATFORM_API_HOST` and `USER_AUTH_KEY` values will the credentials from above.
```
APIHOST=PLATFORM_API_HOST
AUTH=USER_AUTH_KEY
```

View File

@ -0,0 +1,63 @@
<!--
title: Serverless Framework - Apache OpenWhisk Guide - Deploying
menuText: Deploying
menuOrder: 8
description: How to deploy your Apache OpenWhisk 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 Apache OpenWhisk Functions, Triggers and Rules 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 Apache OpenWhisk.
### How It Works
The Serverless Framework translates all syntax in `serverless.yml` to [platform API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/openwhisk/openwhisk/master/core/controller/src/main/resources/whiskswagger.json) calls to provision your Actions, Triggers, Rules and APIs.
* Provider plugin parses `serverless.yml` configuration and translates to OpenWhisk resources.
* The code of your Functions is then packaged into zip files.
* Resources are deployed in the following order: *Functions, Function Sequences, API Routes, Triggers, Feeds, Rules.*
* Resources stages are deployed sequentially due to potential dependencies between the stages.
* Resources within a stage are deployed in parallel.
* Stages without any resources defined will be skipped.
### Tips
* Use this in your CI/CD systems, as it is the safest method of deployment.
* Apache OpenWhisk has a [maximum action artefact](https://github.com/openwhisk/openwhisk/blob/master/docs/reference.md#per-action-artifact-mb-fixed-48mb) size of 48MB. This might be an issue if you are using lots of NPM packages. JavaScript build tools like webpack can help to minify your code and save space.
Check out the [deploy command docs](../cli-reference/deploy.md) for all details and options.
## Deploy Function
This deployment method updates a single function. It performs the platform API call to deploy your package without the other resources. It is much faster than redeploying your whole service each time.
```bash
serverless deploy function --function myFunction
```
### How It Works
* The Framework packages up the targeted Apache OpenWhisk Action into a zip file.
* That zip file is deployed to Apache OpenWhisk using the platform API.
### Tips
* Use this when you are developing and want to test on Apache OpenWhisk 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,57 @@
<!--
title: Serverless Framework - Apache OpenWhisk Guide - Events
menuText: Events
menuOrder: 6
description: Configuring Apache OpenWhisk 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
Simply put, events are the things that trigger your functions to run.
If you are using Apache OpenWhisk as your provider, all `events` in the service are anything in Apache OpenWhisk that can trigger your Actions, like HTTP endpoints, message queues, database updates and cron-scheduled events.
[View the Apache OpenWhisk events section for a list of supported events](../events)
Upon deployment, the framework will set up the Triggers and Rules that correspond to that event and configure your `function` to listen to it.
## Configuration
Events belong to each Function and can be found in the `events` property in `serverless.yml`.
```yml
# 'functions' in serverless.yml
functions:
createUser: # Function name
handler: handler.createUser # Reference to file handler.js & exported function 'createUser'
events: # All events associated with this function
- http: GET /users/create
```
The `events` property is an array, because it is possible for functions to be triggered by multiple events, as shown
You can set multiple Events per Function, as long as that is supported by Apache OpenWhisk.
```yml
# 'functions' in serverless.yml
functions:
createUser: # Function name
handler: handler.users # Reference to file handler.js & exported function 'users'
events: # All events associated with this function
- http: GET /users/create
- http: POST /users/update
- trigger: "custom trigger"
```
## Types
The Serverless Framework supports all of the Apache OpenWhisk 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 Routes, run `serverless deploy`.

View File

@ -0,0 +1,97 @@
<!--
title: Serverless Framework - Apache OpenWhisk Guide - Functions
menuText: Functions
menuOrder: 5
description: How to configure Apache OpenWhisk 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 OpenWhisk as a provider, all *functions* inside the service are OpenWhisk Actions.
## Configuration
All of the OpenWhisk Actions in your serverless service can be found in `serverless.yml` under the `functions` property.
```yml
# serverless.yml
service: myService
provider:
name: openwhisk
runtime: nodejs:6 # optional, default is nodejs:default
memorySize: 512 # optional, default is 256
timeout: 30 # optional, default is 60
functions:
hello:
handler: handler.hello # required, handler set in Apache OpenWhisk
name: some_custom_name # optional, default is ${service}_${function}
runtime: nodejs # optional overwrite, default is provider runtime
memory: 512 # optional overwrite, default is 256
timeout: 10 # optional overwrite, default is 60
```
The `handler` property points to the file and module containing the code you want to run in your function.
```javascript
// handler.js
exports.handler = function(params) {}
```
You can add as many functions as you want within this property.
```yml
# serverless.yml
service: myService
provider:
name: openwhisk
functions:
functionOne:
handler: handler.functionOne
description: optional description for your Action
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: openwhisk
runtime: nodejs:6
memory: 512 # will be inherited by all functions
functions:
functionOne:
handler: handler.functionOne
```
Or you can specify properties at the function level.
```yml
# serverless.yml
service: myService
provider:
name: openwhisk
runtime: nodejs:6
functions:
functionOne:
handler: handler.functionOne
memory: 512 # function specific
```

View File

@ -0,0 +1,65 @@
<!--
title: Serverless Framework - Apache OpenWhisk Guide - Installing The Serverless Framework
menuText: Installation
menuOrder: 2
description: How to install the Serverless Framework and start using Apache OpenWhisk
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.
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.
```bash
npm install -g serverless
```
Once the installation process is done you can verify that Serverless is installed successfully by running the following command in your terminal:
```bash
serverless
```
To see which version of serverless you have installed run:
```bash
serverless --version
```
### Installing OpenWhisk Provider Plugin
Now we need to install the provider plugin to allow the framework to deploy services to the platform. This plugin is also [published](http://npmjs.com/package/serverless-openwhisk) on [npm](https://npmjs.org) and can installed using the same `npm install` command.
```
npm install -g serverless-openwhisk
```
*Due to an [outstanding issue](https://github.com/serverless/serverless/issues/2895) with provider plugins, the [OpenWhisk provider](https://github.com/serverless/serverless-openwhisk) must be installed as a global module.*
### Setting up OpenWhisk
To run serverless commands that interface with the OpenWhisk platform, you will need to setup your OpenWhisk account credentials on your machine.
[Follow these instructions on setting up OpenWhisk credentials](./credentials.md)

View File

@ -0,0 +1,77 @@
<!--
title: Serverless Framework - Apache OpenWhisk Guide - Introduction
menuText: Intro
menuOrder: 1
description: An introduction to using Apache OpenWhisk 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 serverless applications using Apache OpenWhisk. 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](#functions) and [Events](#events).
The Serverless Framework is different than other application frameworks because:
* It manages your code as well as your infrastructure
* It supports multiple languages (Node.js, Python, Java, and more)
## Core Concepts
Here are the Framework's main concepts and how they pertain to Apache OpenWhisk…
### Functions
A Function is an [Apache OpenWhisk Action](https://github.com/openwhisk/openwhisk/blob/master/docs/actions.md). 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 Apache OpenWhisk Action to execute is regarded by the Framework as an **Event**. Events are platform events on Apache OpenWhisk such as:
* *An API Gateway HTTP endpoint (e.g., for a REST API)*
* *A NoSQL database update (e.g., for a user profile)*
* *A scheduled timer (e.g., run every 5 minutes)*
* *A Kafka queue message (e.g., a message)*
* *A Webhook fires (e.g., Github project update)*
* *And more...*
When you define an event for your Apache OpenWhisk Action in the Serverless Framework, the Framework will automatically translate this into [Triggers and Rules](https://github.com/openwhisk/openwhisk/blob/master/docs/triggers_rules.md) needed for that event and configure your functions to listen to it.
### 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
usersDelete:
events:
- http: delete /users/delete
```
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,101 @@
<!--
title: Serverless Framework Guide - Apache OpenWhisk Guide - Packaging
menuText: Packaging
menuOrder: 11
description: How the Serverless Framework packages your Apache OpenWhisk 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 and include allows you to define globs that will be excluded / included from the resulting artifact. If you wish to
include files you can use a glob pattern prefixed with `!` such as `!re-include-me/**` in `exclude` or the dedicated `include` config.
Serverless will run the glob patterns in order.
At first it will apply the globs defined in `exclude`. After that it'll add all the globs from `include`. This way you can always re-include
previously excluded files and directories.
## Examples
Exclude all node_modules but then re-include a specific modules (in this case node-fetch) using `exclude` exclusively
``` yml
package:
exclude:
- node_modules/**
- '!node_modules/node-fetch/**'
```
Exclude all files but `handler.js` using `exclude` and `include`
``` yml
package:
exclude:
- src/**
include:
- src/function/handler.js
```
**Note:** Don't forget to use the correct glob syntax if you want to exclude directories
```
exclude:
- tmp/**
- .git/**
```
## Artifact
For complete control over the packaging process you can specify your own artifact zip file.
Serverless won't zip your service if this is configured and therefore `exclude` and `include` will be ignored. Either you use artifact or include / exclude.
The artifact option is especially useful in case your development environment allows you to generate a deployable artifact like Maven does for Java.
## Example
```yml
service: my-service
package:
exclude:
- tmp/**
- .git/**
include:
- some-file
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`, `include` or `artifact` config options as you can service wide. The `exclude` and `include` option will be merged with the service wide options to create one `exclude` and `include` config per function during packaging.
```yml
service: my-service
package:
individually: true
exclude:
- excluded-by-default.json
functions:
hello:
handler: handler.hello
package:
# We're including this file so it will be in the final package of this function only
include:
- excluded-by-default.json
world:
handler: handler.hello
package:
exclude:
- some-file.js
```

View File

@ -0,0 +1,318 @@
<!--
title: Serverless Framework - Apache OpenWhisk Guide - Plugins
menuText: Plugins
menuOrder: 13
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.
## 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
```
## Service local plugin
If you are working on a plugin or have a plugin that is just designed for one project you can add them to the `.serverless_plugins` directory at the root of your service, and in the `plugins` array in `serverless.yml`.
The plugin will be loaded based on being named `custom-serverless-plugin.js` or `custom-serverless-plugin\index.js` in the root of `.serverless_plugins` folder.
### 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 = this.serverless.getProvider('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,65 @@
<!--
title: Serverless Framework - Apache OpenWhisk Guide - Serverless.yml Reference
menuText: Serverless.yml
menuOrder: 15
description: A list of all available properties on serverless.yml for Apache OpenWhisk
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/serverless.yml)
<!-- DOCS-SITE-LINK:END -->
# Serverless.yml Reference
Here is a list of all available properties in `serverless.yml` when the provider is set to `openwhisk`.
```yml
# serverless.yml
service: myService
frameworkVersion: ">=1.0.0 <2.0.0"
provider:
name: openwhisk
runtime: nodejs:default
memory: 256 # Overwrite default memory size. Default is 512.
timeout: 10 # The default is 60
overwrite: true # Can we overwrite deployed functions? default is true
namespace: 'custom' # use custom namespace, defaults to '_'
functions:
usersCreate: # A Function
handler: users.create # The file and module for this specific function.
sequence: # Use sequences rather than handler to handle events. handler and sequence properties are mutually exclusive.
- function_a
- function_b
- function_c
memory: 256 # memorySize for this specific function.
timeout: 10 # Timeout for this specific function. Overrides the default set above.
runtime: nodejs:6
overwrite: false # Can we overwrite deployed function?
namespace: 'custom' # use custom namespace, defaults to '_'
events: # The Events that trigger this Function
# This creates an API Gateway HTTP endpoint which can be used to trigger this function. Learn more in "events/apigateway"
- http: METHOD /path/to/url
- trigger: my_trigger # bind function to trigger event
- trigger:
name: my_trigger
rule: rule_name
# The "Resources" your "Functions" use. This can be used to define custom Triggers and Rules which are bound to your Actions.
resources:
triggers:
my_trigger: # trigger with default parameter bound.
parameters:
hello: world
alarm_trigger: # trigger connected to event feed
parameters:
hello: world
feed: /whisk.system/alarms/alarm
feed_parameters:
cron: '*/8 * * * * *'
```

View File

@ -0,0 +1,174 @@
<!--
title: Serverless Framework - Apache OpenWhisk Guide - Services
menuText: Services
menuOrder: 4
description: How to manage and configure serverless services, which contain your Apache OpenWhisk functions, their 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/guide/services)
<!-- DOCS-SITE-LINK:END -->
# Services
A `service` is like a project. It's where you define your Apache OpenWhisk Functions, the `events` that trigger them and any `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
myService/
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.
## 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
# Create service with nodeJS template in the folder ./myService
serverless create --template openwhisk-nodejs --path myService
```
Here are the available runtimes for Apache OpenWhisk:
* openwhisk-nodejs
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`
### serverless.yml
Each `service` configuration is managed in the `serverless.yml` file. The main responsibilities of this file are:
- Declare a Serverless service
- Define one or more functions in the service
- Define the provider the service will be deployed to (and the runtime if provided)
- Define any custom plugins to be used
- Define events that trigger each function to execute (e.g. HTTP requests)
- 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: openwhisk
runtime: nodejs:6
memory: 512 # Overwrite the default memory size. Default is 256
functions:
usersCreate: # A Function
handler: users.create
events: # The Events that trigger this Function
- http: post /users/create
usersDelete: # A Function
handler: users.delete
events: # The Events that trigger this Function
- http: delete /users/delete
```
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
**Note:** This file is not created by default
Create this file and add event data so you can invoke your function with the data 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 into calls to the platform API to dynamically define those resources.
To deploy a service, use the `deploy` command:
```bash
serverless deploy
```
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 Apache OpenWhisk 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.
## Version Pinning
The Serverless framework is usually installed globally via `npm install -g serverless`. This way you have the Serverless CLI available for all your services.
Installing tools globally has the downside that the version can't be pinned inside package.json. This can lead to issues if you upgrade Serverless, but your colleagues or CI system don't. You can now use a new feature in your serverless.yml which is available only in the latest version without worrying that your CI system will deploy with an old version of Serverless.
### Pinning a Version
To configure version pinning define a `frameworkVersion` property in your serverless.yaml. Whenever you run a Serverless command from the CLI it checks if your current Serverless version is matching the `frameworkVersion` range. The CLI uses [Semantic Versioning](http://semver.org/) so you can pin it to an exact version or provide a range. In general we recommend to pin to an exact version to ensure everybody in your team has the exact same setup and no unexpected problems happen.
### Examples
#### Exact Version
```yml
# serverless.yml
frameworkVersion: "=1.0.3"
service: users
provider:
name: openwhisk
runtime: nodejs
memorySize: 512
```
#### Version Range
```yml
# serverless.yml
frameworkVersion: ">=1.0.0 <2.0.0"
service: users
provider:
name: openwhisk
runtime: nodejs
memorySize: 512
```

View File

@ -0,0 +1,108 @@
<!--
title: Serverless Framework - Apache OpenWhisk Guide - Testing
menuText: Testing
menuOrder: 9
description: Recommendations and best practices for testing Apache OpenWhisk 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
While the Serverless Architecture introduces a lot of simplicity when it comes to serving business logic, some of its characteristics present challenges for testing. They are:
* The Serverless Architecture is an integration of separate, distributed services, which must be tested both independently, and together.
* The Serverless Architecture is dependent on internet/cloud services, which are hard to emulate locally.
* The Serverless Architecture can feature event-driven, asynchronous workflows, which are hard to emulate entirely.
To get through these challenges, and to keep the [test pyramid](http://martinfowler.com/bliki/TestPyramid.html) in mind, keep the following principles in mind:
* Write your business logic so that it is separate from your FaaS provider (e.g., Apache OpenWhisk), to keep it provider-independent, reusable and more easily testable.
* When your business logic is written separately from the FaaS provider, you can write traditional Unit Tests to ensure it is working properly.
* Write Integration Tests to verify integrations with other services are working correctly.
## A Poor Example
Here is an example in Node.js of how to follow the practices above. The job this Function should perform is to save a user in a database and then send a welcome email:
```javascript
const db = require('db').connect();
const mailer = require('mailer');
module.exports.saveUser = (params) => {
return Promise((resolve, reject) => {
const user = {
email: params.email,
created_at: Date.now()
}
db.saveUser(user, function (err) {
if (err) {
reject(err);
} else {
mailer.sendWelcomeEmail(event.email);
resolve();
}
});
})
};
```
There are two main problems with this function:
* The business logic is not separate from the FaaS Provider. It's bounded to how Apache OpenWhisk passes incoming data (`params` object).
* Testing this function will rely on separate services. Specifically, running a database instance and a mail server.
## Writing Testable Apache OpenWhisk Functions
Let's refactor the above example to separate the business logic from the FaaS Provider.
```javascript
class Users {
constructor(db, mailer) {
this.db = db;
this.mailer = mailer;
}
save(email, callback) {
return new Promise((resolve, reject) => {
const user = {
email: email,
created_at: Date.now()
}
this.db.saveUser(user, function (err) {
if (err) {
reject(err);
} else {
this.mailer.sendWelcomeEmail(email);
resolve();
}
});
})
}
}
module.exports = Users;
```
```javascript
const db = require('db').connect();
const mailer = require('mailer');
const Users = require('users');
let users = new Users(db, mailer);
module.exports.saveUser = (params) => {
return users.save(params.email);
};
```
Now, the above class keeps business logic separate. Further, the code responsible for setting up dependencies, injecting them, calling business logic functions and interacting with Apache OpenWhisk is in its own file, which will be changed less often. This way, the business logic is not provider dependent, easier to re-use, and easier to test.
Further, this code doesn't require running any external services. Instead of a real `db` and `mailer` services, we can pass mocks and assert if `saveUser` and `sendWelcomeEmail` has been called with proper arguments.
Unit Tests can easily be written to cover the above class. An integration test can be added by invoking the function (`serverless invoke`) with fixture email address, check if user is actually saved to DB and check if email was received to see if everything is working together.

View File

@ -0,0 +1,213 @@
<!--
title: Serverless Variables
menuText: Variables
menuOrder: 10
description: How to use Serverless Variables to insert dynamic configuration info into your serverless.yml
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/variables)
<!-- DOCS-SITE-LINK:END -->
# 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
- Recursively reference properties of any type from the same `serverless.yml` file
- Recursively reference properties of any type from other YAML/JSON files
- Recursively nest variable references within each other for ultimate flexibility
- Combine multiple variable references to overwrite each other
**Note:** You can only use variables in `serverless.yml` property **values**, not property keys. So you can't use variables to generate dynamic logical IDs in the custom resources section for 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
provider: aws
custom:
globalSchedule: rate(10 minutes)
functions:
hello:
handler: handler.hello
events:
- schedule: ${self:custom.globalSchedule}
world:
handler: handler.world
events:
- schedule: ${self:custom.globalSchedule}
```
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.
## Referencing Environment Variables
To reference environment variables, use the `${env:SOME_VAR}` syntax in your `serverless.yml` configuration file.
```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 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
service: new-service
provider: openwhisk
custom: ${file(./myCustomFile.yml)} # You can reference the entire file
functions:
hello:
handler: handler.hello
events:
- schedule: ${file(./myCustomFile.yml):globalSchedule} # Or you can reference a specific property
world:
handler: handler.world
events:
- schedule: ${self:custom.globalSchedule} # This would also work in this case
```
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.
## Reference Variables in Javascript Files
To add dynamic data into your variables, reference javascript files by putting `${file(./myFile.js):someModule}` syntax in your `serverless.yml`. Here's an example:
```js
// myCustomFile.js
module.exports.hello = () => {
// Code that generates dynamic data
return 'rate (10 minutes)';
}
```
```yml
# serverless.yml
service: new-service
provider: openwhisk
functions:
hello:
handler: handler.hello
events:
- schedule: ${file(./myCustomFile.js):hello} # Reference a specific module
```
You can also return an object and reference a specific property. Just make sure you are returning a valid object and referencing a valid property:
```yml
# serverless.yml
service: new-service
provider: aws
functions:
scheduledFunction:
handler: handler.scheduledFunction
events:
- schedule: ${file(./myCustomFile.js):schedule.ten}
```
```js
// myCustomFile.js
module.exports.schedule = () => {
// Code that generates dynamic data
return {
ten: 'rate(10 minutes)',
twenty: 'rate(20 minutes)',
thirty: 'rate(30 minutes)'
};
}
```
## 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.
```yml
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.
## 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:
```yml
service: new-service
provider: aws
custom:
myFlexibleArn: ${env:${opt:stage}_arn}
functions:
hello:
handler: handler.hello
```
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:
name: aws
stage: dev
custom:
myStage: ${opt:stage, self:provider.stage}
functions:
hello:
handler: handler.hello
```
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`.
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.
## 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.
**Using the same `serverless.yml` file:** You can store your variables in `serverless.yml` if they don't contain sensitive data, and then reference them elsewhere in the file using `self:someProperty`. For more info, you can check the self reference section above.
**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.
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,68 @@
<!--
title: Serverless Framework Guide - Apache OpenWhisk - Workflow
menuText: Workflow
menuOrder: 14
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
Intro. Quick recommendations and tips for various processes.
### Development Workflow
1. Write your functions
2. Use `serverless deploy` only when you've made changes to `serverless.yml` and in CI/CD systems.
3. Use `serverless deploy function -f myFunction` to rapidly deploy changes when you are working on a specific Apache OpenWhisk Function.
4. Use `serverless invoke -f myFunction -l` to test your Apache OpenWhisk Functions on AWS.
5. Open up a separate tab in your console and stream logs in there via `serverless logs -f myFunction -t`.
6. Write tests to run locally.
### 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 openwhisk-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
```
##### Deploy Function
Use this to quickly overwrite your OpenWhisk Actions, allowing you to develop faster.
```
serverless deploy function -f [FUNCTION NAME]
```
##### Invoke Function
Invokes an OpenWhisk Action and returns logs.
```
serverless invoke function -f [FUNCTION 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]
```