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

如何通过Azure Bicep为EventHub批量添加VNet下所有子网到网络配置

Azure Bicep批量添加VNet所有子网到Event Hub访问规则的实现方案

实现逻辑

  • 直接引用目标现有VNet,通过properties.subnets属性获取该VNet下所有子网的完整配置集合
  • 使用Bicep资源循环语法,遍历子网集合为每个子网独立创建Event Hub的VNet访问规则
  • 规则名称使用子网名称生成,保证全局唯一不会冲突

完整可运行代码

// 创建Event Hub命名空间
var eventHubNamespaceName = 'evhns-demo1436'

resource eventHubNamespace 'Microsoft.EventHub/namespaces@2021-01-01-preview' = {
  name: eventHubNamespaceName
  location: resourceGroup().location
  sku: {
    name: 'Standard'
    tier: 'Standard'
    capacity: 1
  }
  properties: {
    zoneRedundant: true
    networkAcls: {
      defaultAction: 'Deny' // 开启后默认拒绝所有未授权的公网访问
      trustedServiceAccessEnabled: true
    }
  }
}

// 在命名空间内创建Event Hub实例
var eventHubName = 'evh-demo1436'

resource eventHubNamespaceName_eventHubName 'Microsoft.EventHub/namespaces/eventhubs@2021-01-01-preview' = {
  parent: eventHubNamespace
  name: eventHubName
  properties: {
    messageRetentionInDays: 7
    partitionCount: 1
  }
}

// 配置Event Hub的收发权限规则
resource eventHubNamespaceName_eventHubName_ListenSend 'Microsoft.EventHub/namespaces/eventhubs/authorizationRules@2021-01-01-preview' = {
  parent: eventHubNamespaceName_eventHubName
  name: 'ListenSend'
  properties: {
    rights: [
      'Listen'
      'Send'
    ]
  }
  dependsOn: [
    eventHubNamespace
  ]
}

// 引用目标现有VNet
resource testVnet 'Microsoft.Network/virtualNetworks@2021-03-01' existing = {
  name: 'testvnet' // 替换为实际VNet名称
}

// 批量创建VNet所有子网的访问规则
@batchSize(10) // 控制并发创建的规则数量,避免触发API限流
resource enHubVnetRules 'Microsoft.EventHub/namespaces/virtualnetworkrules@2018-01-01-preview' = [for i in range(0, length(testVnet.properties.subnets)): {
  name: 'allow-subnet-${split(testVnet.properties.subnets[i].id, '/')[8]}' // 用子网名作为规则名保证唯一
  parent: eventHubNamespace
  properties: {
    virtualNetworkSubnetId: testVnet.properties.subnets[i].id
    ignoreMissingVnetServiceEndpoint: false // 设为true可跳过子网未开启Event Hub服务端点的校验
  }
}]

可选:过滤指定条件的子网

如果不需要添加所有子网,可提前对子网集合做筛选,示例如下:

// 筛选名称以"evh-access-"为前缀的子网
var allowedSubnetIds = [for subnet in testVnet.properties.subnets: subnet.id if startsWith(split(subnet.id, '/')[8], 'evh-access-')]

// 遍历筛选后的子网创建规则
@batchSize(10)
resource enHubVnetRules 'Microsoft.EventHub/namespaces/virtualnetworkrules@2018-01-01-preview' = [for sid in allowedSubnetIds: {
  name: 'allow-subnet-${split(sid, '/')[8]}'
  parent: eventHubNamespace
  properties: {
    virtualNetworkSubnetId: sid
  }
}]

内容的提问来源于stack exchange,提问作者devops-admin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:24:06