In this blog post, I will show you how to open a firewall port on an Azure Virtual Machine using PowerShell
With Azure PowerShell, we can fully manage every resource that lives inside Azure without using the console.
The reason, PowerShell is good, is because every change can be recorded, documented and versioned controlled with git.
Network Security Groups (NSG)
As a refresher, I will remind you that Azure VMs are secured by Security Groups which acts as a virtual firewall.
The process to open a port of an Azure VM will be as follow:
- Locate Network Security Group name
- Create firewall rule and attach to security Group
Find Security Group Name
If you know the name of your Security Group you can skip this step but if you don’t run the following command:
Note: Change the cmdlet to match your environment
Get-AzNetworkSecurityGroup -ResourceGroupName RGNAME | select name
From the output, copy the name of your Security Group.
using the below command, I am getting the information of Security Group (NSGNAME), I am then adding a rule for port 444 and attaching it to the Security Group.
Get-AzNetworkSecurityGroup -Name "NSGNAME" -ResourceGroupName "RGNAME" ` | Add-AzNetworkSecurityRuleConfig -Name "port_444" -Description "Allow port 444" -Access "Allow" -Protocol "Tcp" ` -Direction "Inbound" -Priority 100 -SourceAddressPrefix "Internet" -SourcePortRange "*" -DestinationAddressPrefix "*" -DestinationPortRange "444" ` | Set-AzNetworkSecurityGroup
To remove the same port, I will use the following cmdlet.
Get-AzNetworkSecurityGroup -Name "NSGNAME" -ResourceGroupName "nRGNAME" ` | Remove-AzNetworkSecurityRuleConfig -Name "port_444" | Set-AzNetworkSecurityGroup