Skip to content

Instantly share code, notes, and snippets.

@abourget
Created November 30, 2012 16:43
Show Gist options
  • Save abourget/4176887 to your computer and use it in GitHub Desktop.
Save abourget/4176887 to your computer and use it in GitHub Desktop.
Ansible helper to connect to remote nodes via ssh, using the Ansible inventory
#!/usr/bin/env python
#
# This is a script we use at Tenscores, and it is specific only in the sense that we use IP addresses
# and use the variable `hostname` to find the correct nodes. Also, it connect to user `ubuntu` by
# default.. that could be checked up in the vars too.
#
# Our hosts file looks like:
#
#[appservers]
#1.2.3.4 hostname=app001
#2.3.4.5 hostname=app002
#3.4.5.6 hostname=app003
#4.5.6.7 hostname=app004
#
"""This script serves to easily connect to hosts, as defined in the
ansible hosts files, without setting up the .ssh/config file, and
changing it all the time, when hosts change.
"""
import sys
import subprocess
import shlex
from argparse import ArgumentParser
import ansible.playbook
from ansible import callbacks
from ansible import utils
def main():
args = parse_args()
stats = callbacks.AggregateStats()
pb = ansible.playbook.PlayBook(
playbook=args.playbook,
callbacks=[],
runner_callbacks=[],
stats=stats,
)
host_list = []
for host_addr in pb.inventory.list_hosts():
host = pb.inventory.get_host(host_addr)
# You might want to alter this line according to your needs:
if host.vars.get('hostname') in args.hostname:
host_list.append(host_addr)
num_hosts = len(host_list)
if not num_hosts:
print "No host found!"
return
elif num_hosts == 1:
cmd = ["ssh", "ubuntu@{0}".format(host_list[0])]
if args.cmd:
cmd.insert(1, '-t') # make a tty buddy :)
cmd += [args.cmd]
else:
# Multi SSH
cmd = ["mssh"]
cmd += ["ubuntu@%s" % h for h in host_list]
if args.cmd:
print "Sorry, can't execute many commands in parallel with `mssh`, why don't you try `ansible` for that type of stuff?"
sys.exit(1)
#sys.exit(0)
cmdline = subprocess.list2cmdline(cmd)
print "Command:", cmdline
p = subprocess.Popen(cmdline, shell=True)
p.communicate()
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument('playbook', help='Playbook .yml file')
parser.add_argument('hostname', help='Name of the `hostname` as " \
"specified in hosts file',
nargs="+")
parser.add_argument('--cmd', help="If you want to execute a " \
"command and exit, pass a command here",
default=None)
return parser.parse_args()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment