Next.js を Terraform で Cloud Run へデプロイした際のメモまとめ
Terraform による Next.js アプリの Cloud Run 環境構築
約1年前
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 セットアップスクリプトの実行手順
約1年前
事前準備:
# 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 ../.envCloud Build トリガーと GitHub リポジトリの連携
約1年前
Cloud Build と GitHub を連携させる手順:
- Cloud Build トリガー ページにアクセス
- 「リポジトリを接続」をクリック
- GitHub を選択し、認証を完了
- 対象リポジトリを選択
この設定により、GitHub へのプッシュ時に自動的に Cloud Build が起動し、CI/CD パイプラインが実行される。
Terraform での環境別デプロイ実行方法
約1年前
開発環境のデプロイ:
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 の権限設定
約1年前
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 アプリのビルド・デプロイ設定
約1年前
Cloud Build を使用して Next.js アプリケーションを Docker イメージとしてビルドし、Cloud Run にデプロイする設定。
主な処理ステップ:
- Docker イメージのビルド(環境変数を build-arg として渡す)
- ビルドしたイメージを Artifact Registry にプッシュ
- Cloud Run へのデプロイ
タグ付け戦略:
- コミットSHA によるタグ: 特定のデプロイバージョンを識別
- latest タグ: 最新のイメージを示す
タイムアウト設定: 1200秒(20分) ログ保存: Cloud Logging のみ
Cloud Build での Next.js ビルド時環境変数の渡し方
約1年前
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 へのイメージプッシュ
約1年前
ビルドした 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 デプロイ
約1年前
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 による環境別設定の管理
約1年前
置換変数を使用した環境別設定の管理方法:
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を無効化する方法
約1年前
Cloud Run のデフォルトURL(*.run.app)を無効化して、カスタムドメインのみでアクセス可能にする設定方法。
必要な要件:
-
Google Provider 6.0以上が必要
- default_uri_disabled パラメータは Provider 6.0 で追加された機能
-
google_cloud_run_v2_service リソースを使用
- v1 の google_cloud_run_service では利用不可
- v2 API でのみサポートされている機能
-
必須の3つの設定
hclresource "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 ドメインマッピングリソース定義
約1年前
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を設定