ものづくりのブログ

うちのネコを題材にしたものづくりができたらいいなと思っていろいろ奮闘してます。

【AWS】sam と docker コンテナを使用して lambda をローカルに実装

sam と docker コンテナを使用して lambda をローカルに実装する方法につて作業の流れを簡単にまとめてみました。
流れとしては、sam build でモジュールを展開して、sam deploy で Lambda を作成するといった作業になります。

samとは

sam は Serverless Application Model の略で、サーバーレスアプリケーション構築用のオープンソースフレームワークです。
AWS Lambda のデプロイ管理に使われるツールで、ローカル上のデバッグ、ビルド、デプロイをサポートします。

セットアップ手順

aws-sam-cli インストール

pipで aws-sam-cli をインストールします。

$ pip install aws-sam-cli
$ sam --version
SAM CLI, version 1.17.0

デプロイ

SAM アプリケーションダウンロード

サンプルの SAM アプリケーションをダウンロードします。

$ sam init --runtime python3.8 --dependency-manager pip --app-template hello-world --name sample

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

sample ディレクトリが作成されるので移動する。

$ cd sample

作成したディレクトリに移動して「sam build」コマンドを実行する。

$ sam build
Building codeuri: hello_world/ runtime: python3.7 metadata: {} functions:
['HelloWorldFunction']
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource
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

動作確認

アプリケーションをローカルでテスト
$ 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-02-15 16:50:01  * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)

別ターミナルを起動してcurlを実行すると”hello world”が返ってくる。

$ curl http://127.0.0.1:3000/hello
{"message": "hello world"}

テスト実行する方法

$ sam local invoke "HelloWorldFunction" -e events/event.json
Invoking app.lambda_handler (python3.8)
Skip pulling image and use local one: amazon/aws-sam-cli-emulation-image-python3.8:rapid-1.17.0.

Mounting /{{xxxxxxxxx}}/sample/hello_world as /var/task:ro,delegated inside runtime container
END RequestId: d9907119-e23b-4eb2-b68f-d098c2f4b08c
REPORT RequestId: d9907119-e23b-4eb2-b68f-d098c2f4b08c	Init Duration: 0.23 ms	Duration: 101.28 ms	Billed Duration: 200 ms	Memory Size: 128 MB	Max Memory Used: 128 MB	
{"statusCode": 200, "body": "{\"message\": \"hello world\"}"}

よく使うコマンド

よく使うコマンドをまとめておきます。

コマンド サブコマンド 内容
sam init なし サンプル(雛形)を作成
sam local generate-event Lambdaのイベントパラメータを作成
invoke Lambdaのテスト実行
start-api APIのテスト用ローカルエンドポイントを準備
start-lambda Lambdaのテスト用ローカルエンドポイントを準備
sam validate なし SAMのテンプレートファイルが正しいか検証
sam package なし デプロイ用にパッケージ化
sam deploy なし Lambdaにデプロイ
sam logs なし Lambdaのログを取得