2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Visual Studio Codeを用いたLambda関数ローカルデバッグ方法メモ

Posted at
  • vscodeでLambdaをデバッグする方法についてメモする。

事前準備

  • SAMプロジェクト作成

    • ひな形作成

      sam init
      

      ※ランタイムはPython3.8を選択。

手順

1.vscodeでSAMプロジェクトを開く。

2.Lambda関数app.pyを開き、テスト用にコメントアウトを外す。

import json
import requests


def lambda_handler(event, context):
    """Sample pure Lambda function

    Parameters
    ----------
    event: dict, required
        API Gateway Lambda Proxy Input Format

        Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format

    context: object, required
        Lambda Context runtime methods and attributes

        Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html

    Returns
    ------
    API Gateway Lambda Proxy Output Format: dict

        Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
    """

    try:
        ip = requests.get("http://checkip.amazonaws.com/")
    except requests.RequestException as e:
         # Send some context about this error to Lambda Logs
         print(e)
         raise e

    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello world",
            "location": ip.text.replace("\n", "")
        }),
    }

3. 28行目ip = requests.get("http://checkip.amazonaws.com/")にブレークポイントを設定する。

4. 関数lambda_handler上部に表示される「AWS:Edit Debug Configuration」を選択する。

5.{project_dir}/template.yaml:HelloWorldFunctionを選択する。

  • SAM Debug Configuration Editorが開く

6. 「Invoke」を選択する。

  • ブレークポイントで一時停止し、再開(F5押下)後にデバッグコンソールに実行結果が出力される。
{"statusCode": 200, "body": "{\"message\": \"hello world\", \"location\": \"xxx.xxx.xxx.xxx\"}"}END RequestId: f17e83bf-567a-4ccf-989a-de759b47aa87
REPORT RequestId: f17e83bf-567a-4ccf-989a-de759b47aa87	Init Duration: 0.23 ms	Duration: 6440.49 ms	Billed Duration: 6441 ms	Memory Size: 128 MB	Max Memory Used: 128 MB	

参考情報

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?