我的Python Firebase Cloud Function部署失败,触发异常如何解决?
问题概述
部署Python Firebase Cloud Function时遭遇构建失败,控制台显示以下异常:
Build failed with status: FAILURE. Could not build the function due to a missing permission on the build service account. If you didn't revoke that permission explicitly, this could be caused by a change in the organization policies.
同时Firebase控制台函数显示“unknown trigger”,Google Cloud控制台出现:
Eventarc trigger projects/myproject/locations/nam5/triggers/sendNotification-xxxxxx for the function was not found. The function may not work correctly. Please redeploy.
Cloud Run service projects/myproject/locations/us-central1/services/sendNotification for the function was not found. The function will not work correctly. Please redeploy.
测试代码如下:
import firebase_admin from firebase_functions import https_fn, firestore_fn from firebase_admin import initialize_app, credentials, firestore, messaging import google.cloud.firestore app = initialize_app() @firestore_fn.on_document_created(document = "users/{userId}/invites/{inviteId}") def sendNotification(event: firestore_fn.Event[firestore_fn.DocumentSnapshot | None],) -> None : if event.data is None: return try: userId = event.params["userId"] db = firestore.client() user_ref = db.collection("users").doc(userId) user_data = user_ref.get().to_dict tokenFCM = user_data.get("tokenFCM") print(f"user token: {tokenFCM}") except KeyError: return
解决方案
1. 修复构建服务账号权限
构建失败是核心诱因,需为项目的Cloud Build服务账号补充权限:
- 找到账号:格式为
[项目编号]@cloudbuild.gserviceaccount.com,可在Google Cloud控制台IAM页面搜索定位 - 添加以下角色:
- Cloud Build Editor:允许执行构建操作
- Eventarc Admin:管理Eventarc触发器
- Cloud Run Developer:创建和管理Cloud Run服务
- Service Account User:允许以服务账号身份部署服务
- 若为组织级策略限制,联系管理员检查是否存在禁用Cloud Build、Eventarc或Cloud Run的组织政策
2. 修正代码中的运行时错误
代码中to_dict是方法,需调用而非直接引用,否则会导致运行时异常:
# 错误代码 user_data = user_ref.get().to_dict # 修正后 user_data = user_ref.get().to_dict()
额外建议添加文档存在性判断,避免空文档报错:
user_doc = user_ref.get() if not user_doc.exists: print(f"User {userId} not found") return user_data = user_doc.to_dict()
3. 清理残留并重新部署
先删除失败部署的残留资源:
firebase functions:delete sendNotification --force
再重新部署函数:
firebase deploy --only functions:sendNotification
内容的提问来源于stack exchange,提问作者Eduardo

