There are scenarios where you want to change key pair for ec2 instance. You may have lost your private key or your key may have been compromised and you need to replace the key pair immediately.
There are multiple ways you can change your ec2 instance key pair and it depends on whether you have the existing key pair and just wants to replace the existing key pair with a new one, or you have lost the existing key and want to create a new key pair for your ec2 instance.
Scenario 1: You have existing keys with you and just want to replace the existing key with a new one.
Step 1: Create a new key pair using AWS console or command line (ssh-keygen)
Using AWS Console:

Get the public key from the downloaded public key
1 2 |
## Get public key from private key ssh-keygen -y -f /path_to_key_pair/mynewkeypair.pem |
Using ssh-keygen:
1 2 3 4 5 |
## Using ssh-keygen ssh-keygen -t rsa -b 4096 -C "your_email@example.com" ## In default configuration, this will generate a public and private key in ~/.ssh directory ## public key ~/.ssh/id_rsa and public key ~/.ssh/id_rsa.pub |
Step 2: Connect to your EC2 instance using the existing ssh key and update the content of .ssh/authorized_keys file with the new public key obtained from step 1.
Step 3: Exist the EC2 connection and test connection with the new private key obtained in step 1.
Scenario 2: You have lost your existing keys and want to create a new key pair for your ec2 instance.
Step 1: Generate a new key pair (step 1 of scenario 1)
Step 2: Login to AWS management console and navigate to your EC2 instance.
Step 3: Stop your EC2 instance.
Step 4: Choose Actions, Instance Settings, Edit user data. Update the user data with the below content –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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: username ssh-authorized-keys: - PublicKeypair |
Replace username with your user name, such as ec2-user. Replace PublicKeypair with the public key retrieved in step 1. Be sure to enter the entire public key, starting with ssh-rsa.