mcpField
G
gcp-cloud-functions

gcp-cloud-functions

github.com/bagelhole云与 DevOps1.2k323 次安装23 周前更新
代码仓库

关于 gcp-cloud-functions

用于通过 Google Cloud Functions Gen1 和 Gen2 构建及运维事件驱动无服务器应用的技能,涵盖 HTTP 与事件触发器、定时任务的部署,以及 Terraform 配置。

主要功能

  1. 01部署 HTTP 函数
  2. 02配置 Pub/Sub 和存储触发器
  3. 03安排函数定时任务
  4. 04管理已部署函数
  5. 05使用 Terraform 配置

适用场景

  1. 01处理 Webhook 和轻量 API
  2. 02处理 Pub/Sub 或文件上传事件
  3. 03运行定时清理任务
  4. 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 对比

功能Gen1Gen2(推荐)
运行时Cloud Functions 基础架构基于 Cloud Run 构建
最大超时时间9 分钟60 分钟
最大内存8 GB32 GB
并发每个实例 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
函数部署成功,但返回 403Gen2 缺少 roles/run.invoker添加 --allow-unauthenticated 或授予调用者角色
冷启动延迟超过 5s依赖项过大或未配置最小实例数设置 --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 - 使用基础设施即代码部署 Cloud Functions
  • gcp-gke - 工作负载超出无服务器架构的适用范围并需要 Kubernetes 时使用

评论

支持 Markdown