Sub topic 3
Key Pairs and the Right Login User for Your AMI
This chapter assumes you can launch an EC2 instance, read a basic IAM policy, and use a Linux shell. It covers the two things SSH needs once the network path works: a key pair that matches the instance, and the correct login user for the image.
What a key pair is
An EC2 key pair is an asymmetric key pair used for SSH public-key authentication. AWS keeps only the public half. You keep the private half. At first boot, the instance's initialization software (cloud-init on most Linux AMIs) reads the public key from the instance metadata service and appends it to ~/.ssh/authorized_keys for the AMI's default user.
Three consequences follow from this model:
- The key is installed once, at first boot. Changing or deleting the key pair in EC2 later does not change a running instance.
- AWS cannot show you the private key again. If you lose the file, you need another way in (see "Recovering from a lost key").
- Key pairs are regional. A key pair named
my-keyinus-east-1does not exist ineu-west-1.
Creating or importing a key pair
You can have AWS generate the pair, or you can generate it locally and import only the public key. Importing is better practice, because the private key never leaves your machine and never travels over the API.
EC2 supports RSA and ED25519 keys for Linux instances. ED25519 keys are shorter and fast, but they are not supported for Windows instances, which use the key pair to decrypt the Administrator password.
Generate the key in AWS and save the private key:
aws ec2 create-key-pair \
--key-name my-key \
--key-type ed25519 \
--key-format pem \
--query KeyMaterial \
--output text > ~/.ssh/my-key.pem
chmod 400 ~/.ssh/my-key.pemOr generate locally and import the public key:
ssh-keygen -t ed25519 -f ~/.ssh/my-local-key -C "my-local-key"
aws ec2 import-key-pair \
--key-name my-local-key \
--public-key-material fileb://$HOME/.ssh/my-local-key.pubThe fileb:// prefix passes the file as raw bytes. Without it, the CLI can encode the content twice and the import fails with an invalid-format error.
Choosing a key at launch
Reference the key pair by name when you launch:
aws ec2 run-instances \
--image-id ami-0123456789abcdef0 \
--instance-type t3.micro \
--key-name my-key \
--subnet-id subnet-0123456789abcdef0 \
--security-group-ids sg-0123456789abcdef0Replace the IDs with values from your account. If you omit --key-name, the instance launches with no key. SSH with a key pair is then impossible unless the image or user data adds a key some other way.
To check which key pair an existing instance was launched with, and which AMI it came from, run:
aws ec2 describe-instances \
--instance-ids i-0123456789abcdef0 \
--query "Reservations[].Instances[].[KeyName,ImageId,PublicIpAddress]" \
--output textThe KeyName tells you which private key you need. The ImageId tells you which login user to expect.
The login user depends on the AMI
The key pair authenticates you, but the instance also needs to know which operating system account you are logging in as. The public key is installed for one specific account, the AMI's default user. Logging in as any other name fails, even with the right key.
| AMI family | Default user |
|---|---|
| Amazon Linux 2 and Amazon Linux 2023 | `ec2-user` |
| Ubuntu | `ubuntu` |
| Debian | `admin` |
| RHEL | `ec2-user` |
| SUSE Linux Enterprise | `ec2-user` |
| Fedora | `fedora` |
| Rocky Linux | `rocky` |
| Bitnami | `bitnami` |
Treat this table as a starting point. Third-party and marketplace images choose their own user, and some change it between versions. The publisher's documentation for that exact AMI is the authority. You can read an AMI's name and description with:
aws ec2 describe-images \
--image-ids ami-0123456789abcdef0 \
--query "Images[0].[Name,Description,OwnerId]" \
--output textIf you log in as root, many AMIs print a message such as Please login as the user "ec2-user" rather than the user "root". That message names the correct user, so read it before changing anything else.
Connecting and verifying
SSH refuses a private key that other users can read. Restrict the file to read-only for your account, then connect as the AMI's default user:
chmod 400 ~/.ssh/my-key.pem
ssh -i ~/.ssh/my-key.pem [email protected]If the login fails, add -v to see the authentication steps:
ssh -v -i ~/.ssh/my-key.pem [email protected]Look for these lines in the output:
Offering public key: /home/you/.ssh/my-key.pemmeans SSH loaded the file.Authenticated to ... using "publickey"means success.Permission denied (publickey)after an offer means the server did not accept that key for that user.Load key ... bad permissionsorUNPROTECTED PRIVATE KEY FILEmeans the file mode is too open. Runchmod 400on it.
Too many keys in the agent
If you run ssh-agent with several keys loaded, SSH offers them in turn. A server allows only a few attempts, so you can see Too many authentication failures before your -i key is tried. Force SSH to offer only the key you named:
ssh -o IdentitiesOnly=yes -i ~/.ssh/my-key.pem [email protected]Checking that a key matches the instance
To confirm which public key a private key produces, derive it:
ssh-keygen -y -f ~/.ssh/my-key.pemTo see which public key the instance received at launch, read it from the metadata service while logged in or from user data scripts. IMDSv2 needs a token first:
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 60")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/public-keys/0/openssh-keyComparing the two outputs tells you whether you hold the right private key. Note that metadata shows the key from launch. Someone may have edited authorized_keys since, so the file on disk is the final authority.
Adding other users and keys
The key pair covers only the default user. For additional people, create separate accounts and give each their own key, instead of sharing one .pem file. Share nothing secret, so you can revoke one person without touching the others.
sudo useradd -m -s /bin/bash alice
sudo install -d -m 700 -o alice -g alice /home/alice/.ssh
echo "ssh-ed25519 AAAA...example alice@laptop" | \
sudo tee /home/alice/.ssh/authorized_keys > /dev/null
sudo chown alice:alice /home/alice/.ssh/authorized_keys
sudo chmod 600 /home/alice/.ssh/authorized_keysThe sshd daemon ignores authorized_keys if the home directory, .ssh directory, or file is writable by others. Wrong ownership or modes on the server side produce the same Permission denied (publickey) as a wrong key.
Recovering from a lost key
Because AWS never stores your private key, a lost file cannot be re-downloaded. Your options depend on what else you can reach:
- If Session Manager is set up, start a session and add a new public key to
authorized_keys. A later chapter covers this setup. - If the instance allows EC2 Instance Connect, push a temporary key and log in with it.
- If neither works, stop the instance, detach its root volume, attach it to a helper instance, edit
authorized_keyson the mounted volume, then reattach it and start the original. Alternatively, launch a new instance from an AMI of the old one with a new key pair.
Deleting a key pair with aws ec2 delete-key-pair removes only the public key record in EC2. Running instances keep the copy in authorized_keys, so delete the key from each instance if you need to revoke access.
Common errors at a glance
| Symptom | Likely cause | Fix |
|---|---|---|
| `UNPROTECTED PRIVATE KEY FILE` | Key file readable by others | `chmod 400` the file |
| `Permission denied (publickey)` | Wrong user, wrong key, or server-side permissions | Check AMI user, `KeyName`, and `authorized_keys` modes |
| `Too many authentication failures` | Agent offers many keys first | Use `-o IdentitiesOnly=yes` |
| Key pair not found at launch | Key pair is in a different Region | Create or import it in the launch Region |
| Import fails with invalid format | Public key passed without `fileb://`, or private key supplied | Pass the `.pub` file with `fileb://` |
Exercise
You launched an Ubuntu instance with key pair team-key. Your ssh -i team-key.pem ec2-user@<ip> command prints Permission denied (publickey), and the file permissions are 400. What do you check and change first, and why is the network not the problem?
Show answer
Change the login user to ubuntu. The public key was installed for the AMI's default user, and Ubuntu's is ubuntu, so ec2-user does not exist there. The network is working, because SSH reached the server and went through key negotiation. A blocked port or route would cause a timeout or Connection refused instead. If ubuntu also fails, confirm with describe-instances that the instance's KeyName is team-key.
Exercise
A colleague deletes the key pair old-key from EC2 to revoke access. Can the holder of old-key.pem still log in to instances already launched with it? Explain.
Show answer
Yes. EC2 copies the public key into authorized_keys at first boot, so deleting the key pair record does not touch running instances. To revoke access, remove the public key from authorized_keys on each instance, for example through Session Manager or EC2 Instance Connect.