Pub/Sub メッセージを使用してイベントを受信する(Terraform)
このクイックスタートでは、Terraform を使用して、Pub/Sub から直接イベントを受信し、イベントを Cloud Run サービスに転送する Eventarc トリガーを作成する方法について説明します。Terraform を使用して Eventarc トリガーを作成する方法については、Terraform を使用してトリガーを作成するをご覧ください。
このクイックスタートでは、次の操作を行います。
Terraform をデプロイする準備を行います。
次の処理を行う Terraform 構成を定義します。
- API を有効にします。
- サービス アカウントを作成し、必要な Identity and Access Management(IAM)ロールを付与します。
- イベントの宛先として Cloud Run にサービスをデプロイします。
- イベント プロバイダとして Pub/Sub トピックを作成する。
- Eventarc トリガーを作成する。
Terraform 構成を適用します。
Pub/Sub トピックにメッセージを公開してイベントを生成し、Cloud Run ログでメッセージを確認する。
始める前に
組織で定義されているセキュリティの制約により、次の手順を完了できない場合があります。トラブルシューティング情報については、制約のある Google Cloud 環境でアプリケーションを開発するをご覧ください。
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Resource Manager and IAM APIs:
gcloud services enable cloudresourcemanager.googleapis.com
iam.googleapis.com -
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
Create or select a Google Cloud project.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_ID
with a name for the Google Cloud project you are creating. -
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace
PROJECT_ID
with your Google Cloud project name.
-
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud Resource Manager and IAM APIs:
gcloud services enable cloudresourcemanager.googleapis.com
iam.googleapis.com -
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
-
プロジェクト作成者には、基本オーナーロール(
roles/owner
)が付与されます。デフォルトでは、この Identity and Access Management(IAM)ロールには、ほとんどの Google Cloudリソースへのフルアクセスに必要な権限が含まれており、この手順は省略できます。プロジェクト作成者でない場合は、プロジェクトで適切なプリンシパルに必要な権限を付与する必要があります。プリンシパルは Google アカウント(エンドユーザーの場合)やサービス アカウント(アプリケーションとコンピューティング ワークロードの場合)になることもあります。詳細については、イベントの宛先のロールと権限のページをご覧ください。
必要な権限
このクイックスタートを完了するために必要な権限を取得するには、プロジェクトに対する次の IAM ロールを付与するよう管理者に依頼してください。
-
Cloud Run 管理者 (
roles/run.admin
) -
Eventarc 管理者 (
roles/eventarc.admin
) -
ログ表示アクセス者 (
roles/logging.viewAccessor
) -
プロジェクト IAM 管理者 (
roles/resourcemanager.projectIamAdmin
) -
Pub/Sub パブリッシャー (
roles/pubsub.publisher
) -
サービス アカウント管理者 (
roles/iam.serviceAccountAdmin
) -
サービス アカウント ユーザー (
roles/iam.serviceAccountUser
) -
Service Usage 管理者(
roles/serviceusage.serviceUsageAdmin
)
ロールの付与については、プロジェクト、フォルダ、組織に対するアクセス権の管理をご覧ください。
-
Cloud Run 管理者 (
Terraform のデプロイを準備する
Terraform 構成ファイルを作成して、Terraform リソースのデプロイを準備します。Terraform 構成ファイルを使用すると、Terraform 構文を使用してインフラストラクチャの望ましい最終状態を定義できます。
ローカルシェルを使用している場合は、Terraform をインストールして構成します。
Terraform は Cloud Shell 環境にすでに統合されています。Terraform をインストールしなくても、Cloud Shell を使用して Terraform リソースをデプロイできます。
Cloud Shell またはローカルシェルで、Terraform 構成を適用するデフォルトの Google Cloud プロジェクトを設定します。このコマンドは、プロジェクトごとに 1 回だけ実行する必要があります。これは任意のディレクトリで実行できます。
export GOOGLE_CLOUD_PROJECT=PROJECT_ID
PROJECT_ID
は、 Google Cloud プロジェクトの ID に置き換えます。
Terraform 構成ファイルに明示的な値を設定すると、環境変数がオーバーライドされます。
ディレクトリを準備する
Terraform 構成ファイルには独自のディレクトリ(ルート モジュール)が必要です。ディレクトリを作成し、そのディレクトリ内に新しいファイルを作成します。
mkdir DIRECTORY && cd DIRECTORY && touch main.tf
ファイル名には .tf
拡張子が必要です。たとえば、このクイックスタートでは、ファイルは main.tf
と呼ばれます。
Terraform 構成を定義する
次の Terraform コード スニペットを新しく作成した main.tf
ファイルにコピーします。必要に応じて、GitHub からコードをコピーします。(コード スニペットの右上にある > [GitHub で表示] をクリックします)。
API を有効にする
Terraform のサンプルでは通常、必要な API がGoogle Cloud プロジェクトで有効になっていることを前提としています。次のコード スニペットを使用して、このクイックスタートに必要な API を有効にします。
サービス アカウントを作成してアクセスを構成する
すべての Eventarc トリガーは IAM サービス アカウントに関連付けられています。このクイックスタートを完了するには、ユーザー管理サービス アカウントに次の IAM ロールを付与する必要があります。
-
Cloud Run 起動元ロール(
roles/run.invoker
) -
Pub/Sub パブリッシャーのロール(
roles/pubsub.publisher
)
次のコード スニペットを使用して、専用のサービス アカウントを作成し、イベントを管理するための特定の IAM ロールを付与します。
2021 年 4 月 8 日以前に Pub/Sub サービス エージェントを有効にした場合は、サービス エージェントにサービス アカウント トークン作成者のロール(roles/iam.serviceAccountTokenCreator
)を付与します。
resource "google_project_iam_member" "tokencreator" { project = data.google_project.project.id role = "roles/iam.serviceAccountTokenCreator" member = "serviceAccount:service-${data.google_project.project.number}@gcp-sa-pubsub.iam.gserviceaccount.com" }
Cloud Run にイベント レシーバをデプロイする
google_cloud_run_v2_service
Terraform リソースを使用して、Eventarc トリガーのイベントの宛先として Cloud Run サービスを作成します。
イベント プロバイダとして Pub/Sub トピックを作成する
google_pubsub_topic
Terraform リソースを使用して Pub/Sub トピックを作成します。
Eventarc トリガーを作成する
google_eventarc_trigger
Terraform リソースを使用して、Pub/Sub メッセージをリッスンする Eventarc トリガーを作成します。
Terraform を適用
Terraform CLI を使用して、構成ファイルに基づいてインフラストラクチャをプロビジョニングします。
Terraform 構成を適用または削除する方法については、基本的な Terraform コマンドをご覧ください。
Terraform を初期化します。これは、ディレクトリごとに 1 回だけ行います。
terraform init
最新バージョンの Google プロバイダを使用する場合は、
-upgrade
オプションを使用します。terraform init -upgrade
構成を確認して、Terraform が作成または更新するリソースが想定どおりであることを確認します。
terraform plan
必要に応じて構成を修正します。
次のコマンドを実行し、プロンプトで「
yes
」と入力して、Terraform 構成を適用します。terraform apply
通常は、構成全体を一度に適用します。ただし、特定のリソースをターゲットにすることもできます。次に例を示します。
terraform apply -target="google_eventarc_trigger.default"
API を有効にしてから、アクションが反映され、他のリソースをデプロイできるようになるまでに数分かかることがあります。問題が発生した場合は、Terraform 構成をもう一度適用してみてください。
Terraform に「Apply complete!」というメッセージが表示されるまで待ちます。
リソースの作成を確認する
Cloud Run サービスが作成されたことを確認します。
gcloud run services list --region us-central1
出力例を以下に示します。
SERVICE: hello-events REGION: us-central1 URL: https://hello-events-13335919645.us-central1.run.app LAST DEPLOYED BY: ... LAST DEPLOYED AT: 2024-12-16T15:00:52.606160Z
Eventarc トリガーが作成されたことを確認します。
gcloud eventarc triggers list --location us-central1
出力例を以下に示します。
NAME: trigger-pubsub-cloudrun-tf TYPE: google.cloud.pubsub.topic.v1.messagePublished DESTINATION: Cloud Run service: hello-events ACTIVE: Yes LOCATION: us-central1
Pub/Sub トピック イベントを生成して表示する
Pub/Sub トピックにメッセージを公開することでイベントを生成できます。Eventarc トリガーは、Cloud Run にデプロイされたイベント レシーバ サービスにメッセージを転送し、サービスはイベント メッセージをログに記録します。
Pub/Sub トピックを検索して、環境変数として設定します。
gcloud config set eventarc/location us-central1 export RUN_TOPIC=$(gcloud eventarc triggers describe trigger-pubsub-cloudrun-tf \ --format='value(transport.pubsub.topic)')
Pub/Sub トピックにメッセージをパブリッシュしてイベントを生成します。
gcloud pubsub topics publish $RUN_TOPIC --message "Hello World!"
イベントが Cloud Run サービスに転送され、イベント メッセージがログに記録されます。
サービスによって作成されたイベント関連ログエントリを表示するには、次のコマンドを実行します。
gcloud logging read 'jsonPayload.message: "Received event of type google.cloud.pubsub.topic.v1.messagePublished"'
次のようなログエントリを探します。
jsonPayload: ... message: 'Received event of type google.cloud.pubsub.topic.v1.messagePublished. Event data: Hello World!'
Terraform を使用してイベント レシーバ サービスを Cloud Run にデプロイし、Eventarc トリガーを作成しました。Pub/Sub からイベントを生成すると、Cloud Run ログで確認できます。
クリーンアップ
このクイックスタートで説明するタスクが完了したら、作成したリソースを削除すると、それ以上の請求は発生しません。
以前に Terraform 構成で適用されたリソースを削除するために、次のコマンドを実行してプロンプトで「yes
」と入力します。
terraform destroy
また、 Google Cloud プロジェクトを削除して、料金が発生しないようにすることもできます。 Google Cloud プロジェクトを削除すると、そのプロジェクト内で使用されているすべてのリソースに対する課金が停止します。
Delete a Google Cloud project:
gcloud projects delete PROJECT_ID
複数のチュートリアルとクイックスタートを実施する予定がある場合は、プロジェクトを再利用すると、プロジェクトの割り当て上限を超えないようにできます。