Skip to main content

[SOLVED] How to Change the Key Pair for an EC2 Instance? - amazon-web-services

[SOLVED] A Simple Guide on Changing the Key Pair for an EC2 Instance - Amazon Web Services

In this chapter, we will look at how to change the key pair for an Amazon EC2 instance. An EC2 key pair helps us securely access our cloud instances using SSH. Sometimes, we need to change our key pair. This could be for security reasons or if we lose the original key. This guide will show us the process step-by-step. We will make sure we can change the key pair easily.

Here’s what we cover in this chapter:

  • Understanding Key Pairs in EC2: We learn what key pairs are and why they are important in AWS.
  • Creating a New Key Pair: We give simple steps on how to create a new key pair.
  • Detaching the Current Key Pair: We show how to safely remove the current key pair from our EC2 instance.
  • Connecting to EC2 Instance with New Key Pair: We find out how to use the new key pair to access our instance.
  • Updating the EC2 Instance with New Key Pair: We give steps on how to update our EC2 instance with the new key.
  • Using Systems Manager Session Manager as an Alternative: We explore another way to access our instance without changing the key pair.
  • Frequently Asked Questions: We answer common questions about EC2 key pairs and access.

For more understanding of AWS management, you may like these resources: How to Fix Specified Key Does Not Exist and How to SSH into Elastic Instances.

Let’s start and make sure we can manage our EC2 instances safely and easily!

Part 1 - Understanding Key Pairs in EC2

Key pairs are very important for safely getting into EC2 instances. A key pair has two parts: a public key and a private key. AWS keeps the public key. We download the private key and keep it safe. When we start an EC2 instance, we choose a key pair. AWS then puts the public key on the instance.

Key Pair Characteristics:

  • Public Key: AWS uses this to lock data. Only the private key can unlock it.
  • Private Key: We must keep this safe. We use it to log in and connect to the EC2 instance using SSH.
  • Format: The private key is usually in PEM format.

Important Notes:

  • We cannot change the key pair for a running EC2 instance. We need to make a new key pair and follow steps to link it to the instance.
  • Always make a backup of your private keys. If we lose the private key, we cannot connect to our instance anymore.

For more details on how to connect to your EC2 instance, check out how to SSH into Elastic.

Part 2 - Creating a New Key Pair

To change the key pair for an EC2 instance, we need to make a new key pair in AWS. We can do this with the AWS Management Console, AWS CLI, or AWS SDKs.

Creating a New Key Pair via AWS Management Console

  1. Sign in to the AWS Management Console.
  2. Go to the EC2 Dashboard.
  3. In the left menu, click on Key Pairs under Network & Security.
  4. Press the Create key pair button.
  5. Type a name for your key pair and pick the file format (PEM or PPK).
  6. Click on Create. The private key file will download automatically. Keep it safe because you can’t download it again.

Creating a New Key Pair via AWS CLI

If we like to use the command line, we can create a new key pair with this command:

aws ec2 create-key-pair --key-name MyNewKeyPair --query 'KeyMaterial' --output text > MyNewKeyPair.pem

Important Configuration

  • Make sure that the .pem file has the right permissions:
chmod 400 MyNewKeyPair.pem
  • Use the new key pair to connect to your EC2 instance. Follow the next steps to detach the current key pair.

For more about managing EC2 instances, you can look at this guide.

Part 3 - Detaching the Current Key Pair

To detach the current key pair from an EC2 instance, we need to stop the instance and change its settings. Remember, detaching a key pair does not delete it. It just removes the link with the instance.

  1. Stop the EC2 Instance:

    • We open the AWS Management Console.
    • Then we go to the EC2 Dashboard.
    • We choose the instance that has the key pair we want to detach.
    • Next, we click on Instance State and then Stop Instance.
    • We confirm the action.
  2. Detach the Key Pair:

    • After the instance is stopped, we select it again.
    • We click on Actions > Instance Settings > Change Instance Settings.
    • In the Key Pair section, we choose None from the dropdown menu to detach the key pair.
    • We click on Update to save the changes.
  3. Restart the EC2 Instance:

    • After we detach the key pair, we go back to Instance State and select Start Instance to restart our EC2 instance.

Now we can attach a new key pair by following the next steps in the article. If we have issues with key pairs, we can check other resources like this guide for help.

Part 4 - Connecting to EC2 Instance with New Key Pair

To connect to our EC2 instance using the new key pair, we can follow these steps:

  1. Ensure Permissions: First, we need to check that the new key pair file has the right permissions. We should set it to read-only for the user.

    chmod 400 /path/to/new-key-pair.pem
  2. Obtain the Public DNS or IP Address: Next, we go to the AWS Management Console. We find the EC2 Dashboard, select our instance, and copy the Public DNS (IPv4) or Public IP.

  3. Connect to Our EC2 Instance: Now, we use the SSH command to connect to our instance with the new key pair. We replace ec2-user with the right username for our AMI. For example, we use ubuntu for Ubuntu AMIs.

    ssh -i /path/to/new-key-pair.pem ec2-user@your-instance-public-dns
  4. Verify Connection: When we connect, we should see the command prompt of our EC2 instance. Now, we can run commands on our instance.

For more details about connecting to our EC2 instance, we can look at this article on how to SSH into your Elastic Cloud. If we have any problems with key permissions, we can check this link for fixing specified key issues.

Part 5 - Updating the EC2 Instance with New Key Pair

