Export All NSG Rules from All Azure Subscriptions With PowerShell

| ,

Published on | Updated on April 28, 2021

3 Min. Read

Updated – 28/04/2021 – If you are using Application Security Groups (ASG), the script was updated to include the source and destination name of the Application Security Group (ASG) used with Network Security Groups (NSG). Please feel free to leave a comment below for additional improvement.

Updated – 12/03/2021 – The script was updated to include the source and destination addresses. Please feel free to leave a comment below for additional improvement.

In this article, I will share with you how to export all Network Security Groups (NSG) rules from all Azure subscriptions with Azure PowerShell.

Introduction

Azure Network Security Group (NSG) can help you limit network traffic to resources in a virtual network, you can think of it as your traditional layer 4 firewall. NSG allows you to create rules (ACLs) at the desired level of granularity: network interfaces, individual VMs, or virtual subnets. You can control access by permitting or denying communication between the workloads within a virtual network, from systems on your network(s) via cross-premises connectivity, or direct Internet communication. Each network interface has zero, or one, associated network security group. Each network interface exists in a virtual network subnet. A subnet can also have zero, or one, associated network security group.

In this article, I will share with you a PowerShell script that will help you to get the list of all Network Security Groups (NSGs) in all Azure subscriptions, and then export it to comma-separated value (CSV) format. This comes in handy when working with many VMs in Azure, and you want to audit all Network Security Group (NSG) rules that you have.

PowerShell script

Here is the script that will do the job for you:

<#
.Synopsis
A script used to export all NSGs rules in all your Azure Subscriptions

.DESCRIPTION
A script used to get the list of all Network Security Groups (NSGs) in all your Azure Subscriptions.
Finally, it will export the report into a csv file in your Azure Cloud Shell storage.

.Notes
Created   : 04-January-2021
Updated   : 28-April-2021
Version   : 3.0
Author    : Charbel Nemnom
Twitter   : @CharbelNemnom
Blog      : https://charbelnemnom.com
Disclaimer: This script is provided "AS IS" with no warranties.
#>

$azSubs = Get-AzSubscription

