How to change key pair for ec2 instance?

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

Using ssh-keygen:

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 –

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.

Step 4: Choose save.

Step 5: Start your EC2 instance and test your connection with new ssh keys generated in step 1.

Step 6: Stop the EC2 instance again and remove the user data section and start again.

Leave a Reply