Skip to content

Instantly share code, notes, and snippets.

@mmerickel
Last active November 11, 2023 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmerickel/3a41cd2c0a00684f7d69253d712958a4 to your computer and use it in GitHub Desktop.
Save mmerickel/3a41cd2c0a00684f7d69253d712958a4 to your computer and use it in GitHub Desktop.
Connect to AWS instance using SSM and ec2-instance-connect with public access, and no shared keys.
#!/bin/bash
# Install an SSH key on an instance automatically and then configure an
# SSM proxy to the instance which will be used by SSH.
#
# Copy this script to ~/.ssh/ssm-proxy and make it executable:
#
# chmod +x ~/.ssh/ssm-proxy
#
# This script should be set as the ProxyCommand. For example:
#
# Host ssm.*
# ProxyCommand ~/.ssh/ssm-proxy %h %r %p
#
# The script will rip the "instance_id" from the end of the hostname, so
# something like "ssh ssm.<instance_id>" is expected.
#
# It's convenient to define a few other helpers for user, region, and
# host aliases. Note it's important for these to be defined BEFORE the
# general "ssm.*" host section. For example:
#
# Host ssm.us-west-2.main
# HostName i-xxxxxxxxxxxxxxxxx
#
# Host ssm.*.use1.* ssm.*.us-east-1*.* ssm.use1.* ssm.us-east-1*.*
# ProxyCommand sh -c 'AWS_REGION=us-east-1 ~/.ssh/ssm-proxy %h %r %p'
#
# Host ssm.*.use2.* ssm.*.us-east-2*.* ssm.use2.* ssm.us-east-2*.*
# ProxyCommand sh -c 'AWS_REGION=us-east-2 ~/.ssh/ssm-proxy %h %r %p'
#
# Host ssm.*.usw2.* ssm.*.us-west-2*.* ssm.usw2.* ssm.us-west-2*.*
# ProxyCommand sh -c 'AWS_REGION=eu-west-2 ~/.ssh/ssm-proxy %h %r %p'
#
# Host ssm.*.euw1.* ssm.*.eu-west-1*.* ssm.euw1.* ssm.eu-west-1*.*
# ProxyCommand sh -c 'AWS_REGION=eu-west-1 ~/.ssh/ssm-proxy %h %r %p'
#
# Host ssm.*.euw2.* ssm.*.eu-west-2*.* ssm.euw2.* ssm.eu-west-2*.*
# ProxyCommand sh -c 'AWS_REGION=eu-west-2 ~/.ssh/ssm-proxy %h %r %p'
#
# Host ssm.*
# User ec2-user
# StrictHostKeyChecking no
# UserKnownHostsFile /dev/null
# ProxyCommand ~/.ssh/ssm-proxy %h %r %p
set -euo pipefail
PUBKEYFILE=${PUBKEYFILE:-~/.ssh/id_ed25519.pub}
host=$1
user=$2
port=$3
# parse the instance id as the last attribute of the hostname
instance_id=$(echo "$host" | sed -E 's/.*\.([^.]+)$/\1/')
aws ec2-instance-connect send-ssh-public-key \
--instance-id "$instance_id" \
--instance-os-user "$user" \
--ssh-public-key "file://$PUBKEYFILE"
aws ssm start-session \
--target "$instance_id" \
--document-name AWS-StartSSHSession \
--parameters "portNumber=$port"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment