Connecting to a Private EC2 Instance Using a Bastion Host with SSH Agent Forwarding


๐ก๏ธ What is a Bastion Host?
A bastion host (also known as a jump box) is a public-facing EC2 instance that serves as a secure entry point to access private EC2 instances in a VPC that have no direct internet access.
โ Prerequisites
You have two EC2 instances:
Bastion Host โ in public subnet with public IP.
Private EC2 โ in private subnet with only a private IP.
Security Groups and routing configured to allow SSH (port 22) between:
You โ Bastion Host
Bastion Host โ Private EC2
You have the
.pem
file (SSH private key).
๐ Step-by-Step Commands Explained
1. Change the SSH Key Permission
chmod 400 your_key.pem
Sets strict read-only permissions for your private key.
SSH refuses to use key files that are too open (e.g.,
chmod 600
is also acceptable).
2. Start the SSH Agent
eval "$(ssh-agent -s)"
Starts the SSH authentication agent (a background process that manages your keys).
Needed especially when using agent forwarding.
3. Add Your SSH Key to the Agent
ssh-add your_key.pem
- Loads your key into the SSH agent so it can be used by forwarded sessions.
4. SSH into Bastion Host with Agent Forwarding
ssh -A ec2-user@bastion_host_public_ip
-A
enables agent forwarding, allowing the bastion to use your SSH key stored on your local machine without copying it to the bastion.You're now inside the bastion host.
5. Connect to the Private EC2 from the Bastion
ssh ec2-user@private_instance_private_ip
From the bastion host, SSH into the private instance using its private IP.
Since the SSH agent is forwarded, your local key is used for authentication, even though it's not present on the bastion host.
๐ Summary Diagram (Flow)
Your_Local_Machine
|
| (SSH -A using your_key.pem)
v
Bastion_Host (public IP)
|
| (SSH using agent-forwarded key)
v
Private_EC2_Instance (private IP)
Subscribe to my newsletter
Read articles from SRINIVAS TIRUNAHARI directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
