May 10, 2018

Script to Clone Azure Network Security Groups (NSGs) in PowerShell

This script is a life saver! I am working on a big project to migrate to Azure, and one of the tedious parts of the project is setting up Network Security Groups, or NSGs. My company uses many granular rules, so setting these up the first time is time consuming. The idea of manually setting them up in other regions is down right daunting!

Well, not anymore! I found this series of commands from Virtual Geek that lets you do it easily in PowerShell!

First, you need the Azure PowerShell module if you don't already have it. After that, run the following:
$TemplateNSGRules =  Get-AzureRmNetworkSecurityGroup -Name '<Original NSG>' -ResourceGroupName '<Resource Group of Original NSG>' | Get-AzureRmNetworkSecurityRuleConfig
This creates a variable called TemplateNSGRules that we will use in step three. Next create your new NSG by running the following:

$NSG = New-AzureRmNetworkSecurityGroup -ResourceGroupName '<Destination Resource Group>' -Location '<Region Where You Want The New NSG>' -Name '<Name of New NSG>'
If you have already created an NSG in the portal, you would use this instead:

 $NSG = Get-AzureRmNetworkSecurityGroup -Name '<Name of New NSG>' -ResourceGroupName '<Destination Resource Group>'
Once you have executed one of the previous two commands, you will have a new variable called NSG that we will run a foreach loop on to import our rules from the original NSG:

 foreach ($rule in $TemplateNSGRules) {
    $NSG | Add-AzureRmNetworkSecurityRuleConfig -Name $rule.Name -Direction $rule.Direction -Priority $rule.Priority -Access $rule.Access -SourceAddressPrefix $rule.SourceAddressPrefix -SourcePortRange $rule.SourcePortRange -DestinationAddressPrefix $rule.DestinationAddressPrefix -DestinationPortRange $rule.DestinationPortRange -Protocol $rule.Protocol # -Description $rule.Description
    $NSG | Set-AzureRmNetworkSecurityGroup
}
Boom! That's it! Now you have an exact clone of your original NSG in just a few minutes! Make sure you replace the items I used in < > to fit your environment!

Did this help you out? Let us know in the comments!



Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | stopping spam