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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s