About a month ago, I wrote the first blog post of this series where I have shown how to set up the xplat-CLI (Cross Platform CLI) on Linux and I described how to create IAAS VMs on Azure.
But the approach described had one important drawback: It creates the VMs with a default user and password, but not with an SSH key set up to login.
So let me fix this here.
When you’re familiar with SSH on unix platforms, the usual pattern is to use ssh-keygen to create a key pair, then push the public key into the ~/.ssh/authorized_keys file on the remote host and keep the private key in your ~/.ssh/id_rsa file. When using the same user name on both sides, the command ssh <remotehost> then just works without entering a password. And so does scp, sftp and (in case you have set the rsync_rsh environment variable to ssh in your login script) rsync. And as you have probably used an empty keyphrase for the secret key, this works nicely from scripts. (And of course I don’t recommend using that empty keyphrase in general, especially not for privileged accounts)
On Microsoft Azure, we have an internal key deployment mechanism that is used for multiple things, it can deploy keys into Windows and Linux VMs, into PAAS roles and so on. And this mechanism is also used to deploy your ssh public key into your IAAS VMs. But in order to work, it needs the keys in a common universal file format. So just generating the keys using ssh-keygen won’t work. Instead, you can use openssl to generate the private and public key files in x.509 der format.
$ openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout myPrivateKey.key -out myCert.pem
$ chmod 600 myPrivateKey.key
$ openssl x509 -outform der -in myCert.pem -out myCert.cer
The first line generates the key pair, as you have probably guessed from the command line parameters, it’s a 2048 bit RSA keypair with a lifetime of 365 days. Again, you can create this key without a passphrase, but that might be a security risk.
Remember the bash script line to create a VM from part one:
$ azure vm create -e -z extrasmall -l “West Europe” $1 $IMAGENAME azureuser “$PASSWORD”
Now let’s modify this to use the newly generated key in addition to the password:
$ azure vm create -e -t myCert.pem -z extrasmall -l “West Europe” $1 $IMAGENAME azureuser “$PASSWORD”
This creates the VM, but this time, azureuser gets a pre-configured authorized_key.
There is one difference when doing a ssh into this VM: you need to specify the key to use as authorization and the remote user name:
$ ssh -i myPrivateKey.key <cloudservicename>.cloudapp.net
And now you’re not asked for a password anymore.
The -i option also works for scp and sftp. For rsync, you can use
$ export RSYNC_RSH=”ssh -i /path/to/myPrivateKey.key”
or use the rsync –rsh “ssh -i /path/to/myPrivateKey.key” command line option to specify the remote shell and identity file to use.
Hope it helps,