AWS Lambda: aws-sdkで自分自身にイベントを送る

Lambdaの無限ループ』を読んで、aws-sdkで自分自身にイベントを投げることができそうだったのでやってみた。

test.js

#!/usr/bin/env lambchop
/*
function_name: test
role: arn:aws:iam::123456789012:role/lambda_exec_role
handler: test.handler
*/
var AWS = require('aws-sdk');

exports.handler = function(event, context) {
  var lambda = new AWS.Lambda({
    accessKeyId: "...",
    secretAccessKey: "...",
    region: "us-east-1"
  });

  setTimeout(function() {
    console.log('hello');

    var params = {
      FunctionName: "test",
      InvokeArgs: '{}'
    };

    lambda.invokeAsync(params, function(err, data) {
      if (err) {
        console.log(err, err.stack);
      } else {
        console.log(data);
      }

      context.done();
    });
  }, 1000);
};

実行結果

START RequestId: 99ee1cf8-73a3-11e4-96e4-2b4bf25bfbdf
2014-11-24T06:32:11.145Z  99ee1cf8-73a3-11e4-96e4-2b4bf25bfbdf    hello
2014-11-24T06:32:11.285Z  99ee1cf8-73a3-11e4-96e4-2b4bf25bfbdf    {}
END RequestId: 99ee1cf8-73a3-11e4-96e4-2b4bf25bfbdf
REPORT RequestId: 99ee1cf8-73a3-11e4-96e4-2b4bf25bfbdf  Duration: 1158.40 ms    Billed Duration: 1200 ms   Memory Size: 128 MB    Max Memory Used: 23 MB
START RequestId: a42eee5c-73a3-11e4-88c1-cf191486f026
2014-11-24T06:32:14.385Z  a42eee5c-73a3-11e4-88c1-cf191486f026    hello
2014-11-24T06:32:14.580Z  a42eee5c-73a3-11e4-88c1-cf191486f026    {}
END RequestId: a42eee5c-73a3-11e4-88c1-cf191486f026
REPORT RequestId: a42eee5c-73a3-11e4-88c1-cf191486f026  Duration: 1204.74 ms    Billed Duration: 1300 ms   Memory Size: 128 MB    Max Memory Used: 23 MB
(以下、繰り返し)