Using Existing AWS SSH Keys with Docker-Machine

If you ended up here you are probably trying to launch EC2 instances with Docker-Machine and use your existing SSH keys. Here’s how you do it!

Creating an instance with Docker-Machine

The basic command structure looks like this…

docker-machine create --driver amazonec2 --amazonec2-region us-east-2 --amazonec2-keypair-name my-existing-key --amazonec2-ssh-keypath my-existing-key.pem my-instance-name

I specify the region because that tripped me up at the beginning. Depending on your setup you may have other parameters. The thing that is confusing is the “--amazonec2-ssh-keypath” parameter. You likely have a .pem file that you use to login to your EC2 instances. This command is really asking for TWO separate files and assumes they are named in a very specific way. The above command assumes you have my-existing-key.pem AND my-existing-key.pem.pub in the directory you are running this command from. Not totally obvious.

// You need two files!
my-existing-key.pem
my-existing-key.pem.pub

What is the .pub file?

Good question. You generally don’t ever interact with this when you SSH into an EC2 instance. What you have to do is log into an instance you already have (or create one) that uses that key and get the public key. It will generally be at ~/.ssh/authorized_keys. You can also just run this magic command:

// SSH into an instance that uses the existing key and run...
curl http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key

Documentation on that here…

https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#retrieving-the-public-key-windows

You’ll get a public key that looks like the stuff below. Copy it (there may be more than one) and that’s what you put into the my-existing-key.pem.pub file..

ssh-rsa AAAAB3NzaC1yc2EAAsfdsfsAQC0KlJg/aE7vfvaCJCfuMjWOmAPpoyeJXZU+q+cp/ITDDgiykFR9No6OsKHjYG1+ZKVbSquVsdfsdfsdfuFLZwaCR7IEl1zogipBFzGDWunHMbP/WnlLfqiGzybWaNwfA9AcNcFZkNhbJ3D+wwQJFyew06HJ1eaB2xvsNpiBPSBXUPFzmPJB2ck2M60qQobeGlMJ2Cg8O0ZEXilQqfNuJTMekTfJxzhEfGpCE6jYvhfsdfsdfZvILp+IO4ZIoiZ7c79cvfLooCrcxL6cyjNGBT0kHUryRA6s1f7IyzuuMy246va9GUkkW/QrNMrx7DKJTLGukpfFMleszrxgg1bIIXrEBH my-existing-key

The User Name is Ubuntu!

Last note here. You likely SSH into most of your EC2 instances using the “ec2-user” name. The default user name in this case (at the time of writing) is going to be “ubuntu.” So make sure you use that when you try to SSH into the instance. That tripped me up as well.

ssh -i my-existing-key.pem ubuntu@ec2-22-114-39-164.us-east-2.compute.amazonaws.com

That’s it. Congratulations.