You're asking about how AWS's infrastructure generates ssh keys. Unless anyone who works for AWS and is allowed to disclose that information (highly unlikely) then you won't get a complete answer.
On top of that, the answer you'll be looking for entirely depends on what virtualization back-end you use.
That being said, what is publicly available knowledge from AWS is that they now use their own home-brewed
KVM virtualization platform rather than
XEN like they used to use.
So we can hazard a guess at how AWS do it, or at least provide a method of doing this via a kvm host. The most common way that I'm aware of is using
virt-sysprep on a
qcow2 image with the
firstly generate the public key on the kvmhost with
ssh-keygen. Lets say your user is
iamAguest and you've stored the new public key in
You'd then run
virt-sysprep to inject those keys into an image:
virt-sysprep -a a_linux_image.qcow2 --run-command 'useradd iamAguest' --ssh-inject iamAguest:file:/home/iamAguest/.ssh/id_rsa.pub
Then once you deploy an instance using that image
a_linux_image.qcow2, you should then be able to ssh in using your new generated keys.
how does amazon do this at a click of a button?
A simple enough script could do this, but on a platform of AWS's scale, it would no doubt be quite complex.
If you're just running a kvm instance of your own, something as simple as this could do the trick:
# get image and user from user input
# fail if no user input
if [ -z "$image" ] || [ -z "$user" ]; then
echo "you must enter a filepath to an image and a user name to run this"
echo "e.g: inject_ssh.bash <image> <user>"
# create ssh key for current logged in user with no passphrase
echo -e "/home/$user/.ssh/id_rsa\n\n" | ssh-keygen
# inject key into image
virt-sysprep -a $image --run-command "useradd $user" --ssh-inject $user:file:/home/$user/.ssh/id_rsa.pub
Note however that it'd be a good idea to copy the image first, so you still have a clean one without any keys, if you're planning on providing this as a consumer solution. It would also be a good idea to put more validation in the script; it's just a simple example as it stands.