Coder Perfect

In a Bicep template, how do I build an Azure Network Security Group / NSG flow log?

Problem

For a network security group and storage account I generated with Bicep, I’d like to produce an NSG flow log.

I’m implementing something similar to an NSG.

resource nsg 'Microsoft.Network/networkSecurityGroups@2020-06-01' = {
  name: networkSecurityGroupName
  location: location
  properties: {
    securityRules: [
...

as well as a storage account similar to

resource stg 'Microsoft.Storage/storageAccounts@2021-01-01' = {
  name: storageName
  location: location
  kind: 'StorageV2'
  sku: {
    name: 'Standard_LRS'
  }
}

However, when it comes to creating and deploying an NSG flow using

resource nsgFlowLogs 'Microsoft.Network/networkWatchers/flowLogs@2020-08-01' = {
  name: 'NetworkWatcher_${location}/${nsgFlowName}'
  location: location
  properties: {
    targetResourceId: nsg.Id
    storageId: stg.Id
    enabled: true
    retentionPolicy: {
      days: 2
      enabled: true
    }
    format: {
      type: 'JSON'
      version: 2
    }
  }
}

I’m getting an error message.

     | 19:02:20 - Error: Code=ResourceCountExceedsLimitDueToTemplate; Message=Subscription
     | 853049fd-4889-45b6-aad9-f3f54421399c has a quota of 1 for resources of type NetworkWatcher with sku SkuNotSpecified.
     | Subscription currently has 1 resources and the template contains 1 new resources of the this type which exceeds the
     | quota. Please contact support to increase the quota for resource type NetworkWatcher

Asked by Kai Walter

Solution #1

It turns out that the Network Watcher resource, as well as the flow log that goes with it, must be created in the NetworkWatcherRG resource group.

Hence nsgflowlog.bicep is a module I extracted.

param name string
param location string = resourceGroup().location
param nsgId string
param storageId string

resource nsgFlowLogs 'Microsoft.Network/networkWatchers/flowLogs@2020-08-01' = {
  name: 'NetworkWatcher_${location}/${name}'
  location: location
  properties: {
    targetResourceId: nsgId
    storageId: storageId
    enabled: true
    retentionPolicy: {
      days: 2
      enabled: true
    }
    format: {
      type: 'JSON'
      version: 2
    }
  }
}

I’m able to switch the resource group during deployment because of this:

module nsgFlow './nsgflowlog.bicep' = {
  name: '${resourcePrefix}-nsgFlow'
  scope: resourceGroup('NetworkWatcherRG')
  params: {
    name: nsgFlowName
    nsgId: nsg.id
    storageId: stg.id
  }
}

Answered by Kai Walter

Post is based on https://stackoverflow.com/questions/67305113/how-can-i-create-an-azure-network-security-group-nsg-flow-log-within-a-bicep-t