(ターゲットをPub/Subとして利用する場合のお話)
2018年11月にリリースされたGoogle Cloud Schedulerは
GCP上で定期実行したいタスクの実装に非常に便利そうな機能です。
ただし、2019年3月現在のCloud Consoleでは
attributes
ほかいくつかの項目の入力フォームが提供されていないため
gcloudを使ってAPI経由で設定したほうが嬉しかったりします。
検証の事前準備
Pub/Subトピックの作成
scheduler_test という名前で作成するのみです。
Cloud Functionsの作成
Cloud FunctionsでPub/Subトピックをサブスクライブする関数を作成します。
Node.js 8のデフォルトのコードに attributes
を出力する処理を追加しただけです。
/**
* Triggered from a message on a Cloud Pub/Sub topic.
*
* @param {!Object} event Event payload.
* @param {!Object} context Metadata for the event.
*/
exports.helloPubSub = (event, context) => {
const pubsubMessage = event.data;
console.log(Buffer.from(pubsubMessage, 'base64').toString());
console.log(event.attributes); // <- 追加
};
トピックを手動でパブリッシュ
属性(attributes
)を設定するフォームがあります。
この状態でパブリッシュしてみると下記のように出力されます。
test message from topic
{ foo: 'bar' }
Cloud Console経由でジョブを作成
Pub/Subトピック経由でCloud Functionに渡せる情報はペイロードくらいです。
この状態で作成したジョブを実行します。
test message from scheduler
null
残念ながら、attributes
は null
です。
gcloudコマンド経由でジョブを作成
Cloud Schedulerはベータ版のため、gcloud beta
での実行コマンドを利用します。
ドキュメント: gcloud beta scheduler
ドキュメント: gcloud beta scheduler jobs create pubsub
attributes
だけでなく、リトライ関連のオプションや
メッセージをファイルから読み込むオプションなどが隠されています。
今回は下記コマンドジョブを作成します。
gcloud beta scheduler jobs create pubsub scheduler_test_gcloud \
--description 'for scheduler test' \
--schedule '0 */3 * * *' \
--time-zone 'Asia/Tokyo' \
--topic 'projects/xxxxxxxxxx/topics/scheduler_test' \
--message-body 'test message from scheduler' \
--attributes 'foo=bar'
なおCloud Consoleとはトピック名の指定方法が違っており
プロジェクトを識別できる形式で記述する必要があるようです。
上記コマンドで作成したジョブを実行してみます。
test message from scheduler
{ foo: 'bar' }
無事に attributes
を取得することができました。
むすび
これでCloudFunctionsに渡せる値の自由度が上がりました。
今しばらくはジョブをgcloud経由で作成するのが懸命そうです。
まだベータ版なので、何も文句は言えないのですが。