LoginSignup
7
1

More than 5 years have passed since last update.

Cloud Schedulerのジョブにattributesを設定する

Last updated at Posted at 2019-03-16

(ターゲットを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 を出力する処理を追加しただけです。

scheduler_test
/**
 * 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)を設定するフォームがあります。

メッセージの公開_-_akiba-session_-_Google_Cloud_Platform.png

この状態でパブリッシュしてみると下記のように出力されます。

CloudFunctionの出力ログ
test message from topic
{ foo: 'bar' }

Cloud Console経由でジョブを作成

Pub/Subトピック経由でCloud Functionに渡せる情報はペイロードくらいです。

ジョブの編集_-_akiba-session_-_Google_Cloud_Platform.png

この状態で作成したジョブを実行します。

CloudFunctionの出力ログ
test message from scheduler
null

残念ながら、attributesnull です。

gcloudコマンド経由でジョブを作成

Cloud Schedulerはベータ版のため、gcloud beta での実行コマンドを利用します。
ドキュメント: gcloud beta scheduler
ドキュメント: gcloud beta scheduler jobs create pubsub

attributes だけでなく、リトライ関連のオプションや
メッセージをファイルから読み込むオプションなどが隠されています。

今回は下記コマンドジョブを作成します。

Pub/Subトピックをパブリッシュするジョブの作成
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とはトピック名の指定方法が違っており
プロジェクトを識別できる形式で記述する必要があるようです。

上記コマンドで作成したジョブを実行してみます。

CloudFunctionの出力ログ
test message from scheduler
{ foo: 'bar' }

無事に attributes を取得することができました。

むすび

これでCloudFunctionsに渡せる値の自由度が上がりました。

今しばらくはジョブをgcloud経由で作成するのが懸命そうです。
まだベータ版なので、何も文句は言えないのですが。

7
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1