You can replace the new key using user data or systems manager.
Using User Data:
1. Create a new key pair from the AWS EC2 Console
2. Generate the Public Key from the downloaded key pair using below cmd:
ssh-keygen -y -f <Key Pair name>.pem
3. 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:
1. If the instance is a managed instance in AWS Systems Manager, you can use the AWSSupport-ResetAccess document to recover the lost key pair.
2. 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
3. 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.
4. When Automation is finished, the new ssh private key is saved and encrypted in parameter store and the parameter store named as /ec2rl/openssh/<InstanceID>/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