Assuming you have your AWS CLI configured properly, and have the “jq” package installed, this is an easy way to SSH to your EC2 instances, and can detect/start an EC2 instance if you attempt to SSH to one that is stopped.
Place the below in ~/.profile, and then source it with “. ~/.profile” (or close and reopen your terminal):
alias ec2start="aws ec2 start-instances --instance-ids"
alias ec2stop="aws ec2 stop-instances --instance-ids"
alias ec2reboot="aws ec2 reboot-instances --instance-ids"
alias ec2list="aws ec2 describe-instances --query 'Reservations[].Instances[].{Name:[Tags[?Key=='Name'].Value][0][0],PublicIP:PublicIpAddress,PrivateIP:PrivateIpAddress,InstanceID:InstanceId,State:State.Name,AZ:Placement.AvailabilityZone }' --output table"
alias ec2idlist="aws ec2 describe-instances | jq '.Reservations[].Instances[].InstanceId' | sed -E 's/\"//g'"
ec2ssh(){
STATE=$(aws ec2 describe-instances --instance-ids "${1}" | jq '.Reservations | .[].Instances | .[].State | .Name' | sed -E 's/"//g')
IP=$(aws ec2 describe-instances --instance-ids "${1}" | awk '/PublicIpAddress/ {print $NF}' | sed -E 's/(,|")//g')
if [ "${STATE}x" == "runningx" ]; then
if [ "${IP}x" != "x" ]; then
echo "ssh to: ${IP}"
ssh -tt -i ~/Downloads/mmoldvan.pem ec2-user@"${IP}" $2
else
echo "Instance ${1} does not have a public IP!"
fi
elif [ "${STATE}x" == "terminatedx" ]; then
echo "Instance ${1} has been terminated. Can't do anything else with it, sorry!"
elif [ "${STATE}x" == "pendingx" ]; then
echo "Instance ${1} has a state of ${STATE}. Wait for it to start? (Y or N): "
read RESPONSE
case "${RESPONSE}" in
Y|y)
echo "Trying to SSH to ${IP} with a timeout of 5 seconds…"
ssh -tt -o ConnectTimeout=1 -i ~/Downloads/mmoldvan.pem ec2-user@"${IP}" $2
while [ $? -ne 0 ]; do
sleep 5
ssh -tt -o ConnectTimeout=1 -i ~/Downloads/mmoldvan.pem ec2-user@"${IP}" $2
done
esac
else
echo "Instance ${1} has a state of ${STATE}. Would you like to start it? (Y or N): "
read RESPONSE
case "${RESPONSE}" in
Y|y)
echo "Starting ${1}…"
ec2start $1
ec2ssh $1
;;
esac
fi
}
A somewhat useful use case:
Write a for loop to stop all EC2 instances:
for INSTANCE in $(ec2list); do
ec2stop "${INSTANCE}"
done