VS Codeでラムダのコードを書く(実行編)
やったこと(続き)
SAMプロジェクトの作成
- コマンドパレットより「Create New Sam Application」を実行
- 「Select a SAM Application Runtime」:python3.7
- 「Select a workspace folder for your new project」:作業ディレクトリを指定する
- 「Enter a name for your new application」:sam-project
「Create New Sam Application」でエラーが起きる場合
Create New Sam Applicationが動作せず、下記のエラーログが表示されることがある。
[ERROR]: An error occurred while creating a new SAM Application. Check the logs for more information by running the "View AWS Toolkit Logs" command from the Command Palette. [ERROR]: Error: SAM CLI was not found
自分の場合は、AWS Toolkitを再インストールすることで動作するようになった。
コマンドラインから実施することも可能(参考リンクの番外編を参照)
SAMプロジェクトのローカル実行用にDockerインストール
SAMプロジェクトのローカル実行用にDockerをインストールする。
※下記の記載もあるのでインストールしなくても問題ない。
Dockerは、アプリケーションをローカルでテストし、--use-containerフラグを使用して展開パッケージを構築するための前提条件です。 これらの機能を最初に使用する予定がない場合は、このセクションをスキップするか、Dockerを後でインストールできます。"
インストールする場合は、下記手順を実施する。
- Dockerのイメージファイルをダウンロード
- Dockerをインストール
- ファイル共有設定より、プロジェクトフォルダを指定 (デフォルトで「/Users」等が共有フォルダ設定されているので、その配下にある場合は設定不要)
- docker psを実行して、エラーにならないことを確認
SAMプロジェクトのローカル実行
「sam local invoke」より、ローカルでラムダを実行する。
$ sam local invoke Invoking app.lambda_handler (python3.7) Fetching lambci/lambda:python3.7 Docker container image.......(省略) Mounting /Users/xxxxx/local-repo/sam-project/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container START RequestId: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Version: $LATEST END RequestId: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx REPORT RequestId: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Init Duration: 187.25 ms Duration: 3.98 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 23 MB {"statusCode":200,"body":"{\"message\": \"hello world\"}"}
初回実行時はDockerコンテナイメージがダウンロードされてから実行されるが、2回目以降はダウンロード処理が省略される。