SSH connection to EC2 instance through Session Manager with ssh-over-ssm
awsSession Manager can execute commands and port forwarding by itself. Besides, it also supports SSH connection with –document-name AWS-StartSSHSession. The content of this document is sessionType Port same as AWS-StartPortForwardingSession, and SSM Agent establishes a TCP connection to the target port.
This allows you to copy files with scp and use tools such as DB clients to perform SSH port forwarding.
Compared to a normal SSH connection, you don’t need to expose ports or prepare a jump host, and you can manage permissions with IAM, but you still need to put the public key on the instance. I was looking for a better way to do this, and I found a ssh-over-ssm script. This script places a generated key on the instance with Run Command and then start-session.
$ git clone --depth=1 https://github.com/elpy1/ssh-over-ssm.git
$ cp ssh-over-ssm/ssh-ssm.sh ~/.ssh/
$ vi ~/.ssh/config
Match Host i-*
User ec2-user
ProxyCommand ~/.ssh/ssh-ssm.sh %h %r
IdentityFile ~/.ssh/ssm-ssh-tmp
StrictHostKeyChecking no
BatchMode yes
$ ssh i-xxxxxxxxxxxxxxxxx
When I ran it with a role that has source IP address limits, Run Command became Access Denied, so I removed the limit.
It is required a minor fix to call from non ssh commands.