Skip to content

Instantly share code, notes, and snippets.

@xenithorb
Last active April 27, 2018 15:40
Show Gist options
  • Save xenithorb/c50fd8b22b0d0a852cc8dc9fbbd0a6c5 to your computer and use it in GitHub Desktop.
Save xenithorb/c50fd8b22b0d0a852cc8dc9fbbd0a6c5 to your computer and use it in GitHub Desktop.
Use ansible's inventory to ssh into hosts quickly, with bash completion!
curl https://gist.githubusercontent.com/xenithorb/c50fd8b22b0d0a852d4f08b40c2fccf/ansible-ssh.sh  >> ~/.bashrc
. ~/.bashrc # Or open a new shell

Then, move to a directory with an inventory defined in ansible.cfg (most projects will have you define that per-project)

Basically, ansible-inventory --list needs to output vars when you're in your playbook directory for this to work

If it does you can now:

$ ansible-ssh <tab>
$ ansible-ssh host-<tab>
host-1
host-2
host-3
host-4
$ ansible-ssh host-4<enter>
[foo@host-4]$ 
ansible-ssh_completion() {
local host_list=($( ansible-inventory --list | python3 -c 'import sys, json; a=json.load(sys.stdin); print("\n".join(a["_meta"]["hostvars"].keys()))' ))
if (( ${#COMP_WORDS[@]} < 3 )); then
local suggestions=($( compgen -W "${host_list[*]}" -- "${COMP_WORDS[1]}" ))
fi
if (( ${#suggestions[@]} > 1 )); then
for (( i=0; i<${#suggestions[@]}; i++ )); do
suggestions[i]=$( printf '%*s' "-$COLUMNS" "${suggestions[i]}" )
done
fi
COMPREPLY=( "${suggestions[@]}" )
}
ansible-ssh() {
local host=$1
shift
eval $(ansible-inventory --host "$host" \
| python -c "$( cat <<-EOF
import sys, subprocess, json
a=json.load(sys.stdin)
print( " ".join(["ssh", "-tt", "-P" + str(a["ansible_port"]), a["ansible_user"] + "@" + a["ansible_host"]]) )
EOF
)"
) "$@"
}
complete -F ansible-ssh_completion ansible-ssh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment