Terraform のチュートリアル


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

このチュートリアルでは例として Node.js HTTP 関数を使用していますが、Python、Go、Java の HTTP 関数にも対応しています。使用しているランタイムがどれであっても、手順は同じです。

Terraform を使用してデプロイする場合は、関数の zip 形式のソースファイルを Cloud Storage バケット(source_archive_bucket)にアップロードし、Terraform 構成で Cloud Storage オブジェクト名(source_archive_object)も指定する必要があります。詳細については、Terraform 仕様ガイドをご覧ください。

Cloud Run functions は、source_archive_bucket にアップロードしたソースファイルを、gcf-v2-sources-PROJECT_NUMBER-REGION(Cloud Run functions)または gcf-sources-PROJECT_NUMBER-REGION Cloud Run functions(第 1 世代)の形式のバケット名を持つプロジェクトのバケットにコピーします。この構成は、CMEK の依存関係によって異なります。

目標

  • Terraform を使用して HTTP 関数をデプロイする方法について学習します。

費用

このドキュメントでは、課金対象である次の 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 Run, 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 Run, 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. 開発環境を準備します。

    Node.js 設定ガイドに移動

  16. 必要なロール

    • 関数をデプロイするユーザーには、Cloud Functions デベロッパーroles/cloudfunctions.developer)の IAM ロールまたは同等の権限を含むロールが必要です。デプロイの追加構成もご覧ください。

    • Cloud Storage バケットにアクセスする権限を取得するには、関数をデプロイする IAM ID にストレージ管理者roles/storage.admin)ロールを付与するよう管理者に依頼してください。Cloud Storage のロールと権限の詳細については、Cloud Storage の IAM をご覧ください。

    環境設定

    このチュートリアルでは、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/basic

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

      terraform {
        required_providers {
          google = {
            source  = "hashicorp/google"
            version = ">= 4.34.0"
          }
        }
      }
      
      resource "random_id" "default" {
        byte_length = 8
      }
      
      resource "google_storage_bucket" "default" {
        name                        = "${random_id.default.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  = "functions/hello-world/"
      }
      resource "google_storage_bucket_object" "object" {
        name   = "function-source.zip"
        bucket = google_storage_bucket.default.name
        source = data.archive_file.default.output_path # Add path to the zipped function source code
      }
      
      resource "google_cloudfunctions2_function" "default" {
        name        = "function-v2"
        location    = "us-central1"
        description = "a new function"
      
        build_config {
          runtime     = "nodejs22"
          entry_point = "helloHttp" # Set the entry point
          source {
            storage_source {
              bucket = google_storage_bucket.default.name
              object = google_storage_bucket_object.object.name
            }
          }
        }
      
        service_config {
          max_instance_count = 1
          available_memory   = "256M"
          timeout_seconds    = 60
        }
      }
      
      resource "google_cloud_run_service_iam_member" "member" {
        location = google_cloudfunctions2_function.default.location
        service  = google_cloudfunctions2_function.default.name
        role     = "roles/run.invoker"
        member   = "allUsers"
      }
      
      output "function_uri" {
        value = google_cloudfunctions2_function.default.service_config[0].uri
      }

    Terraform を初期化する

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

    terraform init
    

    Terraform 構成を適用する

    main.tf ファイルが配置されている terraform-docs-samples/functions/basic ディレクトリで、構成を適用して関数をデプロイします。プロンプトが表示されたら、「yes」と入力します。

    terraform apply
    

    関数をテストする

    1. 関数がデプロイされたら、URI プロパティをメモするか、次のコマンドを使用して検索します。

      gcloud functions describe function-v2 --gen2 --region=us-central1 --format="value(serviceConfig.uri)"
      
    2. この URL にリクエストを送信して、関数の「Hello World」メッセージを表示します。この関数のデプロイには認証が必要です。そのため、リクエストには認証情報が必要です。

      curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" YOUR_FUNCTION_URL

    クリーンアップする

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

    Terraform では、main.tf ファイルを含む terraform-docs-samples/functions/basic ディレクトリで terraform destroy コマンドを実行して、構成ファイルで定義されたすべてのリソースを削除できます。

    terraform destroy
    

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