こちらの記事
で、コンテナイメージの Lambda 関数を VSCode でデバッグできないと書きました。
ですが、改めて試したところ、問題なく VSCode からデバッグできたので、メモっておきます。
当初の launch.jsonとエラー
エラーが起きていた launch.json は次のようなものでした。Lambda 関数の呼び出しに関係のない部分は省略しています。
(略) { "type": "aws-sam", "request": "direct-invoke", "name": "periodic-lambda:PeriodicLambdaFunction", "invokeTarget": { "target": "template", "templatePath": "${workspaceFolder}/template.yaml", "logicalId": "PeriodicLambdaFunction" }, "lambda": { "payload": {}, "environmentVariables": {}, }, }, (略)
これを VSCode から呼び出すと、
SamLaunchRequestError というエラーで落ちていました。
(参考)当初の launch.json の作成方法
当初の launch.json は VSCode のサイドメニューから『実行とデバッグ』を選択し、
にある 『launch.json ファイルを作成します』をクリックしました。
すると、下記のようにデバッガの選択
を求められたので、『AWS SAM: Debug Lambda Function Locally』を選択して、次に、
と選択肢が表示されたので『AWS SAM: Template-based Lambda invoke』を選びました。
その結果
{ // IntelliSense を使用して利用可能な属性を学べます。 // 既存の属性の説明をホバーして表示します。 // 詳細情報は次を確認してください: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "aws-sam", "request": "direct-invoke", "name": "Invoke Lambda", "invokeTarget": { "target": "template", "templatePath": "Template Location", "logicalId": "Function Logical ID" }, "lambda": { "payload": { "json": {} } } }, { "type": "aws-sam", "request": "direct-invoke", "name": "periodic-lambda:PeriodicLambdaFunction", "invokeTarget": { "target": "template", "templatePath": "${workspaceFolder}/template.yaml", "logicalId": "PeriodicLambdaFunction" }, "lambda": { "payload": {}, "environmentVariables": {} } }, { "type": "aws-sam", "request": "direct-invoke", "name": "periodic-lambda:PeriodicLambdaResultTopic", (略)
のように、リソースの数だけデバッグ実行の定義ができた次第です。
launch.json を作成しなおし
aws のドキュメント
サーバーレスアプリケーション入門 - AWS Toolkit for VS Code
をみて、改めて launch.json を作成してみます。
上記のドキュメントにあるように template.yaml ファイルで VSCode の CodeLens を使うために、 YAML 拡張機能をインストールしておきます。
インストール後、一度ワークスペースフォルダを閉じて、開きなおしてから、template.yaml を表示させると、
のように、 『Resources』セクションのところに、『AWS: Add Debug Configuration』とヒントが表示されるので、これをクリックします。
すると、ランタイムを選択するように求められるので、
適切なものを選択します(今回は Python 3.13)。
作成された launch.json はこんな感じです。
{ "configurations": [ { "type": "aws-sam", "request": "direct-invoke", "name": "periodic-lambda:PeriodicLambdaFunction(python3.13)", "invokeTarget": { "target": "template", "templatePath": "${workspaceFolder}/template.yaml", "logicalId": "PeriodicLambdaFunction" }, "lambda": { "payload": {}, "environmentVariables": {}, "runtime": "python3.13" } } ] }
あと、 requirements.txt にも
boto3 urllib3 selenium debugpy>=1.0,<2
として、 debugpy というモジュールが追加されていました。
デバッグ実行
launch.json が改めてできたので、 VSCode の『実行とデバッグ』から呼び出します。すると、問題なくビルドが走ります!
続けて、デバッグ実行が呼ばれて、ブレークポイントで停止します。
こないだまでの苦労は何だったんだろうか?というぐらいあっけなかったですね。
ちなみに、 requirements.txt の debugpy の記述をコメントアウトしたら、 VSCode からデバッグできなくなりましたので、ご参考までに。
まとめ
当初は VSCode からはデバッグできないんじゃないか?と思ったりもしたのですが、やはりちゃんと手順を踏んで作業するのが大事ですね。