-
-
Save hugoeanogueira/7b86d12c80ea98adccee42d9ac1296ae to your computer and use it in GitHub Desktop.
Gcloud ssh autocomplete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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