You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform中能否将tfvars内路由表等值移至别处后引用?

Terraform tfvars配置复用问题解答

1. 在Terraform的tfvars文件中,能否将配置值存储到其他位置,之后直接调用?

不行。tfvars本质是静态键值对文件,仅用于给Terraform变量提供静态赋值,不支持解析表达式、引用其他文件内容,也不能调用variables或locals里的内容。

如果需要拆分配置,可以将不同模块、环境的配置拆分为多个tfvars文件(比如common.tfvars、dev.tfvars),然后通过terraform plan/apply -var-file=common.tfvars -var-file=dev.tfvars命令同时加载多个文件,但tfvars内部无法写引用语法。

2. 能否将路由表的值存储到其他位置,然后在tfvars文件中通过route_table = ""的方式调用?

也不行。tfvars仅支持静态值写入,无法直接引用其他tfvars、variables或locals里的内容。

如果想复用路由表配置,推荐两种实现方式:

方式一:用locals定义复用的路由表结构

在main.tf中定义本地值,把通用的路由表配置存起来,后续在资源配置中直接引用:

locals {
  security_rt_config = {
    disableBgpRoutePropagation = false
    routes = [
      {
        name             = "default-udr"
        addressPrefix    = "0.0.0.0/0"
        nextHopType      = "VirtualAppliance"
        nextHopIpAddress = "10.231.10.100"
      },
      {
        name             = "network-146.189.0.0-16-udr"
        addressPrefix    = "146.189.0.0/16"
        nextHopType      = "VirtualAppliance"
        nextHopIpAddress = "10.231.10.200"
      }
    ]
  }
}

# 创建路由表资源时引用local值
resource "azurerm_route_table" "security_rt" {
  name                = "security-rt"
  resource_group_name = "testrg"
  location            = "eastus"

  disable_bgp_route_propagation = local.security_rt_config.disableBgpRoutePropagation

  dynamic "route" {
    for_each = local.security_rt_config.routes
    content {
      name                   = route.value.name
      address_prefix         = route.value.addressPrefix
      next_hop_type          = route.value.nextHopType
      next_hop_in_ip_address = route.value.nextHopIpAddress
    }
  }
}

# 子网关联路由表
resource "azurerm_subnet_route_table_association" "app1_subnet_rt" {
  subnet_id      = azurerm_subnet.app_1_subnet.id
  route_table_id = azurerm_route_table.security_rt.id
}

方式二:用variables定义可传入的复杂结构

在variables.tf中定义支持复杂结构的变量:

variable "networks" {
  type = map(object({
    resource_group_name = string
    location            = string
    addressSpace        = list(string)
    dnsServers          = optional(list(string))
    subnets = map(object({
      addressPrefix = string
      route_table   = optional(map(object({
        disableBgpRoutePropagation = bool
        routes = list(object({
          name             = string
          addressPrefix    = string
          nextHopType      = string
          nextHopIpAddress = string
        }))
      })))
    }))
  }))
}

之后可以把路由表的静态配置拆分到单独的tfvars文件(比如route_configs.tfvars),通过terraform apply -var-file=main.tfvars -var-file=route_configs.tfvars一起加载,但注意这只是静态配置的拆分,tfvars之间仍然无法互相引用。


内容的提问来源于stack exchange,提问作者Mr.cool

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:17:33