Skip to content

Instantly share code, notes, and snippets.

@miquelbar
Last active October 21, 2020 15:09
Show Gist options
  • Save miquelbar/9af63f328d4f8541c58b049449f4c580 to your computer and use it in GitHub Desktop.
Save miquelbar/9af63f328d4f8541c58b049449f4c580 to your computer and use it in GitHub Desktop.
Gcloud ssh autocomplete
#!/bin/bash
export _SSH_COMPLETE_F_CACHE="/tmp/_ssh_complete"
export _SSH_COMPLETE_HOSTS=""
[[ ! -f "$_SSH_COMPLETE_F_CACHE" ]] && touch "$_SSH_COMPLETE_F_CACHE"
_ssh_complete() {
if [ -z "$_SSH_COMPLETE_HOSTS" ]; then
_SSH_COMPLETE_HOSTS="$(gcloud beta compute instances \
list --format='table(name,networkInterfaces[0].accessConfigs[0].natIP:label=EXTERNAL_IP)' \
| grep -v 'NAME' | awk '{ print $1 }')"
fi
local opts="$_SSH_COMPLETE_HOSTS"
local cur=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=($(compgen -W "$opts" -- "$cur"))
}
ssh_complete() {
local host="$1"
local ip_cached="$(grep -P "$host (.*)" $_SSH_COMPLETE_F_CACHE | wc -l)"
if [ $ip_cached -eq 0 ]; then
ip="$(gcloud beta compute instances list \
--format='table(name,networkInterfaces[0].accessConfigs[0].natIP:label=EXTERNAL_IP)' \
--filter=name=$host | grep -v 'NAME' | awk '{print $NF}')"
[[ -n "$ip" ]] && echo "$host $ip" > $_SSH_COMPLETE_F_CACHE
[[ -z "$ip" ]] && echo "Host $host not found" && return
else
ip="$(grep $host $_SSH_COMPLETE_F_CACHE | awk '{ print $NF }')"
fi;
echo "Connect to $host $ip"
ssh "$ip"
}
complete -F _ssh_complete ssh_complete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment