How to add host redirect from secondary to primary domain using terraform and google cloud

Viewed 629

For example, I have two domains: example.com and example.org. I want to make primary domain example.com and setup host redirect (in google cloud terms) from example.org and www.* to example.com. Intuitively it looks like I have to create two "path matchers", one of them will serve backend and another one do host redirect.

variable "primary_domain" {
  type    = string
  default = "example.com"
}

variable "secondary_domains" {
  type    = set(string)
  default = ["example.org", "www.example.com", "www.example.org"]
}

resource "google_compute_url_map" "landing_url_map" {
  name            = "landing-url-map"
  default_service = google_compute_backend_bucket.landing_backend_bucket.self_link

  host_rule {
    path_matcher = "primary"
    hosts        = [var.primary_domain]
  }

  path_matcher {
    name            = "primary"
    default_service = google_compute_backend_bucket.landing_backend_bucket.self_link
  }

  host_rule {
    path_matcher = "secondary"
    hosts        = var.secondary_domains
  }

  path_matcher {
    name = "secondary"
    default_url_redirect {
      host_redirect = var.primary_domain
    }
  }
}

But it fails:

Error: "path_matcher.1.default_url_redirect": conflicts with default_service

  on landing.tf line 47, in resource "google_compute_url_map" "landing_url_map":
  47: resource "google_compute_url_map" "landing_url_map" {

I've tried multiple other ways to make it work but none of them doesn't work. I make sure it works in the web console but can't find any way how to implement this using terraform.

2 Answers

It looks like you cannot have default_service at the top level of the URL map and have default_url_redirect in a path_matcher. Try removing default_service = google_compute_backend_bucket.landing_backend_bucket.self_link from the top-level as follows:

resource "google_compute_url_map" "landing_url_map" {
  name            = "landing-url-map"

  host_rule {
    path_matcher = "primary"
    hosts        = [var.primary_domain]
  }

  path_matcher {
    name            = "primary"
    default_service = google_compute_backend_bucket.landing_backend_bucket.self_link
  }

  host_rule {
    path_matcher = "secondary"
    hosts        = var.secondary_domains
  }

  path_matcher {
    name = "secondary"
    default_url_redirect {
      host_redirect = var.primary_domain
    }
  }
}

When none of the specified hostRules match, the request is redirected to a URL specified by defaultUrlRedirect. If defaultUrlRedirect is specified, defaultService or defaultRouteAction must not be set. Structure is documented below.

From the default_url_redirect argument docs for the google_compute_url_map.

Related