Skip to content

Instantly share code, notes, and snippets.

@joergrathlev
Created February 24, 2015 14:50
Show Gist options
  • Save joergrathlev/a697b7d74de8a404e81a to your computer and use it in GitHub Desktop.
Save joergrathlev/a697b7d74de8a404e81a to your computer and use it in GitHub Desktop.
Convenience Bash function to connect to a server by its Ansible name
function ssha () {
if [ $# -eq 0 ]
then
echo "Usage: ssha <ansible-hostname> [ssh arguments]" >&2
return 1
fi
local inventory=/path/to/your/inventory # CHANGE THIS LINE
local ansible_name="$1"
shift
local host=$(ansible -i "$inventory" --list-hosts "$ansible_name" | head -n 1)
if [ -z "$host" ]
then
return 1
else
# Arghh, leading whitespace in Ansible's output
host="${host#"${host%%[![:space:]]*}"}"
ssh "$host" "$@"
fi
}
@markus-s24
Copy link

Better use ansible configuration instead of inventory file, because there can be more than one inventory file:

function ssha () {
    if [ $# -eq 0 ]
    then
        echo "Usage: ssha <ansible-hostname> [ssh arguments]" >&2
        return 1
    fi

    local ansible_dir=~/projects/ops-hosting-cm # CHANGE THIS LINE
    local ansible_name="$1"
    shift
    local host=$(cd "$ansible_dir" && ANSIBLE_CONFIG="$ansible_dir/ansible.cfg" ansible --list-hosts "$ansible_name" | head -n 1)
    if [ -z "$host" ]
    then
        return 1
    else
        # Arghh, leading whitespace in Ansible's output
        host="${host#"${host%%[![:space:]]*}"}"
        ssh "$host" "$@"
    fi
}

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