Setting value based on whether the variable exists or not

Hello, I hope everyone is ok!

I use terraform 0.15.4 and I’m building a load balancer module in GCP and I’m having difficulty with the google_compute_url_map resource, because I need to create the following condition

I need when the default_url_redirect map is configured the default_service must be disabled otherwise the default_service must receive the resource value google_compute_backend_service.

variables.tf

variable default_url_redirect {
  type        = list
  default     = []
  description = ""
}

main.tf

resource "google_compute_url_map" "default" {
  for_each    = var.compute_url_map
  name        = each.value["name"]
  description = lookup(each.value, "description", null)
  project     = each.value["project"]

  default_service = try(each.value["default_url_redirect"], element(values(google_compute_backend_service.default)[*].id, length(var.compute_backend_service)))

  dynamic "default_url_redirect" {
    for_each = try(each.value["default_url_redirect"], {})
    content {
      host_redirect          = lookup(default_url_redirect.value, "host_redirect", null)
      https_redirect         = lookup(default_url_redirect.value, "https_redirect ", null)
      path_redirect          = lookup(default_url_redirect.value, "path_redirect", null)
      prefix_redirect        = lookup(default_url_redirect.value, "deprefix_redirectscription", null)
      redirect_response_code = lookup(default_url_redirect.value, "redirect_response_code ", null)
      strip_query            = lookup(default_url_redirect.value, "strip_query", null)
    }
  }

  dynamic "host_rule" {
    for_each = var.host_rule
    content {
      description  = lookup(host_rule.value, "description", null)
      hosts        = lookup(host_rule.value, "hosts", null)
      path_matcher = lookup(host_rule.value, "path_matcher", null)
    }
  }

  dynamic "path_matcher" {
    for_each = var.path_matcher
    content {
      default_service = lookup(path_matcher.value, "default_service", null)
      description     = lookup(path_matcher.value, "description", null)
      name            = lookup(path_matcher.value, "name", null)

      dynamic "path_rule" {
        for_each = var.path_rule
        content {
          service = lookup(path_rule.value, "service", null)
          paths   = (lookup(path_rule.value, "paths", null))
        }
      }
    }
  }
  depends_on = [ google_compute_backend_service.default ]
}

Using the try function I managed to partially work this condition, because when the default_url_redirect variable is empty, the default_service receives the value:

element(values(google_compute_backend_service.default)[*].id, length(var.compute_backend_service))

But when the default_url_redirect variable receives the list of values ​​and the error code, can you help me?