假如每次修改了 lambda 程序, 都要打成 zip 包, 上傳到 aws 後臺看, 才能看到運行情況. 那這樣效率太低了.
讓人興奮的是, 有這個工具, sam cli, 可以用它在本地調試 lambda 程序
Installation
前提
在本地用 sam cli 運行 serverless 程序必須安裝和運行 docker. sam cli 用環境變量 DOCKER_HSOT 和 docker 進程連接
- macOS: Docker for Mac
- Windows: Docker for Windows
- Linux: yum install docker
使用 pip 安裝 sam cli
在 aws 文檔估計沒人更新, 還是隻有 npm 安裝 sam cli 的說明. npm 安裝下來的是舊 sam cli.
所以這裡, 我推薦使用 sam cli 最新的版本, 也就是用 pip 安裝出來的版本
要求 python 2.7
pip install –user aws-sam-cli
檢查是否安裝成功
sam –version
SAM CLI, version 0.3.0
Usage
繼續沿用以上一篇文章 S3 事件觸發的例子, 如果沒有看過的, 建議先看 使用 aws lambda 開發無服務器程序
1. 代碼例子
from __future__ import print_function
import json
import urllib
import boto3
print('Loading function')
s3 = boto3.client('s3')
def lambda_handler(event, context):
# Get the object from the event and show its content type
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8'))
try:
response = s3.get_object(Bucket=bucket, Key=key)
print("CONTENT TYPE: " + response['ContentType'])
return response['ContentType']
except Exception as e:
print(e)
print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
raise e
2. 初始目錄

3. 建立測試用例
sam local generate-event s3 --region us-east-1 --bucket test4lambda --key lambda-test.txt > event.json
S3 的 bucket(test4lambda) 和 key(lambda-test.txt) 需要提前建好
生成如下用例
{
"Records": [
{
"eventVersion": "2.0",
"eventName": "ObjectCreated:Put",
"eventTime": "1970-01-01T00:00:00.000Z",
"userIdentity": {
"principalId": "EXAMPLE"
},
"eventSource": "aws:s3",
"requestParameters": {
"sourceIPAddress": "127.0.0.1"
},
"s3": {
"configurationId": "testConfigRule",
"object": {
"eTag": "0123456789abcdef0123456789abcdef",
"key": "lambda-test.txt",
"sequencer": "0A1B2C3D4E5F678901",
"size": 1024
},
"bucket": {
"ownerIdentity": {
"principalId": "EXAMPLE"
},
"name": "test4lambda",
"arn": "arn:aws:s3:::test4lambda"
},
"s3SchemaVersion": "1.0"
},
"responseElements": {
"x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH",
"x-amz-request-id": "EXAMPLE123456789"
},
"awsRegion": "us-east-1"
}
]
}
4. 編寫 yaml 配置文件
當然, 不需要手寫, 可以到 lambda 後臺導出.
4.1 導出函數

4.2 下載 AWS SAM 文件
4.3 得到的配置文件如下
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: >-
An Amazon S3 trigger that retrieves metadata for the object that has been
updated.
Resources:
myTest1:
Type: 'AWS::Serverless::Function'
Properties:
Handler: lambda_function.lambda_handler
Runtime: python2.7
CodeUri: .
Description: >-
An Amazon S3 trigger that retrieves metadata for the object that has
been updated.
MemorySize: 128
Timeout: 3
Role: 'arn:aws:iam::851829110870:role/service-role/lambdaTest'
Events:
BucketEvent1:
Type: S3
Properties:
Bucket:
Ref: Bucket1
Events:
- 's3:ObjectCreated:*'
Tags:
'lambda-console:blueprint': s3-get-object-python
Bucket1:
Type: 'AWS::S3::Bucket'
4.4 最終的三個文件如下:

運行
sam local invoke myTest1 -e event.json -t myTest1.yaml
竟然提示 “time out after 3 seconds”

解決方法: 在 myTest1.yaml 找到 Timeout 字段, 改成 30
再次運行, 成功輸出 “text/plain”, 也就是 python 代碼那句 print 語句的結果

結語
一個本地調試 lambda 的環境就這樣完成了. sam 還有很多功能, 更多學習, 可以執行以下兩個命令
➜ sam --help
Usage: sam [OPTIONS] COMMAND [ARGS]...
AWS Serverless Application Model (SAM) CLI
The AWS Serverless Application Model extends AWS CloudFormation to provide
a simplified way of defining the Amazon API Gateway APIs, AWS Lambda
functions, and Amazon DynamoDB tables needed by your serverless
application. You can find more in-depth guide about the SAM specification
here: https://github.com/awslabs/serverless-application-model.
Options:
--debug Turn on debug logging
--version Show the version and exit.
--help Show this message and exit.
Commands:
init Initialize a serverless application with a...
package Package an AWS SAM application. This is an alias for 'aws
cloudformation package'.
local Run your Serverless application locally for...
validate Validate an AWS SAM template.
deploy Deploy an AWS SAM application. This is an alias for 'aws
cloudformation deploy'.
➜ sam local generate-event --help
Usage: sam local generate-event [OPTIONS] COMMAND [ARGS]...
Generate an event
Options:
--help Show this message and exit.
Commands:
api Generates a sample Amazon API Gateway event
dynamodb Generates a sample Amazon DynamoDB event
kinesis Generates a sample Amazon Kinesis event
s3 Generates a sample Amazon S3 event
schedule Generates a sample scheduled event
sns Generates a sample Amazon SNS event
相關文章
SpringBoot2.X(三):使用SpringMVC+MyBatis+Thymeleaf開發web應用