Terraform のチュートリアル


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

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

目標

  • 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. Make sure 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. To initialize the gcloud CLI, run the following command:

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

    Go to project selector

  8. Make sure that billing is enabled for your Google Cloud project.

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

    Enable the APIs

  10. Install the Google Cloud CLI.
  11. To initialize the gcloud CLI, run the following command:

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

    gcloud components update
  13. 開発環境を準備します。

    Node.js 設定ガイドに移動

環境設定

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

Cloud Shell を開く

アプリケーションの準備

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

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

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

    cd nodejs-docs-samples/functions

    このチュートリアルで使用する Node.js サンプルは、基本的な「Hello World」HTTP 関数です。

main.tf ファイルを作成する

  1. nodejs-docs-samples/functions/ ディレクトリに、Terraform 構成用の main.tf ファイルを作成します。

    touch main.tf
    
  2. この Terraform 構成を 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     = "nodejs16"
        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
    }
  3. main.tf ファイルを編集して、次の項目に正しい値が設定されていることを確認します。構成が変更される場合は(別のランタイムを使用する場合や、別の関数をデプロイする場合など)、このファイルを編集する必要があります。

    • ランタイム: この例では、nodejs16 を最新の Node.js ランタイム nodejs20 に置き換えます。
    • 関数のエントリ ポイント: この例の関数のエントリ ポイントは helloHttp です。
    • ソース ディレクトリのパス: この例では、source_dirhelloworld/helloworldHttp に変更します。
    • プロジェクトが allUsers プリンシパルへの IAM ロールの付与を制限するドメイン制限組織ポリシーに基づく場合、IAM member="allUsers" 構成は成功しません。本番環境では慎重に使用し、必要に応じてより制限の厳しいメンバーリストを検討してください。

Terraform を初期化する

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

terraform init

Terraform 構成を適用する

main.tf ファイルを含む nodejs-docs-samples/functions/ ディレクトリで、構成を適用して関数をデプロイします。プロンプトが表示されたら、「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 ファイルを含む nodejs-docs-samples/functions/ ディレクトリで terraform destroy コマンドを実行して、構成ファイルで定義されたすべてのリソースを削除できます。

terraform destroy

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