LoginSignup
5
5

More than 1 year has passed since last update.

AWS Lambdaのスケジュール実行をローカルでテストしてみる

Last updated at Posted at 2019-03-18

はじめに

AWSが公式で提供しているサーバーレスアプリケーションを構築するためのフレームワークである、AWS SAMを使うことにより、コードを書いてテストを行い、デプロイするまでを全てローカルで行うことができるようになります。
今回は、AWS SAMを用いてAWS Lambda Functionのスケジュール実行をローカル環境でテストする手順をメモとして残します。

環境

OS: macOS Mojave10.14
言語: Node.js 8.10
Docker: 18.09.2
SAM CLI: 0.11.0

環境構築

Dockerのインストール

AWS SAMはDocker上で動くのでDockerが必要。
以下の公式サイトからインストール。
https://docs.docker.com/docker-for-mac/install/

AWS SAM CLIのインストール

Homebrewでインストール。

$ brew tap aws/tap
$ brew install aws-sam-cli

プロジェクト作成

適当なディレクトリで、以下のコマンドを入力。
※samコマンドについては以下の記事が参考に。
https://qiita.com/gnk263/items/7f8796c26b9b61d33d96

$ sam init -r nodejs8.10 -n sample-app

すると以下のようなプロジェクトが作成される。

sample-app/
├── README.md
├── hello-world
│   ├── app.js
│   ├── package.json
│   └── tests
│       └── unit
│           └── test-handler.js
└── template.yaml

template.yamlの修正

Resources配下のHelloWorldFunctionを以下のように修正。スケジュールの実行間隔は任意に修正。
※Lambdaのスケジュール実行に関しては以下を参照。
https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html

HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
        CodeUri: hello-world/
        Handler: app.lambdaHandler
        Runtime: nodejs8.10
        Events:
            Timer:
                Type: Schedule
                Properties:
                    Schedule: rate(1 minute)

ローカル実行環境構築用の設定ファイルを作成

sample-app配下で以下のコマンドを入力。

$ sam local generate-event cloudwatch scheduled-event > event_file.json

テスト

sample-app配下で以下のコマンドを入力。

$ sam local invoke "HelloWorldFunction" -e event_file.json

以下のような反応が返って来れば成功。

START RequestId: e832090d-203c-19f4-c6ae-580e00b3905f Version: $LATEST
END RequestId: e832090d-203c-19f4-c6ae-580e00b3905f
REPORT RequestId: e832090d-203c-19f4-c6ae-580e00b3905f	Duration: 13.40 ms	Billed Duration: 100 ms	Memory Size: 128 MB	Max Memory Used: 30 MB	

{"statusCode":200,"body":"{\"message\":\"hello world\"}"}

終わりに

色々試したところ、template.yamlのScheduleの所にタイポがあっても成功レスポンスが返ってくるし、実際にCloudWatchに正しいスケジュール間隔で登録されるかどうかはデプロイしてみるまでは分からない模様。うーん。。。
指摘等ありましたらコメントお願いします。

5
5
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
5
5