Azure Docs

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

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

  1. Navigate to Virtual machines and select your VM.
  2. In the left sidebar, click Networking.
  3. Under Network interface, click the NIC name.
  4. On the NIC blade, select Network security group and click Associate.
  5. Choose the NSG you want to attach and click Save.
Azure Portal NSG association

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.