Assign Network Security Group to Virtual Machine Network Interface using PowerShell

A blog post to show how you can assign a Network Security Group (NSG) to a Virtual Machine Network Interface (NIC) in Azure using PowerShell.

Firstly, get the Network Security Group you want to have assigned to the Virtual Machine NIC

$nsg = Get-AzNetworkSecurityGroup -Name "tamops-nsg" -ResourceGroupName "tamops-resourcegroup"

Get the Virtual Machine NIC that you want to assign the NSG to

$vmnic = Get-AzNetworkInterface -name "tamops-vm-nic"

You will notice within the $vmnic properties that NetworkSecurityGroup is blank

NetworkSecurityGroup        : {
                           
                              }

Now that we have the Network Security Group and Virtual Machine Network Interface defined that we want to assign the NSG to, we run the PowerShell together with Set-AzNetworkInterface applied

$nsg = Get-AzNetworkSecurityGroup -Name "tamops-nsg" -ResourceGroupName "tamops-resourcegroup"
$vmnic = Get-AzNetworkInterface -name "tamops-vm-nic"

$nic.NetworkSecurityGroup = $nsg 
$nic | Set-AzNetworkInterface

Running the below, you will now see the NSG has been assigned to the Virtual Machine NIC

$nic.NetworkSecurityGroup.id

/subscriptions/xxxxxxxxxxxxxxx/resourceGroups/tamops-resourcegroup/providers/Microsoft.Network/networkSecurityGroups/tamops-nsg

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: