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

基于变量实现Terraform动态network_rules块的方案咨询

实现方案

核心思路是通过自定义执行角色变量,结合Terraform动态块功能,根据不同执行场景自动生成对应的网络规则。

1. 定义核心变量

先在模块中定义用于区分执行角色的变量,以及对应场景下的网络规则参数:

variable "execution_role" {
  type        = string
  description = "执行角色,仅支持:local_developer/automated_deployer"
  validation {
    condition     = contains(["local_developer", "automated_deployer"], var.execution_role)
    error_message = "execution_role只能是local_developer或automated_deployer。"
  }
}

variable "allowed_subnet_ids" {
  type        = list(string)
  description = "自动化部署时允许访问的子网ID列表"
  default     = []
}

variable "allowed_client_ip" {
  type        = string
  description = "本地开发时允许访问的客户端IP(需带CIDR后缀,例如192.168.1.100/32)"
  default     = ""
}

2. 动态生成network_rules块

在存储账户资源中,使用Terraform的dynamic块,根据execution_role的值动态生成对应的IP或子网规则:

resource "azurerm_storage_account" "main" {
  name                     = "yourstorageaccountname"
  resource_group_name      = var.resource_group_name
  location                 = var.location
  account_tier             = "Standard"
  account_replication_type = "GRS"

  # 全局限制:默认拒绝所有公网访问
  network_rules {
    default_action = "Deny"

    # 自动化部署场景:添加指定子网规则
    dynamic "virtual_network_subnet_ids" {
      for_each = var.execution_role == "automated_deployer" ? var.allowed_subnet_ids : []
      content {
        id = virtual_network_subnet_ids.value
      }
    }

    # 本地开发场景:添加客户端IP规则
    dynamic "ip_rules" {
      for_each = var.execution_role == "local_developer" && var.allowed_client_ip != "" ? [var.allowed_client_ip] : []
      content {
        value = ip_rules.value
      }
    }
  }
}

3. 执行命令示例

本地开发环境执行

开发者需要指定执行角色为local_developer,并传入自己的公网IP(带CIDR后缀):

terraform apply -var execution_role=local_developer -var allowed_client_ip="114.xxx.xxx.xxx/32"

自动化代理部署(dev/qa/prod)

代理机器执行时指定执行角色为automated_deployer,传入预先定义的允许访问的子网ID列表:

terraform apply -var execution_role=automated_deployer -var allowed_subnet_ids='["/subscriptions/xxx/resourceGroups/xxx/providers/Microsoft.Network/virtualNetworks/xxx/subnets/xxx"]'

可选优化:自动获取本地公网IP

如果不想手动输入IP,可以通过external数据源自动获取本地公网IP,仅在本地开发场景下触发:

# 仅当执行角色为local_developer时,才调用外部API获取IP
data "external" "my_public_ip" {
  count = var.execution_role == "local_developer" ? 1 : 0
  program = ["bash", "-c", "curl -s https://api.ipify.org && echo '/32'"]
}

# 允许客户端IP默认使用自动获取的值
variable "allowed_client_ip" {
  type        = string
  description = "本地开发时允许访问的客户端IP(需带CIDR后缀)"
  default     = length(data.external.my_public_ip) > 0 ? data.external.my_public_ip[0].result.stdout : ""
}

这样本地开发时只需执行:

terraform apply -var execution_role=local_developer

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:45:17