Sub topic 7
Key Pairs and Connecting over SSH
This chapter assumes you can use a Linux shell, understand ports and CIDR blocks, and have an AWS account with the AWS CLI configured. You should also know the security group basics from the previous chapter. By the end, you will be able to create a key pair, connect to an instance over SSH, and diagnose the common reasons a connection fails.
What a key pair is
A key pair is a public key and a private key that work together. EC2 stores the public key. You keep the private key. When you connect over SSH, your client proves it holds the private key without ever sending it. Nobody types a password.
When an instance launches with a key pair, the first-boot process (cloud-init) copies the public key into the default user's ~/.ssh/authorized_keys file. That is the only step that matters. If you later delete the key pair in EC2, instances that already booted keep working, because their copy of the public key is already on disk.
| Part | Where it lives | Who can see it |
|---|---|---|
| Public key | EC2, and `authorized_keys` on the instance | Safe to share |
| Private key | Your machine only | Only you |
AWS cannot recover a lost private key. If you create the pair through EC2, the private key is shown once, at creation time.
Creating a key pair
You have two options. EC2 can generate the pair, or you can generate it locally and import only the public half. Importing is the safer habit, since the private key never leaves your machine.
Create the pair in EC2 and save the private key:
aws ec2 create-key-pair \
--key-name my-key \
--key-type ed25519 \
--query KeyMaterial \
--output text > my-key.pem
chmod 400 my-key.pemThe --key-type option accepts rsa (the default) or ed25519. Ed25519 keys are short and fast. Ed25519 is not supported for Windows instances, so use RSA there.
Or generate locally and import the public key:
ssh-keygen -t ed25519 -f ~/.ssh/my-key -C "tutorial"
aws ec2 import-key-pair \
--key-name my-key \
--public-key-material fileb://~/.ssh/my-key.pubKey pairs are Regional. A key pair named my-key in one Region does not exist in another, so import it into each Region where you launch instances.
Attaching the key to an instance
You choose the key at launch time with --key-name my-key in run-instances, as shown in the launch chapter. You can only set it at launch. You cannot attach a different key to a running instance through the API. To add another user's key, append their public key to authorized_keys on the instance.
Connecting with SSH
The login user depends on the AMI. Using the wrong one is a common cause of Permission denied.
| AMI | Default user |
|---|---|
| Amazon Linux 2023, Amazon Linux 2 | `ec2-user` |
| Ubuntu | `ubuntu` |
| Debian | `admin` |
| RHEL | `ec2-user` |
| SUSE Linux | `ec2-user` |
First look up the instance's public address. Then connect:
aws ec2 describe-instances \
--filters Name=tag:Name,Values=tutorial-web \
--query 'Reservations[].Instances[].PublicIpAddress' \
--output text
ssh -i my-key.pem [email protected]Replace 203.0.113.25 with the address returned by the first command. The first time you connect, SSH shows the host key fingerprint and asks you to confirm it. Answering yes stores it in ~/.ssh/known_hosts.
To avoid retyping options, add an entry to ~/.ssh/config:
cat >> ~/.ssh/config <<'EOF'
Host tutorial-web
HostName 203.0.113.25
User ec2-user
IdentityFile ~/.ssh/my-key.pem
IdentitiesOnly yes
EOFThen ssh tutorial-web is enough. IdentitiesOnly yes stops SSH from offering every key in your agent, which can trip the server's limit on authentication attempts. Remember to update HostName if the public IP changes after a stop and start.
The connection path
Several things must all be true before a login succeeds. The diagram shows them in the order a packet meets them.
Each box maps to a failure message, which makes troubleshooting a matter of working through the list.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| `Connection timed out` | Security group lacks a port 22 rule for your IP, no public IP, or no route to an internet gateway | Check the inbound rule, public IPv4 address, and subnet route table |
| `Connection refused` | Instance is reachable, but `sshd` is not running or is on another port | Check the console output and system log |
| `Permission denied (publickey)` | Wrong user name, wrong key, or the key was not set at launch | Confirm the AMI's default user and the key name on the instance |
| `UNPROTECTED PRIVATE KEY FILE` | Key file permissions are too open | Run `chmod 400 my-key.pem` |
| `REMOTE HOST IDENTIFICATION HAS CHANGED` | A new instance reused an old IP address | Remove the stale line with `ssh-keygen -R <ip>` |
A timeout and a refusal are different. A timeout means packets are being dropped, usually by a security group or routing. A refusal means the packet arrived and nothing was listening. Knowing which one you see halves the search.
To confirm which key an instance expects, read it from the API:
aws ec2 describe-instances \
--instance-ids i-0123456789abcdef0 \
--query 'Reservations[].Instances[].KeyName' \
--output textAlternatives to opening port 22
Opening SSH to the internet is the most common source of unwanted login attempts. Keep the source CIDR as narrow as your own address, as in the earlier security group example. Two alternatives avoid the inbound rule entirely.
- EC2 Instance Connect pushes a temporary public key to the instance for about 60 seconds. You log in with
aws ec2-instance-connect ssh --instance-id i-0123456789abcdef0. It requires an AMI with the agent installed, such as Amazon Linux, and an IAM permission. - AWS Systems Manager Session Manager opens a shell through an outbound connection from the instance. It needs no inbound ports and no key pair, but the instance needs an IAM instance profile that allows Systems Manager and a network path to the service.
Both move control into IAM, which gives you audit trails and lets you revoke access without touching the instance.
Recovering from a lost key
If you lose the private key, you cannot add a new one through EC2. The usual recovery is to stop the instance, detach its root volume, attach it to a helper instance, add a public key to authorized_keys there, and reattach it. For anything with data you cannot lose, snapshot the volume first. If the instance is disposable, launching a replacement from an AMI with a new key is faster.
Exercise
You launch an Amazon Linux 2023 instance in a public subnet and run ssh -i my-key.pem ubuntu@<public-ip>. The command fails with 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 user name is wrong. Amazon Linux uses ec2-user, not ubuntu. Because the error is a publickey denial and not a timeout, the network path and security group are working, and sshd answered. Run ssh -i my-key.pem ec2-user@<public-ip>.
Exercise
You delete the key pair my-key in the EC2 console. Can you still SSH into a running instance that was launched with it? Can you launch a new instance with it?
Show answer
Yes to the first, no to the second. The public key was already copied into authorized_keys on the running instance at first boot, so login still works as long as you hold the private key. A new launch needs the key pair to exist in EC2 in that Region, so it fails until you create or import a key pair with that name.