从 GCP 中的云功能访问秘密管理器。使用哪些 IAM 设置?

Access secret manager from cloud function in GCP. What IAM settings to use?

我不知道要在这里设置什么。恕我直言,整个政策、绑定和成员的内容非常混乱。有这些角色吗?无论如何...

正在尝试从云功能访问机密管理器。使用 Terraform 设置云功能:

module "mds_reporting_cloud_function" {
  source                         = "terraform-google-modules/scheduled-function/google"
  version                        = "2.0.0"
  project_id                     = var.function_gcp_project
  job_name                       = var.function_name
  job_description                = var.function_description
  job_schedule                   = var.function_cron_schedule
  function_entry_point           = "main"
  function_source_directory      = "${path.module}/../../../../src"
  function_name                  = var.function_name
  region                         = var.function_gcp_region
  bucket_name                    = var.function_name
  function_description           = var.function_description
  function_environment_variables = var.function_environment_variables
  function_runtime               = "python38"
  topic_name                     = var.function_name
}

resource "google_cloudfunctions_function_iam_binding" "binding" {
  project        = var.function_gcp_project
  region         = var.function_gcp_region
  cloud_function = var.function_name
  role           = "roles/secretmanager.secretAccessor"
  members = [
    "serviceAccount:${var.function_gcp_project}@appspot.gserviceaccount.com"
  ]
}

我的理解是,如果没有指定云功能的服务帐户,它将使用默认的 App Engine 服务帐户。

绑定应 'bind' 角色到 App Engine 服务帐户的现有 IAM 策略。

但是,它抛出这个错误:

Error: 
Error applying IAM policy for cloudfunctions cloudfunction "projects/alpine-proton-280612/locations/europe-west3/functions/mds-reporting-cloud-function":
Error setting IAM policy for cloudfunctions cloudfunction "projects/alpine-proton-280612/locations/europe-west3/functions/mds-reporting-cloud-function": 
googleapi: Error 400: Role roles/secretmanager.secretAccessor is not supported for this resource.

不确定要做什么。

最好的解决方案是仅在机密上授予 Cloud Functions 服务帐户访问机密的权限。为此,请使用 Secret Manager IAM terraform 资源

resource "google_secret_manager_secret_iam_binding" "binding" {
  project = var.function_gcp_project
  secret_id = google_secret_manager_secret.your-secret.secret_id
# If your secret is not created by terraform, use this format for the id projects/{{project}}/secrets/{{secret_id}}
  role = "roles/secretmanager.secretAccessor"
  members = [
    "serviceAccount:${var.function_gcp_project}@appspot.gserviceaccount.com"
  ]
}

重要提示:

  • 您也可以在 project level 授予此角色,但它不太安全,因为该函数将有权访问项目的所有机密
  • 您使用 App Engine(和云功能)默认服务帐户。它也不是那么安全。实际上,任何 App Engine 服务和具有自定义服务帐户的 Cloud Functions 都将默认使用此服务帐户,因此将能够访问机密。更喜欢 custom service account for your Cloud Functions
  • 约翰的第二条评论非常重要。 Terraform 具有多个级别的 IAM 角色的写入和替换。请记住(适用于所有 IAM_XXX terraform 模块)
    • Policy替换整个资源的所有可能角色的所有账户(在一个项目上,这可能是戏剧性的!)
    • 绑定替换特定角色的所有账号
    • 成员 只添加一个特定角色的帐户。什么都不删除。