Add multiple NSGs to multiple subnets in Azure

Hey Scripters! Today quite easy script but very usefull to add multiple nsgs tu subnets in Azure.

Script is using JSON structure to define NSGs (Network Security Groups) and subnets to which they should apply. In NSGs JSON we simply define only NSGs which will be used in next JSON. In nsgAssignment JSON we are providing name of the nsgs and provide as array list of subnets to which they should apply. Once we have this definition script is iterate across all NSGs and adding them to subnets one-by-one. As an input for the script you must provide details about virtual network and corresponding resource group and of course subscription ID.

Prerequsities:

  • Az module
  • Already logged into Azure
  • Network Contributor access on resource group where VNET and subnets are created

Script:

Param (
  [String] [Parameter(Mandatory)]$VnetName= '',
  [String] [Parameter(Mandatory)]$VnetRGName= '',
  [String] [Parameter(Mandatory)]$SubscriptionId= ''
)


Select-AzureRMSubscription -SubscriptionId $SubscriptionID | Out-Null

$vnet = Get-AzVirtualNetwork -ResourceGroupName $VnetRGName -Name $VnetName

$NSGs= @"
{
    "nsgs": [
        "nsg-01",
        "nsg-02"
    ]
}
"@

$nsgTable = ($NSGs | ConvertFrom-Json).nsgs

$nsgsAssignment = @"
{
        "nsg-01": [
            "subnet1",
            "subnet2",
            "subnet3"
        ],
        "nsg-02": [
            "subnet4",
            "subnet5",
            "subnet6"
        ]
}
"@

$nsgAssignmentTable = $nsgsAssignment | ConvertFrom-Json

foreach($nsgName in $nsgTable){
    $nsgSubnets = $nsgAssignmentTable.$nsgName
    $nsg = Get-AzNetworkSecurityGroup -ResourceGroupName $NetworkRG -Name $nsgName
    foreach($subnetName in $nsgSubnets){
        Write-Output "Adding NSG $nsgName to subnet $subnetName"
        Try{
            $subnetAddressPrefix = (Get-AzVirtualNetworkSubnetConfig -Name $subnetName -VirtualNetwork $vnet).AddressPrefix
            $subnetNSG           = Set-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name $subnetName -AddressPrefix $subnetAddressPrefix -NetworkSecurityGroup $nsg -warningAction Ignore
            $Result              = Set-AzVirtualNetwork -VirtualNetwork $subnetNSG
            Write-Output "NSG $nsgName has been added to subnet $subnetName"
        }
        Catch{
            $Err = $_.Exception.Message
            Write-Output "NSG $nsgName was not added to subnet $subnetName. Error: $Err"
        }
    }
}

Hope that it will be usefull for some of you 😉

Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *

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