How to Access an EC2 Instance After Losing the PEM File
Lost your EC2 private key (.pem) file? You can still get back in — and in 2026 you usually don't need the key at all. The fastest modern way to regain access is AWS Systems Manager (SSM) Session Manager if the SSM Agent and an SSM-enabled IAM role are present, or EC2 Instance Connect to push a fresh temporary SSH key. Only when neither is available do you fall back to the classic stop-and-swap-the-root-volume method. None of these require the original key, because AWS never stored your private key in the first place — when you created the key pair, AWS kept only the public half and handed you the private .pem once.
This guide walks through every route to recover access, ordered from least disruptive to last resort, with the exact commands for each. We have run AWS and DevOps for clients for 12+ years across 50+ projects, and lost-key recovery is one of the most common "production fire" tickets we see — so we have lined the methods up the way we actually use them on call.
Important: There is no way to "recover" the lost
.pemfile itself. AWS cannot regenerate or email it to you. The goal is not to recover the file — it is to establish a new way in, then optionally attach a brand-new key pair.
Decision shortcut: which method should you use?
- Can you open the instance in the EC2 console and it shows "Connect" works? Use SSM Session Manager or EC2 Instance Connect — zero downtime, no key needed.
- Is the SSM Agent running with an instance profile that allows SSM? → Session Manager (best).
- Supported Amazon Linux/Ubuntu AMI but no SSM role? → EC2 Instance Connect.
- Neither works and you can tolerate a reboot? → User data on stop/start.
- Everything above is unavailable (no agent, unsupported AMI, locked-down IAM)? → The volume-swap rescue method.
Method 1 — AWS Systems Manager Session Manager (recommended, no key needed)
Session Manager gives you an interactive shell on the instance through the AWS API — no SSH key, no open inbound port 22, no bastion host. This is the cleanest recovery path in 2026 and the one we reach for first.
Prerequisites (all must be true):
- The SSM Agent is installed and running on the instance. It is pre-installed on current Amazon Linux 2, Amazon Linux 2023, Ubuntu (16.04+), and Windows Server AMIs.
- The instance has an IAM instance profile attached that grants SSM permissions — the AWS-managed policy
AmazonSSMManagedInstanceCoreis enough. - The instance can reach the SSM endpoints (via a NAT/Internet gateway, or VPC interface endpoints
ssm,ssmmessages, andec2messagesfor private subnets). - Your IAM user/role has
ssm:StartSession(the AWS-managedAmazonSSMFullAccessor a scoped policy).
If those hold, the instance appears under Fleet Manager → Managed instances in the console. Click Connect → Session Manager, or use the CLI (see the code block below).
Once you have a shell, add a new key pair so normal SSH works again. Generate a new key on your laptop, then append its public half to the instance's authorized_keys (commands in the code block). After that you can SSH in with the new .pem as usual.
If the SSM Agent or IAM role is missing, you cannot bolt them on without already being inside — so move to EC2 Instance Connect or the volume method below. For a refresher on attaching the right instance profile, see our guide to AWS IAM roles and policies.
# --- Install the Session Manager plugin on your laptop (one-time) ---
# macOS: brew install --cask session-manager-plugin
# Linux: see AWS docs for your distro's package
# 1. List instances SSM can manage (confirm yours is "Online")
aws ssm describe-instance-information \
--query "InstanceInformationList[].{Id:InstanceId,Ping:PingStatus,Name:ComputerName}" \
--output table
# 2. Start an interactive session — NO SSH key required
aws ssm start-session --target i-0123456789abcdef0
# --- Now inside the instance, add a brand-new key pair ---
# (Run ssh-keygen on YOUR machine first, then paste the .pub contents below.)
# On your laptop:
# ssh-keygen -t ed25519 -f ~/.ssh/ec2-recovery -C "ec2-recovery"
# Copy the contents of ~/.ssh/ec2-recovery.pub, then on the instance:
sudo -u ec2-user bash -c 'mkdir -p ~/.ssh && chmod 700 ~/.ssh'
echo "ssh-ed25519 AAAA...your-public-key... ec2-recovery" \
| sudo tee -a /home/ec2-user/.ssh/authorized_keys
sudo chmod 600 /home/ec2-user/.ssh/authorized_keys
sudo chown ec2-user:ec2-user /home/ec2-user/.ssh/authorized_keys
# Back on your laptop you can now SSH with the new key:
# ssh -i ~/.ssh/ec2-recovery ec2-user@<public-ip>Method 2 — EC2 Instance Connect (push a temporary SSH key, no stored key needed)
EC2 Instance Connect lets you push a one-time, 60-second SSH public key to the instance through the AWS API, then connect with the matching private key. AWS does not store the key — it is injected just long enough to authenticate. This works without ever having your original .pem.
Prerequisites:
- A supported AMI with the
ec2-instance-connectpackage pre-installed: Amazon Linux 2, Amazon Linux 2023, and Ubuntu 16.04+ ship with it. (Custom or older AMIs may not.) - Your IAM identity has
ec2-instance-connect:SendSSHPublicKey. - A security-group rule allowing SSH (port 22) from your source — or from the EC2 Instance Connect service IP range / endpoint.
Two ways to use it:
- Browser-based: In the EC2 console select the instance → Connect → EC2 Instance Connect → Connect. AWS opens a terminal in your browser with no key handling on your side.
- CLI: Push a public key, then SSH within the 60-second window (commands below).
Private subnets: if the instance has no public IP, create an EC2 Instance Connect Endpoint (EIC Endpoint) in the VPC. It gives you keyless SSH/RDP to private instances without a bastion or public IP — connect with aws ec2-instance-connect ssh or the --connection-type eice option.
As with SSM, once you are in, append a permanent new public key to authorized_keys so future logins do not depend on the 60-second window.
# --- EC2 Instance Connect via CLI ---
# 1. Generate a fresh key pair on your laptop (one-time)
ssh-keygen -t ed25519 -f ~/.ssh/ec2-recovery -C "ec2-instance-connect"
# 2. Push the PUBLIC key to the instance (valid for ~60 seconds)
aws ec2-instance-connect send-ssh-public-key \
--instance-id i-0123456789abcdef0 \
--availability-zone us-east-1a \
--instance-os-user ec2-user \
--ssh-public-key file://~/.ssh/ec2-recovery.pub
# 3. SSH in IMMEDIATELY (within the 60s window) using the private key
ssh -i ~/.ssh/ec2-recovery ec2-user@<public-ip>
# --- One-shot helper that pushes the key and connects for you ---
aws ec2-instance-connect ssh --instance-id i-0123456789abcdef0
# --- Private-subnet instance? Tunnel through an EC2 Instance Connect Endpoint ---
aws ec2-instance-connect ssh \
--instance-id i-0123456789abcdef0 \
--connection-type eiceMethod 3 — Reset the key via user data (requires stop/start)
If SSM and Instance Connect are both unavailable but you can tolerate a short reboot, you can use user data to inject a new authorized key (or a password) when the instance next boots. User data marked to run on every boot — or a one-shot script — runs as root early in startup, so it can write to any user's authorized_keys.
Caveats — read these first:
- You must stop the instance to edit user data (it cannot be changed while running). An instance-store-backed instance loses its data on stop, so this is only safe for EBS-backed instances.
- Stop/start moves the instance to a new host, so the public IPv4 address changes unless you use an Elastic IP. Note the new IP after start.
- User data scripts (
#cloud-config/ shell) run once by default. To force a re-run on the next boot you must clear the cloud-init "instance" semaphore or use#cloud-configwithcloud_final_modulesconfigured to always run — otherwise a previously-booted instance ignores the new script. Because of this gotcha, many teams prefer Method 4 for a guaranteed result.
Steps: Stop the instance → Actions → Instance settings → Edit user data → paste a script that appends your new public key to authorized_keys → start the instance → SSH with the new key. The script content is in the code block below.
#cloud-config
# Paste this as the instance's User data (Actions > Instance settings > Edit user data)
# while the instance is STOPPED. It appends a new public key on next boot.
# Replace the key below with the contents of YOUR ~/.ssh/ec2-recovery.pub
ssh_authorized_keys:
- ssh-ed25519 AAAA...your-public-key... ec2-recovery
# --- Or, a plain shell script alternative (also as User data) ---
#!/bin/bash
USER_HOME=/home/ec2-user # use /home/ubuntu on Ubuntu AMIs
mkdir -p "$USER_HOME/.ssh"
echo "ssh-ed25519 AAAA...your-public-key... ec2-recovery" >> "$USER_HOME/.ssh/authorized_keys"
chmod 700 "$USER_HOME/.ssh"
chmod 600 "$USER_HOME/.ssh/authorized_keys"
chown -R ec2-user:ec2-user "$USER_HOME/.ssh"Method 4 — The classic volume-swap rescue (last resort)
This is the traditional fallback that works on any EBS-backed instance regardless of SSM agent, AMI support, or IAM configuration — because you fix the key from outside by mounting the root disk on a healthy "rescue" instance. It is the most disruptive option (it needs downtime and a second instance), so use it only when Methods 1–3 are not viable.
Step by step:
- Launch a rescue/helper instance in the same Availability Zone as the broken one, using an AMI and a key pair you do have access to. (EBS volumes can only attach to instances in the same AZ.)
- Stop the broken instance — stop, never terminate. (Terminating with "delete on termination" enabled destroys the volume.)
- In EC2 → Volumes, find the broken instance's root volume, detach it.
- Attach that volume to the rescue instance as a secondary device (for example
/dev/sdf, which Linux usually exposes as/dev/xvdf). - SSH into the rescue instance with its working key, mount the attached volume, and replace or append the
authorized_keyswith your new public key (commands below). On modern AMIs the root partition is/dev/xvdf1; on Nitro instances it may appear as/dev/nvme1n1p1— uselsblkto confirm. - Unmount, detach the volume from the rescue instance, re-attach it to the original instance as the root device (
/dev/xvdaor/dev/sda1, matching what the AMI expects). - Start the original instance and SSH in with your new key. Terminate the rescue instance when done.
Generate the new key pair before you start, so the public key is ready to drop in. The original 2-step commands from the older version of this post are preserved and expanded in the code block.
# === On your laptop: create the new key pair you'll install ===
ssh-keygen -t ed25519 -f ~/.ssh/ec2-recovery -C "ec2-volume-rescue"
cat ~/.ssh/ec2-recovery.pub # copy this public key
# === On the RESCUE instance (volume from broken instance attached) ===
# 1. Find the attached volume's root partition
lsblk
# Older Xen instances: /dev/xvdf1 | Nitro instances: /dev/nvme1n1p1
# 2. Mount it
sudo mkdir -p /mnt/rescue
sudo mount /dev/xvdf1 /mnt/rescue # adjust device name from lsblk
# 3. Install your NEW public key into the mounted volume's authorized_keys
# (ec2-user for Amazon Linux; use /home/ubuntu for Ubuntu AMIs)
sudo mkdir -p /mnt/rescue/home/ec2-user/.ssh
echo "ssh-ed25519 AAAA...your-public-key... ec2-volume-rescue" \
| sudo tee -a /mnt/rescue/home/ec2-user/.ssh/authorized_keys
sudo chmod 700 /mnt/rescue/home/ec2-user/.ssh
sudo chmod 600 /mnt/rescue/home/ec2-user/.ssh/authorized_keys
# Match ownership to the original user's UID (ec2-user is usually 1000)
sudo chown -R 1000:1000 /mnt/rescue/home/ec2-user/.ssh
# 4. Unmount cleanly
sudo umount /mnt/rescue
# === Now in the console: detach the volume from the rescue instance,
# re-attach to the original instance as /dev/xvda (root), then START it. ===
# === Finally, from your laptop: ===
ssh -i ~/.ssh/ec2-recovery ec2-user@<new-public-ip>Comparison: which recovery method to choose
| Method | Downtime? | Key needed? | Key prerequisites | Best for |
|---|---|---|---|---|
| SSM Session Manager | None | No | SSM Agent + IAM role (AmazonSSMManagedInstanceCore) + SSM reachability |
Production instances; the default in 2026 |
| EC2 Instance Connect | None | Temporary (auto) | Supported AL2/AL2023/Ubuntu AMI + SendSSHPublicKey IAM perm + SG/EIC endpoint |
Quick keyless SSH on supported AMIs |
| User data on reboot | Stop/start | New key you supply | EBS-backed instance; ability to stop it | When SSM/Instance Connect unavailable but reboot OK |
| Volume-swap rescue | Stop + swap | New key you supply | Same-AZ rescue instance; EBS-backed root volume | Last resort: no agent, unsupported AMI, locked IAM |
Rule of thumb: prefer the no-downtime, keyless options (Methods 1 and 2). Drop to the reboot/volume methods only when the modern tooling is not present on the instance — which itself is a signal to fix your baseline (see Prevention below).
How to never lose EC2 access again
Recovering access is a fire drill. The real fix is to stop depending on a single .pem file:
- Make SSM Session Manager the default access path. Attach an instance profile with
AmazonSSMManagedInstanceCoreto every instance and disable inbound port 22 entirely. No SSH keys to lose, full audit logging via CloudTrail/CloudWatch, and access is governed by IAM — not a file on someone's laptop. This is the single highest-leverage change. - Use EC2 Instance Connect (and EIC Endpoints) as a keyless backup for ad-hoc SSH without bastions or public IPs.
- Store any keys you do keep in a secrets manager — AWS Secrets Manager, AWS Systems Manager Parameter Store, or a team password manager — never in email, Slack, or a lone laptop. Rotate them.
- Manage instances with infrastructure-as-code (Terraform, CloudFormation, CDK) so key pairs, IAM roles, and SSM configuration are reproducible and reviewable rather than hand-clicked.
- Tag and document the user (
ec2-uservsubuntu) and key associated with each fleet so recovery is fast when it is needed.
Locking down access this way also tightens your overall security posture and keeps your bill predictable — themes we cover in our AWS cost and performance optimization guide. If you would rather hand this off, our AWS consulting services team builds keyless, IaC-managed access into every environment, and our cloud migration services practice sets it up correctly from day one.
Frequently Asked Questions
Can I recover a lost EC2 .pem file?
No — AWS never stored your private key, so it cannot be recovered, regenerated, or re-sent. When you created the key pair AWS kept only the public half and gave you the private .pem exactly once. You cannot get the file back, but you can regain access to the instance using SSM Session Manager, EC2 Instance Connect, a user-data reset, or the volume-swap method, and then install a brand-new key pair.
What's the easiest way to access an EC2 instance without a key?
AWS Systems Manager Session Manager. If the instance has the SSM Agent and an IAM instance profile with AmazonSSMManagedInstanceCore, you can open a shell from the console or run aws ssm start-session --target i-xxxx with no SSH key, no open port 22, and no downtime. If SSM is not set up, EC2 Instance Connect is the next-easiest keyless option on supported Amazon Linux and Ubuntu AMIs.
Does SSM Session Manager need an SSH key?
No. Session Manager connects through the AWS API and the SSM Agent, not over SSH, so it needs no key pair and no inbound SSH port. Access is controlled entirely by IAM permissions, and every session can be logged to CloudWatch Logs or S3 for audit. This is exactly why it is the preferred recovery and day-to-day access method in 2026.
How do I add a new key pair to a running instance?
Get a shell on the instance (via SSM Session Manager or EC2 Instance Connect), then append your new public key to the user's ~/.ssh/authorized_keys — for example echo "ssh-ed25519 AAAA..." >> ~/.ssh/authorized_keys with permissions 700 on .ssh and 600 on the file. Generate the key pair locally first with ssh-keygen -t ed25519. No stop/start is required. Note that creating a new key pair in the EC2 console does not apply it to existing instances — you must install the public key yourself.
Do I have to stop or reboot the instance to regain access?
Not for the modern methods. SSM Session Manager and EC2 Instance Connect work on a running instance with zero downtime. Only the user-data reset and the volume-swap rescue require stopping the instance — which also changes its public IPv4 address unless an Elastic IP is attached. Always exhaust the no-downtime options first.
How do I prevent losing EC2 access again?
Stop relying on a single .pem file. Make SSM Session Manager the default access path (attach AmazonSSMManagedInstanceCore and close port 22), keep EC2 Instance Connect as a keyless backup, store any remaining keys in AWS Secrets Manager or a password manager, and provision key pairs, IAM roles, and SSM config through infrastructure-as-code so access is reproducible and never lives only on one laptop.