如何使用 terraform 和 google cloud 添加从辅助域到主域的主机重定向

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

例如,我有两个域:example.com 和 example.org。 我想使主域 example.com 和设置主机重定向(在 google 云术语中)从 example.org 和 www.* 到 example.com。 直觉上看起来我必须创建两个 "path matchers",其中一个将服务于后端,另一个用于主机重定向。

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
    }
  }
}

但是失败了:

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" {

我已经尝试了多种其他方法来使它起作用,但是 none 其中的方法不起作用。我确保它在 Web 控制台中工作,但找不到任何方法如何使用 terraform 实现它。

看起来你不能在 URL 地图的顶层有 default_service 而有 default_url_redirect 在 path_matcher 中。尝试从顶层删除 default_service = google_compute_backend_bucket.landing_backend_bucket.self_link,如下所示:

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.

来自default_url_redirect argument docs for the google_compute_url_map.

回滚到 3.25.0 有帮助

此问题已在 GitHub

上报告

https://github.com/terraform-providers/terraform-provider-google/issues/6695