Recovering lost AWS EC2 Key Pairs - amazon-web-services

AWS rookie here. I created a few EC2 instances under my AWS account and reused the same Key Pair for all of them. I believe (IIRC) that I had generated the Key Pair from inside AWS, but that could be wrong.
Over this past weekend I sold my old laptop (after completely wiping the hard disk) and got a new one. I'm just remembering now (:facepalm) that I forgot to copy all my SSH private keys to a flash drive and that I no longer have them.
All I want/need to do is to SSH into my EC2 instances, but to do that I need my SSH keys. I still have AWS console access, and I can log in and view all my EC2 Key Pairs. But I don't see any options for downloading them or updating my EC2 instances with new Key Pairs.
So I ask:
Is it possible for me to recover my existing Key Pairs somehow so that I can SSH into my EC2 instances? Again I can log into the AWS console. If not, then...
Is it possible to generate another Key Pair and "swap it out" for my existing Key Pair?
I really don't want to have to tear down my old EC2 instances and re-provision new ones, that will take about a week for me to do (although, arguably, it would serve me right!).

Rebuild shouldnt be nesserary. Id suggest option 2 as its quicker and easier.
1.> Its possible to change/append a new key?
Power off the ec2 instance you want to access ("target").
Create a new ("temporary") instance.
Detach the primary EBS volume from target instance (taking note of its current attachment!).
Attach/mount target volume on temporary instance.
edit appropriate authorized_keys file on the mounted volume.
unmount target volume, and reattach to target ec2 instance (using config you noted when detatching it)
start target instance and login with new key.
delete temporary instance
2.> Yes. Snapshot the instance. Provision a new instance from the snapshot selecting a different key (keypair popup appears when you click launch at end of launch wizard)

Step 1: Go to IAM.
Step 2: Create a policy with the permission
"AmazonSSMManagedInstanceCore".
Step 3: Create a new role and attach
the previously created policy to that role.
Step 4: Go to EC2, select
the instance in "Actions" ==> "Security" ==> "Modify IAM role" select
the created role and save.
Step 5: Wait for 1 hour. It will take some
time to resolve.
Step 6: Select the EC2, Click on "Connect" ==>
"Session Manager" ==> "Connect"
You will get a session with that session you can add a new key to authorized keys.

Change ec2 user data to a multipart mime.
Parts:
cloud config
cloud_final_modules:
- [scripts-user, always]
shell script
Overwrites /home/ec2-user/.ssh/authorized_keys
Refer to this blog article replace ec2 ssh key

You can replace the new key using user data or systems manager.
Using User Data:
Create a new key pair from the AWS EC2 Console
Generate the Public Key from the downloaded key pair using below cmd:
ssh-keygen -y -f .pem
Stop the EC2 instance and edit the user data of the instance and pass the below script and start the Instance
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [users-groups, once]
users:
- name:ec2-user
ssh-authorized-keys:
- <**Paste the Public key here**>
Now, You will be able to login to EC2 instance with the downloaded key pair.
Using Systems Manager:
If the instance is a managed instance in AWS Systems Manager, you can use the AWSSupport-ResetAccess document to recover the lost key pair.
Open the AWS Systems Manager console, select Automation in left navigation pane, click execute Automation. In automation document section select owned by Amazon. In the run book list, search for AWSSupport-ResetAccess
In Execute automation document page, choose Simple execution. In document details section, verify Document version is set to Default. In the input parameter section, specify the Instance ID, Subnet ID and Instance type in parameter and execute.
When Automation is finished, the new ssh private key is saved and encrypted in parameter store and the parameter store named as /ec2rl/openssh//key
You can refer the below link for more detailed steps:
https://cloudsolutionsonline.blogspot.com/2021/11/connect-to-linux-ec2-instance-if-ssh.html?m=1

Related

What is the packer ssh key in .ssh/authorized_keys for on my ec2 instance?

When I look instead ~/.ssh/authorized_keys as the root user on my ami I see something like:
no-port-forwarding,no-agent-forwarding,no-X11-forwarding,command="echo 'Please login as the user \"ubuntu\" rather than the user \"root\".';echo;sleep 10;exit 142" ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC5Cfdsafdafdas_some_public_key packer_610ad8fb-0ed3-eddc-c48f-0f8553d421da
no-port-forwarding,no-agent-forwarding,no-X11-forwarding,command="echo 'Please login as the user \"ubuntu\" rather than the user \"root\".';echo;sleep 10;exit 142" ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC5Cfdsafdafdas_some_public_key my-key
The second key is the key is the one I used to set up my instance so I understand that one. Is the packer key just a temporary key used to upload the instance somewhere and I can safely delete it?
Packer is used to create AMI and during that process it needs to ssh into the image. Normally, people who create the AMI remove them during the finalization and cleanup, seems they forgot to do that. It's safe to delete them.

