Apply a Network Security Group to a Virtual Machine
This guide walks you through attaching an existing Network Security Group (NSG) to a virtual machine’s network interface (NIC) using PowerShell, Azure CLI, and the Azure portal.
Prerequisites
- An existing Azure subscription.
- A virtual network with a subnet.
- A virtual machine (or NIC) you want to protect.
- An existing Network Security Group (create one if needed).
- Azure PowerShell module or Azure CLI installed locally, or access to the Azure portal.
Using Azure PowerShell
Run the following commands in an elevated PowerShell prompt.
# Variables
$resourceGroup = "MyResourceGroup"
$vmName = "MyVM"
$nsgName = "MyNSG"
# Retrieve the NIC attached to the VM
$nic = Get-AzNetworkInterface -ResourceGroupName $resourceGroup `
-Name (Get-AzVM -ResourceGroupName $resourceGroup -Name $vmName).NetworkProfile.NetworkInterfaces[0].Id.Split('/')[-1]
# Get the NSG
$nsg = Get-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Name $nsgName
# Associate the NSG with the NIC
$nic.NetworkSecurityGroup = $nsg
Set-AzNetworkInterface -NetworkInterface $nic
Using Azure CLI
Execute the following in a Bash shell.
# Variables
RG="MyResourceGroup"
VM="MyVM"
NSG="MyNSG"
# Get NIC name
NIC=$(az vm show -g $RG -n $VM --query "networkProfile.networkInterfaces[0].id" -o tsv | cut -d'/' -f9)
# Associate NSG
az network nic update -g $RG -n $NIC --network-security-group $NSG
Using the Azure Portal
- Navigate to Virtual machines and select your VM.
- In the left sidebar, click Networking.
- Under Network interface, click the NIC name.
- On the NIC blade, select Network security group and click Associate.
- Choose the NSG you want to attach and click Save.

Validate the NSG Association
Confirm the NSG is attached to the NIC:
Get-AzNetworkInterface -ResourceGroupName $resourceGroup -Name $nic.Name |
Select-Object -ExpandProperty NetworkSecurityGroup
Or via Azure CLI:
az network nic show -g $RG -n $NIC --query "networkSecurityGroup.id" -o tsv
Now the NSG rules will be enforced for inbound and outbound traffic to your VM.