Serverless Framework を使って AWS でお手軽 kintone REST API を実行してみよう

著者名: 門屋 亮 (External link) クローバ株式会社 (External link)

目次

はじめに

こんにちは。クローバの門屋です。
AWS Lambda の登場以来、サーバーレスなアーキテクチャを使ったシステムの構築が注目されています。
kintone でサーバーレスの恩恵を受けやすいのはやはり 他のサービスとの連携 ではないでしょうか。
Lambda と API Gateway を使えば、常時稼働するサーバーいらずで kintone との連携サービスを作ることができます。
ただやってみるとわかるのですが、複数の Lambda 関数や API を開発する場合に都度、Lambda や API Gateway の設定を手作業で行うのはわりと面倒くさいものです。
Serverless Framework と serverless-kintone プラグインを使えば、煩わしい設定を極力行わずにサーバーレスなシステムを構築できます。

Serverless Framework とは?

Serverless Framework は今非常に注目されているサーバーレスなアーキテクチャを簡単に作成できるオープンソースのフレームワークです。
AWS Lambda だけでなく、Azure Functions、Google CloudFunctions などに対応しており、2017 年 3 月現在でバージョン 1.8 が提供されています。

serverless-kintone とは?

serverless-kintone とは、Serverless Framework で kintone を扱うためのプラグインです。
設定ファイルに kintone の設定を記述するだけで、簡単に kintone を操作できます。

下準備

必要なもの

  • kintone アカウント
  • AWS アカウント
  • AWS コマンドラインインターフェース
  • node.js および npm

AWS CLI のセットアップ

AWS コマンドラインインターフェースは事前に aws configure コマンドでセットアップを行ってください。
詳しくは AWS CLI のインストールと設定 (External link) を参照してください。

kintone アプリの作成と API トークンの取得

詳しい方法は省略します。
API トークンの取得については 過去の記事 を参考にしてください。

Serverless Framework のインストール

Serverless Framework は npm で提供されており、以下のコマンドでインストールできます。
g オプションをつけてグローバル環境でインストールします。

1
npm install serverless -g

アプリケーションの初期化

新しくディレクトリーを作って、Serverless Framework の初期化コマンドを実行します。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
mkdir sls-kintone
cd sls-kintone
serverless create --template aws-nodejs

Serverless: Generating boilerplate...
 _______                             __
|   _   .-----.----.--.--.-----.----|  .-----.-----.-----.
|   |___|  -__|   _|  |  |  -__|   _|  |  -__|__ --|__ --|
|____   |_____|__|  \___/|_____|__| |__|_____|_____|_____|
|   |   |             The Serverless Application Framework
|       |                           serverless.com, v1.5.1
 -------'
Serverless: Successfully generated boilerplate for template: "aws-nodejs"
Serverless: NOTE: Please update the "service" property in serverless.yml with your service name

作成されるファイルについて説明します。

  • handler.js: Lambda 関数を実装する JS ファイル
  • serverless.yml: フレームワークの設定ファイル

package.json の初期化

なにはともあれ npm init を実行して package.json を初期化します。
いろいろ聞かれますがとりあえずすべてデフォルトで大丈夫です。

1
npm init

serverless-kintone プラグインのインストール

現時点ではまだ serverless-kintone は npm のレジストリに登録されていないため、直接 GitHub からインストールします。

1
npm install https://github.com/kintone/serverless-kintone --save

API トークンの暗号化

serverless-kintone では、API トークンとパスワード認証に対応しており、API トークンとパスワードはどちらも暗号化して AWS にアップロードできます。
運用環境では必ず暗号化を行うようにしてください。
事前に AWS にて KMS のキーを作成しておく必要があります。
とりあえず試すだけなら、本章は省略してもかまいません。

KMS キーの作成

Creating keys (External link) を参考にしてキーを作成してください。
あとで作成される Lambda 関数の実行アカウントに、このキーの kms:Decrypt 権限を与える必要があります(Lambda 関数の作成後に設定します)。

暗号化

コマンドラインで以下のコマンドを実行します(AWS コマンドラインインターフェースが必要です)。
表示される暗号化されたキー(CiphertextBlob の値)をメモしておいてください。

1
2
3
4
5
6
aws kms encrypt --key-id alias/{KMSキーのエイリアス} --region ap-northeast-1 --plaintext {APIトークン}

{
    "KeyId": "arn:aws:kms:ap-northeast-1:xxxxxxx:key/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx",
    "CiphertextBlob": "{your key}"
}

これで下準備ができました!

アプリケーションの開発

serverless.yml の編集

serverless.yml を以下のように編集します。
kintone の情報はご利用のものに置き換えてください。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
service: kintone-sample # 任意のアプリケーション名を設定します。

provider:
  name: aws
  runtime: nodejs8.10
  region: ap-northeast-1

functions:
  hello:
    handler: handler.hello # helloという名前のLambda関数を実装します。
    events:
      - http:
          path: hello # API Gatewayのパス
          method: get # API Gatewayのメソッド

