Search code examples
azurepowershellobjectnullazure-nsg

Automate NSG rule creation for NSGs within azure: Type error from Get-AzNetworkSecurityGroup


I am trying to write a script to automate creating NSG rules for our production NSGs. I am pretty sure I have something close to working but the issue I run into is that the Get-AZNetworkSecurityGroup command returns a string and so I cant feed it into the Add-AzNetworkSecurityRuleConfig command.

Import-Module Az.network
Connect-AzAccount
$tcpports = @(22,53,80,135,137,161,427,443,515,548,5060,5480,5985,5986,5989,9100,9443)
$udpports = @(53,161,427,515,548)
$solservers = #Server IP here
$file = Import-Csv C:\Users\temp\Downloads\AzureNSGs.csv

foreach ($NSG in $file){
$RGname=$NSG.'RESOURCE GROUP'
$nsgname=$NSG.NAME
$NSGObj = Get-AzNetworkSecurityGroup | Where-Object -Property Name -Like $RGname | Select-Object -Property Name
$name = "AllowSolarWinds"
    if($NSGObj){
    $name = $name + 1 
    $NSGObj | Add-AzNetworkSecurityRuleConfig -Name $name -NetworkSecurityGroup $NSGObj -Protocol Icmp -SourceAddressPrefix $solservers -DestinationPortRange "*" -Priority 555 
    $NSGObj | Set-AzNetworkSecurityGroup 
    }
}

Whenever I run this I get two kinds of returns. It either looks like it ran successfully with no errors but the rule is never created in azure. Or powershell spits out one of the following errors.

Add-AzNetworkSecurityRuleConfig : Cannot bind argument to parameter 'NetworkSecurityGroup' because it is null.

or

Add-AzNetworkSecurityRuleConfig : Cannot bind parameter 'NetworkSecurityGroup'. Cannot convert the value of type "System.String" to type 
"Microsoft.Azure.Commands.Network.Models.PSNetworkSecurityGroup".

Solution

  • I tried to reproduce the same in my environment I got the same error like below:

    enter image description here

    To resolve the error, try to modify the code like below:

    Connect-AzAccount
    Import-Module Az.network
    $tcpports = @(22,53,80,135,137,161,427,443,515,548,5060,5480,5985,5986,5989,9100,9443)
    $udpports = @(53,161,427,515,548)
    $solservers = "112.121.61.196"
    $file = Import-Csv C:\Users\v-khanimran\Downloads\AzureNSGs.csv
    
    foreach ($NSG in $file){
    $RGname=$NSG.RESOURCEGROUPNAME
    $nsgname=$NSG.NAME
    $NSGObj =Get-AzNetworkSecurityGroup -Name $nsgname -ResourceGroupName $RGname
    #Get-AzNetworkSecurityGroup | Where-Object {$_.Name -Like $nsgname} | Select-Object -Property Name
    $name = "AllowSolarWinds"
        if($NSGObj){
        $name = $name + 1 
        $NSGObj | Add-AzNetworkSecurityRuleConfig -Name $name  -Protocol Icmp -SourceAddressPrefix $solservers -DestinationPortRange  "*" -SourcePortRange "*" -DestinationAddressPrefix "*" -Priority 555 -Access Allow -Direction Inbound 
        
        $NSGObj | Set-AzNetworkSecurityGroup 
        }
    }
    

    Output:

    enter image description here

    In the portal NSG rule got added successfully like below:

    enter image description here