Skip to content

Instantly share code, notes, and snippets.

@mfurlend
Created January 16, 2019 14:43
Show Gist options
  • Save mfurlend/8ea59afc30e06a1a344d0543c65ea542 to your computer and use it in GitHub Desktop.
Save mfurlend/8ea59afc30e06a1a344d0543c65ea542 to your computer and use it in GitHub Desktop.
Fast google cloud VM ssh sessions
gcp () {
local inp1 inp2
inp1=$1
inp2=$2
DEFAULT_USER=SOME_USER
if (( ! $# ))
then
inp1="-h"
fi
if [[ $inp1 == "-h" || $inp1 == "--help" ]]
then
echo "$0 - google compute connect\n"
echo "usage: $0 -h"
echo "usage: $0 -l"
echo "usage: $0 -c default\n\nOptions:"
echo "\t-h, --help\t\t\t display help message and exit"
echo "\t-l, --list\t\t\t list instances"
echo "\t-c, --connect=user@name\t\t ssh to instance"
return 1
elif [[ $inp1 == "-l" || $inp1 == "--list" ]]
then
VM_USER=""
VM_INSTANCE="${inp2#*@}"
FILTER=""
if [[ $inp2 != "" ]]
then
read -r -d '' FILTER <<EOF
--filter="name=${VM_INSTANCE}"
EOF
VM_USER="${inp2%@*}"
VM_INSTANCE="${inp2#*@}"
fi
eval gcloud compute instances list $FILTER
elif [[ ( $inp1 == "-c" || $inp1 == "--connect" ) && $inp2 != "" ]]
then
VM_USER="${inp2%@*}"
VM_INSTANCE="${inp2#*@}"
FILTER=""
read -r -d '' FILTER <<EOF
--filter="name=${VM_INSTANCE}"
EOF
OUTPUT=$(eval gcloud compute instances list $FILTER)
if [[ $(echo $OUTPUT|grep -c '.') > 1 ]]
then
IP=$(echo $OUTPUT | tail -n 1 | awk '{print $5}')
echo $3
echo "Connecting to $VM_INSTANCE ($IP)..."
sleep 1
if [[ $VM_USER != $VM_INSTANCE ]]
then
ssh ${VM_USER}@${IP} || gcloud compute ssh ${VM_USER}@${VM_INSTANCE}
else
ssh weatherbell@${IP} || gcloud compute ssh ${DEFAULT_USER}@${VM_INSTANCE}
fi
fi
else
echo "idk wtf"
fi
}
gcp is /usr/local/bin/gcp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment