I use the following alias to quickly SSH into Compute Engine instances in Google Cloud.
It saves having to type out gcloud compute ssh <name> --zone <zone>
each time and will automatically connect to the most recently created and RUNNING
instance.
function gssh() {
readonly local name="$1"
local filter result instance_name zone
printf "🖥️ Connecting to instance: %s\\n\\n" "$name"
filter="(name:${name} AND status:RUNNING)"
result="$(gcloud compute instances list --sort-by=-createTime --format='value(name,zone)' --filter="$filter")"
instance_name="$(echo "$result" | awk 'NR==1 {print $1}')"
zone="$(echo "$result" | awk 'NR==1 {print $2}')"
if [ -n "$instance_name" ]; then
gcloud beta compute ssh "$name" --zone "$(basename "$zone")"
else
printf "❌ Instance not found\\n"
fi
}
Usage:
$ gssh my-server
🖥️ Connecting to instance: my-server
[email protected] ~ $
If an instance doesn’t exist or is unavailable (turned off, etc):
$ gssh nonexistent-server
🖥️ Connecting to instance: nonexistent-server
❌ Instance not found