Finding all Network Interfaces that are connected to Virtual Machines in Azure
Recently I was involved in a discovery project to find all our network interfaces and virtual machines in Azure.
I was aware that you could go to the Network Interface dashboard or the Virtual Machine dashboard but this was too manual for my liking. Also I needed to know which Network Interface was used by which Virtual Machine.
So my solution was using Azure Resource Graph Explorer.
The following KQL is used to get all Network Interfaces in your azure tenant.
resources
| where type =~ 'microsoft.network/networkinterfaces'
| extend privateIp = properties.ipConfigurations[0].properties.privateIPAddress
| extend id = name
| project name, privateIp, properties.macAddress, id
Running this KQL gives me a output like this in my test tenant.
To get the Virtual Machines that use the Network Interfaces a left outer join can be used to join the networkinterfaces table with the virtalmachines table using the IDs.
This is the KQL I used the left outer join.
| join kind=leftouter (
resources
| where type == "microsoft.compute/virtualmachines"
| extend idString = tostring(properties.networkProfile.networkInterfaces[0].id)
| extend id = extract(@"networkInterfaces\/(.*)", 1, idString)
| extend virtualMachineName = name
| project virtualMachineName, id)
on id
When using the above KQL extracts together, this is the output.
Below is the final rendition of the KQL with comments added into explain what each line does. I am more than happy for anyone to use the below KQL, if it is not working for you or you need assistance in editing it I am more than happy to help.
//table to use
resources
//which part of the table to look at
| where type =~ 'microsoft.network/networkinterfaces'
//get the privateIP address as it was stored in an array
| extend privateIp = properties.ipConfigurations[0].properties.privateIPAddress
//sets id to equal name, this will be needed for the join later on
| extend id = name
//specifies which variable to show
| project name, privateIp, properties.macAddress, id
//joins the networkinterface and virtaulmachines together
| join kind=leftouter (
resources
//which part of the table to look at
| where type == "microsoft.compute/virtualmachines"
//get the string which includes the id
| extend idString = tostring(properties.networkProfile.networkInterfaces[0].id)
//uses a regular expression to pull the virtual machine id from the string
| extend id = extract(@"networkInterfaces\/(.*)", 1, idString)
//changes the name of name so that is easier to understand what it is
| extend virtualMachineName = name
//works out if the network adapter has a virtual machine attached
//specifies which variable to show
| project virtualMachineName, id)
//specifies the tables to join on the id
on id
| extend vmOrNot = iif(isnotempty(virtualMachineName), "vm", "not")
| project-away id1, id
Comments
Post a Comment