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.

Note

We recommend that you use the Azure Az PowerShell module to interact with Azure. To get started, see Install Azure PowerShell. To learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.

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

Sample script

Connect-AzAccount -Environment AzureChinaCloud
Get-AzSubscription
Set-AzContext -SubscriptionId "yourSubscriptionID"

$RGname="sfclustertutorialgroup"
$port=8081
$rulename="allowAppPort$port"
$nsgname="sf-vnet-security"

# 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.