Some time back, unfortunately, we had lost an SSH key pair belonging to an important EC2 instance. At that point in time, we had just taken a snapshot of the instance and moved on to create a new one with a new key pair. In this blog post, we shall see how to restore SSH connectivity.
Step #1:
- Create a new EC2 instance. If performing on an existing instance, make sure you hold that machine's SSH private key
Step #2:
- Stop the instance you lost the SSH key pair to and detach its volume right after (Make absolutely sure that before you go about detaching the volume, it is the correct one)
Goto --> AWS --> EC2 --> Volumes(EBS)
Step #3:
- Post volume detachment, attach the volume to the EC2 machine of choice from #1, which is either a new or an existing
Goto --> AWS --> EC2 --> Volumes(EBS)
- Select that detached volume and click
action
chooseAttach volume
, and select the EC2 instance that wants the volume attached to
- Verify that you have attached the volume to the right instance. Go to the EC2 console, select the instance, and select storage, and you should see two volumes: one is the root and the other is our attached
Note
Before moving on to Step #4, you have to create an SSH key pair
ssh-keygen -t rsa -b 4096
Step #4:
- Login to the instance from #3. Then, mount the attached volume into a directory
$ ssh -i path/to/private.key username@ip-addr
$ lsblk
$ mkdir ~/data
$ sudo mount /dev/xvdf1 /data
Step #5:
- Once mounted, navigate to the mounted directory
cd ~/data/home/ubuntu/.ssh
- Edit the
authorized_keys
file, delete the existing public key and paste the new public key generated in #4 - Once, that is done, unmount the volume
sudo umount ~/data
- Finish it by detaching the volume from the instance, and reattaching the volume back to its former owner i.e; stopped instance.
1. Goto --> AWS --> EC2 --> Volumes (EBS)
2. Select the correct volume, then "action --> force detach/detach volume"
3. Select the volume again, "action --> attach volume"
Note "Device name" should be "/dev/sda1"
Because this is the device naming supported by the root volume
Step #6:
- Here on forth, you can SSH back into the machine you lost your SSH keys to, using the new private key which was created in #3