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

如何在Terraform中定义对象数组并遍历创建SQL防火墙规则?

在Terraform中定义对象数组并遍历创建Azure SQL防火墙规则

1. 定义对象数组

在Terraform中,你可以通过local本地值或variable变量来定义对象数组,语法和Bicep略有差异,需要注意使用等号赋值、对象间用逗号分隔:

# 用本地值定义(适合固定规则场景)
locals {
  array_of_rules = [
    {
      name            = "1stRule"
      start_ip_address = "0.0.0.0"
      end_ip_address   = "0.0.0.0"
    },
    {
      name            = "2ndRule"
      start_ip_address = "0.0.0.1"
      end_ip_address   = "0.0.0.1"
    }
  ]
}

# 或用变量定义(适合外部传入规则场景)
variable "array_of_rules" {
  type = list(object({
    name            = string
    start_ip_address = string
    end_ip_address   = string
  }))
  default = [
    {
      name            = "1stRule"
      start_ip_address = "0.0.0.0"
      end_ip_address   = "0.0.0.0"
    },
    {
      name            = "2ndRule"
      start_ip_address = "0.0.0.1"
      end_ip_address   = "0.0.0.1"
    }
  ]
}

2. 遍历数组创建防火墙规则

Terraform通过for_each实现资源批量创建,需要将数组转换为键唯一的映射(map)(因为防火墙规则名称在SQL服务器下必须唯一,正好可以用规则名作为键),示例代码如下:

# 假设你已经定义了SQL服务器资源
resource "azurerm_mssql_server" "example" {
  name                         = "example-sql-server"
  resource_group_name          = azurerm_resource_group.example.name
  location                     = azurerm_resource_group.example.location
  version                      = "12.0"
  administrator_login          = "sqladmin"
  administrator_login_password = "H@shPass123"
}

# 遍历规则数组创建防火墙规则
resource "azurerm_mssql_firewall_rule" "sql_server_firewall" {
  # 将数组转为以规则名为键的映射,确保每个资源实例唯一
  for_each = { for rule in local.array_of_rules : rule.name => rule }

  name             = each.value.name
  server_id        = azurerm_mssql_server.example.id
  start_ip_address = each.value.start_ip_address
  end_ip_address   = each.value.end_ip_address
}

关键说明

  • Terraform的Azure SQL防火墙规则资源类型是azurerm_mssql_firewall_rule,对应Bicep中的Microsoft.Sql/servers/firewallRules
  • for_each相比count更稳定:如果数组元素顺序变化,count会导致资源重建,而for_each基于唯一键(规则名)只会变更对应资源
  • each.value用于访问当前遍历到的规则对象的属性,和Bicep中的rule变量作用一致

内容的提问来源于stack exchange,提问作者user346206

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:09:24