バスと登録を作成してイベントを公開、受信する(Terraform)

このクイックスタートでは、Terraform を使用して プロジェクト Google Cloud に Eventarc Advanced バスと登録を作成し、イベント メッセージを公開して受信する方法について説明します。

  • バスは、イベントソースからメッセージを受信したり、プロバイダによって公開されたメッセージを受信したりする中央ルーターとして機能します。

  • 登録は、バスが受信したメッセージを 1 つ以上の 宛先に処理パイプラインを介してルーティングします。

このクイックスタートでは、以下の操作を行います。

  1. イベント レシーバ サービスを Cloud Run にデプロイする。

  2. Eventarc Advanced バスを作成する。

  3. Google ソースからのイベントを有効にする。

  4. Eventarc Advanced パイプラインと登録を作成する。

  5. ワークフローを作成して、イベント メッセージをバスに公開する。

  6. Cloud Run のログでイベントデータを確認する。

このクイックスタートの手順のほとんどは、Terraform を使用して完了できます。Google Cloud CLI を使用してすべての手順を完了するには、 Google ソースからイベントを公開するをご覧ください。

Terraform の使用方法について詳しくは、 Terraform on Google Cloud のドキュメントをご覧ください。

始める前に

組織で定義されているセキュリティの制約により、次の手順を完了できない場合があります。トラブルシューティング情報については、 制約のある Google Cloud 環境でアプリケーションを開発するをご覧ください。

  1. アカウントに Google Cloud ログインします。 Google Cloudを初めて使用する場合は、 アカウントを作成して、実際のシナリオで Google プロダクトのパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

  4. Verify that billing is enabled for your Google Cloud project.

  5. Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  6. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  7. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

  8. Verify that billing is enabled for your Google Cloud project.

  9. Enable the Cloud Resource Manager and Identity and Access Management (IAM) APIs.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  10. コンソール Google Cloud で Cloud Shell をアクティブにします。

    Cloud Shell をアクティブにする

    コンソールの下部にある Google Cloud Cloud Shell セッションが開始し、コマンドライン プロンプトが表示されます。Cloud Shell はシェル環境です 。Google Cloud CLI がすでにインストールされており、現在のプロジェクトの値もすでに設定されています 。セッションが初期化されるまで数秒かかることがあります。

  11. Terraform は Cloud Shell シェル環境に統合されているため、Cloud Shell を使用して Terraform リソースをデプロイできます。Terraform をインストールする必要はありません。

必要なロール

このクイックスタートを完了するために必要な権限を取得するには、プロジェクトに対する次の IAM ロールを付与するよう管理者に依頼してください。

ロールの付与については、プロジェクト、フォルダ、組織へのアクセスを管理するをご覧ください。

必要な権限は、カスタム ロールや他の事前定義 ロールから取得することもできます。

Terraform をデプロイする準備をする

Terraform リソースをデプロイする前に、Terraform 構成ファイルを作成する必要があります。Terraform 構成ファイルを使用すると、Terraform 構文を使用してインフラストラクチャの望ましい最終状態を定義できます。

  1. Cloud Shell で、Terraform 構成を適用するデフォルトの Google Cloud プロジェクトを 設定します。このコマンドは、プロジェクトごとに 1 回だけ実行する必要があります。これは任意のディレクトリで実行できます。

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    PROJECT_ID は、 Google Cloud プロジェクトの ID に置き換えます。

    Terraform 構成ファイルに明示的な値を設定すると、環境変数がオーバーライドされます。

  2. 各 Terraform 構成ファイルには独自のディレクトリ(ルート モジュール)が必要です。 Cloud Shell で、ディレクトリを作成し、そのディレクトリ内に新しいファイルを作成します。

    mkdir DIRECTORY && cd DIRECTORY && touch main.tf

    DIRECTORY は、Terraform ディレクトリの名前に置き換えます。

    ファイル名の拡張子は .tf にする必要があります。たとえば、このクイックスタートでは、構成ファイルは main.tf です。

Terraform 構成を定義する

次の Terraform コードスニペットを main.tf ファイルにコピーします。または、GitHub からコードサンプル全体をコピーするには、コードスニペットの右上にある more_vert をクリックして > [GitHub で表示]を選択します。

API を有効にする

google_project_service Terraform リソースを使用して、Terraform 構成の適用に必要な API を有効にします。

# Enable APIs
resource "google_project_service" "apis" {
  for_each = toset([
    "eventarc.googleapis.com",
    "eventarcpublishing.googleapis.com",
    "run.googleapis.com"
  ])
  service            = each.key
  disable_on_destroy = false
}

