Skip to content

Instantly share code, notes, and snippets.

@iolloyd
Last active August 1, 2019 11:06
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 iolloyd/4167653665d9eb5957bf7acebf9bc676 to your computer and use it in GitHub Desktop.
Save iolloyd/4167653665d9eb5957bf7acebf9bc676 to your computer and use it in GitHub Desktop.
AWS EC2 temporarily connect to an instance by id
#!/bin/sh
# Allows you to temporarily connect to an ec2 instance, using
# awscli to first push your own key to the instance, then using ssh
# to log in to the instance.
# Assumes a public key called ec2.pub and a private
# key called ec2.
# Usage ec2_connect.sh i-12345679abcdef <other-user> <other-file>
INSTANCE_ID=$1
SSHUSER=${2:-"ec2-user"}
FILE=${3:-'ec2'}
INSTANCE=$( aws ec2 describe-instances \
--instance-ids $INSTANCE_ID \
--query 'Reservations[0].Instances[0]' \
)
AZ=$(echo $INSTANCE|jq '.Placement.AvailabilityZone'|sed 's/"//g')
IP=$(echo $INSTANCE|jq '.PrivateIpAddress'|sed 's/"//g')
REGION=$(echo $AZ|rev|cut -c 2-|rev)
aws ec2-instance-connect send-ssh-public-key \
--region $REGION \
--availability-zone $AZ \
--instance-id $INSTANCE_ID \
--instance-os-user $SSHUSER \
--ssh-public-key file://${FILE}.pub
ssh -i $FILE ${SSHUSER}@${IP}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment