AWS Lambda をローカルでVisual Studio Codeを使ってデバックしてみる。

前回でAWS Lambda をローカルで使用できるようになったので、さらに開発効率を上げるためVisual Studio Codeを使ってデバックしてみる。
具体的には実行コードにブレイクポイントを設定、実際に処理を止めて使われている変数などをチェックする。
もちろんステップ実行などもできる。

手順としては

上記でブレークポイントで止まるのでデバッグしやすい。

ではまず。

Visual Studio Code にlanch.jsonを追加。
Visual Studio Codeのルートは自動作成されたsam-appフォルダに設定、以下のようになっているはず。

f:id:treehitsuji:20190307142003p:plain

Visual Studio Codeの左の虫アイコンをクリックして上の緑の△ボタンの選択をAdd Configurationを選ぶ。Select EnvironmnetNode.js を選択すると、自動的にlanch.jsonのひな型が作成される。

f:id:treehitsuji:20190307142411p:plain

このlanch.jsonを以下のコードに書き換える

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Attach to SAM CLI",
            "type": "node",
            "request": "attach",
            "address": "localhost",
            "port": 5858,
            // From the sam init example, it would be "${workspaceRoot}/hello_world"
            "localRoot": "${workspaceRoot}/hello-world",
            "remoteRoot": "/var/task",
            "protocol": "inspector",
            "stopOnEntry": false
        }
    ]
}

f:id:treehitsuji:20190307142524p:plain

Visual Studio Codeのメニューから Terminalを呼び出し、ターミナルを表示する。(通常のターミナルでもOK)

f:id:treehitsuji:20190307142937p:plain

ターミナルウインドウで sam を デバッグモードで起動する。

sam local start-api --debug-port 5858

Running on http://127.0.0.1:3000/ (Press CTRL+C to quit) と表示され待機状態へ

f:id:treehitsuji:20190307143435p:plain

ブレークポイントで止めたいソースコードにブレイクポイントを設定

f:id:treehitsuji:20190307143612p:plain

ブラウザからURLをたたく f:id:treehitsuji:20190307143732p:plain

処理が待機状態になったので、Visual Studio Codeデバッグを開始する。(F5キーを押すか、Debug > Start Debugging)
すると、設定したデバッグポイントで停止するので、変数など確認できる。ステップ実行も可能。

f:id:treehitsuji:20190307144053p:plain

やったね、デバッグやりやすい!!