From 186c200a313e7d584f5628e0f9bcdf7d401f5584 Mon Sep 17 00:00:00 2001
From: Ryan Kowalewski <rk725@cam.ac.uk>
Date: Mon, 7 Nov 2022 09:51:38 +0000
Subject: [PATCH] use boolean var to grant sql perms

Currently uses sql_instance_connection_name which causes
issues when the provided value is not known until apply.
---
 main.tf      | 6 +++---
 variables.tf | 9 +++++++++
 2 files changed, 12 insertions(+), 3 deletions(-)

diff --git a/main.tf b/main.tf
index 5a263cf..753057d 100644
--- a/main.tf
+++ b/main.tf
@@ -7,10 +7,10 @@ resource "google_service_account" "webapp" {
   display_name = coalesce(var.service_account_display_name, "Web application Cloud Run service account")
 }
 
-# The webapp service account has the ability to connect to the SQL instance.
-# (Only if sql_instance_connection_name is non-empty.)
+# Grant the webapp service account the ability to connect to the SQL instance
+# via the grant_sql_client_role_to_webapp_sa boolean variable.
 resource "google_project_iam_member" "webapp_sql_client" {
-  count = (var.sql_instance_connection_name != "") ? 1 : 0
+  count = var.grant_sql_client_role_to_webapp_sa ? 1 : 0
 
   project = local.sql_instance_project
   role    = "roles/cloudsql.client"
diff --git a/variables.tf b/variables.tf
index bf74452..2d24f78 100644
--- a/variables.tf
+++ b/variables.tf
@@ -19,6 +19,15 @@ variable "sql_instance_connection_name" {
   default     = ""
 }
 
+variable "grant_sql_client_role_to_webapp_sa" {
+  description = <<EOI
+    When set to true the 'roles/cloudsql.client' role will be granted to the
+    webapp service account at the project level to allow it to connect to Cloud SQL.
+  EOI
+  type        = bool
+  default     = false
+}
+
 variable "cloud_run_region" {
   description = "Override region used to create Cloud Resources"
   default     = ""
-- 
GitLab