AWS SAM LocalをGetting Startedしてみる

Githubawslabs は様々なAWSに関連するソフトウェアのリポジトリですが、その中でAWS SAM Localというものがあります。

AWS SAM Local 🐿 とは?

AWS SAM Local 🐿 is a CLI tool for local development and testing of Serverless applicationsということで、日本語にすると『AWS SAM Localはサーバーレスなアプリケーションをローカルで開発およびテストするためのCLIツールです』といった感じになるのかな、と。

Getting Startedしてみる

README.mdには様々なことが書かれていますが、まずは手を動かしてはじめてみましょう。詳細はHOWTO.mdに書かれています。

RestfulにCRUDなサービスを提供するAPI

今回はCRUDなアプリケーションを作成します。 - products.js - template.yaml

yamlファイルはAWS SAMのテンプレートで、下記のように/productsに対するAPIリクエストに対する設定になります。 - Createの場合は、POSTリクエストを /products に - 全てをListする場合は、GETリクエストを /products に - Read, update, deleteの場合は、それぞれGET, PUT or DELETEリクエストを /products/{product} に

AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: My first serverless application.

Resources:
            
  Products:
    Type: AWS::Serverless::Function
    Properties:
      Handler: products.handler
      Runtime: nodejs6.10
      Events:
        ListProducts:
          Type: Api
          Properties:
            Path: /products
            Method: get
        CreateProduct:
          Type: Api
          Properties:
            Path: /products
            Method: post
        Product:
          Type: Api
          Properties:
            Path: /products/{product}
            Method: any

上記のAPIに対応するLambda Functionのコードを products.js に例えば動作確認目的用にコメントだけ返すようなコードを以下のように実装します。

'use strict';

exports.handler = (event, context, callback) => {

    let id = event.pathParameters.product || false;
    switch(event.httpMethod){
        
        case "GET":
            
            if(id) {
                callback(null, { 
                   statusCode: 200,
                   body: "This is a READ operation on product ID " + id
                });
                return;  
            } 
            
            callback(null, { 
               statusCode: 200,
               body: "This is a LIST operation, return all products"
            });
            break;
            
        case "POST":
            callback(null, { 
               statusCode: 200,
               body: "This is a CREATE operation"
            });
            break;

        case "PUT": 
            callback(null, { 
               statusCode: 200,
               body: "This is a UPDATE operation on product ID " + id
            });
            break;
             
        case "DELETE": 
            callback(null, { 
               statusCode: 200,
               body: "This is a DELETE operation on product ID " + id
            });
            break;

        default:
            // Send HTTP 501: Not Implemented
            console.log("Error: unsupported HTTP method (" + event.httpMethod + ")");
            callback(null, { statusCode: 501 })
            
    }

}

SAM CLIを使う

上記のファイルをディレクトリに配置した状態でsamコマンドを叩きます。SAM CLIはnpmを使って簡単にインストールすることが出来ます。

npm install -g aws-sam-local

と言いつつ、私の場合(Mac)は権限周りで失敗してて↓しましたが、、、

$ sudo chown -R $(whoami) /usr/local/{lib/node_modules,bin,share}

詳細は→のISSUE参照 https://github.com/awslabs/aws-sam-local/issues/66

また、AWS SAMはDockerを使うので、もしご自身のマシンにまだDockerが入っていなかったら普通にDocker for Macとか使ったりして。

そんなこんなで sam local start-api を叩くと、それっぽいDocker Imageとか落としてくるので最初は多少時間かかりますが↓のようにローカルホストの3000ポートを使ってアレコレできるようになります。

$ sam local start-api
2017/10/23 10:32:58 Connected to Docker 1.32
2017/10/23 10:32:58 Runtime image missing, will pull....
2017/10/23 10:32:58 Fetching lambci/lambda:nodejs6.10 image for nodejs6.10 runtime...
nodejs6.10: Pulling from lambci/lambda
5aed7bd8313c: Pull complete 
d60049111ce7: Pull complete 
df2c17ad5e5e: Pull complete 
93956b6301bb: Pull complete 
Digest: sha256:7eb4ced6a15ae3c30effc4ec0cd3aabb2bd57c9a8330b37920c3d5d722d81083
Status: Downloaded newer image for lambci/lambda:nodejs6.10

Mounting products.handler (nodejs6.10) at http://127.0.0.1:3000/products/{product} [OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT]
Mounting products.handler (nodejs6.10) at http://127.0.0.1:3000/products [POST]
Mounting products.handler (nodejs6.10) at http://127.0.0.1:3000/products [GET]
Mounting static files from public at /

You can now browse to the above endpoints to invoke your functions.
You do not need to restart/reload SAM CLI while working on your functions,
changes will be reflected instantly/automatically. You only need to restart
SAM CLI if you update your AWS SAM template.

例えばプロダクトをLISTするようなオペレーションは、Lambda用のJavaScriptで書いたコメントが表示されます。

$ curl http://localhost:3000/products
This is a LIST operation, return all products
$ curl -XPUT http://localhost:3000/products/1
This is a UPDATE operation on product ID

JavaScriptに変更を入れる場合は、自動的に反映されるのでstart-apiしなくてもOKです。

CloudFormationを使ってAWSの環境へデプロイ

ココから先はSAMというより、CloudFormationを利用する形になります。具体的には、独自のサーバーレスアプリケーションを作成する に記載されているように↓のような流れ。それぞれのコマンドのパラメーター等の詳細に関しては↓公式のドキュメントをご参照ください。 http://docs.aws.amazon.com/cli/latest/reference/cloudformation/package.html http://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/index.html

  • パッケージを配置するS3のバケットを用意して
aws s3 mb s3://bucket-name --region region
aws cloudformation package 
   --template-file example.yaml 
   --output-template-file serverless-output.yaml 
   --s3-bucket s3-bucket-name
aws cloudformation deploy 
   --template-file serverless-output.yaml 
   --stack-name new-stack-name 
   --capabilities CAPABILITY_IAM

実践AWS Lambda 「サーバレス」を実現する新しいアプリケーションのプラットフォーム

Amazonで西谷 圭介の{ProductTitle}。アマゾンならポイント還元本が多数。一度購入いただいた電子書籍は、KindleおよびFire端末、スマートフォンタブレットなど、様々な端末でもお楽しみいただけます。

//cdn.embedly.com/widgets/platform.js