AWS Serveless Application Model

AWS 无服务器应用程序模型 (AWS SAM) 是一个开源框架,可用于在 AWS 上构建无服务器应用程序。它包含用于定义无服务器应用程序的 AWS SAM 模板规范和用于构建、测试和部署无服务器应用程序的 AWS SAM 命令行界面 (AWS SAM CLI)

Posted by Jamie Zhang on Monday, June 10, 2019

AWS SAM - lambda demo

Demo User Case

User requirement:

dynamically get regional mobile app feature availability status,status data is kept in AWS dynamodb.

Projectcodes hierarchical structure presented as below

├── README.md                   -- This instructions file
├── event.json                  -- API Gateway Proxy Integration event payload
├── feature_availability        -- Source code for a lambda function
│   ├── __init__.py
│   ├── app.py                  -- Lambda function code
│   ├── requirements.txt        -- Lambda function code - dependencies list
├── template.yaml               -- SAM Template
└── tests                       -- Unit tests
    ├── __init__.py
    └── app_test.py

Business Flow

Prerequisites

AWS CLI already configured with Administrator permission Python 3 installed Docker installed

Setup process

Local development

Invoking function locally using a local sample payload

sam local invoke GetEntityConfigFunction --event event.json

Invoking function locally through local API Gateway

sam local start-api

If the previous command ran successfully you should now be able to hit the following local endpoint to invoke your function http://localhost:3000/ca

SAM CLI is used to emulate both Lambda and API Gateway locally and uses our template.yaml to understand how to bootstrap this environment (runtime, where the source code is, etc.) - The following excerpt is what the CLI will read in order to initialize an API and its routes

...
Events
    FeatureAvailability
        Type Api # More info about API Event Source httpsgithub.comawslabsserverless-application-modelblobmasterversions2016-10-31.md#api
        Properties
            Path {entity}
            Method get

Packaging and deployment

AWS Lambda Python runtime requires a flat folder with all dependencies including the application. SAM will use CodeUri property to know where to look up for both application and dependencies

...
GetEntityConfigFunction
    Type AWSServerlessFunction
    Properties
        CodeUri feature_availability
        ...

Firstly, we need a S3 bucket where we can upload our Lambda functions packaged as ZIP before we deploy anything - If you don’t have a S3 bucket to store code artifacts then this is a good time to create one

aws s3 mb s3BUCKET_NAME

Next, run the following command to package our Lambda function to S3

sam package 
    --output-template-file packaged.yaml 
    --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME

Next, the following command will create a Cloudformation Stack and deploy your SAM resources.

sam deploy 
    --template-file packaged.yaml 
    --stack-name feature-availability-getentityconfig-api 
    --capabilities CAPABILITY_IAM

See Serverless Application Model (SAM) HOWTO Guide for more details in how to get started.

After deployment is complete you can run the following command to retrieve the API Gateway Endpoint URL

aws cloudformation describe-stacks 
    --stack-name feature-availability-getentityconfig-api 
    --query 'Stacks[].Outputs[OutputKey==`GetEntityConfigAPI`]' 
    --output table

Fetch, tail, and filter Lambda function logs

To simplify troubleshooting, SAM CLI has a command called sam logs. sam logs lets you fetch logs generated by your Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug.

NOTE This command works for all AWS Lambda functions; not just the ones you deploy using SAM.

sam logs -n GetEntityConfigFunction --stack-name feature-availability-getentityconfig-api --tail

You can find more information and examples about filtering Lambda function logs in the SAM CLI Documentation.

Testing

Next, we install test dependencies and we run pytest against our tests folder to run our initial unit tests

pip install pytest pytest-mock --user
python -m pytest tests -v

Cleanup

In order to delete our Serverless Application recently deployed you can use the following AWS CLI Command

aws cloudformation delete-stack --stack-name feature-availability-get-entityconfig-api

Bringing to the next level

Here are a few things you can try to get more acquainted with building serverless applications using SAM

Learn how SAM Build can help you with dependencies

Uncomment lines on app.py Build the project with sam build --use-container Invoke with sam local invoke GetEntityConfigFunction --event event.json Update tests

Create an additional API resource

Create a catch all resource (e.g. hello{proxy+}) and return the name requested through this new path Update tests

Step-through debugging

Enable step-through debugging docs for supported runtimes

Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications AWS Serverless Application Repository main page

Appendix

Building the project

AWS Lambda requires a flat folder with the application as well as its dependencies in deployment package. When you make changes to your source code or dependency manifest, run the following command to build your project local testing and deployment

sam build

If your dependencies contain native modules that need to be compiled specifically for the operating system running on AWS Lambda, use this command to build inside a Lambda-like Docker container instead

sam build --use-container

By default, this command writes built artifacts to .aws-sambuild folder.

SAM and AWS CLI commands

All commands used throughout this document

# Generate event.json via generate-event command
sam local generate-event apigateway aws-proxy  event.json

# Invoke function locally with event.json as an input
sam local invoke HelloWorldFunction --event event.json

# Run API Gateway locally
sam local start-api

# Create S3 bucket
aws s3 mb s3BUCKET_NAME

# Package Lambda function defined locally and upload to S3 as an artifact
sam package 
    --output-template-file packaged.yaml 
    --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME

# Deploy SAM template as a CloudFormation stack
sam deploy 
    --template-file packaged.yaml 
    --stack-name sam-app 
    --capabilities CAPABILITY_IAM

# Describe Output section of CloudFormation stack previously created
aws cloudformation describe-stacks 
    --stack-name sam-app 
    --query 'Stacks[].Outputs[OutputKey==`HelloWorldApi`]' 
    --output table

# Tail Lambda function Logs using Logical name defined in SAM Template
sam logs -n HelloWorldFunction --stack-name sam-app --tail

You can find source code on github

「真诚赞赏,手留余香」

Jamie's Blog

真诚赞赏,手留余香

使用微信扫描二维码完成支付