Posted in

CSV <--- import/export ---> Azure NSG

Sometimes we need to import rules to NSG from an Excell file. I had to do it to allow communication with Salesforce – so I had to implement IP whitelist according to this: https://help.salesforce.com/articleView?id=000003652&type=1.

So the script to do it is here:

$importFile = ‘Salesforce-nsg.csv’
$nsgname = ‘acobybylonsg-nsg’
$nsgrg = ‘acobybylonsg’
$subscription=’a3eaae72-4091-4bb6-8e79-ad91f956ac87′
$rulesArray = @()
##############
Login-AzureRmAccount
Select-AzureRmSubscription -SubscriptionId $subscription
##############
$nsg = Get-AzureRmNetworkSecurityGroup -Name $nsgname -ResourceGroupName $nsgrg
foreach ($rule in import-csv $importFile)
{
$nsg|Add-AzureRmNetworkSecurityRuleConfig `
-Name $rule.Name `
-Description $rule.Description `
-Protocol $rule.Protocol `
-SourcePortRange ($rule.SourcePortRange -split ‘,’) `
-DestinationPortRange ($rule.DestinationPortRange -split ‘,’) `
-SourceAddressPrefix ($rule.SourceAddressPrefix -split ‘,’) `
-DestinationAddressPrefix ($rule.DestinationAddressPrefix -split ‘,’) `
-Access $rule.Access `
-Priority $rule.Priority `
-Direction $rule.Direction
}
$nsg|Set-AzureRmNetworkSecurityGroup

CSV file is here.

Before doing it could be helpful to export NSG using this script:

$exportPath = ‘C:temp’
$nsgname = ‘acobybylonsg-nsg’
$nsgrg = ‘acobybylonsg’
$subscription=’a3eaae72-4091-4bb6-8e79-ad91f956ac87′
##############
Login-AzureRmAccount
Select-AzureRmSubscription -SubscriptionId $subscription
##############
$nsgs = Get-AzureRmNetworkSecurityGroup -Name $nsgname -ResourceGroupName $nsgrg
#backup nsgs to csv
Foreach ($nsg in $nsgs) {
New-Item -ItemType file -Path “$exportPath$($nsg.Name).csv” -Force
$nsgRules = $nsg.SecurityRules
foreach ($nsgRule in $nsgRules) {
$nsgRule | Select-Object Name,Description,Priority,@{Name=’SourceAddressPrefix’;Expression={[string]::join(“,”, ($_.SourceAddressPrefix))}},@{Name=’SourcePortRange’;Expression={[string]::join(“,”, ($_.SourcePortRange))}},@{Name=’DestinationAddressPrefix’;Expression={[string]::join(“,”, ($_.DestinationAddressPrefix))}},@{Name=’DestinationPortRange’;Expression={[string]::join(“,”, ($_.DestinationPortRange))}},Protocol,Access,Direction `
| Export-Csv “$exportPath$($nsg.Name).csv” -NoTypeInformation -Encoding ASCII -Append
}
}

Microsoft Certified Trainer, Office 365, AWS, Azure and Cloud Expert-Architect. In the IT world for over than 20 years.

Apart from the main area of Microsoft Azure expert in the field of infrastructure servers Windows Server 2003-2019, Microsoft Active Directory, Hyper-V Private Cloud, IIS, System Center, SQL.

Private Cloud, System Center, Hyper-V, Open Stack Expert and all Microsoft products Expert. Linux Server administrator.

My Azure community projects:

https://mazeball.azurewebsites.net/
https://github.com/MariuszFerdyn?tab=repositories

More

Leave a Reply

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