Share the love

Virtual network peering using bicep in same resource group is straight-forward and pretty easy. However, nested files come into picture when one has to peer virtual networks in two different resource groups.

Here, we will use modular approach to do this. It considers that required virtual networks are already deployed.

First we will write the actual peering code, followed by main.bicep file. You can fine them in my GitHub repo as well.

@description('Set the local VNet name')
param existingLocalVirtualNetworkName string

@description('Set the remote VNet name')
param existingRemoteVirtualNetworkName string

@description('Sets the remote VNet Resource group')
param existingRemoteVirtualNetworkResourceGroupName string

resource existingLocalVirtualNetworkName_peering_to_remote_vnet 'Microsoft.Network/virtualNetworks/virtualNetworkPeerings@2021-02-01' = {
  name: '${existingLocalVirtualNetworkName}/peering-to-remote-vnet'
  properties: {
    allowVirtualNetworkAccess: true
    allowForwardedTraffic: false
    allowGatewayTransit: false
    useRemoteGateways: false
    remoteVirtualNetwork: {
      id: resourceId(existingRemoteVirtualNetworkResourceGroupName, 'Microsoft.Network/virtualNetworks', existingRemoteVirtualNetworkName)
    }
  }
}

Name of the peering resource should be mentioned as shown above. Check Microsoft documentation on naming child resources to get more details on the same.

With module in place, lets write the main.bicep file accordingly.

targetScope = 'resourceGroup'

module peerFirstVnetSecondVnet 'peering.bicep' = {
  name: 'peerFirstToSecond'
  scope: resourceGroup('FirstVnetRg')
  params: {
    existingLocalVirtualNetworkName: 'firstVnet'
    existingRemoteVirtualNetworkName: 'secondVnet'
    existingRemoteVirtualNetworkResourceGroupName: 'secondVnetRg'
  }
}

module peerSecondVnetFirstVnet 'peering.bicep' = {
  name: 'peerSecondToFirst'
  scope: resourceGroup('SecondVnetRg')
  params: {
    existingLocalVirtualNetworkName: 'secondVnet'
    existingRemoteVirtualNetworkName: 'firstVnet'
    existingRemoteVirtualNetworkResourceGroupName: 'firstVnetRg'
  }
}

Parameters file is not included. I hope you would be able to come up with one for your use.