EC2 Key Pairs
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
- When launching an instance you can either select an existing key pair or have AWS create a new one.
- After creation you download the private key; AWS then deletes it from its side.
- The public key is stored in the instance’s
~/.ssh/authorized_keysfile. - 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
- The user initiates a connection via the EC2 Instance Connect API.
- Instance Connect generates a temporary key pair.
- The temporary public key is sent to the instance through instance metadata and is valid for only 60 seconds.
- EC2 Instance Connect uses the temporary private key to SSH into the instance (within the AWS IP address range).
- The session is logged in CloudTrail.
Recover Access When the Private Key Is Lost
- Create a new key pair in the EC2 console.
- Stop the affected EC2 instance.
- Detach its root EBS volume.
- Attach the volume to a temporary EC2 instance as a secondary volume.
- Mount the volume (if not auto‑mounted) and edit
~/.ssh/authorized_keysto add the new public key. - Detach the volume from the temporary instance and re‑attach it to the original instance.
- Start the original instance; you can now SSH using the newly created private key.