Skip to content

Instantly share code, notes, and snippets.

@pahud
Created June 28, 2019 03:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save pahud/f6545440c0436308d933d2459d5c7ac4 to your computer and use it in GitHub Desktop.
Save pahud/f6545440c0436308d933d2459d5c7ac4 to your computer and use it in GitHub Desktop.
One Time EC2 SSH public key connect
#!/bin/bash
TMPKEY="my-ssh-tmp-key-${RANDOM}"
EC2USER='ec2-user'
generate_ssh_key_pair(){
ssh-keygen -t rsa -f ~/.ssh/${TMPKEY} -N "" && \
chmod 600 ~/.ssh/${TMPKEY}.pub
}
get_az_from_instance_id(){
# get_az_from_instance_id iid region
aws --region "$2" ec2 describe-instances --instance-id "$1" --query 'Reservations[0].Instances[0].Placement.AvailabilityZone' --output text
}
get_public_ip(){
aws --region "$2" ec2 describe-instances --instance-id "$1" --query 'Reservations[0].Instances[0].NetworkInterfaces[0].Association.PublicIp' --output text
}
send_ssh_public_key(){
aws ec2-instance-connect send-ssh-public-key --region "$1" --instance-id "$2" \
--availability-zone "$3" \
--instance-os-user ec2-user --ssh-public-key file://$HOME/.ssh/${TMPKEY}.pub
}
iid="$1"
region="$2"
az=$(get_az_from_instance_id $iid $region)
publicip=$(get_public_ip $iid $region)
echo "connecting to $iid at $az as $EC2USER on $publicip"
generate_ssh_key_pair && \
send_ssh_public_key $region $iid $az && \
ssh -i $HOME/.ssh/${TMPKEY} ${EC2USER}@${publicip};
echo "clean up the temp key pair"
rm -f ~/.ssh/"${TMPKEY}*" && echo "DONE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment