Minimum Viable Template: VM With SSH Auth

This post is part of a series of posts showing how to create a “minimum viable ARM template” and how to modify it to suit various scenarios. To see the full list of posts in this series, see this page: https://negatblog.wordpress.com/minimum-viable-arm-templates/.

We want to modify our VM template to use ssh auth instead of password auth. We start from the “minimum-viable-vm” branch (https://github.com/gatneil/MinimumViableArmTemplate/blob/minimum-viable-vm/azuredeploy.json) and end at the “vm-with-ssh-key” branch (https://github.com/gatneil/MinimumViableArmTemplate/blob/vm-with-ssh-key/azuredeploy.json). Below is the diff.

First, we rename the “adminPassword” parameter to “adminPublicKey” since we will be using ssh key to authenticate to the VM instead of a password. Next, we add the ssh key details in the “linuxConfiguration” part of the “osProfile” configuration of the VM. We disable password auth and provide the path to where the public key should end up in the VM, as well as the actual public key to put there (not the private key). When we deploy this template, we should provide the actual public key (likely beginning with “ssh-rsa …”) as the parameter value, not the file path on your machine to the public key (other Azure tooling can take the key from a file, but this template does not).

...
   "parameters": {
     "adminUsername": {
       "type": "string"
     },

-    "adminPassword": {
+    "adminPublicKey": {
       "type": "securestring"
     }
   },

...

     {
       "type": "Microsoft.Compute/virtualMachines",
       "apiVersion": "2020-06-01",
       "name": "myVM",
       "location": "[resourceGroup().location]",
       "dependsOn": [
         "[resourceId('Microsoft.Network/networkInterfaces', 'myNic')]"
       ],
       "properties": {
         "hardwareProfile": {
           "vmSize": "Standard_D2_v4"
         },
         "storageProfile": {
           "imageReference": {
             "publisher": "Canonical",
             "offer": "UbuntuServer",
             "sku": "18.04-LTS",
             "version": "latest"
           }
         },
         "networkProfile": {
           "networkInterfaces": [
             {
               "id": "[resourceId('Microsoft.Network/networkInterfaces', 'myNic')]"
             }
           ]
         },
         "osProfile": {
           "computerName": "myVM",
           "adminUsername": "[parameters('adminUsername')]",

-          "adminPassword": "[parameters('adminPassword')]"
+          "linuxConfiguration": {
+            "disablePasswordAuthentication": true,
+            "ssh": {
+              "publicKeys": [
+                {
+                  "path": "[concat('/home/', parameters('adminUsername'), '/.ssh/authorized_keys')]",
+                  "keyData": "[parameters('adminPublicKey')]"
+                }
+              ]
+            }
+          }

         }
       }
     }
   ]
 }

Leave a comment