バスと登録を作成してイベントをパブリッシュして受信する(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 の使用方法の詳細については、 Google Cloudでの Terraform のドキュメントをご覧ください。

始める前に

組織で定義されているセキュリティの制約により、次の手順を完了できない場合があります。トラブルシューティング情報については、制約のある 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, if any are not already enabled.

    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, if any are not already enabled.

    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 からコードサンプル全体をコピーするには、コード スニペットの右上にある > [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_account と google_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 プロジェクトを削除して、料金が発生しないようにすることもできます。 Google Cloud プロジェクトを削除すると、そのプロジェクト内で使用されているすべてのリソースに対する課金が停止します。

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

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

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

次のステップ