Automate Azure Route Table testing using Network Watcher and PowerShell scripting - Code Sample

@20aman    Jul 21, 2021

In any enterprise environment, you will have lots of customer User Defined Routes or UDRs written within Azure Route Tables. You will want to test all of these route tables and check if the "Next Hop" is as per the route tables set by you or not. This could prove to be a tedious task if done manually. I have automated this task using PowerShell scripting. I am sharing the sample in this post.

NOTE: You should enable Network Watcher in your environment for this script sample to work. Also, note that you need to enable the Network watcher only in the region where your resources exist.

Script location

The latest version of the script can be found in GitHub here: Test-NetworkWatcherRouteNextHop.

A sample input CSV file is also located at the same location.

Script Working

For the script to work, make sure that you have filled the input CSV file as per your environment. In every test, there will be a source and a destination for the communication pair. The script primary looks for the below information from the csv file:

  1. SourceSubscription - The subscription for the source.
  2. SourceRG - The resource group of the source VM
  3. SourceVMName - Name of the source VM
  4. Source IP - Indicative - Actual IP address of the source VM. Please ignore the "indicative" text
  5. DestinationIP-Actual - Actual IP address of the destination VM
  6. SourceLocation - Azure region location of the source VM

NOTE: Within the script update the Network Watcher names as per your primary and secondary regions in Azure where "Get-AzNetworkWatcher" cmdlet is used. E.g. to fetch the Network Watcher in the East US 2 region the command used is as below.

$nw = Get-AzNetworkWatcher -Name NetworkWatcher_eastus2 -ResourceGroupName NetworkWatcherRG

The script then fetches the VM using the Get-AzVM cmdlet.

$vm = Get-AzVM -Name $SourceVMName -ResourceGroupName $SourceVMResourceGroupName

Finally, it executes the test by using the Get-AzNetworkWatcherNextHop command.

$nextHop = Get-AzNetworkWatcherNextHop -NetworkWatcher $nw -TargetVirtualMachineId $vm.Id -SourceIPAddress $SourceVMIPAddress -DestinationIPAddress $DestinationIPAddress

To get the results it uses the output of the above command.

$eachVM.NextHopType = $nextHop.NextHopType
$eachVM.IPAddressResult = $nextHop.NextHopIpAddress
$eachVM.RouteTableID = $nextHop.RouteTableId

You can then compare the output with the expected output to check if the test case passed or failed.

If you have any improvements you would like to see in the script feel free to provide that as a comment here or a pull request on GitHub.





Comments powered by Disqus