Search code examples
azureazure-virtual-machineazure-cli

I forgot to use -openports when using New-AzVm, is there a way to modify it after the VM creation?


I'm a total Azure newbie, and just started AZ-104. During one of the exercice, I had to create a new vm and pass the port 22 with -openports but went too fast and forgot to add the parameter.

I went through the New-AzVm and Update-AzVm documentation and couldn't find anything. I did find out I could use a security rule to open port 22, but is there another way to quickly fix my oversight? I must admit I did learn quite a bit from that simple mistake, but I'd like to ask the pros if I really can't fix this beside using a security rule. Thanks.


Solution

  • Use below PowerShell code to modify the VM port after creation.

    $vm= ""
    $resourceGroup=""
    $port= 22
    $vmdata = Get-AzVM -ResourceGroupName $resourceGroup -Name $vm
    $nsgId = $vmdata.NetworkProfile.NetworkInterfaces[0].Id
    $nsg = Get-AzNetworkinterface -ResourceId $nsgId  
    $nsggroup = Get-AzNetworkSecurityGroup -Name "xxx"
    $nsggroup | Add-AzNetworkSecurityRuleConfig -Name "AllowSSH" -Priority 1001 -Direction Inbound -Access Allow -Protocol Tcp -SourceAddressPrefix "*" -SourcePortRange "*" -DestinationAddressPrefix "*" -DestinationPortRange $port -Description "Allow"
    $nsggroup | Set-AzNetworkSecurityGroup
    Update-AzVM -ResourceGroupName $resourceGroup -VM $vmdata
    

    enter image description here