Add an inbound network security group rule

This sample script creates a network security group rule to allow inbound traffic on port 8081. The script gets the network security group, creates a new network security configuration rule, and updates the network security group. Customize the parameters as needed.


This article has been updated to use the new Azure PowerShell Az module. You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. For Az module installation instructions, see Install Azure PowerShell.

If needed, install the Azure PowerShell using the instructions found in the Azure PowerShell guide.

Sample script

Set-AzContext -SubscriptionId "yourSubscriptionID"


# Get the NSG resource
$nsg = Get-AzNetworkSecurityGroup -Name $nsgname -ResourceGroupName $RGname

# Add the inbound security rule.
$nsg | Add-AzNetworkSecurityRuleConfig -Name $rulename -Description "Allow app port" -Access Allow `
    -Protocol * -Direction Inbound -Priority 3891 -SourceAddressPrefix "*" -SourcePortRange * `
    -DestinationAddressPrefix * -DestinationPortRange $port

# Update the NSG.
$nsg | Set-AzNetworkSecurityGroup

Script explanation

This script uses the following commands. Each command in the table links to command specific documentation.

Command Notes
Get-AzResource Gets the Microsoft.Network/networkSecurityGroups resource.
Get-AzNetworkSecurityGroup Gets the network security group by name.
Add-AzNetworkSecurityRuleConfig Adds a network security rule configuration to a network security group.
Set-AzNetworkSecurityGroup Sets the goal state for a network security group.

Next steps

For more information on the Azure PowerShell module, see Azure PowerShell documentation.