LoginSignup
7
3

More than 5 years have passed since last update.

AWS SAM のとても簡単なサンプル:Lambda + API Gateway

Last updated at Posted at 2017-01-19

デプロイの流れ

Step0. 下ごしらえ

  • S3 にバケットを用意してください。(以降バケット名を bucket_name として進めます)
  • brew awscli などで、aws コマンドを使えるようにしておいてください。

用意したバケットには、index.js を zip したような(よくわからない)ものが、アップされます。

Step1. 用意するファイルは2つです。

  • index.js
  • template.yml

index.js に Lambda のロジックを書いて、template.yml にデプロイ設定を書きます。ファイルの中身は後述。

Step2. 実行コマンドは2つです。

package
$ aws cloudformation package \
 --template-file template.yml \
 --output-template-file new_template.yml \
 --s3-bucket {bucket_name}

上のコマンドで、new_template.yml が生成され、S3バケットにファイルがアップされます。

deploy
$ aws cloudformation deploy \
 --template-file new_template.yml \
 --stack-name {my-stack-name} \
 --capabilities CAPABILITY_IAM

上のコマンド、Lambda + API Gateway のデプロイが完了します。

ファイルの中身

index.js
'use strict';
console.log('Loading function');

const createResponse = (statusCode, body) => {
  return {
    "statusCode": statusCode,
    "body": body || ""
  }
};

exports.handler = (event, context, callback) => {
  const response = createResponse(200, "Hello SAM.");
  callback(null, response);
};
template.yml
AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Send data to Pardot from ferretone's form.
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      Events:
        GetResource:
          Type: Api
          Properties:
            Path: /
            Method: get

以上となります。

index.js 内の、 response の形式を上述のようにしないと、Lambda 単体ではエラーにならないけど、API Gateway のテストでは、エラーが発生します。

ほかにもマッピングを調整することで、やりようはあると思いますが、今回は、シンプルな例としてまとめてみました。

ありがとうございます。

7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3