1 min read

How to open virtual machine port using Azure CLI

In this post I will cover some ways to open virtual machine ports in Azure using the Azure CLI.

The first way is using the az vm open-port command with the resource group name and the virtual machine name.

az vm open-port \
    --resource-group myResourceGroup \
    --name myVirtualMachine \
    --port 8080

You can also use an asterisk to open all ports.

az vm open-port \
    --resource-group myResourceGroup \
    --name myVirtualMachine \
    --port *

Another way is by using the Azure Network Security Groups (NSGs) to control traffic to and from resources in an Azure virtual network. Here's how you can do it:

Execute the following command to get the virtual machine network interface id and assign the result to a variable.

NETWORK_INTERFACE_ID=$(az vm show \
    --resource-group myResourceGroup \
    --name myVirtualMachine \        
    --query 'networkProfile.networkInterfaces[].id' \
    --output tsv)

Now, use the network interface id to get the network security group id. Again, assign the result to a variable.

NETWORK_SECURITY_GROUP_ID=$(az network nic show \
    --ids $NETWORK_INTERFACE_ID \
    --query 'networkSecurityGroup.id' \
    --output tsv)

With the network security group id, run the following command to get the network security group details.

az network nsg show \
    --ids $NETWORK_SECURITY_GROUP_ID \
    --query "[resourceGroup, name]"

And finally, use the resource group name and network security group name from the previous step to create a new rule to open the virtual machine port.

az network nsg rule create \
    --resource-group myResourceGroup \
    --nsg-name myNsgName \
    --name MyNsgRule \
    --priority 400 \
    --source-port-ranges '*' \
    --destination-port-ranges '8080' \
    --direction Inbound \
    --access Allow \
    --protocol Tcp \
    --description "My rule description."

For more details, click on the link below to access the official documentation

az network nsg rule