How to Use Key Pair in EC2: Simple Steps for Secure Access
To use a
key pair in EC2, create or select a key pair when launching your instance, then use the private key file (.pem) to securely connect via SSH. The key pair acts like a secure password, allowing you to access your EC2 instance safely without a traditional password.Syntax
When launching an EC2 instance, specify the KeyName parameter to associate a key pair. Use the private key file (.pem) with an SSH client to connect.
KeyName: The name of the key pair linked to the instance.Private Key (.pem): Downloaded file used to authenticate your SSH connection.ssh -i path/to/key.pem user@public-ip: Command to connect to your instance.
bash
aws ec2 run-instances --image-id ami-12345678 --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-12345678 --subnet-id subnet-12345678
Example
This example shows how to launch an EC2 instance with a key pair named MyKeyPair and then connect to it using SSH.
bash
aws ec2 run-instances --image-id ami-0abcdef1234567890 --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-0abc1234 --subnet-id subnet-0abc1234 # After instance is running, connect using: ssh -i /path/to/MyKeyPair.pem ec2-user@ec2-203-0-113-25.compute-1.amazonaws.com
Output
Connected to EC2 instance via SSH as user ec2-user.
Common Pitfalls
- Not downloading the private key: AWS only lets you download the private key once when creating the key pair. Losing it means you cannot connect.
- Wrong permissions on the private key file: The private key file must have strict permissions (e.g., 400) or SSH will refuse to use it.
- Using the wrong username: Different AMIs use different default usernames (e.g.,
ec2-user,ubuntu,admin). - Not specifying the key pair at launch: You cannot add a key pair to an existing instance; it must be set when launching.
bash
chmod 400 /path/to/MyKeyPair.pem ssh -i /path/to/MyKeyPair.pem ec2-user@ec2-203-0-113-25.compute-1.amazonaws.com
Quick Reference
| Step | Description | Command/Action |
|---|---|---|
| 1 | Create or select a key pair in AWS EC2 console | Use AWS Console or CLI to create/download key pair |
| 2 | Launch EC2 instance with key pair | Specify --key-name MyKeyPair in CLI or select in console |
| 3 | Set private key file permissions | chmod 400 /path/to/key.pem |
| 4 | Connect to instance via SSH | ssh -i /path/to/key.pem ec2-user@public-ip |
| 5 | Keep private key safe | Store .pem file securely; no password recovery |
Key Takeaways
Always create or select a key pair when launching your EC2 instance to enable secure SSH access.
Download and securely store the private key file (.pem) as AWS does not allow re-downloading it.
Set strict permissions (chmod 400) on your private key file before connecting via SSH.
Use the correct default username for your AMI when connecting (e.g., ec2-user, ubuntu).
You cannot add or change a key pair on an existing EC2 instance; it must be set at launch.