Skip to content

Instantly share code, notes, and snippets.

@neerolyte
Last active November 16, 2016 23:24
Show Gist options
  • Save neerolyte/9343952 to your computer and use it in GitHub Desktop.
Save neerolyte/9343952 to your computer and use it in GitHub Desktop.
vssh - significantly faster ssh for vagrant
#!/bin/bash -e
# vssh - significantly faster Vagrant SSHing
# Usage: vssh [vagrant host] [regular ssh arguments]
# find the .vagrant directory scanning up from $PWD
find_vagrant_dir() {
cdir="$PWD"
while ! [[ -d "$cdir/.vagrant" ]] && [[ "$cdir" != "/" ]]; do
cdir="$(dirname "$cdir")"
done
echo "$cdir/.vagrant"
}
get_host_uuid() {
host="$1"
cat "$vagrant_dir/machines/$host/virtualbox/id"
}
cache_ssh_config() {
{
echo "ControlMaster auto"
echo "ControlPath $HOME/.ssh/master-%r@%h:%p"
echo "ControlPersist 120s"
vagrant ssh-config "$host"
} > "$ssh_config"
}
get_ssh_config_date() {
date +%s -r "$ssh_config"
}
get_vm_date_in_vbox_format() {
vm="$1"
uuid="$(get_host_uuid "$vm")"
# load the variable directly rather than parsing with "sed -r" so we can work on OS X too
. <(
VBoxManage showvminfo --machinereadable "$uuid" | grep ^VMStateChangeTime
)
echo "$VMStateChangeTime"
}
get_vm_date() {
vm="$1"
date +%s --date="$(get_vm_date_in_vbox_format "$vm")"
}
refresh_ssh_config_cache() {
if ! [[ -f "$ssh_config" ]] \
|| [[ "$(get_vm_date "$host")" -ge "$(get_ssh_config_date)" ]]; then
cache_ssh_config
fi
}
vagrant_dir="$(find_vagrant_dir)"
# extract host arg
host=default
if ! [[ -z "$1" ]] && [[ -d "$vagrant_dir"/machines/"$1" ]]; then
host="$1"
shift
fi
ssh_config="$vagrant_dir/ssh-config-$host"
refresh_ssh_config_cache
ssh -F "$ssh_config" "$host" "$@"
@neerolyte
Copy link
Author

This script was put together mainly as a PoC for hashicorp/vagrant#3057

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment