Skip to content

Instantly share code, notes, and snippets.

@hoegertn
Created August 17, 2019 11:10
Show Gist options
  • Save hoegertn/9abc1730425b03455320f9b47122091d to your computer and use it in GitHub Desktop.
Save hoegertn/9abc1730425b03455320f9b47122091d to your computer and use it in GitHub Desktop.
SSM Instance Connect
  1. Copy the file ssm-connect to a folder in your path
  2. Run ssm-connect setup, it will create a new SSH key-pair and configure SSH config
  3. Use it like ssh user@i-1234567890
#!/bin/bash -e
setup() {
ssh-keygen -t rsa -m PEM -N '' -f ${HOME}/.ssh/ssm-connect-rsa
chmod 600 ${HOME}/.ssh/ssm-connect-rsa
cat - ${HOME}/.ssh/config <<EOF > ${HOME}/.ssh/config_temp
# SSH over Session Manager
Host i-* mi-*
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
User ec2-user
IdentityFile ${HOME}/.ssh/ssm-connect-rsa
ProxyCommand sh -c "ssm-connect connect %h %r %p"
EOF
cat ${HOME}/.ssh/config_temp > ${HOME}/.ssh/config
rm -f ${HOME}/.ssh/config_temp
}
connect() {
INSTANCE_ID=$1
TARGET_USER=$2
TARGET_PORT=$3
AZ=$(aws ec2 describe-instances --instance-ids ${INSTANCE_ID} --query "Reservations[0].Instances[0].Placement.AvailabilityZone" --output text)
aws ec2-instance-connect send-ssh-public-key --instance-id ${INSTANCE_ID} --instance-os-user ${TARGET_USER} --availability-zone ${AZ} --ssh-public-key file://${HOME}/.ssh/ssm-connect-rsa.pub > /dev/null
exec aws ssm start-session --target ${INSTANCE_ID} --document-name AWS-StartSSHSession --parameters "portNumber=${TARGET_PORT}"
}
CMD=${1:?Missing command}
case $CMD in
setup*)
setup
;;
connect*)
connect $2 $3 $4
;;
*)
# unknown
echo "Usage: ssm-connect setup"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment