user346206
user346206

Reputation: 313

Assign NSG to VNet subnet using Bicep template

I want to add an existing NSG to existing VNet subnet. I tried doing it this way:

@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
    }
  }
}

Unfortunately, I can't pass the review/validation on Azure portal. It says that:

{"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.'."}

How to assign a NSG to existing VNet subnet, or how to get rid of this Circular dependency error?

Upvotes: 2

Views: 4703

Answers (1)

Thomas
Thomas

Reputation: 29522

You will have to use a module to update the subnet:

// 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
}

From you main, you could invoke it like that:

// 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
      }
    })
  }
}

Upvotes: 4

Related Questions