foreach ( $azSub in $azSubs ) {
    Set-AzContext -Subscription $azSub | Out-Null
    $azSubName = $azSub.Name

    $azNsgs = Get-AzNetworkSecurityGroup 
    
    foreach ( $azNsg in $azNsgs ) {
        # Export custom rules
        Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $azNsg | `
            Select-Object @{label = 'NSG Name'; expression = { $azNsg.Name } }, `
            @{label = 'NSG Location'; expression = { $azNsg.Location } }, `
            @{label = 'Rule Name'; expression = { $_.Name } }, `
            @{label = 'Source'; expression = { $_.SourceAddressPrefix } }, `
            @{label = 'Source Application Security Group'; expression = { $_.SourceApplicationSecurityGroups.id.Split('/')[-1] } },
            @{label = 'Source Port Range'; expression = { $_.SourcePortRange } }, Access, Priority, Direction, `
            @{label = 'Destination'; expression = { $_.DestinationAddressPrefix } }, `
            @{label = 'Destination Application Security Group'; expression = { $_.DestinationApplicationSecurityGroups.id.Split('/')[-1] } }, `
            @{label = 'Destination Port Range'; expression = { $_.DestinationPortRange } }, `
            @{label = 'Resource Group Name'; expression = { $azNsg.ResourceGroupName } } | `
            Export-Csv -Path "$($home)\clouddrive\$azSubName-nsg-rules.csv" -NoTypeInformation -Append -force
        
        # Export default rules
        Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $azNsg -Defaultrules | `
            Select-Object @{label = 'NSG Name'; expression = { $azNsg.Name } }, `
            @{label = 'NSG Location'; expression = { $azNsg.Location } }, `
            @{label = 'Rule Name'; expression = { $_.Name } }, `
            @{label = 'Source'; expression = { $_.SourceAddressPrefix } }, `
            @{label = 'Source Port Range'; expression = { $_.SourcePortRange } }, Access, Priority, Direction, `
            @{label = 'Destination'; expression = { $_.DestinationAddressPrefix } }, `
            @{label = 'Destination Port Range'; expression = { $_.DestinationPortRange } }, `
            @{label = 'Resource Group Name'; expression = { $azNsg.ResourceGroupName } } | `
            Export-Csv -Path "$($home)\clouddrive\$azSubName-nsg-rules.csv" -NoTypeInformation -Append -force
      
    }    
}

From the example above, I am exporting the following information:

  • Network Security Group (NSG) Name
  • Network Security Group (NSG) Location
  • For each Network Security Group, I will export the custom rule, as well as the default rule:
    • Rule Name
    • Source address
    • Port Range
    • Access
    • Priority
    • Direction
      • Inbound
      • Outbound
    • Destination address
  • Resource Group Name

Run the script

To run the script, you can either install the latest Azure PowerShell version on your machine, or jump over the Cloud Shell (https://shell.azure.com), or use the Azure Cloud Shell Connector in Windows Terminal.

Export All NSG Rules from All Azure Subscriptions With PowerShell 1

The report will be saved in the clouddrive path following the Azure Subscription name (-nsg-rules.csv).

Export All NSG Rules from All Azure Subscriptions With PowerShell 2

Switch to the cloud shell storage account and download the CSV files as shown in the figure below.

Export All NSG Rules from All Azure Subscriptions With PowerShell 3

And here is the final report showing in CSV format:

Export All NSG Rules from All Azure Subscriptions With PowerShell 4

Please note that you can accomplish the same thing using Azure CLI, however, I prefer to use Azure PowerShell.

Summary

In this article, I showed you how to export all Network Security Groups (NSG) rules from all your Azure Subscriptions with Azure PowerShell.

Azure Cloud Shell is so powerful, you don’t need to install Azure CLI or PowerShell modules locally on your machine to automate your tasks.

Learn more on how to get the list of Network Security Group with RDP port open.

This is version 1.0 of this tool, do you want additional features? Please feel free to leave a comment below.

Hope this helps!

__
Thank you for reading my blog.

If you have any questions or feedback, please leave a comment.

-Charbel Nemnom-

Related Posts

Previous

Reflecting on 2020… Goodbye 2020 and Welcome 2021! #HappyNewYear

How To Export and Backup Azure Policy Definitions

Next

16 thoughts on “Export All NSG Rules from All Azure Subscriptions With PowerShell”

Leave a comment...

  1. Does not work. All kinds of error messages specifically relating to Expressions are only allowed as the first element of a pipeline

  2. Hello Brandon,
    Thanks for your comment. Please note that I just tried it and it works flawlessly.
    Please make sure that you copy the code correctly including the backtick (`) and pipes (|). Hope this helps.

  3. HI Charbel

    Where can I get a copy of this NSG script

  4. Hello Everett, thanks for your comment.
    Please note that you can copy this NSG script from the ‘Code Block’ in the black box here. Could you please confirm that you can copy it? It should work.

  5. Great script! However, the output does not contain source and destination addresses which are crucial to have in any form of a backup copy.

  6. Thank you Marek for the feedback, much appreciated! I have updated the script to include the source and destination addresses. Please check it and let me know if it works for you.

  7. Under Export Default rules you have a single quotation mark instead of an apostrophe

    @{label = ‘Source Port Range’;

    Should be

    @{label = ‘Source Port Range’;

  8. Thank you Stephen for the feedback, much appreciated! I have updated it.

  9. Awesome work! Is it possible to include VM/Network Interface/Subnet association with this script?

  10. Thank you Harpreet for the feedback! Yes, it is possible to include VM/Network Interface/Subnet association with this script.

  11. Great Script. Just what i needed. Thank you for sharing

  12. Hello sir, thanks for the wonderful script , its running fine but it is not displaying the name of ASG in source and destination in NSG rule where we are using Application security group.. ( showing blank over there)

  13. Thank you Deepak for the feedback, please note that I have updated the script to include the Application Security Group (ASG) name in the source and destination for each NSG rule used. Please give it a try and let me know if it works for you. Thanks!

  14. I want to download json of all the NSG in given subscription using PowerShell or any other way.

  15. Hello Suraj, thanks for your comment.
    You could try to convert to JSON instead of Export-Csv as follows:
    ConvertTo-Json -Depth 12 | Out-File "$($home)\clouddrive\$azSubName-nsg-rules.json"
    Hope this helps!

  16. Thanks a lot Charbel, it has saved tons of time.

Let me know what you think, or ask a question...

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to Stay in Touch

Never miss out on your favorite posts and our latest announcements!

The content of this website is copyrighted from being plagiarized! You can copy from the 'Code Blocks' in Black.

Please send your feedback to the author using this form for any 'Code' you like.

Thank you for visiting!