gcp-cloud-functions について
Google Cloud Functions Gen1/Gen2 でイベント駆動型のサーバーレスアプリを構築・運用するためのスキルです。HTTP やイベントトリガー、スケジュール実行のデプロイと Terraform の設定を扱います。
主な機能
- 01HTTP 関数のデプロイ
- 02Pub/Sub とストレージのトリガー設定
- 03関数ジョブのスケジュール設定
- 04デプロイ済み関数の管理
- 05Terraform 設定の利用
活用シーン
- 01Webhook や軽量 API の処理
- 02Pub/Sub またはファイルアップロードイベントの処理
- 03定期的なクリーンアップの実行
- 04マイクロサービスのプロトタイプ作成
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ bagelhole/ devops-security-agent-skills --skill gcp-cloud-functionsインストール後、Claude Code で/gcp-cloud-functionsを入力して読み込まれたか確認します。
詳細
GCP Cloud Functions
Google Cloud Functions(Gen1 および Gen2)を使用して、イベント駆動型のサーバーレスアプリケーションを構築・デプロイします。
使用する場面
- Webhook、API エンドポイント、軽量な HTTP バックエンドを処理する
- Pub/Sub、Cloud Storage、Firestore、Eventarc のイベントに反応する
- サーバーを管理せずにスケジュールタスク(cron)を実行する
- ファイルのアップロードをトリガーとするデータ処理パイプラインを構築する
- Cloud Run や GKE の利用を決める前に、マイクロサービスのプロトタイプを作成する
前提条件
- Google Cloud SDK(
gcloud)がインストールされ、認証済みであること - API が有効になっていること:Cloud Functions、Cloud Build、Artifact Registry、Cloud Run(Gen2)
- IAM ロール
roles/cloudfunctions.developer(Gen2 の場合はroles/run.developer)
gcloud services enable cloudfunctions.googleapis.com cloudbuild.googleapis.com \
artifactregistry.googleapis.com run.googleapis.com eventarc.googleapis.com
Gen1 と Gen2 の比較
| 機能 | Gen1 | Gen2(推奨) |
|---|---|---|
| ランタイム | Cloud Functions インフラストラクチャ | Cloud Run 上に構築 |
| 最大タイムアウト | 9 分 | 60 分 |
| 最大メモリ | 8 GB | 32 GB |
| 同時実行数 | 1 インスタンスあたり 1 リクエスト | インスタンスあたり最大 1000 |
| トラフィック分割 | なし | あり |
| Eventarc トリガー | なし | あり |
HTTP 関数をデプロイする(Gen2)
# Python HTTP function
gcloud functions deploy hello-http \
--gen2 --region=us-central1 --runtime=python312 \
--trigger-http --allow-unauthenticated \
--entry-point=hello_http \
--memory=256Mi --timeout=60s \
--min-instances=0 --max-instances=100 \
--set-env-vars=APP_ENV=production --source=.
# Node.js HTTP function
gcloud functions deploy hello-node \
--gen2 --region=us-central1 --runtime=nodejs20 \
--trigger-http --allow-unauthenticated \
--entry-point=helloNode --memory=256Mi --source=.
Pub/Sub トリガー関数をデプロイする
gcloud pubsub topics create order-events
gcloud functions deploy process-order \
--gen2 --region=us-central1 --runtime=python312 \
--trigger-topic=order-events \
--entry-point=process_order \
--memory=512Mi --timeout=120s --retry \
--service-account=order-processor@${PROJECT_ID}.iam.gserviceaccount.com \
--source=.
Cloud Storage トリガー関数をデプロイする
gcloud functions deploy process-upload \
--gen2 --region=us-central1 --runtime=python312 \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=my-upload-bucket" \
--entry-point=process_upload \
--memory=1Gi --timeout=300s --source=.
スケジュール関数をデプロイする
gcloud functions deploy daily-cleanup \
--gen2 --region=us-central1 --runtime=python312 \
--trigger-http --no-allow-unauthenticated \
--entry-point=daily_cleanup --source=.
gcloud scheduler jobs create http daily-cleanup-job \
--schedule="0 2 * * *" \
--uri="https://us-central1-${PROJECT_ID}.cloudfunctions.net/daily-cleanup" \
--http-method=POST \
--oidc-service-account-email=scheduler-sa@${PROJECT_ID}.iam.gserviceaccount.com \
--location=us-central1
Python 関数の例
# main.py
import functions_framework
import base64, json
from flask import jsonify
from google.cloud import firestore
@functions_framework.http
def hello_http(request):
"""HTTP Cloud Function."""
name = request.args.get("name", "World")
return jsonify({"message": f"Hello, {name}!", "status": "ok"}), 200
@functions_framework.cloud_event
def process_order(cloud_event):
"""Triggered by a Pub/Sub message."""
data = base64.b64decode(cloud_event.data["message"]["data"]).decode("utf-8")
order = json.loads(data)
db = firestore.Client()
db.collection("orders").document(order["id"]).set({
"status": "processing", "items": order["items"], "total": order["total"],
})
@functions_framework.cloud_event
def process_upload(cloud_event):
"""Triggered when a file is uploaded to Cloud Storage."""
data = cloud_event.data
bucket_name, file_name = data["bucket"], data["name"]
if not file_name.lower().endswith((".png", ".jpg", ".jpeg")):
return
from google.cloud import vision
client = vision.ImageAnnotatorClient()
image = vision.Image(source=vision.ImageSource(
gcs_image_uri=f"gs://{bucket_name}/{file_name}"))
labels = [l.description for l in client.label_detection(image=image).label_annotations]
print(f"Labels for {file_name}: {labels}")
# requirements.txt
functions-framework==3.*
google-cloud-firestore==2.*
google-cloud-storage==2.*
google-cloud-vision==3.*
flask>=2.0
Node.js 関数の例
// index.js
const functions = require("@google-cloud/functions-framework");
functions.http("helloNode", (req, res) => {
const name = req.query.name || "World";
res.json({ message: `Hello, ${name}!`, status: "ok" });
});
functions.cloudEvent("processMessage", (cloudEvent) => {
const data = Buffer.from(cloudEvent.data.message.data, "base64").toString();
console.log(`Processing: ${JSON.parse(data)}`);
});
デプロイ済み関数の管理
gcloud functions list --gen2 --region=us-central1
gcloud functions describe hello-http --gen2 --region=us-central1
gcloud functions logs read hello-http --gen2 --region=us-central1 --limit=50
gcloud functions delete hello-http --gen2 --region=us-central1 --quiet
# Update env vars without redeploying code
gcloud functions deploy hello-http --gen2 --region=us-central1 \
--update-env-vars=APP_ENV=staging
# Test locally before deploying
functions-framework --target=hello_http --port=8080
Terraform の設定
resource "google_cloudfunctions2_function" "api" {
name = "hello-http"
location = "us-central1"
build_config {
runtime = "python312"
entry_point = "hello_http"
source {
storage_source {
bucket = google_storage_bucket.source.name
object = google_storage_bucket_object.source.name
}
}
}
service_config {
min_instance_count = 0
max_instance_count = 100
available_memory = "256Mi"
timeout_seconds = 60
service_account_email = google_service_account.fn.email
environment_variables = { APP_ENV = "production" }
}
}
resource "google_cloud_run_service_iam_member" "invoker" {
location = google_cloudfunctions2_function.api.location
service = google_cloudfunctions2_function.api.name
role = "roles/run.invoker"
member = "allUsers"
}
resource "google_cloudfunctions2_function" "processor" {
name = "process-order"
location = "us-central1"
build_config {
runtime = "python312"
entry_point = "process_order"
source {
storage_source {
bucket = google_storage_bucket.source.name
object = google_storage_bucket_object.source.name
}
}
}
service_config {
max_instance_count = 50
available_memory = "512Mi"
timeout_seconds = 120
service_account_email = google_service_account.fn.email
}
event_trigger {
trigger_region = "us-central1"
event_type = "google.cloud.pubsub.topic.v1.messagePublished"
pubsub_topic = google_pubsub_topic.orders.id
retry_policy = "RETRY_POLICY_RETRY"
}
}
トラブルシューティング
| 症状 | 原因 | 対処方法 |
|---|---|---|
デプロイ時に PERMISSION_DENIED が発生する | Cloud Build または Artifact Registry の権限が不足している | Cloud Build SA に roles/cloudbuild.builds.builder を付与する |
| 関数はデプロイされるが、403 を返す | Gen2 の roles/run.invoker が不足している | --allow-unauthenticated を追加するか、invoker ロールを付与する |
| コールドスタートのレイテンシが 5 秒を超える | 依存関係が大きい、または最小インスタンス数が設定されていない | --min-instances=1 を設定し、依存関係を減らすか、遅延インポートを使用する |
| Pub/Sub メッセージが再配信される | 関数でエラーが発生しているか、タイムアウトしている | --timeout を増やし、エラー処理を修正して、デッドレタートピックを追加する |
デプロイ中に Build failed が発生する | 構文エラーまたは依存関係の不足 | gcloud builds log を確認し、requirements.txt を検証する |
| VPC リソースに接続できない | 関数に VPC コネクタが設定されていない | デプロイ時に --vpc-connector=my-connector を追加する |
関連スキル
- gcp-networking - 関数からプライベートリソースにアクセスするための VPC コネクタ
- gcp-cloud-sql - Cloud Functions とマネージドデータベースの接続
- terraform-gcp - Infrastructure as Code を使用した Cloud Functions のデプロイ
- gcp-gke - ワークロードがサーバーレスの範囲を超え、Kubernetes が必要な場合
コメント
Markdown 対応