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

如何用Azure Bicep共享模块给现有应用服务追加IP限制而非替换?

问题描述

我希望使用一个共享Azure Bicep模块,为现有应用服务添加多条IP安全限制记录。当前编写的模块会将应用服务中已有的IP限制规则(比如之前部署函数应用时配置的子网访问规则)替换掉,而非追加。

现有模块代码:

param appSvcName string

resource appSvc 'Microsoft.Web/sites@2021-02-01' existing = {
  name: appSvcName
}

var proxyIpAddresses = ['xxx.xxx.xxx.250/32','xxx.xxx.xxx.245/32']

resource sitesConfig 'Microsoft.Web/sites/config@2021-02-01' =  {
  name: 'web'
  parent: appSvc
  properties: {
    ipSecurityRestrictions: [for (ip,i) in proxyIpAddresses: {
        ipAddress: ip
        action: 'Allow'
        tag: 'Default'
        priority: 900 + i
        name: 'ProxyIp_${i}'
        description: 'Allow request from proxy ${i}'
      }]
    }
  }

主Bicep文件调用方式:

module ipRestrictions 'common.appSvc.ipSecurityRestrictions.bicep' = {
  scope: resourceGroup(utrnRg)
  name: 'ipRestrictionsDeploy'
  params: {
    appSvcName: functionAppName
  }
  dependsOn: [
    functionAppDeploy
  ]
}
解决方案

要实现追加而非替换,核心是读取应用服务当前已有的IP安全限制规则,再与新规则合并后部署:

  1. 从现有应用服务资源中读取当前的ipSecurityRestrictions,用coalesce处理规则为空的情况,确保得到一个数组
  2. 将现有规则数组与新的代理IP规则数组合并
  3. (可选)添加去重逻辑,避免重复添加相同规则

修改后的模块代码:

param appSvcName string

resource appSvc 'Microsoft.Web/sites@2021-02-01' existing = {
  name: appSvcName
}

var proxyIpAddresses = ['xxx.xxx.xxx.250/32','xxx.xxx.xxx.245/32']

// 读取现有IP限制规则,为空则转为空数组
var existingIpRestrictions = coalesce(appSvc.properties.siteConfig.ipSecurityRestrictions, [])

// 生成新的代理IP规则
var newProxyIpRules = [for (ip,i) in proxyIpAddresses: {
    ipAddress: ip
    action: 'Allow'
    tag: 'Default'
    priority: 900 + i
    name: 'ProxyIp_${i}'
    description: 'Allow request from proxy ${i}'
  }]

// 合并现有规则与新规则
var mergedIpRestrictions = concat(existingIpRestrictions, newProxyIpRules)

resource sitesConfig 'Microsoft.Web/sites/config@2021-02-01' =  {
  name: 'web'
  parent: appSvc
  properties: {
    ipSecurityRestrictions: mergedIpRestrictions
  }
}

注意事项

  • 确保新规则的priority不会与现有规则冲突,避免规则执行顺序异常
  • 如果需要避免重复添加相同规则,可以在合并前添加去重逻辑,例如:
    var uniqueExistingRules = existingIpRestrictions where rule => !contains(newProxyIpRules, newRule => newRule.ipAddress == rule.ipAddress)
    var mergedIpRestrictions = concat(uniqueExistingRules, newProxyIpRules)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:05:27