サービス アカウントを作成する

テスト用に専用のサービス アカウントを作成し、特定の IAM ロールを付与します。

google_service_accountgoogle_project_iam_member の Terraform リソースを使用してサービス アカウントを作成し、イベントの公開と受信に必要な ロールを付与します。

# Used to retrieve project information later
data "google_project" "project" {}

# Create a dedicated service account
resource "google_service_account" "default" {
  account_id   = "eventarc-advanced-sa"
  display_name = "Eventarc Advanced quickstart service account"
}

# Grant permission to receive Eventarc events
resource "google_project_iam_member" "eventreceiver" {
  project = data.google_project.project.id
  role    = "roles/eventarc.eventReceiver"
  member  = "serviceAccount:${google_service_account.default.email}"
}

# Grant permission to invoke Cloud Run services
resource "google_project_iam_member" "runinvoker" {
  project = data.google_project.project.id
  role    = "roles/run.invoker"
  member  = "serviceAccount:${google_service_account.default.email}"
}

イベントの宛先を作成する

google_cloud_run_v2_service Terraform リソースを使用して、イベントの内容をログに記録するイベントの宛先として Cloud Run サービス を作成します。

# Deploy Cloud Run service
resource "google_cloud_run_v2_service" "default" {
  name     = "example-service"
  location = "us-central1"

  deletion_protection = false # set to "true" in production

  template {
    containers {
      # This sample container listens to HTTP requests and logs received events
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
    service_account = google_service_account.default.email
  }

  depends_on = [google_project_service.apis]
}

Eventarc Advanced バスを作成する

バスは、メッセージ ソースからイベント メッセージを受信するか、プロバイダによって公開されたイベント メッセージを受信し、メッセージ ルーターとして機能します。詳細については、 メッセージをルーティングするバスを作成するをご覧ください。

google_eventarc_message_bus Terraform リソースを使用して、Eventarc Advanced バスを作成します。

# Create an Eventarc Advanced bus
resource "google_eventarc_message_bus" "default" {
  location       = "us-central1"
  message_bus_id = "example-bus"
}

Google ソースからのイベントを有効にする

Google ソースからイベントを公開するには、特定の Eventarc Advanced バスに対する Google API イベントのサブスクリプションを表す GoogleApiSource リソースを作成する必要があります。詳細については、 Google ソースからイベントを公開するをご覧ください。

google_eventarc_google_api_source Terraform リソースを使用して、Google ソースからのイベントを有効にします。

# Enable events from Google API sources
resource "google_eventarc_google_api_source" "default" {
  location             = "us-central1"
  google_api_source_id = "example-google-api-source"
  destination          = google_eventarc_message_bus.default.id
}

Google ソースから直接送信されるサポートされているすべての Google イベントタイプ が収集され、バスに公開されます。

Eventarc Advanced パイプラインを作成する

パイプラインを使用すると、ターゲットの宛先を構成できます。また、一致したイベントを宛先に配信する前に変換するオプションも提供されます。

google_eventarc_pipeline Terraform リソースを使用してパイプラインを作成します。

# Create an Eventarc Advanced pipeline
resource "google_eventarc_pipeline" "default" {
  location    = "us-central1"
  pipeline_id = "example-pipeline"
  destinations {
    http_endpoint {
      uri = google_cloud_run_v2_service.default.uri
    }
    authentication_config {
      google_oidc {
        service_account = google_service_account.default.email
      }
    }
  }
}

イベントの宛先は、Cloud Run サービスの完全修飾 URL です(例: https://SERVICE_NAME-abcdef-uc.a.run.app)。サービス アカウントのメールアドレスは、 OIDC トークンの生成に使用されます。

Eventarc Advanced 登録を作成する

登録は、宛先にルーティングされるメッセージを決定します。また、イベント メッセージの宛先を構成するために使用されるパイプラインも指定します。詳細については、 イベントを受信する登録を作成するをご覧ください。

google_eventarc_enrollment Terraform リソースを使用して登録を作成します。

# Create an Eventarc Advanced enrollment
resource "google_eventarc_enrollment" "default" {
  location      = "us-central1"
  enrollment_id = "example-enrollment"
  message_bus   = google_eventarc_message_bus.default.id
  destination   = google_eventarc_pipeline.default.id
  cel_match     = "message.type == 'google.cloud.workflows.workflow.v1.created'"
}

登録の一致式では ワークフローが作成されるたびにイベント メッセージを公開するために Common Expression Language(CEL) を使用します。次のステップで、 ワークフローを作成します

Terraform 構成を適用する

Terraform CLI を使用して、構成ファイルに基づいてインフラストラクチャをプロビジョニングします。詳細については、 基本的な Terraform コマンドをご覧ください。

  1. Terraform を初期化します。これは、ディレクトリごとに 1 回だけ行います。

    terraform init

    最新バージョンの Google プロバイダを使用する場合は、-upgrade オプションを使用します。

    terraform init -upgrade
  2. 構成を確認して、Terraform が作成または更新するリソースが想定どおりであることを確認します。

    terraform plan

    必要に応じて構成を修正します。

  3. 次のコマンドを実行し、プロンプトで「yes」と入力して、Terraform 構成を適用します。

    terraform apply

    通常、構成全体を一度に適用します。ただし、特定のリソースをターゲットにすることもできます。次に例を示します。

    terraform apply -target="google_eventarc_message_bus.default"

    Terraform に「Apply complete!」というメッセージが表示されるまで待ちます。

ワークフローを作成して、イベント メッセージをバスに公開する

Workflows は、フルマネージドの オーケストレーション プラットフォームで、定義した順序(ワークフロー)でサービスを実行します。ワークフローを作成して、Google ソースから サポートされているイベントタイプを生成します。

  1. ホーム ディレクトリで、myWorkflow.yaml という名前の新しいファイルを作成します。

  2. 次のワークフローをコピーして新しいファイルに貼り付け、保存します。

    main:
        params: [input]
        steps:
        - checkSearchTermInInput:
            switch:
                - condition: '${"searchTerm" in input}'
                  assign:
                    - searchTerm: '${input.searchTerm}'
                  next: readWikipedia
        - getLocation:
            call: sys.get_env
            args:
                name: GOOGLE_CLOUD_LOCATION
            result: location
        - setFromCallResult:
            assign:
                - searchTerm: '${text.split(location, "-")[0]}'
        - readWikipedia:
            call: http.get
            args:
                url: 'https://en.wikipedia.org/w/api.php'
                query:
                    action: opensearch
                    search: '${searchTerm}'
            result: wikiResult
        - returnOutput:
                return: '${wikiResult.body[1]}'
    

    このワークフローは、ワークフローがデプロイされているリージョンを Wikipedia APIに渡し、 関連する Wikipedia の記事の一覧を返します。

  3. gcloud workflows deploy コマンドを使用してワークフローをデプロイします。

    gcloud workflows deploy example-workflow --source=myWorkflow.yaml \
        --service-account=eventarc-advanced-sa@PROJECT_ID.iam.gserviceaccount.com \
        --location=us-central1

Cloud Run のログでイベントデータを確認する

Eventarc Advanced バスにイベントを公開したら、Cloud Run サービスのログを確認して、イベントが想定どおりに受信されたことを確認できます。

  1. サービスによって作成されたログエントリをフィルタします。

    gcloud logging read 'jsonPayload.message: "Received event of type google.cloud.workflows.workflow.v1.created."'
    
  2. 次のようなログエントリを探します。

    message: 'Received event of type google.cloud.workflows.workflow.v1.created.
    Event data: {"@type":"type.googleapis.com/google.events.cloud.workflows.v1.WorkflowEventData","payload":{"name":"projects/PROJECT_ID/locations/us-central1/workflows/example-workflow","state":"ACTIVE"...
    

Eventarc Advanced バスと登録を作成し、Google ソースからのイベントの公開を有効にしました。また、Google プロバイダからサポートされているイベントタイプを生成するワークフローを作成し、イベント レシーバ サービスのログで想定される結果を確認しました。

クリーンアップ

次のコマンドを実行しています。プロンプトでyesと入力して、以前に Terraform 構成で適用されたリソースを削除します。

terraform destroy

プロジェクト Google Cloud を削除して、料金が発生しないようにすることもできます。 your Google Cloud プロジェクトを削除すると、その プロジェクト内で使用されているすべてのリソースに対する課金が停止します。

  1. コンソール Google Cloud で [**リソースの管理**] ページに移動します。

    [リソースの管理] に移動

  2. プロジェクト リストで、削除するプロジェクトを選択し、[削除] をクリックします。
  3. ダイアログでプロジェクト ID を入力し、 [Shut down] をクリックしてプロジェクトを削除します。

次のステップ