Skip to content
Stuff I'm Up To
Go back
AWS SSH using SSM

AWS SSH using SSM

Updated:

You can access a closed off AWS EC2 instance using SSH by using SSM as a proxy. This means no ports need be exposed from your EC2 at all.

Configure the AWS Client

aws configure

Specify your user access key, secret and region.

Connect to the EC2 instance

aws ssm start-session --target [instance_id]

Connect to SSH through an SSM port forward

aws ssm start-session --target [instance_id] \
  --document-name AWS-StartPortForwardingSession \
  --parameters '{"portNumber":["22"], "localPortNumber":["2222"]}'

ssh -p 2222 -i ~/.ssh/id_rsa root@localhost

A Real-World SSH Config

Running the aws ssm commands by hand every time gets tedious, so it’s worth putting the proxy command into ~/.ssh/config instead. Here’s an entry from my own config, sanitised:

Host web-1
  User ubuntu
  Hostname i-0123456789abcdef0
  IdentityFile ~/.ssh/my_aws_key
  IdentitiesOnly yes
  ProxyCommand sh -c "aws ssm start-session --profile my-aws-profile --region eu-west-2 --target %h --document-name AWS-StartSSHSession --parameters 'portNumber=%p'"
  StrictHostKeyChecking=no
  UserKnownHostsFile=/dev/null

ssh web-1 now works exactly like SSH to any other host, and so does everything built on it, scp, rsync -e ssh, port forwards, Git and Ansible pointed at the host by name.

A few things worth calling out:

References

https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started-enable-ssh-connections.html

https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-start.html#sessions-start-ssh


Share this post:

Previous Post
How to Connect to GCP MySQL Using Cloud SQL Proxy
Next Post
Homepage Dashboard