Firebase Functionsのcron起動(メモ書き)
GoogleによるとFirebase Functionsのcron起動には以下の2つの方法があるとのことだ。
- GAE+PubSub
- 外部サービス
twitterでアドバイスいただいたのと、たかだかcronでPubSub必要か?とも思ったので、今回は外部サービスを使うことにした。
Googleの動画内で紹介されていたcronサービスのcron-job.org*1を使ってみる。
cron-job.org - Kostenlose Cron-Jobs, von minütlich bis einmal im Jahr.
blog記事(PubSub実行)
手順
ほとんど動画通りに実施。
環境設定のアクセスキーを設定
Firebaseが知らない人から呼ばれまくると嫌なので、アクセスキーを設定する。
Firebaseはhttpsが標準なのでアクセスキーは盗まれない…と思う。
ただし、Firebase自身でアクセス制御する方式なので悪意攻撃されたらリソースは食う。
これについては、Apigeeというサービスでリバースプロキシを噛まして悪意対策はできそう。
(この記事では触れない)
1. 環境にアクセスキーの設定する
環境の設定 | Firebase
1.1 アクセスキー文字列はlinuxにて自動生成
qiita.com
pwgen -s 65 1
1.2 アクセスキーを書いたjsonファイルを用意
{ "key":"xxx", "id":"xxxx" }
1.2 アクセスキーをjsonファイルから設定
qiita.com
firebase functions:config:set service_account="$(cat config.json)"
2.Functionsの公開関数先頭にアクセスキー制御処理を追加
動画の参考ソース置き場
functions-samples/index.js at master · firebase/functions-samples · GitHub
抜粋内容
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); const secureCompare = require('secure-compare'); exports.accountcleanup = functions.https.onRequest((req, res) => { const key = req.query.key; // Exit if the keys don't match if (!secureCompare(key, functions.config().service_account.key)) { console.log('The key provided in the request does not match the key set in the environment. Check that', key, 'matches the cron.key attribute in `firebase env:get`'); res.status(403).send('Security key does not match. Make sure your "key" URL query parameter matches the ' + 'cron.key environment variable.'); return; } //この下に通常処理を記載する
firebaseにdeployする
firebase deploy --only functions
うまくいけばwebapiのURLが生成されるのでコピーする
cron-job.orgでURLの呼び出し設定を行う
設定方法は以下のサイトが詳しい。
www.lancork.net
呼び出しURLには?key=xxxxxxをつけてパラメータを渡す。以下のような感じ。
その他
試しに数分後に起動する設定を行い、cron-job.orgにてsuccessと表示されたらcronが成功したということだ。
firebase側のconsoleからもlogや実行数が変化するので動作していることが確認できる。