To update our EC2 instance with a new key pair, we can follow these simple steps:

  1. Stop the EC2 Instance:
    We must stop the instance to change the key pair. We can use the AWS Management Console or the AWS CLI.

    AWS CLI Command:

    aws ec2 stop-instances --instance-ids <instance-id>
  2. Detach the Root Volume:
    We need to detach the root EBS volume from the instance. We can do this using the console or the CLI.

    AWS CLI Command:

    aws ec2 detach-volume --volume-id <volume-id>
  3. Attach the Volume to Another Instance:
    We attach the detached volume to another instance as an extra volume. This lets us access the file system.

    AWS CLI Command:

    aws ec2 attach-volume --volume-id <volume-id> --instance-id <other-instance-id> --device /dev/sdf
  4. Mount the Volume:
    We SSH into the other instance and mount the volume.

    sudo mkdir /mnt/temp
    sudo mount /dev/xvdf /mnt/temp
  5. Update the Authorized Keys:
    We go to the .ssh directory of the original instance’s user and add the new public key to authorized_keys.

    echo "<new-public-key>" >> /mnt/temp/home/ec2-user/.ssh/authorized_keys
  6. Unmount the Volume:
    After we update the keys, we unmount the volume.

    sudo umount /mnt/temp
  7. Reattach the Volume to the Original Instance:
    We detach the volume from the temporary instance and reattach it to the original instance.

    Detach Command:

    aws ec2 detach-volume --volume-id <volume-id>

    Attach Command:

    aws ec2 attach-volume --volume-id <volume-id> --instance-id <instance-id> --device /dev/sda1
  8. Start the EC2 Instance:
    We can start the instance using the console or CLI.

    AWS CLI Command:

    aws ec2 start-instances --instance-ids <instance-id>
  9. Connect Using the New Key Pair:
    Finally, we connect to our EC2 instance using the new key pair.

    ssh -i <new-key-pair.pem> ec2-user@<instance-public-dns>

For more details on managing EC2 instances, we can check this guide on how to fix specified key issues.

Part 6 - Using Systems Manager Session Manager as an Alternative

We can change the key pair for an EC2 instance without connecting directly using SSH. We can use AWS Systems Manager Session Manager for this. This way, we can access our instance safely without needing an SSH key.

Prerequisites:

  • Check that your EC2 instance has the AWS Systems Manager agent installed and running. Most Amazon Machine Images (AMIs) already have this.
  • The instance needs to be in a VPC with the right IAM roles for Systems Manager access.
  • The IAM role must have the AmazonSSMManagedInstanceCore policy.

Steps to Use Session Manager:

  1. Attach the IAM Role: If the IAM role is not attached, we need to assign one to our instance with the right permissions. Example IAM policy:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "ssm:UpdateInstanceInformation",
            "ssm:ListAssociations",
            "ssm:GetDeployablePatchSnapshotForInstance",
            "ssm:DescribeInstanceProperties",
            "ssm:ListInstanceAssociations",
            "ssm:ListInstancePatches",
            "ssm:DescribeInstancePatchStates",
            "ssm:ListDocumentVersions",
            "ssm:SendCommand",
            "ssm:UpdateDocumentDefaultVersion",
            "ssm:CreateAssociation",
            "ssm:DeleteAssociation"
          ],
          "Resource": "*"
        }
      ]
    }
  2. Open the AWS Systems Manager Console: We go to the AWS Systems Manager console.

  3. Start a Session:

    • Click on Session Manager under Instances & Nodes.
    • Click Start session.
    • Choose the instance we want to connect to and click on Start session.
  4. Change the Key Pair:

    • After we connect, we can change or replace SSH keys like this:
    • To add a new key pair, we create a new key pair using the EC2 console or CLI:
    aws ec2 create-key-pair --key-name NewKeyPair --query 'KeyMaterial' --output text > NewKeyPair.pem
    chmod 400 NewKeyPair.pem
    • Then, we add our public key to the ~/.ssh/authorized_keys file:
    echo "ssh-rsa AAAAB3... your_key_comment" >> ~/.ssh/authorized_keys
  5. Exit Session: After we update the authorized keys, we exit the session.

Using AWS Systems Manager Session Manager is a good way to change the key pair for an EC2 instance. It is helpful when we cannot access the instance using SSH. For more info on managing instances, we can check this guide on EC2 instance management.

Frequently Asked Questions

1. How can we securely connect to our EC2 instance after changing the key pair?

After we change the key pair for our EC2 instance, we need to use the new private key file (.pem) to connect via SSH. If we have problems, we should check the permissions for the key file. It should be set to (chmod 400). For more help, we can look at this guide on how to fix specified key does not match.

2. What happens to our existing EC2 instance data when we change the key pair?

Changing the key pair for our EC2 instance does not change the data or applications. The key pair is just a security tool for SSH access. For more details about key pairs and our instance, we can read this article on the importance of private keys.

3. Can we change the key pair on a running EC2 instance without downtime?

Yes, we can change the key pair for a running EC2 instance without any downtime. We can use AWS Management Console or CLI to create a new key pair and update the instance’s settings. For step-by-step help, we can check the article on how to SSH into Elastic.

4. Is it necessary to detach the current key pair before adding a new one?

We do not need to detach the current key pair when we add a new one. We can just create a new key pair and set up our EC2 instance to use the new key. But we should keep track of which keys are allowed for access to keep things safe.

5. What alternative methods can we use to connect to our EC2 instance without SSH keys?

If we do not want to use SSH keys, we can use AWS Systems Manager Session Manager to connect to our EC2 instance safely. This service lets us connect to our instance using the AWS Management Console or CLI without needing to manage key pairs. For more information, we can check the guide on how to securely pass AWS credentials.

Comments