EC2 Key Pairs

Published: (December 19, 2025 at 12:46 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

EC2 Key Pairs

  • Public key – stored by AWS and placed on the EC2 instance (in ~/.ssh/authorized_keys).
  • Private key – downloaded to your local machine; AWS never stores it and it cannot be recovered once downloaded.

How EC2 Key Pairs Work

  1. When launching an instance you can either select an existing key pair or have AWS create a new one.
  2. After creation you download the private key; AWS then deletes it from its side.
  3. The public key is stored in the instance’s ~/.ssh/authorized_keys file.
  4. SSH connections use the private key instead of a password.

Note: Removing a key pair from the EC2 console does not delete the corresponding public key from the instance’s root volume. If an instance is launched from a pre‑built AMI that already contains a key, both the old and the new public keys will be present, allowing SSH with either private key.

Instance Connect

  1. The user initiates a connection via the EC2 Instance Connect API.
  2. Instance Connect generates a temporary key pair.
  3. The temporary public key is sent to the instance through instance metadata and is valid for only 60 seconds.
  4. EC2 Instance Connect uses the temporary private key to SSH into the instance (within the AWS IP address range).
  5. The session is logged in CloudTrail.

Recover Access When the Private Key Is Lost

  1. Create a new key pair in the EC2 console.
  2. Stop the affected EC2 instance.
  3. Detach its root EBS volume.
  4. Attach the volume to a temporary EC2 instance as a secondary volume.
  5. Mount the volume (if not auto‑mounted) and edit ~/.ssh/authorized_keys to add the new public key.
  6. Detach the volume from the temporary instance and re‑attach it to the original instance.
  7. Start the original instance; you can now SSH using the newly created private key.
Back to Blog

Related posts

Read more »