azure - 使用 Bicep 模板将 NSG 分配到 VNet 子网

标签 azure azure-resource-manager azure-rm-template azure-bicep

我想将现有 NSG 添加到现有 VNet 子网。 我尝试这样做:

@description('Name of nsg')
param nsgName string
@description('Name of vnet')
param vnetName string
@description('Name of subnet')
param subnetName string

resource nsg 'Microsoft.Network/networkSecurityGroups@2022-01-01' existing = {
  name: nsgName
}
resource subnet 'Microsoft.Network/virtualNetworks/subnets@2022-01-01' existing = {
  name: '${vnetName}/${subnetName}'
}
resource nsgAttachment 'Microsoft.Network/virtualNetworks/subnets@2022-01-01' = {
  name: '${vnetName}/${subnetName}'

  properties: {
    addressPrefix: subnet.properties.addressPrefix
    networkSecurityGroup: {
      id: nsg.id
    }
  }
}

不幸的是,我无法通过 Azure 门户上的审核/验证。它说:

{"code":"InvalidTemplate","message":"Deployment template validation failed: 'Circular dependency detected on resource: '/subscriptions/xxxxxxxxx-02eaf5d20f25/resourceGroups/bicepRG/providers/Microsoft.Network/virtualNetworks/myVnetName/subnets/api'. Please see https://aka.ms/arm-template/#resources for usage details.'."}

如何将 NSG 分配到现有 VNet 子网,或者如何消除此循环依赖错误

最佳答案

您必须使用 module更新子网:

// update-subnet.bicep

param vnetName string
param subnetName string
param properties object

// Get existing vnet
resource vnet 'Microsoft.Network/virtualNetworks@2022-01-01' existing = {
  name: vnetName
}

resource subnet 'Microsoft.Network/virtualNetworks/subnets@2022-01-01' = {
  name: subnetName
  parent: vnet
  properties: properties
}

从你的 main 中,你可以像这样调用它:

// main.bicep

param nsgName string = 'thomastest-nsg2'
param vnetName string = 'thomastest-vnet'
param subnetName string = 'subnet1'

// Reference to nsg
resource nsg 'Microsoft.Network/networkSecurityGroups@2022-01-01' existing = {
  name: nsgName
}

// Get existing vnet
resource vnet 'Microsoft.Network/virtualNetworks@2022-01-01' existing = {
  name: vnetName
}

// Get existing subnet
resource subnet 'Microsoft.Network/virtualNetworks/subnets@2022-01-01' existing = {
  name: subnetName
  parent: vnet
}

// Update the subnet
module attachNsg 'update-subnet.bicep' = {
  name: 'update-vnet-subnet-${vnetName}-${subnetName}'
  params: {
    vnetName: vnetName
    subnetName: subnetName
    // Update the nsg
    properties: union(subnet.properties, {
      networkSecurityGroup: {
        id: nsg.id
      }
    })
  }
}

关于azure - 使用 Bicep 模板将 NSG 分配到 VNet 子网,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73568924/

相关文章:

.net - 寻求有关在云上配置开发环境的建议

azure - 在 Azure Functions Http 触发器上设置 UTF-8 编码

azure - 将静态 HTML 文件添加到 Azure MVC 应用程序的根目录

azure - 用于从不同资源组查找资源 ID 的 ARM 模板命令

azure - ARM 模板中的连接对象和字符串

azure - 使用 Azure 设备预配服务的 REST API 删除设备?

azure - 使用 Azure 资源管理器模板创建容器

Azure 模板 : Dynamically output all items created in CopyIndex() iteration

azure - 链接的 ARM 模板导致模板无效