Azure Resource Graph Query For Network Security Group Rules

1 minute read

Few months ago, I had a requirement to produce a process to document Network Security Group (NSG) rules. Using Azure Resource Graph seemed like a logical choice.

I was lucky enough to find an existing Resource Graph query for NSG rules. However, this query has many limitations. For example, it doesn’t support ASGs, multiple source and destinations, multiple ports, etc.

I ended up created an updated version based on it, here’s what I have created:

List all inbound and outbound NSG rules

| where type =~ ""
| join kind=leftouter (resourcecontainers | where type =='microsoft.resources/subscriptions' | project SubscriptionName=name, subscriptionId) on subscriptionId
|mv-expand rules=properties.securityRules
|extend direction=tostring(
|extend priority=toint(
|extend rule_name =
|extend nsg_name = name
|extend destination_prefix=iif('[]',, strcat_array(, ","))
|extend destination_asgs=iif(isempty(, '', strcat_array(parse_json(, ","))
|extend destination=iif(isempty(destination_asgs), destination_prefix, destination_asgs)
|extend destination=iif(destination=='*', "Any", destination)
|extend destination_port=iif(isempty(, strcat_array(,","),
|extend source_prefix=iif('[]',, strcat_array(, ","))
|extend source_asgs=iif(isempty(, "", strcat_array(parse_json(, ","))
|extend source=iif(isempty(source_asgs), source_prefix, tostring(source_asgs))
|extend source=iif(source=='*', 'Any', source)
|extend source_port=iif(isempty(, strcat_array(,","),
|extend subnets = strcat_array(properties.subnets, ",")
|project SubscriptionName, resourceGroup, nsg_name, rule_name, subnets, direction, priority, action, source, source_port, destination, destination_port, description, subscriptionId, id
|sort by SubscriptionName, resourceGroup asc, nsg_name, direction asc, priority asc


This query is also stored in my Azure Resource Graph GitHub repo (HERE)

Leave a comment