normcore.dev

SAMを使ったAWS Lambdaのローカル開発環境の構築

SAMとは

  • Serverless Application Modelの略。
  • AWS上のサーバーレスアプリケーション構築用のフレームワーク。
  • CloudFormationのテンプレートより簡潔に記載できる。
  • デプロイ時にSAMの文法をCloudFormationの文法に変換して展開

SAMのインストール

インストール

$ brew tap aws/tap
$ brew install aws-sam-cli
$ sam --version
SAM CLI, version 1.30.0
$ sam init

	SAM CLI now collects telemetry to better understand customer needs.

	You can OPT OUT and disable telemetry collection by setting the
	environment variable SAM_CLI_TELEMETRY=0 in your shell.
	Thanks for your help!

	Learn More: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-telemetry.html

Which template source would you like to use?
	1 - AWS Quick Start Templates
	2 - Custom Template Location
Choice: 1
What package type would you like to use?
	1 - Zip (artifact is a zip uploaded to S3)
	2 - Image (artifact is an image uploaded to an ECR image repository)
Package type: 1

Which runtime would you like to use?
	1 - nodejs14.x
	2 - python3.9
	3 - ruby2.7
	4 - go1.x
	5 - java11
	6 - dotnetcore3.1
	7 - nodejs12.x
	8 - nodejs10.x
	9 - python3.8
	10 - python3.7
	11 - python3.6
	12 - python2.7
	13 - ruby2.5
	14 - java8.al2
	15 - java8
	16 - dotnetcore2.1
Runtime: 1

Project name [sam-app]: practice-lambda-app

Cloning from https://github.com/aws/aws-sam-cli-app-templates

AWS quick start application templates:
	1 - Hello World Example
	2 - Step Functions Sample App (Stock Trader)
	3 - Quick Start: From Scratch
	4 - Quick Start: Scheduled Events
	5 - Quick Start: S3
	6 - Quick Start: SNS
	7 - Quick Start: SQS
	8 - Quick Start: Web Backend
Template selection: q
Error: invalid choice: q. (choose from 1, 2, 3, 4, 5, 6, 7, 8)
Template selection: 1

    -----------------------
    Generating application:
    -----------------------
    Name: practice-lambda-app
    Runtime: nodejs14.x
    Dependency Manager: npm
    Application Template: hello-world
    Output Directory: .

    Next steps can be found in the README file at ./practice-lambda-app/README.md
$ cd ./practice-lambda-app
$ sam build
Building codeuri: /example-path/hello-world runtime: nodejs14.x metadata: {} functions: ['HelloWorldFunction']
Running NodejsNpmBuilder:NpmPack
Running NodejsNpmBuilder:CopyNpmrc
Running NodejsNpmBuilder:CopySource
Running NodejsNpmBuilder:NpmInstall
Running NodejsNpmBuilder:CleanUpNpmrc

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Deploy: sam deploy --guided

いくつかローカルで実行するためのコマンドがある。

ローカルで関数を呼び出す

https://docs.aws.amazon.com/ja_jp/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-invoke.html

sam local invoke コマンドで実行できる。

関数の論理IDとイベントファイルを指定して、関数をローカルで呼び出す。

$ sam local invoke "HelloWorldFunction" -e events/event.json

Invoking app.lambdaHandler (nodejs14.x)
Skip pulling image and use local one: public.ecr.aws/sam/emulation-nodejs14.x:rapid-1.30.0.

Mounting /example-path/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: c1fc710b-a997-4c5e-b659-eb81fed62a34 Version: $LATEST
END RequestId: c1fc710b-a997-4c5e-b659-eb81fed62a34
REPORT RequestId: c1fc710b-a997-4c5e-b659-eb81fed62a34  Init Duration: 0.19 ms  Duration: 131.12 ms     Billed Duration: 200 ms Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode":200,"body":"{\"message\":\"hello world\"}"}

API Gateway のローカル実行

https://docs.aws.amazon.com/ja_jp/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-start-api.html

sam local start-api コマンドで実行できる。

はAPI Gatewayのローカルでインスタンスを起動する。
HTTPリクエストとレスポンスのテストに使用できる。

ホットリロードも機能もあるらしい。

$ sam local start-api
Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
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
2021-09-04 17:35:12  * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
Invoking app.lambdaHandler (nodejs14.x)
Skip pulling image and use local one: public.ecr.aws/sam/emulation-nodejs14.x:rapid-1.30.0.

# http://127.0.0.1:3000/hello
# でアクセスできるようになった

END RequestId: bcf4b429-0cc5-4174-ba50-7b5d2ba161f3
REPORT RequestId: bcf4b429-0cc5-4174-ba50-7b5d2ba161f3	Init Duration: 0.19 ms	Duration: 160.36 ms	Billed Duration: 200 ms	Memory Size: 128 MB	Max Memory Used: 128 MB
No Content-Type given. Defaulting to 'application/json'.
2021-09-04 17:35:17 127.0.0.1 - - [04/Sep/2021 17:35:17] "GET /hello HTTP/1.1" 200 -

試しにcurlしてみる。
とりあえずローカルまでは動いた。

$ curl -s -X GET http://localhost:3000/hello
{"message":"hello world"}

参考

https://qiita.com/gnk263/items/7f8796c26b9b61d33d96