Resetting Azure Linux VM SSH keys quickly

Resetting Azure Linux VM SSH keys quickly

2021, Jan 21    

SSH keys are definitely the preferred way to connect to Linux VM’s in Azure. Passwords get complex, you check them into code or you lose them. Never the case with SSH Keys, eh? Unless of course the VM’s are just for throwaway testing and like me you’ve got too many disposable development environments. I usually just recreate VM’s from script, but i needed a quicker way this time.

Thankfully, you can use the Azure API’s and agents that get deployed onto the VM’s to reset the SSH keys for specific users. The AZ CLI (and agent on the VM) requires a json file, with a specific format containing the public key.

My bash script

#Create SSH key pair
ssh-keygen -m PEM -t rsa -b 2048 -C "azureuser@azure" -f ~/.ssh/gordansiblevm_rsa -N ""

#Grab the public key part
SSHPUB=$(cat /home/admingeneric/.ssh/gordansiblevm_rsa.pub)

#Create the Json needed for Azure API
JSON_STRING=$( jq -n --arg u "azureuser" --arg s "$SSHPUB" '{username: $u, ssh_key: $s}' )
echo $JSON_STRING > update_ssh_key.json

#Reset SSH key for user
az vm extension set \
  --resource-group ansible-inventory-test-rg \
  --vm-name ansible-inventory-test-vm3 \
  --name VMAccessForLinux \
  --publisher Microsoft.OSTCExtensions \
  --version 1.4 \
  --protected-settings update_ssh_key.json

The script runs quickly and I can then explicitly use my new SSH key to run an Ansible command

ansible all -m ping -i ./myazure_rm.yml --user azureuser --key-file ~/.ssh/gordansiblevm_rsa