LoginSignup
16
16

More than 5 years have passed since last update.

Google Cloud Functions を Google Cloud Pub/Sub からトリガーしてみる

Last updated at Posted at 2018-09-24

本記事でやること

Google Cloud Pub/Sub から Google Cloud Functions をトリガーしてみます。

背景

諸事情により Google Cloud Functions を定期実行してみたいと思い調べてみると、この辺りの記事が引っかかりました。

なるほど。大きく分けると以下の2パターンがありそう。

  1. GCP 内で完結する方法
    • App Engine Cron, Cloud Pub/Sub を使う
  2. 外部サービスを使って定期実行してあげる方法
    • HTTP 関数を定期的に叩く

2番目の方法だと、一見簡単そうですが、そのままだと URL さえ知っていれば誰でも叩けることになり、認証の仕組みを入れようとすると面倒臭そうな印象。(参考 : Cloud FunctionsでIAMを利用する - Studio Andy

ということで、今回は1番目の GCP 内で完結する方法を採用してみようと思いました。

まずは App Engine Cron は使わずに Google Cloud Pub/Sub から Google Cloud Functions をトリガーしてみることにしました。

追記: 今は Cloud Scheduler があるので、定期実行に関しては、素直にそちらを使ってあげるのが良さそうです! => https://cloud.google.com/scheduler/

環境

  • macOS High Sierra 10.13.6
$ gcloud --version
Google Cloud SDK 217.0.0
beta 2018.07.16
bq 2.0.34
core 2018.09.17
gsutil 4.34

Google Cloud Functions を動かしてみる

私は クイックスタート: gcloud コマンドライン ツールの使用  |  Cloud Functions のドキュメント  |  Google Cloud を参考に Google Cloud Functions 単体で動かしてみました。既に Google Cloud Functions を動かしたことがある人は、飛ばして良いと思います。

region の設定

東京リージョンに設定します。

$ gcloud beta functions regions list # 利用できるリージョンの確認
$ gcloud config set functions/region asia-northeast1 # 東京リージョンに設定
$ gcloud config list
[core]
account = xxx@xxx.xxx
disable_usage_reporting = False
project = xxx
[functions]
region = asia-northeast1

Google Cloud Functions を Google Cloud Pub/Sub からトリガーしてみる

ようやく本題です。
バックグラウンド関数  |  Cloud Functions のドキュメント  |  Google Cloud を参考に進めていきます。

Cloud Pub/Sub の例 を参考に、以下のようにしてみました。

exports.helloPubSub = (event, callback) => {
  const pubsubData = event.data;
  console.log(pubsubData.message);

  callback();
};

Google Cloud Pub/Sub トリガー  |  Cloud Functions のドキュメント  |  Google Cloud を参考にデプロイする。

$ gcloud beta functions deploy helloPubSub --trigger-resource hello_world --trigger-event google.pubsub.topic.publish 

ちなみに

から、Pub/Sub と Functions が作成されていることを確認できる。

動作確認

$ gcloud beta functions call helloPubSub --data '{"message":"Hello, GCF!!"}'

https://console.cloud.google.com/logs からログに Hello, GCF!! が出力されていることを確認できました。

16
16
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
16
16