[英]How to properly create gcp service-account with roles in terraform
这是我用来创建服务帐户并将角色绑定到它的 terraform 代码:
resource "google_service_account" "sa-name" {
account_id = "sa-name"
display_name = "SA"
}
resource "google_project_iam_binding" "firestore_owner_binding" {
role = "roles/datastore.owner"
members = [
"serviceAccount:sa-name@${var.project}.iam.gserviceaccount.com",
]
depends_on = [google_service_account.sa-name]
}
上面的代码效果很好......除了它从项目中先前分配此角色的任何其他服务帐户中删除了datastore.owner
。 我们有许多团队使用的单个项目,并且有由不同团队管理的服务帐户。 我的 terraform 代码只有我们团队的服务帐户,我们最终可能会破坏其他团队的服务帐户。
在 terraform 中还有其他方法可以做到这一点吗?
这当然可以通过 GCP UI 或 gcloud cli 完成,没有任何问题或影响其他 SAs。
从 terraform 文档中,“google_project_iam_binding”是Authoritative. Sets the IAM policy for the project and replaces any existing policy already attached
Authoritative. Sets the IAM policy for the project and replaces any existing policy already attached
。 这意味着它完全替换了其中给定角色的成员。
要将角色添加到新服务帐户,而不编辑该角色中的其他所有人,您应该使用资源“google_project_iam_member”:
resource "google_service_account" "sa-name" {
account_id = "sa-name"
display_name = "SA"
}
resource "google_project_iam_member" "firestore_owner_binding" {
project = <your_gcp_project_id_here>
role = "roles/datastore.owner"
member = "serviceAccount:${google_service_account.sa-name.email}"
}
您的示例的额外更改:使用服务帐户资源email
生成的属性来删除显式的depends_on
。 如果您这样做,则不需要depends_on
,并且可以避免配置错误的错误。
Terraform 可以通过使用来自另一个资源的变量来推断依赖关系。 检查此处的文档以更好地了解此行为。
这是 Terraform 的常见问题。 要么你用它做所有事情,要么什么都不做。 如果您介于两者之间,可能会发生意想不到的事情!
如果要使用 terraform,则必须将现有的导入 tfstate。 这里是bindind 的文档,当然,您必须在 Terraform 文件中添加所有帐户。 如果没有,绑定将被删除,但这一次,您将在tf plan
中看到删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.