使用 sam 在本地调试 aws lambda 程序

3,361 阅读3分钟

假如每次修改了 lambda 程序, 都要打成 zip 包, 上传到 aws 后台看, 才能看到运行情况. 那这样效率太低了.

让人兴奋的是, 有这个工具, sam cli, 可以用它在本地调试 lambda 程序

Installation


前提

在本地用 sam cli 运行 serverless 程序必须安装和运行 docker. sam cli 用环境变量 DOCKER_HSOT 和 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