The Problem with Connecting to EC2 Instances
If you manage AWS EC2 instances day-to-day, you’ll be familiar with the dance:
- Open the AWS console (or run
aws ec2 describe-instances ...with a wall of JSON) - Hunt for the instance ID
- Copy it somewhere
- Run
aws ssm start-session --target i-0abc123...
Even with a previous post on SSHing to EC2 instances over SSM, you still need to know the instance ID upfront. I wanted something closer to just typing ssh hostname.
The Solution
I’ve published a PowerShell toolkit as a Gist:
👉 AWS EC2 Lookup & Connectivity Toolkit
Add it to your PowerShell profile and you get four short commands:
| Command | What it does |
|---|---|
ec2 <name> | Look up instances matching a name (partial match supported) |
ssh2 <name> | SSH to the instance (falls back to SSM if SSH fails) |
ssm2 <name> | Start an SSM Session Manager session |
rdp2 <name> | Open Remote Desktop to the instance |
Example Usage
# Find instances with "web" in their Name tag
ec2 web
# SSH to an instance called "ukwebserver01"
ssh2 ukwebserver01
# SSH as a non-default user
ssh2 ukwebserver01 -User ubuntu
# Start an SSM session
ssm2 ukwebserver01
# Search across all your configured AWS CLI profiles
ec2 web -AllAccounts
# Force a fresh lookup (skip the in-session cache)
ec2 web -NoCache
# Open RDP to a Windows instance
rdp2 winserver01
How It Works
Instance Lookup
The core Get-EC2Instance function queries EC2 using aws ec2 describe-instances with a wildcard filter on the Name tag, so ec2 uk will match ukwebserver01, uk-bastion, and anything else with “uk” in the name.
It searches across multiple regions by default (eu-west-2 and eu-west-1) and can optionally loop through all your configured AWS CLI profiles with -AllAccounts.
Results are cached in memory for the duration of your PowerShell session, so repeated lookups are fast.
Multiple Matches
If more than one instance matches your search, you get an interactive picker. On Windows with PowerShell 5+ you’ll get an Out-GridView popup. On other platforms (or if Out-GridView isn’t available) you get a numbered CLI menu instead.
AWS SSO Support
Before querying, the toolkit checks whether your SSO session is still valid. If it isn’t, it automatically runs aws sso login for you rather than failing silently.
SSH with SSM Fallback
ssh2 tries a normal SSH connection first. If that fails (e.g. port 22 isn’t open, or you’re connecting via a private IP), it automatically falls back to an SSM session — no manual intervention needed.
Setup
- Copy the script from the Gist into your PowerShell profile (
$PROFILE). - Update the default
$Profileparameter inGet-EC2Instanceandec2ssm/ec2sshto match your AWS CLI profile name. - Optionally update the default
$Regionsarray to match the regions you use most. - Reload your profile (
. $PROFILE) or open a new PowerShell window.
You’ll need the AWS CLI v2 installed and configured with SSO or standard credentials.
PowerShell icon from Devicons — MIT licensed.