Terraform 0.12+ 错误属性 "service_account" 的值不合适:try() 函数需要字符串

Terraform 0.12+ Error Inappropriate value for attribute "service_account": string required with try() function

我有一个 google_service_account 模块,刚刚转换为 Terraform-12 (0.12.24)

resource "google_service_account" "service_account" {
  count        = var.enabled ? 1 : 0
  account_id   = var.account_id
  display_name = var.display_name
}
output.tf retrieves the email

output "email" {
  value = try(google_service_account.service_account.*.email, null)
  # value = element( --> Commented out part works fine
  #   concat(google_service_account.service_account.*.email, [""]),
  #   0,
  # )
  description = "The e-mail address of the service account. Usually use this when constructing IAM policies."

在另一个资源中使用此模块时如下

resource "google_storage_bucket_iam_member" "registry_bucket_iam" {
  bucket = "artifacts.${var.project}.appspot.com"
  role   = "roles/storage.objectViewer"
  member = "serviceAccount:${module.k8s-node-service-account.email}"
}

我收到以下错误

  48:   member = "serviceAccount:${module.k8s-node-service-account.email}"
    |----------------
    | module.k8s-node-account.email is tuple with 1 element

Cannot include the given value in a string template: string required.

如何解决这个问题?

google_service_account.service_account.*.email 根据 var.enabled 评估为 1 或 0 个元素的数组 - 而 google_service_account.service_account[0].email 评估为 string 或如果 var.enabledfalse。因此,当使用 try() 时,您想评估 string 或在出现错误时默认为 null

将您的输出更改为以下内容应该会导致具有类型为 string 的电子邮件输出的预期结果。

output "email" {
  value = try(google_service_account.service_account[0].email, null)
}