Assigning an NSG to a subnet with PowerShell
Alternatively, we can associate an NSG using Azure PowerShell. In this recipe, we are going to show you how to associate an NSG with a subnet.
Getting ready
Open the PowerShell console and make sure you are connected to your Azure subscription.
How to do it...
To associate an NSG with a subnet, execute the following command:
$vnet = Get-AzVirtualNetwork -Name 'Packt-Script' -ResourceGroupName 'Packt-Networking-Script' $subnet = Get-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name BackEnd $nsg = Get-AzNetworkSecurityGroup -ResourceGroupName 'Packt-Networking-Script' -Name 'nsg1' $subnet.NetworkSecurityGroup = $nsg Set-AzVirtualNetwork -VirtualNetwork $vnet
How it works...
To assign an NSG using PowerShell, we need to collect information on the virtual network, subnet, and NSG. When all of the information is gathered, we can perform the association using the Set-AzVirtualNetwork...