Terraform Pub/Sub のチュートリアル


このチュートリアルでは、関数のソースコードの zip ファイルを Cloud Storage バケットにアップロードし、Terraform を使用してリソースをプロビジョニングして、Pub/Sub 関数をデプロイする方法について説明します。Terraform は、宣言型の構成ファイルを使用して Google Cloud リソースをプロビジョニングできるオープンソース ツールです。

このチュートリアルでは例として Node.js 関数を使用していますが、Python、Go、Java の関数にも対応しています。使用しているランタイムがどれであっても、手順は同じです。Cloud Functions v2 API で Terraform を使用する方法については、Hashicorp のリファレンス ページをご覧ください。

目標

  • Terraform を使用して Pub/Sub 関数をデプロイする方法を学習します。

費用

このドキュメントでは、課金対象である次の Google Cloudコンポーネントを使用します。

For details, see Cloud Run functions pricing.

料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。

新規の Google Cloud ユーザーは無料トライアルをご利用いただける場合があります。

始める前に

  1. 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.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

  4. Enable the Cloud Functions, Cloud Build, Artifact Registry, and Cloud Storage APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. 外部 ID プロバイダ(IdP)を使用している場合は、まずフェデレーション ID を使用して gcloud CLI にログインする必要があります。

  7. gcloud CLI を初期化するには、次のコマンドを実行します。

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

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

  10. Enable the Cloud Functions, Cloud Build, Artifact Registry, and Cloud Storage APIs.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. 外部 ID プロバイダ(IdP)を使用している場合は、まずフェデレーション ID を使用して gcloud CLI にログインする必要があります。

  13. gcloud CLI を初期化するには、次のコマンドを実行します。

    gcloud init
  14. gcloud CLI がすでにインストールされている場合は、次のコマンドを実行して更新します。

    gcloud components update
  15. デフォルトのコンピューティング サービス アカウントに roles/run.invokerroles/cloudbuild.builds.builder を付与します。
  16. 開発環境を準備します。

    Node.js 設定ガイドに移動

  17. 環境設定

    このチュートリアルでは、Cloud Shell でコマンドを実行します。Cloud Shell は、Google Cloud CLI がすでにインストールされているシェル環境で、現在のプロジェクトの値もすでに設定されています。Cloud Shell の初期化には数分かかることがあります。

    Cloud Shell を開く

    アプリケーションの準備

    Cloud Shell で次の操作を行います。

    1. Cloud Shell インスタンスにサンプルアプリ リポジトリのクローンを作成します。

      git clone https://github.com/terraform-google-modules/terraform-docs-samples.git
    2. Cloud Run functions のサンプルコードが含まれているディレクトリに移動します。

      cd terraform-docs-samples/functions/pubsub

      このチュートリアルで使用する Node.js サンプルは、基本的な「Hello World」Pub/Sub 関数です。main.tf ファイルは次のようになっています。

      terraform {
        required_providers {
          google = {
            source  = "hashicorp/google"
            version = ">= 4.34.0"
          }
        }
      }
      
      resource "random_id" "bucket_prefix" {
        byte_length = 8
      }
      
      
      resource "google_service_account" "default" {
        account_id   = "test-gcf-sa"
        display_name = "Test Service Account"
      }
      
      resource "google_pubsub_topic" "default" {
        name = "functions2-topic"
      }
      
      resource "google_storage_bucket" "default" {
        name                        = "${random_id.bucket_prefix.hex}-gcf-source" # Every bucket name must be globally unique
        location                    = "US"
        uniform_bucket_level_access = true
      }
      
      data "archive_file" "default" {
        type        = "zip"
        output_path = "/tmp/function-source.zip"
        source_dir  = "function-source/"
      }
      
      resource "google_storage_bucket_object" "default" {
        name   = "function-source.zip"
        bucket = google_storage_bucket.default.name
        source = data.archive_file.default.output_path # Path to the zipped function source code
      }
      
      resource "google_cloudfunctions2_function" "default" {
        name        = "function"
        location    = "us-central1"
        description = "a new function"
      
        build_config {
          runtime     = "nodejs22"
          entry_point = "helloPubSub" # Set the entry point
          environment_variables = {
            BUILD_CONFIG_TEST = "build_test"
          }
          source {
            storage_source {
              bucket = google_storage_bucket.default.name
              object = google_storage_bucket_object.default.name
            }
          }
        }
      
        service_config {
          max_instance_count = 3
          min_instance_count = 1
          available_memory   = "256M"
          timeout_seconds    = 60
          environment_variables = {
            SERVICE_CONFIG_TEST = "config_test"
          }
          ingress_settings               = "ALLOW_INTERNAL_ONLY"
          all_traffic_on_latest_revision = true
          service_account_email          = google_service_account.default.email
        }
      
        event_trigger {
          trigger_region = "us-central1"
          event_type     = "google.cloud.pubsub.topic.v1.messagePublished"
          pubsub_topic   = google_pubsub_topic.default.id
          retry_policy   = "RETRY_POLICY_RETRY"
        }
      }

    Terraform を初期化する

    main.tf ファイルを含む terraform-docs-samples/functions/pubsub ディレクトリで、次のコマンドを実行して必要なプラグインを追加し、.terraform ディレクトリをビルドします。

    terraform init
    

    Terraform 構成を検証する

    Terraform 構成をプレビューします。このステップは省略可能ですが、main.tf の構文が正しいかどうかを確認できます。このコマンドにより、作成されるリソースのプレビューが表示されます。

    terraform plan
    

    Terraform 構成を適用する

    構成を適用して関数をデプロイします。プロンプトが表示されたら、「yes」と入力します。

    terraform apply
    

    関数のトリガー

    Pub/Sub 関数をテストするには:

    1. トピックにメッセージをパブリッシュします(この例のトピック名は functions2-topic です)。

      gcloud pubsub topics publish TOPIC_NAME --message="Friend"
    2. 関数のログで結果を確認します。ここで、FUNCTION_NAME は関数の名前です(この例の関数名は function です)。

      gcloud functions logs read FUNCTION_NAME

      ログの出力に、新しい「Friend」メッセージが含まれているはずです。

    クリーンアップ

    チュートリアルの完了後は、それ以上の費用が発生しないように、作成したものをすべて削除できます。

    Terraform では、terraform destroy コマンドを実行して、構成ファイルで定義されているすべてのリソースを削除できます。

    terraform destroy
    

    Terraform でリソースを削除できるようにするには、「yes」と入力します。