plugins:
  - serverless-kintone # serverless-kintone プラグインを使用します。

custom:
  kintone:
    - name: test_app # アプリ名(kintoneのアプリ名と一致する必要はありません)
      domain: example # ドメイン
      api_token: {your key} # 暗号化されたAPI トークン
      encrypted: true # 暗号化を行う

詳しい設定方法については、 Serverless のドキュメント (External link) を参照してください。

暗号化を行わない場合は、encrypted の行を削除して、api_token に暗号化されていない値を設定してください。

handler.js の編集

handler.js を以下のように編集します。
今回は単純に、kintone の特定のアプリからレコード情報を返すだけの API を作成してみることにします。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
 * Serverless Framework sample
 * Copyright (c) 2019 Cybozu
 *
 * Licensed under the MIT License
 * https://opensource.org/license/mit/
 */

'use strict';

const Kintone = require('kintone');
const app = new Kintone('test_app');

module.exports.hello = (event, context, callback) => {
  const params = {
    app: 1 // your APP ID
  };
  app.get('/k/v1/records', params).then((res) => {
    const response = {
      statusCode: 200,
      body: JSON.stringify({
        records: res.records
      }),
    };

    callback(null, response);
  });
};

複数の Lambda 関数の作成も可能です。
アプリケーションが大きくなるとフォルダーを作成してファイルを整理することもあると思います。
このとき、アプリケーション直下に「kintone」という名前のフォルダーを作成すると serverless-kintone に上書きされてしまうので注意してください。

デプロイ

以下のコマンドで、アプリケーションを AWS にデプロイします。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
serverless deploy

Serverless: Creating Stack...
Serverless: Checking Stack create progress...
.....
Serverless: Stack create finished...
Serverless: Packaging service...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading service .zip file to S3 (1.93 MB)...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
...............................
Serverless: Stack update finished...
Service Information
service: kintone-sample
stage: dev
region: ap-northeast-1
api keys:
  None
endpoints:
  GET - https://xxxxxx.execute-api.ap-northeast-1.amazonaws.com/dev/hello
functions:
  kintone-sample-dev-hello: arn:aws:lambda:ap-northeast-1:xxxxxx:function:kintone-sample-dev-hello

デプロイには少し時間がかかります。
Lambda 関数を修正した場合などは、deploy function コマンドを使うと関数だけの更新もできます。

API の実行

デプロイ時に表示された URL へ curl コマンドやブラウザーでアクセスしてみます。
API トークンを暗号化した場合は、トークンを復号できないためにエラーが発生します。
Serverless Framework によって作成された IAM Role に、復号するための kms:Decrypt 権限を付与すると実行できます。
詳しくは Key policies in AWS KMS (External link) の、「キーユーザーに CMK の使用を許可する」を参照してください。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
curl https://xxxxxx.execute-api.ap-northeast-1.amazonaws.com/dev/hello | jq .

{
  "records": [
    {
      "Updated_datetime": {
        "type": "UPDATED_TIME",
        "value": "2017-03-11T08:13:00Z"
      },
      "Created_datetime": {
        "type": "CREATED_TIME",
        "value": "2017-03-11T08:13:00Z"
      },
      "file": {
        "type": "FILE",
        "value": []
      },
      "Record_number": {
        "type": "RECORD_NUMBER",
        "value": "17"
      },
      "multi_text": {
        "type": "MULTI_LINE_TEXT",
        "value": "aaabbb"
      },
      "checkbox": {
        "type": "CHECK_BOX",
        "value": []
      },
      "Created_by": {
        "type": "CREATOR",
        "value": {
          "code": "Administrator",
          "name": "Administrator"
        }
      },
      "text": {
        "type": "SINGLE_LINE_TEXT",
        "value": "test1"
      },
      "$revision": {
        "type": "__REVISION__",
        "value": "1"
      },
      "Updated_by": {
        "type": "MODIFIER",
        "value": {
          "code": "Administrator",
          "name": "Administrator"
        }
      },
      "$id": {
        "type": "__ID__",
        "value": "17"
      }
    },

kintone からデータが取得できています!

おわりに

いかがだったでしょうか。
暗号化のところが少し複雑でしたが、キーの作成はじめに一度行うだけでよく、自前で暗号化のしくみを作成することと比べると、とても簡単にセキュアなサーバーレスアプリケーションを構築できます。
Lambda や API Gateway、DynamoDB 等の設定が設定ファイルで管理できるため、ちょっと API を作ってみたいというケースから大規模な開発まで対応できます。
Serverless Framework は開発のスピードが早いため、最新情報をキャッチアップしていく必要がありますが、使いこなせば強力なツールになることは間違いありません。
ぜひ試してみてください。

注意事項

ソースコードの変更および再配布、商用利用等はライセンスにしたがってご利用可能です。

information

この Tips は、2019 年 8 月版 kintone で動作を確認しています。