客户端通过http访问 lambda 函数;
serverless实现客户端的 deploy
Vagrant--------------虚拟环境作成
VirtualBox-----------vagrant环境管理工具
AWS------------------API Gateway;Lambda;DynamoDB; AWS CLI(客户端的权限配置)
Serverless Framework----无服务应用开发的第三方framework
Node.js--------------构建 lambda 函数
Vagrant的虚拟环境建立,参照: Vagrant-环境搭建.
NodeJs环境建立,参照: NodeJs环境相关安装.
利用 Serverless Framework deploy应用时,需要aws的认证信息,可以利用Serverless Framework的配置命令来配置,也可以使用AWS-CLI进行配置。
在这里使用AWS-CLI进行配置,将来如果使用EB-CLI时,也就不用配置了。
参照: AWS-CLI.
[vagrant@localhost vagrant]$ pwd
/vagrant
[vagrant@localhost vagrant]$ sudo npm install -g serverless
[vagrant@localhost vagrant]$ sls -v
1.36.3
[vagrant@localhost vagrant]$ sls
Commands
* You can run commands with "serverless" or the shortcut "sls"
* Pass "--verbose" to this command to get in-depth plugin info
* Pass "--no-color" to disable CLI colors
* Pass "--help" after any <command> for contextual help
Framework
* Documentation: https://serverless.com/framework/docs/
config ........................ Configure Serverless
config credentials ............ Configures a new provider profile for the Serverless Framework
create ........................ Create new Serverless service
install ....................... Install a Serverless service from GitHub or a plugin from the Serverless registry
package ....................... Packages a Serverless service
deploy ........................ Deploy a Serverless service
deploy function ............... Deploy a single function from the service
deploy list ................... List deployed version of your Serverless Service
deploy list functions ......... List all the deployed functions and their versions
invoke ........................ Invoke a deployed function
invoke local .................. Invoke function locally
info .......................... Display information about the service
logs .......................... Output the logs of a deployed function
metrics ....................... Show metrics for a specific function
print ......................... Print your compiled and resolved config file
remove ........................ Remove Serverless service and all resources
rollback ...................... Rollback the Serverless service to a specific deployment
rollback function ............. Rollback the function to the previous version
slstats ....................... Enable or disable stats
plugin ........................ Plugin management for Serverless
plugin install ................ Install and add a plugin to your service
plugin uninstall .............. Uninstall and remove a plugin from your service
plugin list ................... Lists all available plugins
plugin search ................. Search for plugins
Plugins
AwsConfigCredentials, Config, Create, Deploy, Info, Install, Invoke, Logs, Metrics, Package, Plugin, PluginInstall, PluginList, PluginSearch, PluginUninstall, Print, Remove, Rollback, SlStats
[vagrant@localhost vagrant]$
使用 sls 的 create 命令生成样例应用
参照: AWS - Create.
[vagrant@localhost vagrant]$ sls create --template aws-nodejs --path sampleSls
Serverless: Generating boilerplate...
Serverless: Generating boilerplate in "/vagrant/sampleSls"
_______ __
| _ .-----.----.--.--.-----.----| .-----.-----.-----.
| |___| -__| _| | | -__| _| | -__|__ --|__ --|
|____ |_____|__| \___/|_____|__| |__|_____|_____|_____|
| | | The Serverless Application Framework
| | serverless.com, v1.36.3
-------'
Serverless: Successfully generated boilerplate for template: "aws-nodejs"
[vagrant@localhost vagrant]$ cd sampleSls
[vagrant@localhost sampleSls]$ ls -la
total 20
drwxrwxr-x. 2 vagrant vagrant 4096 Jan 28 03:41 .
drwxr-xr-x. 3 vagrant vagrant 4096 Jan 28 03:41 ..
-rw-r--r--. 1 vagrant vagrant 86 Jan 28 03:41 .gitignore
-rw-r--r--. 1 vagrant vagrant 414 Jan 28 03:41 handler.js
-rw-r--r--. 1 vagrant vagrant 2886 Jan 28 03:41 serverless.yml
可以看到,serverless.yml 自动生成。
看一下,缺省生成的文件内容
# 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: sampleSls # 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: nodejs8.10
# 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:
# include:
# - include-me.js
# - include-me-dir/**
# exclude:
# - exclude-me.js
# - exclude-me-dir/**
functions:
hello:
handler: 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
# - alexaSkill: amzn1.ask.skill.xx-xx-xx-xx
# - alexaSmartHome: amzn1.ask.skill.xx-xx-xx-xx
# - iot:
# sql: "SELECT * FROM 'some_topic'"
# - cloudwatchEvent:
# event:
# source:
# - "aws.ec2"
# detail-type:
# - "EC2 Instance State-change Notification"
# detail:
# state:
# - pending
# - cloudwatchLog: '/aws/lambda/hello'
# - cognitoUserPool:
# pool: MyUserPool
# trigger: PreSignUp
# 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"
其中可以自定义一些内容,event,function,resource,plugin等实现其他功能。
修改生成的区域设定(vi serverless.yml)
you can overwrite defaults here
# stage: dev
# region: us-east-1
stage: dev
region: ap-northeast-1
[vagrant@localhost vagrant]$ cd sampleSls
[vagrant@localhost sampleSls]$ sls deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
.....
Serverless: Stack create finished...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (387 B)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
...................
Serverless: Stack update finished...
Service Information
service: sampleSls
stage: dev
region: ap-northeast-1
stack: sampleSls-dev
api keys:
None
endpoints:
None
functions:
hello: sampleSls-dev-hello
layers:
None
可以看到,AWS自动生成了 CloudFormation 的 stack;sampleSls-dev
将stack文件上传到了S3
并且生成了函数 sampleSls-dev-hello
layers默认不生成,之后会做测试
[vagrant@localhost sampleSls]$ sls invoke -f helllo
{
"statusCode": 200,
"body": "{\"message\":\"Go Serverless v1.0! Your function executed successfully!\",\"input\":{}}"
}
[vagrant@localhost sampleSls]$ sls invoke --help
Plugin: Invoke
invoke ........................ Invoke a deployed function
invoke local .................. Invoke function locally
--function / -f (required) ......... The function name
--stage / -s ....................... Stage of the service
--region / -r ...................... Region of the service
--path / -p ........................ Path to JSON or YAML file holding input data
--type / -t ........................ Type of invocation
--log / -l ......................... Trigger logging data output
--data / -d ........................ Input data
--raw .............................. Flag to pass input data as a raw string
[vagrant@localhost sampleSls]$ sls invoke -f hello -d '{"key":"value"}'
{
"statusCode": 200,
"body": "{\"message\":\"Go Serverless v1.0! Your function executed successfully!\",\"input\":{\"key\":\"value\"}}"
}
也可以做成 json 文件,传递文件的形式
sls invoke -f sample-func -p event.json
[vagrant@localhost sampleSls]$ serverless remove -v
Serverless: Getting all objects in S3 bucket...
Serverless: Removing objects in S3 bucket...
Serverless: Removing Stack...
Serverless: Checking Stack removal progress...
CloudFormation - DELETE_IN_PROGRESS - AWS::CloudFormation::Stack - sampleSls-dev
CloudFormation - DELETE_SKIPPED - AWS::Lambda::Version - HelloLambdaVersioniho9mkkARwjhvPj06NIDsjejjddua3SO0ijT7IlM
CloudFormation - DELETE_IN_PROGRESS - AWS::Lambda::Function - HelloLambdaFunction
CloudFormation - DELETE_COMPLETE - AWS::Lambda::Function - HelloLambdaFunction
CloudFormation - DELETE_IN_PROGRESS - AWS::S3::Bucket - ServerlessDeploymentBucket
Serverless: Stack removal finished...
可以确认到,S3 bucket,CloudFormation Stack, Lambda 全部自动清除