Created
August 2, 2015 23:57
-
-
Save carnesen/57e8794246ad0d8289de to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env python | |
import sys | |
import argparse | |
import ansible.constants as C | |
import ansible.inventory | |
import subprocess | |
def get_inventory(subset_pattern): | |
inventory = ansible.inventory.Inventory() | |
if subset_pattern: | |
inventory.subset(subset_pattern) | |
if len(inventory.list_hosts()) == 0: | |
print "Error: no hosts found" | |
exit(1) | |
return inventory | |
def show(subset_pattern): | |
inventory = get_inventory(subset_pattern) | |
print 'Hosts:' | |
for host in sorted([g for g in inventory.get_hosts()], key=lambda x: x.name): | |
hostvars = host.get_variables() | |
if 'ansible_ssh_port' in hostvars: | |
port_specifier = ':' + str(hostvars['ansible_ssh_port']) | |
else: | |
port_specifier = '' | |
print ' ' + hostvars['inventory_hostname'] + ' ' + hostvars['ansible_ssh_host'] + port_specifier + ' ' + ' '.join(hostvars['group_names']) | |
def ssh(subset_pattern): | |
inventory = get_inventory(subset_pattern) | |
ssh_host = inventory.get_hosts()[0] | |
ssh_args = ['ssh', '-i', C.DEFAULT_PRIVATE_KEY_FILE, | |
"{}@{}".format(C.DEFAULT_REMOTE_USER, ssh_host.vars['ansible_ssh_host'])] | |
if 'ansible_ssh_port' in ssh_host.vars: | |
ssh_args.append('-p') | |
ssh_args.append(str(ssh_host.vars['ansible_ssh_port'])) | |
print "+", " ".join(ssh_args) | |
subprocess.call(ssh_args) | |
def main(args): | |
parser = argparse.ArgumentParser( | |
description='A command-line tool') | |
parser.add_argument("action", help='action to be performed (default: show)', | |
default='show', nargs="?", choices=['show', 'ssh']) | |
parser.add_argument('-l', '--limit', dest='subset_pattern', | |
help='limit action to selected hosts') | |
parsed_args = parser.parse_args() | |
if parsed_args.action == "show": | |
show(parsed_args.subset_pattern) | |
if parsed_args.action == "ssh": | |
ssh(parsed_args.subset_pattern) | |
if __name__ == "__main__": | |
try: | |
sys.exit(main(sys.argv[1:])) | |
except KeyboardInterrupt, ke: | |
print "Error: Interrupted by user" | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment