Optional create for service accounts

This commit is contained in:
Julio Castillo 2021-05-06 12:07:24 +02:00
parent a1814a5b16
commit 875b786171
4 changed files with 25 additions and 5 deletions

View File

@ -41,6 +41,7 @@ module "myproject-default-service-accounts" {
| *iam_project_roles* | Project roles granted to the service account, by project id. | <code title="map&#40;list&#40;string&#41;&#41;">map(list(string))</code> | | <code title="">{}</code> |
| *iam_storage_roles* | Storage roles granted to the service account, by bucket name. | <code title="map&#40;list&#40;string&#41;&#41;">map(list(string))</code> | | <code title="">{}</code> |
| *prefix* | Prefix applied to service account names. | <code title="">string</code> | | <code title="">null</code> |
| *service_account_create* | Create service account. When set to false, uses a data source to reference an existing service account. | <code title="">bool</code> | | <code title="">true</code> |
## Outputs

View File

@ -57,10 +57,23 @@ locals {
: map("", null)
, {})
prefix = var.prefix != null ? "${var.prefix}-" : ""
resource_iam_email = "serviceAccount:${google_service_account.service_account.email}"
resource_iam_email = "serviceAccount:${local.service_account.email}"
service_account = (
var.service_account_create
? try(google_service_account.service_account.0, null)
: try(data.google_service_account.service_account.0, null)
)
}
data "google_service_account" "service_account" {
count = var.service_account_create ? 0 : 1
project = var.project_id
account_id = "${local.prefix}${var.name}"
}
resource "google_service_account" "service_account" {
count = var.service_account_create ? 1 : 0
project = var.project_id
account_id = "${local.prefix}${var.name}"
display_name = var.display_name
@ -68,12 +81,12 @@ resource "google_service_account" "service_account" {
resource "google_service_account_key" "key" {
for_each = var.generate_key ? { 1 = 1 } : {}
service_account_id = google_service_account.service_account.email
service_account_id = local.service_account.email
}
resource "google_service_account_iam_binding" "roles" {
for_each = var.iam
service_account_id = google_service_account.service_account.name
service_account_id = local.service_account.name
role = each.key
members = each.value
}

View File

@ -16,12 +16,12 @@
output "service_account" {
description = "Service account resource."
value = google_service_account.service_account
value = local.service_account
}
output "email" {
description = "Service account email."
value = google_service_account.service_account.email
value = local.service_account.email
}
output "iam_email" {

View File

@ -77,3 +77,9 @@ variable "project_id" {
description = "Project id where service account will be created."
type = string
}
variable "service_account_create" {
description = "Create service account. When set to false, uses a data source to reference an existing service account."
type = bool
default = true
}