首页 > 解决方案 > Terraform 对于每个带有子模块

问题描述

我正在为我们的应用程序网关使用 Terraform 修改我们的 IaC,并希望使用 for_each 循环来简化重复语句的数量。我有这个工作,但我的问题是我试图将此逻辑应用于包含多个子模块。我希望能够循环不同的值而不必创建多个应用程序网关,但因为它们是资源组的子模块,它会尝试创建多个应用程序网关

这是我所拥有的一个例子:

variable "portals" {
  description = "Map of sub-domain portals"
  type: map(string)
  default = {
    ipu = "ipu"
    ipu_uat = "ipu-uat"
  }

}

resource "azurerm_application_gateway" "app_gateway" {
  for_each = var.portals
  name                = var.ag_name
  resource_group_name = azurerm_resource_group.sre.name
  location            = azurerm_resource_group.sre.location
  enable_http2 = true

  tags = merge(var.tags, tomap({"role" = "app_gateway"} ))
  lifecycle {
    ignore_changes = [tags,]
  }

  sku {
    name     = "WAF_v2"
    tier     = "WAF_v2"
  }

  autoscale_configuration {
    min_capacity = 0
    max_capacity = 100
  }

  gateway_ip_configuration {
    name      = "ag_ip_config"
    subnet_id = azurerm_subnet.app_gateway.id
  }

  frontend_port {
    name = "ag_http_port"
    port = 80
  }

  frontend_port {
    name = "ag_https_port"
    port = 443
  }

  frontend_ip_configuration {
    name                 = "ag_public_ip"
    public_ip_address_id = azurerm_public_ip.app_gateway.id
  }

  frontend_ip_configuration {
    name = "ag_private_ip"
    subnet_id = azurerm_subnet.app_gateway.id
    private_ip_address_allocation = "Static"
    private_ip_address = var.ag_private_ip
  }


  backend_http_settings {
    name                  = [for name, url in portals : "${name}_http"]
    cookie_based_affinity = "Disabled"
    port                  = 80
    protocol              = "HTTP"
    request_timeout       = var.backend_http_request_timeout
    pick_host_name_from_backend_address = false
    host_name = [for name, url in portals : "${url}.mywebsite.com"]
  }

  backend_http_settings {
    name                  = [for name, url in portals : "${name}_http"]
    cookie_based_affinity = "Disabled"
    port                  = 443
    protocol              = "HTTPS"
    request_timeout       = var.backend_http_request_timeout
    pick_host_name_from_backend_address = false
    host_name = [for name, url in portals : "${url}.mywebsite.com"]
  }

目标是让它只使用循环创建子模块资源,这样将来当我们想要添加更多子域时,我们只需将其添加到列表中,其余的就可以通过编程方式创建。

标签: terraform

解决方案


推荐阅读