Hands-on AWS knowledge base for developers Managed Ops
Talk to Us

How to Connect an AWS EC2 Instance Using VS Code (3 Ways)

Export PDF Print-friendly layout with a copyright watermark; choose Save as PDF in the print dialog
How to Connect an AWS EC2 Instance Using VS Code (3 Ways)

TL;DR

  • One dev, one box: the Remote-SSH extension over port 22 is the fastest path — about 10 minutes — but every engineer's IP change breaks it.
  • Small team (3–10): tunnel SSH through SSM Session Manager (AWS-StartPortForwardingSession) and let Remote-SSH connect to localhost:2222. No inbound rules, no key distribution, roughly 30 minutes of one-time setup.
  • Platform teams: EC2 Instance Connect Endpoint gives you IAM-audited access with zero inbound security group rules, at the cost of a VPC endpoint and a stricter IAM policy.

Three ways in, and the team each one actually fits

VS Code doesn't "support EC2" in a special way. It runs a small server process on the remote host and talks to it over SSH. Everything below is really a different answer to one question: how does port 22 traffic reach that instance?

Here's the honest comparison, from the perspective of whoever has to keep it working.

Option Setup time Inbound SG rules Who owns it Breaks when
Remote-SSH direct to public IP ~10 min 22 from your IP/32 each engineer home IP changes, no public IP, instance in private subnet
Remote-SSH over SSM port forward ~30 min once none one person, once SSM agent stopped, missing instance profile, no 443 egress
AWS Toolkit "Connect to EC2" (SSM under the hood) ~10 min none AWS-managed extension same SSM dependencies; less terminal control
EC2 Instance Connect Endpoint ~20 min infra none platform team endpoint SG must allow 22 outbound to instance SG

The pattern worth internalising: options 2–4 all move the hard part (network reachability) into IAM and AWS-managed infrastructure, and that's exactly where you want it when more than one person connects.

Solo developer: Remote-SSH on port 22, locked to your IP

For a t3.medium dev box in us-east-1 and one person, nothing beats the direct route. Install the Microsoft "Remote – SSH" extension, make sure the instance is in a public subnet with a public IPv4 (or a stable Elastic IP), and open 22 only to your current address.

# from your laptop, us-east-1, instance sg-0a1b2c3d4e5f67890
ssh-keygen -t ed25519 -f ~/.ssh/ec2-dev -C "vs-code-dev"

MYIP=$(curl -s https://checkip.amazonaws.com | tr -d 'n')
aws ec2 authorize-security-group-ingress 
  --group-id sg-0a1b2c3d4e5f67890 
  --protocol tcp --port 22 --cidr "${MYIP}/32"


Then in `~/.ssh/config`:

```text
Host ec2-dev
    HostName 203.0.113.42
    User ec2-user
    IdentityFile ~/.ssh/ec2-dev
    ServerAliveInterval 30
    ServerAliveCountMax 4


`ServerAliveInterval` matters more than people expect — without it, a laptop that sleeps mid-session leaves a zombie `node` process on the instance holding 300 MB of RAM.

Size the instance for the editor, not just your app. VS Code Server idles around 250–350 MB RSS, and a `npm run build` on top of that will OOM a 1 GB t3.micro. I've watched a webpack build get killed at 04:10 by the kernel OOM reaper on exactly that setup.

Do **not** open 22 to `0.0.0.0/0` "temporarily". On us-east-1 you'll see failed `admin` and `ubuntu` logins in `/var/log/secure` within minutes.

## Small team (3–10 engineers): SSH tunneled through SSM Session Manager

This is the configuration I recommend to almost every small team I work with. The instance needs no public IP and no inbound rule at all; the SSM agent on the host opens an outbound connection to Systems Manager, and you forward a local port into it.

Prerequisites, all one-time: the SSM agent running (Amazon Linux 2023 and Ubuntu 22.04+ AMIs ship it), an instance profile with `AmazonSSMManagedInstanceCore`, and either a NAT gateway or VPC interface endpoints for `ssm` and `ssmmessages`.

```bash
# verify the agent before blaming VS Code
aws ssm describe-instance-information 
  --query "InstanceInformationList[?InstanceId=='i-0abc123def4567890'].[PingStatus,AgentVersion]" 
  --output text
# expected: Online  3.3.xxxx.0

# then start the tunnel (leave this running in its own terminal)
aws ssm start-session 
  --target i-0abc123def4567890 
  --document-name AWS-StartPortForwardingSession 
  --parameters '{"portNumber":["22"],"localPortNumber":["2222"]}'


The SSH config for that tunnel is short:

```text
Host ec2-dev-ssm
    HostName localhost
    Port 2222
    User ec2-user
    IdentityFile ~/.ssh/ec2-dev


Give each engineer a `ssm:StartSession` policy scoped to the instance ARN rather than `*`:

```json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["ssm:StartSession", "ssm:TerminateSession"],
    "Resource": ["arn:aws:ec2:us-east-1:123456789012:instance/i-0abc123def4567890"]
  }]
}


