AWS lambdaでhello world

AWS lambda で hello world しようとしたら思ったよりハマったので共有。

目的

ポイント

  • GET パラメータを渡すには API Gateway で設定が必要
  • API Gateway の Resources の設定は Stage に Deploy する事で反映される

手順

microservice-http-endpoint をベースに lambda ファンクションを作る

lambda ファンクションを作る

Step2 の Configure function 画面で

  • コードの書き換え
  • IAM Role の作成

を行います。

コードを次のように書き換えます。

console.log('Loading function');

exports.handler = function(event, context) {
    //console.log('Received event:', JSON.stringify(event, null, 2));

    var operation = event.operation;

    if (event.tableName) {
        event.payload.TableName = event.tableName;
    }

    switch (operation) {
        case 'helloworld':
            context.succeed('helloworld');
            break;
        case 'ping':
            context.succeed('pong');
            break;
        default:
            context.fail(new Error('Unrecognized operation "' + operation + '"'));
    }
};

ざっくり解説すると、event にパラメータとかが入ってきて、context が処理に必要な引数っぽいです。

このコードでやりたい事としては

です。

IAM Role の作成は Lambda function handler and role の Role 部分で指定すれば作成できます。設定された IAM Role を作成できるので、選択した後は名前だけ決めて作成すれば大丈夫です。

今回 Dynamo はつかわないので Basic execution role で大丈夫です。

API Gateway の設定をする

Step3 の Configure endpoints に進むと API Gateway の設定になります。ここでは、

  • Security を Open に設定する

を行います。この設定をする事で認証なしで API を実行できます。

余談

この作成ウィザードで作成する場合はここで API Gateway が作成されるので、別途 API Gateway を作成する必要はなくて楽です。

ちなみに、おそらく

- AWS IAM ほかのサービスからアクセスする場合に IAM で許可を出す
- Open with access key 認証ありで外部からアクセスする

だと思うので、EC2 などから API Gateway へアクセスしたい場合は AWS IAM を指定するとよさそうです。

API Gateway に追加設定する

GET の場合、API Gateway で追加設定しないと script 中の event へ値が渡りません。

以下の設定が必要です。

  • Method Request で Query String を設定する
  • Integration Request で Body Mapping Templates を設定する

設定画面は API Gateway の Resources の GET にあります。

f:id:sora_sakaki:20160319180150p:plain

こういう画面。(これは設定済み画面です)

  1. Method Request で Query String(URL Query String Parameters) に operation を設定
  2. Integration Request の Body Mapping Templates で application/json の Mapping を作成、中身を以下のようにする
{
    "operation":"$input.params('operation')"
}

すべて終わったら、上画面の Deploy API というボタンで設定を反映します。

設定反映前でも、Test でテストできるのでそこで確認してから Deploy すると良いと思います。

動かす

https://path?operation=helloworld で helloworld が帰ってきたら完成です。

参考

qiita.com