AWS SAMでLambdaとAPI Gateway(編集中)


準備

aws cliがインストールされてユーザーとか設定されていること
S3にバケットを用意。
sam-bucket
という名前で。
I AMロール作成。Lambdaで使います。
信頼関係のところでLambdaを設定してあげないとだめ。
あとアクセス権限で一応
S3とLambdaとAPI Gatewayのフルアクセスを付けとく。こんなにいらないかも。
名前は
sam-roleで作ります。
適当なディレクトリを作成
sam_test

console
$ pwd
/Development
$ mkdir sam_test
$ cd sam_test

Lambda関数の作成

sam_func.py
def lambda_handler(event, context):
    return 'AWS SAM test'

テンプレートファイルを作成

template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: sample
Resources:
  SamSample:
    Type: AWS::Serverless::Function
    Properties:
      Handler: sam_func.lambda_handler # 実行するハンドラ
      Runtime: python3.6 # lambda のランタイムを書く
      Role: arn:aws:iam::<your acount>:role/sam-role # AM Role の Arn
      Timeout: 60 # Lambda のタイムアウト
      Events:
        GetResource: # API Gateway 側の識別子
          Type: Api
          Properties:
            Path: /api # API Gateway のリソースのパス
            Method: get # API Gateway のメソッド
console
$ ls

デプロイ用のファイル作成

console
$ aws cloudformation package --template-file template.yaml --output-template-file template-output.yaml --s3-bucket my-bucket
Uploading to <zipped file>  3262 / 3262.0  (100.00%)%)
Successfully packaged artifacts and wrote output template to file template-output.yaml.
Execute the following command to deploy the packaged template
aws cloudformation deploy --template-file /Development/sam_test/template-output.yaml --stack-name <YOUR STACK NAME>

デプロイ

console
$ aws cloudformation deploy --template-file /Development/sam_test/template-output.yaml --stack-name SamTest
Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - SamTest

確認

ウェブコンソールから確認
API Gateway
Lambda

まとめ