We need to follow the following steps in order to recover the SSH key pair:
- Launch new ec2 Machine(Recovery Machine)
- Stop(ShutDown) the first machine(Web server) and Detach the root volume.
- Attach the volume with the recovery machine.
- Mount the block device and copy the SSH key contents.
- Release the volume from the recovery machine.
- Reattach the Volume with the first machine(Web server) and log in with new ssh recovery key.
1. Launch new ec2 Machine
Launch a new ec2 machine as a recovery machine but make sure it should have the same VPC network ID as the Web Server machine.
2. ShutDown the first machine and Detach the root volume
Now you need to stop the first machine (Web Server) so you can detach the root volume, otherwise, you are not allowed to detach the root volume while the machine is in running state. The screenshots below show how to find out associated root volume (a) and how to detach the root volume (b)?
3. Attach the volume with a recovery machine
Now, we have detached the root volume from the Web Server machine. Again from the same location go to the “Actions” showing in the screenshot (b). Attach the volume with Recovery Machine, as shown in the following screenshot(c).
4. Mount the block device and copy the SSH key contents
SSH to new recovery machine with your new key pair (RecoverKey.pem) and switch to root user from ec2-user. Run the following command to view the block devices and confirm your attached volume in the O/P list. Check my O/P below.
[root@ip-172-31-10-78 ~]# lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT xvda 202:0 0 8G 0 disk └─xvda1 202:1 0 8G 0 part / xvdm 202:192 0 8G 0 disk └─xvdm1 202:193 0 8G 0 part <- New Attached Volume [root@ip-172-31-10-78 ~]#
5. Release the volume from the recovery machine
Before using the newly attached volume you have to mount this volume with Recovery machine file structure, Please run the following command:
:~# mount /dev/xvdm1 /mnt Now copy the SSH key and unmount the volume from the current file structure. :~# cat /home/ec2-user/.ssh/authorized_keys > /mnt/home/ec2-user/.ssh/authorized_keys :~# umount /dev/xvdm1 /mnt
6. Reattach the Volume with the first machine and login with a new ssh recovery key
Now detach the volume from the recovery machine and reattach the volume with the “Web Server” machine again, Check the below screenshot.
Now start the Web Server machine, you would be able to access your web server machine with a new Recovery key.