DEV Community

Wriju's Blog
Wriju's Blog

Posted on

Reconfigure SSH Public Key in Azure VM

"I have lost my ssh private key and now I cannot login to my Azure VM"

If you create Azure VM from Azure CLI which has a parameter --generate-ssh-keys that will generate the keys (both public and private). The private key will be in the local machine from where the az vm create... command was executed. Unless you have explicitly mentioned the path of the ssh key file.

In case you change the machine from where you connect to the VM you need to carry your private key. If you do not have it and want to access the VM you can reset it.

First, generate a new pair of keys. Both private and public. Then update the existing VM with the new public key. Below are the simple steps.

Generate a new key if you do not have any. Just follow the instruction by running the command.

ssh-keygen
Enter fullscreen mode Exit fullscreen mode

Make sure the keys are stored in .ssh folder.

Then run the following command to update your existing Azure VM. You need Azure Subscription access with the necessary permission.

az vm user update \
  --resource-group MyRG --name MyVM \
  --username NewUser \
  --ssh-key-value ~/.ssh/id_rsa.pub
Enter fullscreen mode Exit fullscreen mode

Now you are done. From the machine where you have this new private key can now simply log in using ssh

ssh NewUser@PublicIP
Enter fullscreen mode Exit fullscreen mode

Thank you very much. Hope you have enjoyed it.

Top comments (0)