override with v2 version

This commit is contained in:
doteast 2016-02-25 22:12:15 +00:00
parent b904e77026
commit 2ed3b026b9
2 changed files with 83 additions and 99 deletions

View file

@ -25,37 +25,51 @@ SOFTWARE."""
:contact: opensource@till.name :contact: opensource@till.name
:license: MIT :license: MIT
""" """
""" :changes: Ali AlKhalidi
:contact: doteast@fedoraproject.org
"""
import os import os
import sys
import copy
import itertools
from ansible import plugins
from ansible.errors import AnsibleOptionsError
from ansible.plugins.callback import CallbackBase
from ansible.plugins.callback import default
from ansible.cli.adhoc import AdHocCLI
ALIAS_PATH = '/srv/web/infra/hosts/{hostname}/host_aliases' ALIAS_PATH = '/srv/web/infra/hosts/{hostname}/host_aliases'
os.environ['ANSIBLE_HOST_KEY_CHECKING'] = 'False'
import ansible.runner
if __name__ == "__main__": class ResultAccumulator(CallbackBase):
runner = ansible.runner.Runner(module_name="setup") def __init__(self, *args, **kwargs):
results = runner.run() super(ResultAccumulator, self).__init__(*args, **kwargs)
self.unreachable = set()
self.host_status = {}
self.sshhostkeys = {}
sshhostkeys = {} def v2_runner_on_unreachable(self, result):
for (hostname, result) in results['contacted'].items(): self.unreachable.add(result._host.get_name())
facts = result["ansible_facts"]
key = "ssh-rsa {0}".format(facts["ansible_ssh_host_key_rsa_public"])
names = [hostname] def v2_runner_on_ok(self, result, *args, **kwargs):
ansible_fqdn = facts["ansible_fqdn"] facts = result._result['ansible_facts']
key = "ssh-rsa {0}".format(facts['ansible_ssh_host_key_rsa_public'])
names = [result._host.get_name()]
ansible_fqdn = facts['ansible_fqdn']
if ansible_fqdn not in names: if ansible_fqdn not in names:
names.append(ansible_fqdn) names.append(ansible_fqdn)
ansible_hostname = facts["ansible_hostname"] ansible_hostname = facts['ansible_hostname']
if ansible_hostname not in names: if ansible_hostname not in names:
if ansible_fqdn.find('.stg.') != -1 or hostname.find('.stg.') != -1: if ansible_fqdn.find('.stg.') != -1 or result._host.get_name().find('.stg.') != -1:
names.append(ansible_hostname+".stg") names.append(ansible_hostname+".stg")
else: else:
names.append(ansible_hostname) names.append(ansible_hostname)
try: try:
with open(ALIAS_PATH.format(hostname=hostname), with open(ALIAS_PATH.format(hostname=result._host.get_name()),
"rb") as alias_file: "rb") as alias_file:
aliases = [a.strip() for a in alias_file.readlines()] aliases = [a.strip() for a in alias_file.readlines()]
for alias in aliases: for alias in aliases:
@ -78,9 +92,23 @@ if __name__ == "__main__":
tunnel_addresses=facts["ansible_tun0"] tunnel_addresses=facts["ansible_tun0"]
names.append(tunnel_addresses['ipv4']['address']) names.append(tunnel_addresses['ipv4']['address'])
sshhostkeys[hostname] = {"key": key, self.sshhostkeys[result._host.get_name()] = {"key": key,
"names": ",".join(names)} "names": ",".join(names)}
for host in sorted(sshhostkeys.keys()): if __name__ == '__main__':
print "{names} {key} {comment}".format(comment=host, args = copy.copy(sys.argv)
**sshhostkeys[host]) args.extend(['-m', 'setup'])
cb = ResultAccumulator()
cli = AdHocCLI(copy.copy(args), callback=cb)
try:
cli.parse()
except AnsibleOptionsError:
if len(cli.args) != 1:
cli.args = copy.copy(args)
cli.args.append('all')
cli.parse()
cli.run()
for host in sorted(cb.sshhostkeys.items()):
print "{names} {key} {comment}".format(comment=host[0],**host[1])

View file

@ -1,92 +1,48 @@
#!/usr/bin/env python #!/usr/bin/python -tt
# Author: Toshio Kuratomi <toshio@fedoraproject.org>
# (c) 2012, Red Hat, Inc # Copyright: December, 2015
# Seth Vidal <skvidal at fedoraproject.org> # License: LGPLv3+
#
#
########################################################
#list to stdout vms on each virthost/libvirt-running box
#list to stderr hosts you could not contact
####
import sys import sys
import copy
import itertools
import ansible.runner from ansible import plugins
import ansible.constants as C from ansible.errors import AnsibleOptionsError
from ansible import utils from ansible.plugins.callback import CallbackBase
from ansible import callbacks from ansible.plugins.callback import default
import logging from ansible.cli.adhoc import AdHocCLI
logging.basicConfig()
######################################################## class ResultAccumulator(CallbackBase):
def __init__(self, *args, **kwargs):
super(ResultAccumulator, self).__init__(*args, **kwargs)
self.unreachable = set()
self.host_status = {}
def main(args): def v2_runner_on_unreachable(self, result):
self.unreachable.add(result._host.get_name())
# simple parser def v2_runner_on_ok(self, result, *args, **kwargs):
parser = utils.base_parser(constants=C, runas_opts=True, async_opts=False, for vm in (vm for vm in result._result.keys() if vm not in ('invocation', 'changed', '_ansible_no_log')):
output_opts=True, connect_opts=True, usage='list-vms-per-host [options]') self.host_status[(result._host.get_name(), vm)] = (result._result[vm]['state'], str(result._result[vm]['autostart']))
parser.add_option('--host', dest='hostlist', action='append',
help="hosts to contact, defaults to all in your inventory", default=[])
options, args = parser.parse_args(args)
options.module_name = 'virt'
options.module_args = 'command=info'
# no hosts specified? Run against all of them
if not options.hostlist:
options.pattern = 'all'
else:
options.pattern = ';'.join(options.hostlist)
# setup the cli call back so we can use the simple output handling
# our callbacks for easy terminal formatting
mycallback = callbacks.DefaultRunnerCallbacks()
mycallback.options = options
# if options.connection == 'paramiko':
# logging.basicConfig()
runner = ansible.runner.Runner(
module_name=options.module_name, module_path=options.module_path,
module_args=options.module_args,
remote_user=options.remote_user,
host_list=options.inventory, timeout=options.timeout,
forks=options.forks,
pattern=options.pattern,
callbacks=mycallback,
transport=options.connection
)
res = runner.run()
for hn in sorted(res['contacted']):
if 'failed' in res['contacted'][hn] and res['contacted'][hn]['failed']:
continue
for vm in sorted(res['contacted'][hn]):
info = res['contacted'][hn][vm]
if vm == 'Domain-0':
continue
elif type(info) != dict:
continue
elif 'maxMem' not in info:
continue
autostart = '?'
if 'autostart' in info:
autostart = info['autostart']
print '%s:%s:%s:%s' % (hn, vm, info['state'], autostart)
for hn in sorted(res['dark']):
print >> sys.stderr, hn
if __name__ == '__main__': if __name__ == '__main__':
args = copy.copy(sys.argv)
args.extend(['-m', 'virt', '-a', 'command=info'])
cb = ResultAccumulator()
cli = AdHocCLI(copy.copy(args), callback=cb)
try: try:
main(sys.argv) cli.parse()
except Exception, e: except AnsibleOptionsError:
# Generic handler for ansible specific errors if len(cli.args) != 1:
print "ERROR: %s" % str(e) cli.args = copy.copy(args)
sys.exit(1) cli.args.append('virtservers')
cli.parse()
cli.run()
for host in cb.unreachable:
sys.stderr.write('unreachable: %s\n' % host)
for host, status in sorted(cb.host_status.items()):
print(':'.join(itertools.chain(host, status)))