How to connect to aws instance using new keypair(New pem file)

I have one running instance on aws and I lost my .pem file for that instance. So I go to network and security section of aws and created one new kaepair. After that I Run chmod 400 test.pem then I run ssh -i test.pem ec2-user#mypublicip
Then I got an option to enter password so I entered my aws password But my authentication got failed.
Please help me how I can login to my existing aws instance on new keypair
The Connecting to Your Linux Instance if You Lose Your Private Key chapter in the EC2 user guide describes in depth how you can regain access to an EC2 instance. To summarize:
Stop the instance (make sure to back up any data stored in the instance store to persistence storage that you would like to keep)
Launch a temporary instance
Detach the root volume of the original instance and attach it to the temporary instance
Update the authorized_keys on the mounted volume with the new public key
Unmount the volume from the temporary instance
Attach the volume to the original volume
Start the original instance
(Terminate the temporary instance)
Please see the link above for details.

Unable to SSH in EC2 instance

I am unable to ssh AWS ec2 instance. It shows error Permission denied (public Key).I have tried to generate new pem key
# ssh-keygen -y -f /path/to/keypair.pem
and added it in Instance Settings View/Change User Data
#cloud-config
#ssh_deletekeys: false
#ssh_authorized_keys:
# - ssh-rsa ENTER YOUR PUBLIC KEY HERE ...
#cloud_final_modules: - [ssh, always]
But it didn't work and I also tried this tutorial
https://aws.amazon.com/premiumsupport/knowledge-center/recover-access-lost-key-pair/
Still it is not working.
What you are trying to do wont work. Neither will the answer #Rajeev provided. If it was a file permission error you would see a message indicating the .pem file had unsecure read permissions. What I suspect you'll need to do is kill off that instance and relaunch with a new key. Will be easier than troubleshooting it, and you can make a snapshot to launch a new instance from if you have done a lot of config on it already.
AWS best practices state instances should be treated as ephemeral. Follow those guidelines and you'll save yourself a lot of hassle in the long run.

In auto scaling AMI launch how to copy my private key file in new instance

I have a instance in aws and private key file is authorized keys which is stored in .ssh path.When auto scaling AMI is launched then that file should copy to new server in the same location i.e .ssh how can we do it by using Cloud formation template.
what code or what commands should I keep in CFN template.
Thanks
you can create a new ami with your private key stored and use the ami in your CloudFormation template.
steps:
1. launch new instance from the current ami you are using
2. ssh to your instance and copy the private key file
3. stop the instance in aws console and right click the instance -> image -> create image
4. use your new ami as EcsAmiId
You can specify user data script in your CF template where you are describing your EC2 instance. user data script is just a normal bash script that will be executed when the instance boots up, which means that you can automate any such task as copying files using it, which you would otherwise needed to do manually.
You can also pre-bake a custom AMI, or in other words, create a new AMI that has all the settings already in place and use that AMI in your CF template instead of whatever default AMI you are using right now.
A Keypair can be created within the EC2 console, or the public half of an existing Keypair can be uploaded to EC2.
Once this is done, an Amazon EC2 instance can be launched with a reference to this Keypair. Software on the instance (if using an Amazon Linux AMI) will automatically copy the public half of the nominated keypair to the /home/ec2-user/.ssh/authorized_keys file.
This applies for launching an EC2 instance via any method, eg console, API, CloudFormation.
This is much easier than trying to manipulate the authorized_keys file yourself via User Data.

Creating custom AMI for AWS Data Pipeline

I've read https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-custom-ami.html on how to create a custom AMI for use with AWS Data Pipeline. The document mostly makes sense except for the last line:
"Create and configure a user account named ec2-user."
What does this mean? What credentials (if any?) do I use for this AMI user? What SSH key do I allow to log in here?
The keypair that you should use can be specified in EC2 resource definition. See https://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-resources-vpc.html
In case of the above EC2 resource snippet, my-key-pair would have a PEM file associated with it. Your ec2-account should correspond to that PEM file so that DPL can login to that EC2 resource.