如何通过Terraform配置GCP Cloud Function允许未授权访问?
解决GCP Cloud Functions v2 Terraform部署后未授权访问被禁止的问题
你遇到的403 Forbidden错误,核心原因是Cloud Functions v2(第二代函数)默认强制要求身份验证,仅添加IAM绑定roles/cloudfunctions.invoker给allUsers不足以开启未授权访问,还需要显式配置函数允许匿名请求。
关键修改步骤
需要对Terraform代码做两处调整:
- 在
google_cloudfunctions2_function的service_config块中添加allow_unauthenticated = true,这是开启未授权访问的必要配置 - 修正存储桶名称的硬编码问题,使用Terraform资源引用替代固定字符串,避免配置不一致
修改后的完整代码
provider "google" { project = var.project_id region = var.region credentials = "../tf-key.json" } resource "google_storage_bucket" "bucket" { name = "${var.project_id}-bucket1" location = var.region } resource "google_storage_bucket_object" "source_code" { name = "objects" bucket = google_storage_bucket.bucket.name // 修正:引用创建的存储桶资源 source = "D:/gcf-terraform/gcf-1.zip" } resource "google_cloudfunctions2_function_iam_binding" "default" { cloud_function = google_cloudfunctions2_function.function.name role = "roles/cloudfunctions.invoker" members = ["allUsers"] } resource "google_cloudfunctions2_function" "function" { name = "getAllEmployees" location = "us-central1" description = "Retrieve all employees." build_config { runtime = "go121" entry_point = "GetAllEmployees" source { storage_source { bucket = google_storage_bucket.bucket.name // 修正:引用创建的存储桶资源 object = "objects" } } } service_config { min_instance_count = 1 max_instance_count = 10 available_memory = "128Mi" timeout_seconds = 120 all_traffic_on_latest_revision = false service_account_email = "terraform-gcf@terraform-cloud-functions-ems.iam.gserviceaccount.com" allow_unauthenticated = true // 新增:开启未授权访问 } }
配置说明
allow_unauthenticated = true:该参数会直接允许未经过GCP身份验证的请求访问函数,配合IAM绑定中给allUsers授予的roles/cloudfunctions.invoker权限,即可实现函数的公开访问- 存储桶引用修正:使用
google_storage_bucket.bucket.name替代硬编码的存储桶名称,确保代码包上传的目标桶和实际创建的桶一致,避免部署时出现代码包找不到的错误
内容的提问来源于stack exchange,提问作者Shreyas Awankar
相关产品推荐
相关产品推荐

