Sub topic 7
Key pairs and connecting over SSH
This chapter assumes you know basic SSH usage, how security groups allow inbound ports, and that your instance has a public IPv4 address in a public subnet.
How a key pair works
A key pair is a public key and a private key. EC2 stores the public key and puts it on the instance at launch. You keep the private key. When you connect, SSH proves you hold the private key without sending it over the network. Linux instances use this instead of passwords.
Two facts shape everything else:
- AWS shows you the private key only once, when it creates the pair. If you lose it, you cannot recover it.
- The public key is copied onto the instance only at launch, and only into the default user's
authorized_keysfile. Changing the key pair later does not change a running instance.
Create a key pair
Create the pair with the CLI and save the private key in one step. Ed25519 keys are short and widely supported. Use RSA only for older software.
aws ec2 create-key-pair \
--key-name my-key \
--key-type ed25519 \
--query KeyMaterial \
--output text > my-key.pem
chmod 400 my-key.pemThe chmod 400 command makes the file readable only by you. SSH refuses to use a private key that other users can read.
You then pass --key-name my-key to run-instances, as in the launch chapter. You can also import a key you already have with aws ec2 import-key-pair. That way AWS never holds anything but the public half, and the private key never leaves your computer.
Connect
You need the instance's public IP address and the right username. The username depends on the AMI, not on your key.
| AMI | Default username |
|---|---|
| Amazon Linux 2023 | `ec2-user` |
| Ubuntu | `ubuntu` |
| Debian | `admin` |
ssh -i my-key.pem [email protected]Replace 203.0.113.25 with the public IP from describe-instances. The first time, SSH asks you to confirm the host fingerprint. Answer yes only on a first connection you expect.
Troubleshooting
Match the symptom to the layer that failed:
- Connection timed out. Traffic never reached the instance. Check that the security group allows TCP 22 from your current IP, that the subnet has a route to an internet gateway, and that the instance has a public IP.
- Permission denied (publickey). The network works but authentication failed. Check the username, check that you are using the key named at launch, and check that you pointed
-iat the right file. - UNPROTECTED PRIVATE KEY FILE. The file permissions are too open. Run
chmod 400 my-key.pem.
Exercise
You launched an instance from an Amazon Linux 2023 AMI. Running ssh -i my-key.pem [email protected] returns "Permission denied (publickey)". The security group allows port 22 from your IP. What is the most likely cause, and how do you fix it?
Show answer
The username is wrong. The SSH connection reached the instance, so the network path is fine. Amazon Linux uses ec2-user, not ubuntu. Run ssh -i my-key.pem [email protected].