azureazure-powershellazure-virtual-networkazure-storage-accountazure-nsg

How to create an Azure Network Security Group Flow log with Azure PowerShell


I want to create a NSG flow log for the network security group of a given Virtual Machine and link to a given Storage Account with PowerShell.

How can I achieve this?


Solution

  • This can be achieved with this sequence of operations:

    1. determine the NSG linked to a Virtual Machine
    2. get or create a `NetworkWatcher for the location of the NSG
    3. find a suitable storage account
    4. set a Flow Log configuration, if there is none existing
    param(
        # RegEx pattern to find your first VM in your current subscription
        [Parameter(Mandatory = $true, Position = 1)]
        [string]$vmNamePattern,
        # RegEx pattern to find a storage account in your current subscription
        [Parameter(Mandatory = $true, Position = 2)]
        [string]$storageNamePattern
    )
    
    $vm = Get-AzVM | Where-Object { $_.Name -match $vmNamePattern } | Select-Object -First 1
    $nic = Get-AzNetworkInterface -ResourceId $vm.NetworkProfile.NetworkInterfaces[0].Id
    $sn = Get-AzVirtualNetworkSubnetConfig -ResourceId $nic.IpConfigurations[0].Subnet.Id
    $nsgRes = Get-AzResource -ResourceId $sn.NetworkSecurityGroup.Id
    $nsg = Get-AzNetworkSecurityGroup -ResourceGroupName $nsgRes.ResourceGroupName -Name $nsgRes.ResourceName
    
    # create or get NetworkWatcher
    $nw = Get-AzNetworkWatcher -ResourceGroupName NetworkWatcherRg | ? { $_.Location -eq $nsg.Location }
    if (!$nw) {
        New-AzNetworkWatcher -ResourceGroupName NetworkWatcherRg -Location $nsg.Location -Name $("NetworkWatcher_" + $nsg.Location)
        $nw = Get-AzNetworkWatcher -ResourceGroupName NetworkWatcherRg | ? { $_.Location -eq $nsg.Location }
    }
    
    # detect first viable storage account
    $storageAccount = Get-AzStorageAccount  | Where-Object { $_.StorageAccountName -match $storageNamePattern -and $_.PrimaryEndpoints.Blob -match "^http" } | Select-Object -First 1
    
    # get or set NSG flow log if not yet established
    $fl = Get-AzNetworkWatcherFlowLogStatus -NetworkWatcher $nw -TargetResourceId $nsg.Id
    if (!$fl) {
        # https://learn.microsoft.com/de-de/azure/network-watcher/network-watcher-nsg-flow-logging-powershell
        Set-AzNetworkWatcherConfigFlowLog -NetworkWatcher $nw -TargetResourceId $nsg.Id -StorageAccountId $storageAccount.Id -EnableFlowLog $true -FormatType Json -FormatVersion 2
    }