使用Terraform批量创建Azure Linux Web App的IP白名单配置问题
批量Azure Web App互加IP白名单的循环依赖问题解决
问题场景
通过count = length(var.webapp_name)批量创建多个Azure Linux Web App,需要将这些应用彼此的outbound_ip_addresses加入对方的IP白名单,但当前配置触发循环依赖错误,提示无法在资源创建阶段引用自身实例的outbound_ip_addresses属性。
错误原因
在azurerm_linux_web_app.API资源的site_config内部直接引用自身实例的outbound_ip_addresses属性,Terraform在创建资源时还未生成该属性值,导致循环依赖。
解决方案
将IP白名单配置拆分为独立的azurerm_linux_web_app_configuration资源,先完成所有Web App的创建,再单独配置IP限制规则,彻底消除循环依赖。
修正后的代码
1. 原Web App资源(移除内部的互斥IP限制配置)
resource "azurerm_linux_web_app" "API" { depends_on = [azurerm_subnet.subnet] count = length(var.webapp_name) name = lower("${var.customer4letter}-${var.env3letter}-${var.locationid3letter}-${var.servicetype}-${element(var.webapp_name, count.index)}") location = var.location //West US 2 resource_group_name = azurerm_resource_group.rg.name service_plan_id = azurerm_service_plan.api-farm.id https_only = "true" app_settings = { "WEBSITE_USE_DIAGNOSTIC_SERVER" = "True" } identity { type = "SystemAssigned" } site_config { ftps_state = "FtpsOnly" websockets_enabled = "false" use_32_bit_worker = "false" always_on = "true" application_stack { dotnet_version = "6.0" } dynamic "ip_restriction" { for_each = local.ip_address_list3 content { action = "Allow" name = ip_restriction.value["name"] service_tag = ip_restriction.value["service_tag"] priority = ip_restriction.value["prior"] } } } }
2. 新增独立的Web App配置资源(处理互加IP白名单)
resource "azurerm_linux_web_app_configuration" "API" { count = length(var.webapp_name) web_app_id = azurerm_linux_web_app.API[count.index].id scm_ip_restriction = azurerm_linux_web_app.API[count.index].site_config.scm_ip_restriction ip_restriction = concat( azurerm_linux_web_app.API[count.index].site_config.ip_restriction, flatten([ for app in azurerm_linux_web_app.API : [ for ip in split(",", app.outbound_ip_addresses) : { action = "Allow" ip_address = cidrhost(trimspace(ip), 0) priority = 103 + index(azurerm_linux_web_app.API, app) name = "${app.name}-outbound-ip" } ] if app.id != azurerm_linux_web_app.API[count.index].id ]) ) }
变量与本地值定义(保持不变)
variable "webapp_name" { default = [ "app1", "app2", "app3" ] } locals { ip_address_list3 = [ { service_tag = "AppService" prior = "102" name = "VirtualNetwork" } ] }
关键说明
- 拆分配置资源后,Terraform会先完成所有Web App的创建,此时
outbound_ip_addresses属性已生成,可安全引用 - 使用
split(",", app.outbound_ip_addresses)拆分多个出站IP,trimspace处理可能的空格 - 通过
if app.id != azurerm_linux_web_app.API[count.index].id过滤当前Web App自身,避免添加无用规则 - 为每个IP规则设置递增的
priority,确保规则不冲突
内容的提问来源于stack exchange,提问作者Igor
相关产品推荐
相关产品推荐

