Merge pull request #6403 from tbarlow12/guide-docs

Update Azure provider guide docs
This commit is contained in:
Philipp Muens 2019-09-16 09:52:38 +02:00 committed by GitHub
commit de3c1aeb4e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 404 additions and 571 deletions

View File

@ -29,7 +29,7 @@ If you have any questions, [search the forums](https://forum.serverless.com?utm_
<li><a href="./guide/quick-start.md">Quickstart</a></li>
<li><a href="./guide/installation.md">Installation</a></li>
<li><a href="./guide/credentials.md">Credentials</a></li>
<li><a href="./guide/services.md">Services</a></li>
<li><a href="./guide/function-apps.md">Function Apps</a></li>
<li><a href="./guide/functions.md">Functions</a></li>
<li><a href="./guide/events.md">Events</a></li>
<li><a href="./guide/deploying.md">Deploying</a></li>

View File

@ -16,6 +16,6 @@ Welcome to the Serverless Azure Functions 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](http://forum.serverless.com/)
If you have questions, join the [chat in gitter](https://gitter.im/serverless/serverless), [post over on the forums](http://forum.serverless.com/) or [post issues in the plugin repo](https://github.com/serverless/serverless-azure-functions/issues)
**Note:** Before continuing [Azure user credentials](./credentials.md) are required for using the CLI.

View File

@ -14,136 +14,95 @@ layout: Doc
# Azure - Credentials
The Serverless Framework needs access to account credentials for your Azure
account so that it can create and manage resources on your behalf.
The Serverless Framework needs access to Azure account credentials so that it can create and manage resources on your behalf.
Here we'll provide setup instructions for both options, just pick the one that
you're using.
## Create an Azure Account
---
Azure provides a hosted serverless computing solution based upon [Azure Functions](https://azure.microsoft.com/en-us/services/functions/).
## Pre-requisite
If you don't have an Azure account, get started by [signing up for a free account](https://azure.microsoft.com/en-us/free/), which includes \$200 of free credit
You'll need an Azure account to continue. Azure provides a hosted serverless computing solution based upon Azure Functions.
### Interactive Login
### Register with Azure
Upon running `$ serverless deploy`, you will automatically be prompted to login via your browser. Simply follow the instructions.
Here's how to get started…
### Authenticating with a Service Principal
- Sign up for a free account @ [azure.com](https://azure.microsoft.com/en-us/services/functions/)
For anything more than just experimenting with the plugin, it is recommended to use a [service principal](https://docs.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals). Below are steps on creating one:
Azure comes with a [free trial](https://azure.microsoft.com/en-us/free/) that
includes \$200 of free credit.
> Note: If you're using non-public Azure, such as national clouds or Azure Stack, be sure you set your Azure endpoint before logging in.
---
##### 1. Download the [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli) or use the [Azure Cloud Shell](https://docs.microsoft.com/en-us/azure/cloud-shell/overview)
## Interactive Login
##### 2. Login to Azure
> Note: Interactive login is **CURRENTLY NOT SUPPORTED** for free/trial Azure subscription, thus we recommend you stick with using the [Service Principal](#Using-Service-Principal) method
```sh
$ az login
```
Upon running `sls deploy`, if you don't already have service principal set in your
environment, you will automatically be prompted to login via your browser.
Simply follow the instructions.
This will give you a code and prompt you to visit [aka.ms/devicelogin](https://aka.ms/devicelogin).
> Note: Once you've authenticated, the credentials will be
> created and cached, allow them to be used for subsequent deployments.
> This prevents you from needing to manually login again.
##### 3. Get your subscription and tenant id
---
```sh
$ az account list
{
"cloudName": "AzureCloud",
"id": "c6e5c9a2-a4dd-4c05-81b4-6bed04f913ea",
"isDefault": true,
"name": "My Azure Subscription",
"registeredProviders": [],
"state": "Enabled",
"tenantId": "5bc10873-159c-4cbe-a7c9-bce05cb065c1",
"user": {
"name": "hello@example.com",
"type": "user"
}
}
```
## Using Service Principal
If you have multiple accounts, you can specify the "current" subscription for the session by running
Setting up service principal in your environment is an alternative to using interactive login.
```sh
$ az account set -s <subscriptionId>
```
You can do this very simply through the [Azure Portal](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal),
[PowerShell commandlets](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authenticate-service-principal),
or through the Azure CLI, as the instructions below illustrate.
##### 4. Create a service principal
> Note: If you're using non-public Azure, such as national clouds or Azure Stack, be sure
> you set your Azure endpoint before logging in.
```sh
$ az ad sp create-for-rbac
```
### Pre-requisite: Azure-CLI
This will yield something like:
1. Get the Azure CLI
```json
{
"appId": "19f7b7c1-fc4e-4c92-8aaf-21fffc93b4c9",
"displayName": "azure-cli-1970-01-01-00-00-00",
"name": "http://azure-cli-1970-01-01-00-00-00",
"password": "48d82644-00f2-4e64-80c5-65192f9bb2d0",
"tenant": "16f63fe8-17db-476f-b2b3-ba3752a03a33"
}
```
Follow the guide on [docs.microsoft.com](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli)
or use the [Azure Cloud Shell](https://docs.microsoft.com/en-us/azure/cloud-shell/overview).
Save this somewhere secure.
1. Login to Azure
##### 5. Set up environment variables
```sh
az login
```
Add the following environment variables to the shell session or CI/CD tool that will be used for deployment of your Azure Function App:
This will give you a code and prompt you to visit
[aka.ms/devicelogin](https://aka.ms/devicelogin). Provide the code and then
login with your Azure identity (this may happen automatically if you're
already logged in). You'll then be able to access your account via the CLI.
```sh
# bash
export azureSubId='<subscriptionId>' # From step 3
export azureServicePrincipalTenantId='<tenant>'
export azureServicePrincipalClientId='<name>'
export azureServicePrincipalPassword='<password>'
```
### Generate Service Principal
The rest of the process can be done 2 ways.
#### Easy way
Download this [script](https://github.com/serverless/serverless-azure-functions/blob/master/scripts/generate-service-principal.sh) and run it.
#### Hard way
1. Get your subscription and tenant id
```sh
$ az account list
{
"cloudName": "AzureCloud",
"id": "c6e5c9a2-a4dd-4c05-81b4-6bed04f913ea",
"isDefault": true,
"name": "My Azure Subscription",
"registeredProviders": [],
"state": "Enabled",
"tenantId": "5bc10873-159c-4cbe-a7c9-bce05cb065c1",
"user": {
"name": "hello@example.com",
"type": "user"
}
}
```
Save the ID of the subscription for a later step.
1. Create a service principal
```sh
$ az ad sp create-for-rbac
{
"appId": "19f7b7c1-fc4e-4c92-8aaf-21fffc93b4c9",
"displayName": "azure-cli-1970-01-01-00-00-00",
"name": "http://azure-cli-1970-01-01-00-00-00",
"password": "48d82644-00f2-4e64-80c5-65192f9bb2d0",
"tenant": "16f63fe8-17db-476f-b2b3-ba3752a03a33"
}
```
This will return an JSON object containing the other pieces that you need to
authenticate with Azure.
1. Set up environment variables
Finally, create environment variables for subscription ID,
tenant, name, and password.
```sh
# bash
export AZURE_SUBSCRIPTION_ID='<subscriptionId>'
export AZURE_TENANT_ID='<tenant>'
export AZURE_CLIENT_ID='<name>'
export AZURE_CLIENT_SECRET='<password>'
```
```powershell
# PowerShell
$env:AZURE_SUBSCRIPTION_ID='<subscriptionId>'
$env:AZURE_TENANT_ID='<tenant>'
$env:AZURE_CLIENT_ID='<name>'
$env:AZURE_CLIENT_SECRET='<password>'
```
```powershell
# PowerShell
$env:azureSubId='<subscriptionId>' # From step 3
$env:azureServicePrincipalTenantId='<tenant>'
$env:azureServicePrincipalClientId='<name>'
$env:azureServicePrincipalPassword='<password>'
```

View File

@ -14,72 +14,44 @@ layout: Doc
# Azure - Deploying
The Serverless Framework was designed to provision your Azure Functions
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 Azure Functions.
**Note:** You can specify a different configuration file name with the the `--config` option.
The `serverless-azure-functions` plugin can deploy a Function App as well as other resources (storage account, App Insights, API Management, etc.). Here is some guidance on using the `deploy` command.
### How It Works
The Serverless Framework translates all syntax in `serverless.yml` to an Azure
Resource Manager Template and Azure Function project.
The Serverless Framework translates all syntax in `serverless.yml` to an [Azure Resource Manager Template](https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-authoring-templates) and [Azure function bindings](https://docs.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings)
- Provider plugin parses `serverless.yml` configuration and translates to Azure resources.
- The code of your Functions is then packaged into a directory and zipped.
- Resources are deployed in the following order: _ARM template, Functions_
### Tips
### Deployment Approach #1 - Upload Package to Function App
- Use this in your CI/CD systems, as it is the safest method of deployment.
> Note: Recommended for Function Apps running on Windows
Check out the [deploy command docs](../cli-reference/deploy.md) for all details and options.
Current default behavior. To set explicitly in `serverless.yml`, add this section:
## 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
```yaml
deploy:
runFromBlobUrl: false
```
### How It Works
### Deployment Approach #2 - Run from Package in Blob Storage
- The Framework packages up the targeted Azure Function into a zip file.
- That zip file is deployed to the Function App using the kudu zip API.
> Note: Not currently recommended for Function Apps running on Windows
To set in `serverless.yml`, add this section:
```yaml
deploy:
runFromBlobUrl: true
```
Visit the [docs](https://docs.microsoft.com/en-us/azure/azure-functions/run-functions-from-deployment-package#enabling-functions-to-run-from-a-package) for more detail on the two approaches to deployment.
### Rollback
By default, the `rollback` functionality is enabled. This allows for users to revert to a previous deployment should something go wrong with the current release. See our [rollback docs](../cli-reference/rollback.md) for more detail.
### Tips
- Use this when you are developing and want to test on Azure Functions 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.
## Deploying a package
This deployment option takes a deployment directory that has already been created
with `serverless package` and deploys it to the cloud provider. This allows you
to easier integrate CI / CD workflows with the Serverless Framework.
```bash
serverless deploy --package path-to-package
```
### How It Works
- The argument to the `--package` flag is a directory that has been previously packaged by Serverless (with `serverless package`).
- The deploy process bypasses the package step and uses the existing package to deploy and update Resources.

View File

@ -16,17 +16,11 @@ layout: Doc
Simply put, events are the things that trigger your functions to run.
If you are using Azure Functions as your provider, all `events` in the service
are anything in Azure Functions that can trigger your Functions, like HTTP
endpoints, message queues, blob updates, and cron-scheduled events. In Azure
Functions, events are called "Triggers" and are defined as a binding. You can
also set additional input and output bindings which make it easy to get data from
table storage or send message to queue services, for example.
If you are using Azure Functions as your provider, all `events` in the service are anything in Azure Functions that can trigger your Functions, like HTTP endpoints, message queues, blob updates, and cron-scheduled events. In Azure Functions, events are called "Triggers" and are defined as a binding. You can also set additional input and output bindings which make it easy to get data from table storage or send message to queue services, for example.
[View the Azure Functions 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.
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
@ -41,8 +35,7 @@ functions:
- http: true
```
The events property is an array, in this case, because I can also use it do
define my input and output bindings.
The events property is an array, in this case, because I can also use it do define my input and output bindings.
```yml
queuejs:
@ -59,9 +52,7 @@ queuejs:
## Types
The Serverless Framework supports all of the Azure Functions 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)
The Serverless Framework supports all of the Azure Functions 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

View File

@ -0,0 +1,179 @@
<!--
title: Serverless Framework - Azure Functions Guide - Function Apps
menuText: Function Apps
menuOrder: 4
description: How to manage and configure serverless function apps, which contain your Azure 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/azure/guide/function-apps)
<!-- DOCS-SITE-LINK:END -->
# Azure - Function Apps
A `function app` is like a project. It's where you define your Azure 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 `function app`.
## Organization
In the beginning of an application, many people use a single function app to define all of the Functions, Events and Resources for that project. This is what we recommend in the beginning.
```bash
myFunctionApp/
serverless.yml # Contains all functions and infrastructure resources
```
However, as your application grows, you can break it out into multiple function apps. A lot of people organize their function apps by workflows or data models, and group the functions related to those workflows and data models together in the function app.
```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 get started, you can simply use the `create` command to generate a new function app:
```bash
serverless create -t azure-nodejs --path <my-app>
```
## Contents
You'll see the following files in your working directory:
- `serverless.yml`
- `hello.js`
- `goodbye.js`
### serverless.yml
Each `function app` configuration is managed in the `serverless.yml` file. The main responsibilities of this file are:
- Declare a function app
- Define one or more functions in the function app
- Define the provider the function app 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 function app, the provider configuration and the first function inside the `functions` definition which points to the `handler.js` file. Any further function app configuration will be done in this file.
```yml
# serverless.yml
service: azfx-node-http
provider:
name: azure
location: West US
plugins:
- serverless-azure-functions
functions:
hello:
handler: hello.handler
events:
- http: true
x-azure-settings:
authLevel: anonymous
- http: true
x-azure-settings:
direction: out
name: res
goodbye:
handler: goodbye.handler
events:
- http: true
x-azure-settings:
authLevel: anonymous
- http: true
x-azure-settings:
direction: out
name: res
```
### hello.js and goodbye.js
The `hello/goodbye.js` files contains your function code. There are two functions defined to demonstrate the configuration for multiple functions. These two functions in particular take the name provided as input to HTTP request and respond with "Hello/Goodbye {name}". The function definitions in `serverless.yml` will point to this `hello/goodbye.js` files and the functions exported there.
## Deployment
When you deploy a function app, all of the Functions, and Events in your `serverless.yml` are translated into calls to the platform API to dynamically define those resources.
To deploy a function app, first `cd` into the relevant function app directory:
```bash
cd my-function-app
```
Then use the `deploy` command:
```bash
serverless deploy
```
Check out the [deployment guide](https://serverless.com/framework/docs/providers/azure/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 function app from your Azure Functions 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 function app is removed.
The removal process removes the entire resource group containing your function app with its ancillary resources.
## Version Pinning
The Serverless framework is usually installed globally via `npm i -g serverless`. This way you have the Serverless CLI available for all your function apps.
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"
```
#### Version Range
```yml
# serverless.yml
frameworkVersion: ">=1.0.0 <2.0.0"
```
## Installing Serverless in an existing function app
If you already have a Serverless function app, and would prefer to lock down the framework version using `package.json`, then you can install Serverless as follows:
```bash
# from within a function app
npm i serverless --save-dev
```

View File

@ -81,3 +81,33 @@ getFoo:
deleteFoo:
handler: handler.foo
```
```yml
#bar-functions-yml
getBar:
handler: handler.bar
deleteBar:
handler: handler.bar
```
Handlers can also be referenced by a file path relative to the root. If your directory structure were something like:
```yml
serverless.yml
src/
handlers/
foo.js # exported `handler` function
bar.js # exported `handler` function
```
Your `serverless.yml` would look something like:
```yml
# serverless.yml
---
functions:
foo:
handler: src/handlers/foo.handler
bar:
handler: src/handlers/bar.handler
```

View File

@ -16,12 +16,7 @@ layout: Doc
### 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.
Serverless is a [Node.js](https://nodejs.org) CLI tool so the first thing you need to do is to [install Node.js](https://nodejs.org/en/download/) on your machine.
**Note:** The Azure Functions Serverless Framework plugin requires Node v6.5.0
@ -34,23 +29,23 @@ out.
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.
Open up a terminal and type `npm i -g serverless` to install Serverless.
```bash
npm install -g serverless
npm i -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
sls
```
To see which version of serverless you have installed run:
```bash
serverless --version
sls --version
```
### Installing Azure Functions Provider Plugin
@ -63,7 +58,6 @@ npm i --save serverless-azure-functions
### Setting up Azure Functions
To run serverless commands that interface with the Azure platform, you will need
to setup your Azure subscription credentials on your machine.
To run serverless commands that interface with the Azure platform, you will need to set up your Azure subscription credentials on your machine.
[Follow these instructions on setting up Azure subscription credentials](./credentials.md)

View File

@ -14,16 +14,7 @@ layout: Doc
# Azure - Introduction
The Serverless Framework helps you develop and deploy serverless applications
using Azure Functions. 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)
The Serverless Framework helps you develop and deploy serverless applications using Azure Functions. It's a CLI that offers structure, automation and best practices for deployment of both code and infrstructure, allowing you to focus on building sophisticated, event-driven, serverless architectures, comprised of [Functions](#functions) and [Events](#events).
## Core Concepts
@ -31,23 +22,17 @@ Here are the Framework's main concepts and how they pertain to Azure Functions
### Functions
A Function is an [Azure Function](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference).
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:
A Function is an [Azure Function](https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference). 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.
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 Azure Function to execute is regarded by the Framework
as an **Event**. Events are platform events on Azure Functions such as:
Anything that triggers an Azure Function to execute is regarded by the Framework as an **Event**. Events are platform events on Azure Functions such as:
- _An HTTP Trigger (e.g., for a REST API)_
- _A scheduled timer (e.g., run every 5 minutes)_
@ -56,18 +41,11 @@ as an **Event**. Events are platform events on Azure Functions such as:
- _A Webhook fires (e.g., Github project update)_
- _And more..._
When you define an event for your Azure Function in the Serverless Framework, the
Framework will automatically translate this into
[bindings](https://docs.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings)
needed for that event and configure your functions to listen to it.
When you define an event for your Azure Function in the Serverless Framework, the Framework will automatically translate this into [bindings](https://docs.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings) needed for that event and configure your functions to listen to it.
### Services
### Function App
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 by default entitled `serverless.yml` (or
`serverless.json` or `serverless.js`). It looks like this:
A **Function App** 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 by default entitled `serverless.yml` (or `serverless.json` or `serverless.js`). It looks like this:
```yml
# serverless.yml
@ -93,14 +71,11 @@ functions: # Your "Functions"
route: /users/delete
```
When you deploy with the Framework by running `serverless deploy`, everything in
`serverless.yml` (or the file specified with the `--config` option) is deployed at once.
When you deploy with the Framework by running `serverless deploy`, everything in `serverless.yml` (or the file specified with the `--config` option) 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.
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

View File

@ -16,48 +16,29 @@ layout: Doc
## Package CLI Command
Using the Serverless CLI tool, you can package your project without deploying it
to Azure. This is best used with CI / CD workflows to ensure consistent
deployable artifacts.
Using the Serverless CLI tool, you can package your project without deploying it to Azure.
Running the following command will build and save all of the deployment artifacts
in the service's .serverless directory:
Running the following command will build and save all of the deployment artifacts in the `.serverless` directory:
```bash
serverless package
```
However, you can also use the --package option to add a destination path and
Serverless will store your deployment artifacts there (./my-artifacts in the
following case):
```bash
serverless package --package my-artifacts
sls package
```
## Package Configuration
Sometimes you might like to have more control over your function artifacts and
how they are packaged.
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.
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.
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.
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
Exclude all node_modules but then re-include a specific modules (in this case node-fetch) using `exclude` exclusively
```yml
package:
@ -87,13 +68,9 @@ exclude:
### 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.
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.
The artifact option is especially useful in case your development environment allows you to generate a deployable artifact like Maven does for Java.
### Example
@ -110,15 +87,9 @@ package:
### 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 or function wide packaging settings.
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 or function 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.
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
@ -140,8 +111,7 @@ functions:
- some-file.js
```
You can also select which functions to be packaged separately, and have the rest
use the service package by setting the `individually` flag at the function level:
You can also select which functions to be packaged separately, and have the rest use the service package by setting the `individually` flag at the function level:
```yml
service: my-service
@ -166,3 +136,43 @@ You can opt-out of automatic dev dependency exclusion by setting the `excludeDev
package:
excludeDevDependencies: false
```
### Pro Tips
##### `serverless-webpack` for Node.js applications
The `serverless-azure-functions` plugin plays nicely with the `serverless-webpack` plugin. This speeds up the packaging process and minimizes the size of the package quite a bit.
To enable this functionality, add `serverless-webpack` to the `plugins` section of `serverless.yml`:
```yaml
---
plugins:
- serverless-azure-functions
- serverless-webpack
```
Install the dependencies:
```bash
$ npm i serverless-webpack webpack webpack-cli --save
```
Add the following `webpack.config.js` to the root of your project:
```javascript
const path = require('path');
const slsw = require('serverless-webpack');
module.exports = {
entry: slsw.lib.entries,
target: 'node',
output: {
libraryTarget: 'commonjs2',
library: 'index',
path: path.resolve(__dirname, '.webpack'),
filename: '[name].js',
},
plugins: [],
};
```

View File

@ -14,29 +14,22 @@ layout: Doc
# Azure - 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.
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.
- [How to create serverless plugins - Part 1](https://serverless.com/blog/writing-serverless-plugins/)
- [How to create serverless plugins - Part 2](https://serverless.com/blog/writing-serverless-plugins-2/)
## 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
External Plugins are added on a per function app basis and are not applied globally.
Make sure you are in your function app's root directory, then install the
corresponding Plugin with the help of npm:
```
npm install --save custom-serverless-plugin
npm i --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.
We need to tell Serverless that we want to use the plugin inside our function app. We do this by adding the name of the Plugin to the `plugins` section in the `serverless.yml` file.
```yml
# serverless.yml file

View File

@ -1,217 +0,0 @@
<!--
title: Serverless Framework - Azure Functions Guide - Services
menuText: Services
menuOrder: 4
description: How to manage and configure serverless services, which contain your Azure 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/azure/guide/services)
<!-- DOCS-SITE-LINK:END -->
# Azure - Services
A `service` is like a project. It's where you define your Azure 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 get started, you can simply use the `create` command to generate a new service:
```bash
serverless create -t azure-nodejs --path <my-app>
```
> Alternatively, you can use the `install` command to create a new service, based on an existing GitHub boilerplate: `serverless install --url https://github.com/azure/boilerplate-azurefunctions --name my-app`
## 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: azfx-node-http
provider:
name: azure
location: West US
plugins:
- serverless-azure-functions
functions:
hello:
handler: handler.hello
events:
- http: true
x-azure-settings:
authLevel: anonymous
```
### 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
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, and Events in your
`serverless.yml` are translated into calls to the platform API to dynamically
define those resources.
To deploy a service, first `cd` into the relevant service directory:
```bash
cd my-service
```
Then use the `deploy` command:
```bash
serverless deploy
```
Check out the [deployment guide](https://serverless.com/framework/docs/providers/azure/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 Azure Functions 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"
```
#### Version Range
```yml
# serverless.yml
frameworkVersion: ">=1.0.0 <2.0.0"
```
## Installing Serverless in an existing service
If you already have a Serverless service, and would prefer to lock down the
framework version using `package.json`, then you can install Serverless as
follows:
```bash
# from within a service
npm install serverless --save-dev
```
### Invoking Serverless locally
To execute the locally installed Serverless executable you have to reference the
binary out of the node modules directory.
Example:
```
node ./node_modules/serverless/bin/serverless deploy
```

View File

@ -14,17 +14,13 @@ layout: Doc
# Azure - 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:
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 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:
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., Azure Functions), 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.
@ -32,9 +28,7 @@ following principles in mind:
## 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:
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();
@ -110,17 +104,8 @@ module.exports.saveUser = (context, req) => {
};
```
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 Azure Functions 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.
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 Azure Functions 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.
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.
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

@ -186,39 +186,23 @@ module.exports.schedule = () => {
## 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.
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(azure-resources.json)}
```
The corresponding resources which are defined inside the `azure-resources.json`
file will be resolved and loaded into the `Resources` section.
The corresponding resources which are defined inside the `azure-resources.json` file will be resolved and loaded into the `Resources` section.
## 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.
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 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 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.
**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.
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

@ -19,55 +19,42 @@ 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 Azure Functions Function.
2. Run function app locally by using `sls offline` and `npm start` (or `func host start`). See [quickstart](./quick-start).
3. Use `serverless deploy` to deploy your function app (preferrably in a CI/CD environment)
4. Use `serverless invoke -f myFunction` to test your Azure Functions.
5. Open up a separate tab in your console and stream logs in there via `serverless logs -f myFunction`.
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.
- Break your application/project into multiple Function Apps.
- Model your Function Apps around Data Models or Workflows.
- Keep the Functions and Resources in your Function Apps to a minimum.
## Cheat Sheet
A handy list of commands to use when developing with the Serverless Framework.
##### Create A Service:
##### Create A Function App:
Install the boilerplate application.
```bash
serverless install --url https://github.com/azure/boilerplate-azurefunctions --name my-app
sls create -t azure-nodejs -p my-app
```
##### Install A Service
This is a convenience method to install a pre-made Serverless Service locally by
downloading the GitHub repo and unzipping it.
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
##### Deploy
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.
Use this when you have made changes to your Function App
```
serverless deploy
```
##### Deploy Function
Use this to quickly overwrite your Azure Functions, allowing you to develop faster.
```
serverless deploy function -f [FUNCTION NAME]
sls deploy
```
##### Invoke Function
@ -75,14 +62,5 @@ serverless deploy function -f [FUNCTION NAME]
Invokes an Azure Function
```
serverless invoke function -f [FUNCTION NAME]
```
##### 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]
sls invoke function -f [FUNCTION NAME]
```