How to create and apply Network Security Group/Rules Using PowerShell in Azure

What is NSG in Azure?
NSG is the region specific and can be used only within the region specified at creation time.



You can create network security group (NSG) using the PowerShell script. Here are some steps to create and apply NSG

1. Create a new NSG. Since I am in New Zealand and closet data centre for me is "Australia East" so i will use this in example
New-AzureNetworkSecurityGroup -Name "WFE_NSG" -Location " Australia East" -Label "WebFrontEnd NSG in Australia East"

2. Apply the rule to the NSG. Rule will allows all traffic from the Internet
Get-AzureNetworkSecurityGroup -Name "WFE_NSG" | Set-AzureNetworkSecurityRule -Name WEB -Type Inbound -Priority 100 -Action Allow -SourceAddressPrefix 'INTERNET' -SourcePortRange '*' -DestinationAddressPrefix '*' -DestinationPortRange '*' -Protocol TCP

3. Enabling inbound SQL communication
Get-AzureNetworkSecurityGroup -Name "WFE_NSG" | Set-AzureNetworkSecurityRule -Name SQL -Type Inbound -Priority 110 -Action Allow -SourceAddressPrefix '10.0.1.0/24' -SourcePortRange '*' -DestinationAddressPrefix '10.0.2.0/24' -DestinationPortRange '1433' -Protocol TCP

4. Applying Network Security Group (NSG)
Get-AzureVM -ServiceName $service -Name $VM | Set-AzureNetworkSecurityGroupConfig -NetworkSecurityGroupName "WFE_NSG"

5. Apply NSG to a virtual subnet
Get-AzureNetworkSecurityGroup -Name "WFE_NSG" | Set-AzureNetworkSecurityGroupToSubnet -VirtualNetworkName 'MyTestVNet' -SubnetName 'WFE_Subnet'
Get-AzureNetworkSecurityGroup -Name "WFE_NSG" | Set-AzureNetworkSecurityRule -Name RDPIN -Type Inbound -Priority 101 -Action Allow -SourceAddressPrefix 'INTERNET' -SourcePortRange '*' -DestinationAddressPrefix '*' -DestinationPortRange '3389' -Protocol '*'