Accessing your Amazon EC2 Instance After Loosing Your KeyPair
in Systems administration on Ec2, Linux, Systems administration
I setup my first EC2 instance about 9 months ago when I was moving all of my Atlassian instances for Cerberus from a server I recently moved out of our Colo4Dallas Datacenter. It was nice to have around and did me good when I needed to access the instances only on occasion - saving me money. The problem I encountered today was I had moved between a couple of desktops and failed to take an (adequate) backup of the KeyPair used to connect to the instance. I tried re-downloading the KeyPair from the Amazon site, only to find that it cannot be downloaded. Thus, I had no way to access my virtual machine…easily.
Instructions
- Stop your EC2 instance (but don't terminate it).
- Create a new KeyPair (and backup the key this time!).
- Create a new EC2 instance, but use the new keypair. (ec2-run-instances ami-abc01234 -k new-keypair-name -g old-security-group)
- Detach the volume from the existing instance.
- Create a snapshot of that volume.
- Spawn a new instance of the volume in the same Availability Zone as your new EC2 instance.
- Attach the new volume to your new EC2 instance, using the mountpoint
/dev/sdb1
. - Login to your new EC2 instance using the newly generated security key.
- Mount the additional volume somewhere (e.g.
/mnt/existing
). - Append the output of
/root/.ssh/authorized_keys
to/mnt/existing/root/.ssh/authorized_keys
. - Append the output of
/home/ubuntu/.ssh/authorized_keys
to/mnt/existing/home/ubuntu/.ssh/authorized_keys
. - Umount the additional volume (
umount /mnt/existing
). - Detach the volume from the new EC2 instance.
- Create a new snapshot of the volume.
- Spawn a new instance of the volume in the original Availability Zone as the original EC2 instance.
- Attach the new volume to the existing EC2 instance using the mountpoint
/dev/sda1
. - Start the existing instance again. Once started, you should be able to connect as the root (or ubuntu) user with the new keypair you generated.