Next.js を Terraform で Cloud Run へデプロイした際のメモまとめ

Terraform による Next.js アプリの Cloud Run 環境構築

16日前


Google Cloud Platform 上で Next.js アプリケーションをホストするためのインフラを Terraform で管理する構成。

管理対象リソース:

  • Secret Manager: 環境変数の安全な管理
  • Cloud Build: CI/CD パイプライン
  • Artifact Registry: Docker イメージの保存
  • Cloud Run: アプリケーションのホスティング
  • IAM: 適切な権限管理

ディレクトリ構造:

  • modules/: 再利用可能なモジュール(cloud-run, cloud-build, secret-manager)
  • environments/: 環境別設定(dev, prod)
  • scripts/: セットアップ・削除スクリプト

Cloud Run 用 Terraform セットアップスクリプトの実行手順

16日前


事前準備:

# Google Cloud SDK のインストール brew install google-cloud-sdk # Terraform のインストール brew install terraform # Google Cloud にログイン gcloud auth login gcloud auth application-default login

自動セットアップスクリプトの実行:

cd terraform/scripts ./setup.sh

スクリプトが自動実行する処理:

  • プロジェクト ID の設定
  • 必要な GCP API の有効化
  • Terraform 用サービスアカウントの作成と権限付与
  • Cloud Build サービスアカウントの権限設定
  • Terraform State 管理用 GCS バケットの作成
  • サービスアカウントキーの生成
  • 環境変数ファイル (.env) の作成

環境変数の適用:

source ../.env

Cloud Build トリガーと GitHub リポジトリの連携

16日前


Cloud Build と GitHub を連携させる手順:

  1. Cloud Build トリガー ページにアクセス
  2. 「リポジトリを接続」をクリック
  3. GitHub を選択し、認証を完了
  4. 対象リポジトリを選択

この設定により、GitHub へのプッシュ時に自動的に Cloud Build が起動し、CI/CD パイプラインが実行される。

Terraform での環境別デプロイ実行方法

16日前


開発環境のデプロイ:

source ../.env cd terraform/environments/dev cp terraform.tfvars.example terraform.tfvars vi terraform.tfvars # 環境変数を設定 terraform init terraform plan terraform apply

本番環境のデプロイ:

source ../.env cd terraform/environments/prod cp terraform.tfvars.example terraform.tfvars vi terraform.tfvars # 環境変数を設定 terraform init terraform plan terraform apply

注意点:

  • terraform.tfvars には機密情報が含まれるため Git にコミットしない
  • 本番環境への適用前に必ず terraform plan で変更内容を確認する

Cloud Build と Secret Manager の権限設定

16日前


Cloud Build の権限エラー対処:

# プロジェクト番号を取得 PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)") # Cloud Build サービスアカウントに権限を付与 gcloud projects add-iam-policy-binding $PROJECT_ID \ --member="serviceAccount:${PROJECT_NUMBER}@cloudbuild.gserviceaccount.com" \ --role="roles/run.admin"

Secret Manager のアクセスエラー対処:

# Cloud Run サービスアカウントに権限を付与 gcloud projects add-iam-policy-binding $PROJECT_ID \ --member="serviceAccount:paput-front-${ENV}-sa@${PROJECT_ID}.iam.gserviceaccount.com" \ --role="roles/secretmanager.secretAccessor"

API 有効化:

# エラーメッセージに表示された API を有効化 gcloud services enable [API_NAME]

Cloud Build での Next.js アプリのビルド・デプロイ設定

16日前


Cloud Build を使用して Next.js アプリケーションを Docker イメージとしてビルドし、Cloud Run にデプロイする設定。

主な処理ステップ:

  1. Docker イメージのビルド(環境変数を build-arg として渡す)
  2. ビルドしたイメージを Artifact Registry にプッシュ
  3. Cloud Run へのデプロイ

タグ付け戦略:

  • コミットSHA によるタグ: 特定のデプロイバージョンを識別
  • latest タグ: 最新のイメージを示す

タイムアウト設定: 1200秒(20分) ログ保存: Cloud Logging のみ

Cloud Build での Next.js ビルド時環境変数の渡し方

16日前


Next.js のビルド時に必要な環境変数を Docker build-arg として渡す方法:

- name: 'gcr.io/cloud-builders/docker' args: - 'build' - '--build-arg' - 'NODE_ENV=${_NODE_ENV}' - '--build-arg' - 'NEXT_PUBLIC_BASE_URL=${_NEXT_PUBLIC_BASE_URL}' - '--build-arg' - 'NEXT_PUBLIC_BASE_API_URL=${_NEXT_PUBLIC_BASE_API_URL}' - '--build-arg' - 'NEXT_PUBLIC_GOOGLE_CLIENT_ID=${_NEXT_PUBLIC_GOOGLE_CLIENT_ID}' - '--build-arg' - 'NEXT_PUBLIC_GOOGLE_REDIRECT_URI=${_NEXT_PUBLIC_GOOGLE_REDIRECT_URI}'

置換変数(substitutions)を使用して、Terraform から環境別の値を注入可能。 NEXT_PUBLIC_ プレフィックスのついた変数はクライアントサイドでも利用される。

Cloud Build から Artifact Registry へのイメージプッシュ

16日前


ビルドした Docker イメージを Artifact Registry にプッシュする設定:

- name: 'gcr.io/cloud-builders/docker' args: - 'push' - '--all-tags' - '${_REGION}-docker.pkg.dev/$PROJECT_ID/${_SERVICE_NAME}-docker/${_SERVICE_NAME}'

イメージの命名規則: [リージョン]-docker.pkg.dev/[プロジェクトID]/[サービス名]-docker/[サービス名]

--all-tags オプションによって、commit SHA と latest の両方のタグがプッシュされる。

gcloud コマンドによる Cloud Run デプロイ

16日前


Cloud Build から Cloud Run にデプロイするコマンド設定:

- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk' entrypoint: gcloud args: - 'run' - 'deploy' - '${_SERVICE_NAME}' - '--image' - '${_REGION}-docker.pkg.dev/$PROJECT_ID/${_SERVICE_NAME}-docker/${_SERVICE_NAME}:$COMMIT_SHA' - '--region' - '${_REGION}' - '--platform' - 'managed'

コミット SHA タグを使用してデプロイすることで、どのコミットがデプロイされているかを明確に追跡できる。 --platform managed は完全マネージド版の Cloud Run を指定。

Cloud Build substitutions による環境別設定の管理

16日前


置換変数を使用した環境別設定の管理方法:

substitutions: _SERVICE_NAME: paput-front _REGION: asia-northeast1 _ENV: dev _NODE_ENV: production _NEXT_PUBLIC_BASE_URL: https://dev.paput.example.com _NEXT_PUBLIC_BASE_API_URL: https://api-dev.paput.example.com _NEXT_PUBLIC_GOOGLE_CLIENT_ID: your-google-client-id _NEXT_PUBLIC_GOOGLE_REDIRECT_URI: https://dev.paput.example.com/api/auth/callback/google

これらのデフォルト値は Terraform から環境に応じて上書きされる。 変数名は _ (アンダースコア) で始まる規則を使用。

Cloud Run v2 でデフォルトURLを無効化する方法

16日前


Cloud Run のデフォルトURL(*.run.app)を無効化して、カスタムドメインのみでアクセス可能にする設定方法。

必要な要件:

  1. Google Provider 6.0以上が必要

    • default_uri_disabled パラメータは Provider 6.0 で追加された機能
  2. google_cloud_run_v2_service リソースを使用

    • v1 の google_cloud_run_service では利用不可
    • v2 API でのみサポートされている機能
  3. 必須の3つの設定

    resource "google_cloud_run_v2_service" "app" { provider = google-beta launch_stage = "BETA" default_uri_disabled = true }

設定の詳細:

  • provider = google-beta: ベータ版プロバイダーの使用が必要
  • launch_stage = "BETA": BETA ステージの機能として提供
  • default_uri_disabled = true: デフォルトURLを無効化

この設定により、*.run.app のURLでのアクセスが無効になり、カスタムドメインでのみサービスにアクセス可能となる。セキュリティ強化や、意図しないアクセスを防ぐ場合に有効。

Terraform での Cloud Run ドメインマッピングリソース定義

16日前


Terraform で Cloud Run のカスタムドメインを設定するリソース定義:

resource "google_cloud_run_domain_mapping" "default" { count = var.custom_domain != "" ? 1 : 0 location = var.region name = var.custom_domain metadata { namespace = var.project_id } spec { route_name = google_cloud_run_v2_service.app.name } depends_on = [google_cloud_run_v2_service.app] }

ポイント:

  • count で条件付きリソース作成(custom_domain が設定されている場合のみ)
  • name にカスタムドメインを指定
  • route_name で対象の Cloud Run サービスを指定
  • Cloud Run サービスの作成後に実行されるよう depends_on を設定