The failure mode you'll hit first is `An error occurred (TargetNotConnected) when calling the StartSession operation: i-0abc123def4567890 is not connected.` That's never VS Code. It's the agent, the instance profile, or missing 443 egress — check in that order.

One gotcha specific to the `localhost:2222` pattern: when you point the same port at a different instance, OpenSSH throws `WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!` and refuses to connect. Clear it with `ssh-keygen -R "[localhost]:2222"` and move on.

## Platform team: EC2 Instance Connect Endpoint, zero inbound rules

If you're running 30 dev instances and someone asks "who SSH'd into prod-db-01 last Tuesday", SSM session documents and CloudTrail give you an answer; raw port 22 does not. EC2 Instance Connect Endpoint (EIC) pushes further — the endpoint lives in your VPC, IAM controls who can open a tunnel, and the instance security group stays completely closed.

```bash
# needs a recent AWS CLI v2; check `aws ec2-instance-connect help` lists open-tunnel
aws ec2-instance-connect open-tunnel 
  --instance-id i-0abc123def4567890 
  --local-port 2222 
  --remote-port 22


Two things bite people here. The endpoint's security group must allow **outbound** 22 to the instance's security group, and the instance's group must allow **inbound** 22 from the endpoint's group — a lot of teams lock the instance down to "nothing" and then wonder why the tunnel opens but the handshake dies. The second is IAM: your engineers need `ec2-instance-connect:OpenTunnel` plus `ec2:DescribeInstances` in the target region.

### When NOT to use Remote-SSH

Skip remote development entirely if the instance is a spot instance that gets reclaimed mid-afternoon — you'll lose unsaved buffers and the VS Code Server install every time. Use a local dev container instead. Skip it too if the code needs a 16 GB dataset that lives in S3: sync a subset, or run `code-server` in the browser behind an ALB with Cognito, rather than giving laptops a 500 ms-latency editing experience over a cross-region link.

And if the instance's only job is running a build, don't attach an editor to it at all. Push, let CodeBuild run, read the logs.

## Learning cost, failure modes, and the 2am session that wouldn't start

| What you maintain | Remote-SSH / 22 | SSM tunnel | EIC endpoint |
|---|---|---|---|
| Per-engineer setup | ~10 min each | ~2 min after the first | ~5 min each |
| Inbound rules to audit | one per engineer | zero | zero |
| Moving parts | keypair + SG | agent, IAM, egress | endpoint, SG pair, IAM |
| Typical 2am cause | your IP changed | `TargetNotConnected` | tunnel opens, handshake times out |

Here's the one that cost me a night. On 2026-11-04, a `m5.xlarge` dev instance in us-east-1, private subnet, reached through an SSM tunnel. SSH itself was instant — `ssh ec2-dev-ssm` gave a shell in under a second. But VS Code hung at `Setting up SSH Host ec2-dev-ssm: Downloading VS Code Server (3%)` for six minutes and then printed:


Failed to parse remote port from server output


My first configuration assumed the only requirement was "port 22 is reachable." It isn't. VS Code Server downloads its payload (roughly 120 MB for `vscode-server-linux-x64.tar.gz`) from `update.code.visualstudio.com` **on the instance**, over HTTPS. That subnet's route table had only the local route — no NAT gateway — so the instance had zero outbound internet. SSH worked because it rode the SSM tunnel; the download had nowhere to go.

Diagnosis took two commands on the box:

```bash
curl -sS -m 10 -o /dev/null -w "%{http_code}n" https://update.code.visualstudio.com/api/releases/stable
# curl: (28) Connection timed out after 10001 milliseconds


`Failed to parse remote port from server output` is almost always the server failing to install or start — treat it as "look at the Remote-SSH output channel", not "the SSH connection is broken."

The fix didn't need a NAT gateway. Setting `remote.SSH.localServerDownload` to `always` in VS Code settings makes the client download the tarball on your laptop and copy it over the existing SSH channel, then extract it into `~/.vscode-server/bin/<commit>/`. Reconnect, and the log line changes to `Downloading VS Code Server locally`; the window opened in about 40 seconds. I verified with `ls ~/.vscode-server/bin` on the instance — one commit directory, no partial extract.

If you're running a fleet and want the NAT gateway anyway, fine, but budget for it consciously: NAT gateways bill hourly plus per GB processed, and in us-east-1 that's a real monthly line item for a dev VPC. For a handful of instances, the local-download setting or a VPC interface endpoint is cheaper and easier to reason about.

We do this kind of "why won't the remote session start" triage for SMB teams through awsgood.com managed services when there's no platform engineer to own the SSM and VPC side.

## Sources

- [Connect to your EC2 instance using SSH](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-using-ssh.html)
- [Start a port forwarding session with Session Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-start.html)
- [Connect to an instance using EC2 Instance Connect End

Leave a Reply

Your email address will not be published. Required fields are marked *