Solution: Change VM Scale Set SSH Key

Based your company policy, SSH key might need periodically change, this article covers how to change it without login each VM one by one, remember, you might have up to 1000 VMs.


You cannot use VM Access Agent or ARM template to complete this task. In order to reset VMSS password, please refer to the following article


This time, we are going to use custom script extension to execute a script to achive your goal. Here is an example:


1. Generate a key pair

You can refer this article:


2. Make a Shell script

Get the public key from the step 1 and make the following script to write the new key to authorized_keys file in each VM in VMSS, please replace the user to actual user name.

echo "ssh-rsa +623POccGEa1jEG4APM+dfdg +ddsfdafdasfasnklpads== rsa-key-20170402" >>/home/user/.ssh/authorized_keys


3. Upload the Script to Azure Storage


4. Run the following PowerShell Script to update extension and run the shell script.

$vmssName = "vmssName" 
$vmssResourceGroup = "VMSSGroup"
$ExtensionName = 'changekeyscript' 
$ExtType = 'customscript' 
$Publisher = 'Microsoft.Azure.Extensions'
$TheURI = 
$ScriptSettings = @{"fileUris" = @($TheURI); "commandToExecute" = "sh";} 
$ProtectedSettings = @{"storageAccountName" = $stoname; "storageAccountKey" = $stokey}; 
$vmss = Get-AzureRmVmss -ResourceGroupName $vmssResourceGroup -VMScaleSetName $vmssName
$vmss = Add-AzureRmVmssExtension -VirtualMachineScaleSet $vmss -Name $ExtensionName -Publisher $Publisher  -ProtectedSetting $ProtectedSettings -Type $ExtType -Setting $ScriptSettings -TypeHandlerVersion "2.0"  -AutoUpgradeMinorVersion $true 
Update-AzureRmVmss -ResourceGroupName $vmssResourceGroup -Name $vmssName -VirtualMachineScaleSet $vmss


5. Update instance manually

Once you complete above steps, you can see the VMSS LATEST MODEL is NO


Let’s update each instance

Update-AzureRmVmssInstance -ResourceGroupName $vmssResourceGroup -VMScaleSetName $vmssName -InstanceId "3"


Here are the CLI Example:

az login
az account list
az account set --subscription "sub Name"

az vmss list
az vmss extension list --resource-group VMSSGroup --vmss-name VMSSName

az vmss extension set --resource-group VMSSGroup --vmss-name VMSSName --name customScript --publisher Microsoft.Azure.Extensions --settings ./script-config.json

cat script-config.json
  "commandToExecute": "sh",
  "fileUris": [""]

az vmss update --resource-group VMSSGroup --name VMSSName

az vmss update-instances --resource-group VMSSGroup --name VMSSName --instance-ids 2


You can refer to the following article to create json file.


Fill in your details below or click an icon to log in: 徽标

您正在使用您的 账号评论。 注销 /  更改 )

Google photo

您正在使用您的 Google 账号评论。 注销 /  更改 )

Twitter picture

您正在使用您的 Twitter 账号评论。 注销 /  更改 )

Facebook photo

您正在使用您的 Facebook 账号评论。 注销 /  更改 )

Connecting to %s