简体   繁体   中英

Azure NSG - Filter certain IPs from input csv

I am using PowerShell to create Azure NSGs which will use input from a .csv file with security rules. I am using the script below.

$NSG = Get-AzureRmNetworkSecurityGroup -Name test -ResourceGroupName RG-VM-QTY

foreach($rule in import-csv "SystemPath\inputfile.csv") 
{ 
$NSG | Add-AzureRmNetworkSecurityRuleConfig -Name $rule.name -Access Allow -Protocol $rule.protocol -Direction $rule.direction -Priority $rule.priority 
-SourceAddressPrefix $rule.source -SourcePortRange * 
-DestinationAddressPrefix $rule.destination -DestinationPortRange $rule.port 
}

$NSG | Set-AzureRmNetworkSecurityGroup

Wanted to check if there is a way to restrict adding a particular IP lets say 127.0.0.1 to be added as source or destination in any of the rules. Any check that I can put to avoid creating the NSG altogether if the IP 127.0.0.1 is present in the .csv?

Thanks in advance guys.! Cheers.

Here is the modified PowerShell script with a simple if condition added to check that SourceAddressPrefix and DestinationAddressPrefix should not be exactly 127.0.0.1

$NSG = Get-AzureRmNetworkSecurityGroup -Name test -ResourceGroupName RG-VM-QTY 

foreach($rule in import-csv "SystemPath\inputfile.csv") 
{
   # additional if condition to check that source or destination address prefix should not be 127.0.0.1
   if($rule.SourceAddressPrefix -ne "127.0.0.1" -And $rule.DestinationAddressPrefix -ne "127.0.0.1")
   { 
          $NSG | Add-AzureRmNetworkSecurityRuleConfig -Name $rule.name -Access Allow -Protocol $rule.protocol -Direction $rule.direction -Priority $rule.priority 
             -SourceAddressPrefix $rule.source -SourcePortRange * -DestinationAddressPrefix $rule.destination -DestinationPortRange $rule.port 
   }
} 

$NSG | Set-AzureRmNetworkSecurityGroup

Your condition right now is very simple to check for 127.0.0.1 so if condition should be good enough.

In case you get to a more complicated logic, consider creating a separate function say something like ValidateRule(), that can encapsulate all conditions and call that function to check whether or not the rule should be added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM