Skip to content

Instantly share code, notes, and snippets.

@olivertappin
Created February 25, 2019 13:36
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 olivertappin/574a410dc1cef1acdbcbc5ea3b843f86 to your computer and use it in GitHub Desktop.
Save olivertappin/574a410dc1cef1acdbcbc5ea3b843f86 to your computer and use it in GitHub Desktop.
Google Cloud helper functions to access instances from the command line
# SSH into an instance using the instance name (supports partial matching)
# Usage: gcessh <instance-name>
gcessh() { $(gcloud compute instances list --filter="name~'$1'" --sort-by name | tail -n +2 | head -1 | awk '{print "ssh "$1}' ) 2>/dev/null; };
# Describe an instance using the instance name (exact match only)
# Usage: gcedesc <instance-name>
gcedesc() { $(gcloud compute instances list | grep $1 | awk '{print "gcloud compute instances describe "$1" --zone "$2}'); };
# List all matching instances using a partially matched instance name (perfect for listing nodes from an instance group)
# Usage: gcelsn <instance-name>
gcelsn() { gcloud compute instances list --filter="name~'$1'" --sort-by name; };
# List all matching instances using zone names (exact match only)
# Usage: gcelsz <zone-name>[,<zone-name> ...]
gcelsz() { gcloud compute instances list --filter="zone:($1)" --sort-by name; };
# Execute a command against each matching instance using the instance name (supports partial matching)
# Example: gcesshcmd <instance-name> '<command>'
gcesshcmd() { OLDIFS=$IFS; IFS=$'\n'; ARG1=$1; ARG2=$2; for I in $(gcloud compute instances list --filter="name~'$1'" --sort-by name | tail -n +2 | awk '{print "echo \"---[ "$1" ]---\"; ssh "$1" '\'"$ARG2"\'' 2>/dev/null"}'); do false && echo "$I"; true && eval "$I"; echo ""; done; IFS=$OLDIFS; };
echo 'Available commands:'
echo 'gcessh <instance-name> (ssh into to an instance, using instance name, or regex)'
echo 'gcedesc <instance-name> (describe an instance, using instance name)'
echo 'gcelsn <instance-name> (list instances, using instance name, or regex)'
echo 'gcelsz <zone-name> (list instances, using zone name)'
echo 'gcesshcmd <instance-name> <command> (execute a command on matching instances, using instance name, or regex)'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment