我正在尝试创建一个具有调用单个云功能的受限访问权限的 ServiceAccount。
resource "google_service_account" "service_account" {
account_id = "service-account-id"
display_name = "Service Account"
}
data "google_iam_policy" "invoker" {
binding {
role = "roles/cloudfunctions.invoker"
members = [
"serviceAccount:${google_service_account.service_account.email}",
]
condition {
expression = "resource.name == projects/project_name/locations/region/functions/function_name"
title = foo
}
}
}
resource "google_cloudfunctions2_function_iam_policy" "binding" {
cloud_function = "projects/project_name/locations/region/functions/function_name"
project = var.common.project_id
location = var.common.default_region
policy_data = data.google_iam_policy.invoker.policy_data
}
但是,当我应用此更改时,我收到错误。
module.handler-build.google_cloudfunctions2_function_iam_policy.binding:创建... ╷ │ 错误:为 cloudfunctions2 函数“projects/project_name/locations/region/functions/function_name”设置 IAM 策略时出错:googleapi:错误 400:无效参数:'指定了无效参数。请检查字段并重试。'
我会尝试调用
google_cloudfunctions2_function_iam_binding
或 google_cloudfunctions2_function_iam_member
但他们没有我可以使用的条件表达式。添加条件非常重要,以便该服务帐户无法调用其他云功能。
如何将调用者策略添加到服务帐户?
对于 v2 云函数,您需要在使用 Terraform 时在生成的 Cloud Run 实例上创建 IAM 绑定。您还需要使用 Roles/run.invoker 角色。
您可以引用 Cloud Function terraform 资源中的参数,但使用 google_cloud_run_v2_service_iam_binding 资源。比如:
resource "google_cloud_run_v2_service_iam_binding" "binding" {
location = google_cloudfunctions2_function.default.location
project = google_cloudfunctions2_function.default.project
name = google_cloudfunctions2_function.default.name
role = "roles/run.invoker"
members = [
"serviceAccount:${google_service_account.service_account.email}"
]
}
提供程序中似乎存在错误,因为我认为 google_cloudfunctions2_function_iam_binding 无法正常工作!
@kefa的回答给了我一个错误“为cloudrunv2服务“projects/my-project/locations/us-central1/services/my_function_name”设置IAM策略时出错:googleapi:错误404:区域中类型为“SERVICE”的资源“my_function_name”项目“my-project”中的“us-central1”不存在。”
这似乎是因为我指定了该函数运行的服务帐户,并且该服务帐户具有不同的名称。以下对我有用:
# Set up a service account that the function will run as
resource "google_service_account" "main" {
account_id = "my-service-account-name"
...
}
resource "google_cloudfunctions2_function" "main" {
name = "my_function_name"
...
service_config {
service_account_email = google_service_account.main.email
...
}
}
# Allow unauthenticated access to the function
# This is the equivalent of `gcloud functions add-invoker-policy-binding my_function_name --member=allUsers`
resource "google_cloud_run_v2_service_iam_binding" "invoker" {
location = google_cloudfunctions2_function.main.location
name = google_service_account.main.account_id
role = "roles/run.invoker"
members = ["allUsers"]
}