diff --git a/modules/postgresql/main.tf b/modules/postgresql/main.tf index a8284879..bf84ccb6 100644 --- a/modules/postgresql/main.tf +++ b/modules/postgresql/main.tf @@ -46,7 +46,13 @@ locals { database_name = var.enable_default_db ? var.db_name : (length(var.additional_databases) > 0 ? var.additional_databases[0].name : "") - encryption_key = var.encryption_key_name != null ? var.encryption_key_name : var.use_autokey ? google_kms_key_handle.default[0].kms_key : null + encryption_key = var.encryption_key_name != null ? var.encryption_key_name : var.use_autokey ? local.autokey_kms_key : null + autokey_location = coalesce(var.region, join("-", slice(split("-", var.zone), 0, 2))) + + // Get autokey kms key + existing_handle_key = var.use_existing_key_handle ? try([for handle in data.google_kms_key_handles.existing.key_handles : handle.kms_key if endswith(handle.name, "/${var.name}")][0], null) : null + create_handle = var.use_autokey && local.existing_handle_key == null + autokey_kms_key = local.create_handle ? google_kms_key_handle.default[0].kms_key : local.existing_handle_key } resource "random_id" "suffix" { @@ -224,12 +230,19 @@ resource "google_sql_database_instance" "default" { depends_on = [null_resource.module_depends_on] } +data "google_kms_key_handles" "existing" { + provider = google-beta + project = var.project_id + location = local.autokey_location + resource_type_selector = "sqladmin.googleapis.com/Instance" +} + resource "google_kms_key_handle" "default" { - count = var.use_autokey ? 1 : 0 + count = local.create_handle ? 1 : 0 provider = google-beta project = var.project_id name = local.instance_name - location = coalesce(var.region, join("-", slice(split("-", var.zone), 0, 2))) + location = local.autokey_location resource_type_selector = "sqladmin.googleapis.com/Instance" } diff --git a/modules/postgresql/variables.tf b/modules/postgresql/variables.tf index 6596b0e8..09385083 100644 --- a/modules/postgresql/variables.tf +++ b/modules/postgresql/variables.tf @@ -477,3 +477,9 @@ variable "use_autokey" { type = bool default = false } + +variable "use_existing_key_handle" { + description = "kms_key_handle resource can not be delete from GCP (https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/kms_key_handle). If you recreate cloudsql instance with same name module will try to create kms_key_handle resource again. This will fail if you have existing key handle. Set this to true to use existing key handle with same name and fail. In that case make this variable true." + type = bool + default = false +}