Last active
August 18, 2021 04:17
-
-
Save seiji/368aa095eb937a41a3ce76df55875eb2 to your computer and use it in GitHub Desktop.
aws-ssm-ec2.sh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env sh | |
######## Usage ################################################################# | |
# Setup | |
# - Install aws cli (https://aws.amazon.com/cli/) | |
# - Install session-manager-plugin (https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html) | |
# - Move this script to ~/.ssh/aws-ssm-ec2.sh | |
# - Ensure it is executable (chmod +x ~/.ssh/aws-ssm-ec2.sh) | |
# | |
# Add following SSH Config Entry to ~/.ssh/config | |
# host i-* mi-* | |
# IdentityFile ~/.ssh/id_rsa | |
# ProxyCommand ~/.ssh/aws-ssm-ec2.sh %h %r %p ~/.ssh/id_rsa.pub | |
# StrictHostKeyChecking no | |
# User ec2-user | |
# | |
# Open SSH Connection | |
# ssh <INSTANCE_ID> | |
# | |
# Ensure AWS CLI environemnt variables are set properly | |
# e.g. aws-vault exec xxxx -- ssh ec2-user@i-xxxxxxxxxxxxxxxx | |
# | |
################################################################################ | |
set -eu | |
ec2_instance_id="$1" | |
os_user="$2" | |
port_num="$3" | |
ssh_public_key="$4" | |
>/dev/stderr echo "Add public key ${ssh_public_key} to instance ${os_user}@${ec2_instance_id} for 60 seconds" | |
az="$(aws ec2 describe-instances \ | |
--instance-id "$ec2_instance_id" \ | |
--query "Reservations[0].Instances[0].Placement.AvailabilityZone" \ | |
--output text)" | |
aws ec2-instance-connect send-ssh-public-key \ | |
--instance-id "$ec2_instance_id" \ | |
--instance-os-user "$os_user" \ | |
--ssh-public-key "file://$ssh_public_key" \ | |
--availability-zone "$az" | |
>/dev/stderr echo "Start ssm session to instance ${ec2_instance_id}" | |
aws ssm start-session \ | |
--target "${ec2_instance_id}" \ | |
--document-name 'AWS-StartSSHSession' \ | |
--parameters "portNumber=${port_num}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment