From 5ad8f6b2d3165075504773805890cef5139a61b4 Mon Sep 17 00:00:00 2001 From: Christopher Hornberger Date: Thu, 22 Feb 2024 20:29:48 +0100 Subject: [PATCH] feat: make code more readable --- vagrant_inventory.py | 129 +++++++++++++++++++++++-------------------- 1 file changed, 69 insertions(+), 60 deletions(-) diff --git a/vagrant_inventory.py b/vagrant_inventory.py index 143b5bd..a999f86 100755 --- a/vagrant_inventory.py +++ b/vagrant_inventory.py @@ -6,20 +6,15 @@ machine name or - if set to default - the directory name of the Vagrantfile as ansible inventory hostname. -# Copyright (C) 2013 Mark Mandel -# 2015 Igor Khomyakov -# 2021 Christopher Hornberger github.com/chornberger-c2c -# -# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +Copyright (C) 2013 Mark Mandel + 2015 Igor Khomyakov + 2021 Christopher Hornberger github.com/chornberger-c2c + +GNU General Public License v3.0+ (see LICENSE.md or https://www.gnu.org/licenses/gpl-3.0.txt) """ from __future__ import (absolute_import, division, print_function) -# -# Thanks to the spacewalk.py inventory script for giving me the basic structure -# of this. -# - import sys import os.path import subprocess @@ -32,36 +27,73 @@ from ansible.module_utils._text import to_text from paramiko import SSHConfig -MetaClass = type +def main(): + """ + Thanks to the spacewalk.py inventory script for giving me the basic structure + of this. + """ -_GROUP = 'vagrant' # a default group -_ssh_to_ansible = [('user', 'ansible_user'), - ('hostname', 'ansible_host'), - ('identityfile', 'ansible_private_key_file'), - ('port', 'ansible_port')] + global MetaClass + MetaClass = type + + global _GROUP + _GROUP = 'vagrant' # a default group + + global _ssh_to_ansible + _ssh_to_ansible = [('user', 'ansible_user'), + ('hostname', 'ansible_host'), + ('identityfile', 'ansible_private_key_file'), + ('port', 'ansible_port')] + + parse_options() + process_options() + +def parse_options(): + """ + Parse command line options + """ -# Options -# ------------------------------ + parser = argparse.ArgumentParser(description="") + parser.add_argument('--list', default=False, dest="list", action="store_true", + help="Produce a JSON consumable grouping of Vagrant servers for Ansible") + parser.add_argument('--host', default=None, dest="host", + help="Generate additional host specific details for given host for Ansible") + global options + options = parser.parse_args() -parser = argparse.ArgumentParser(description="") -parser.add_argument('--list', default=False, dest="list", action="store_true", - help="Produce a JSON consumable grouping of Vagrant servers for Ansible") -parser.add_argument('--host', default=None, dest="host", - help="Generate additional host specific details for given host for Ansible") -options = parser.parse_args() + global mapping + mapping = {} -# -# helper functions -# -# get all the ssh configs for all boxes in an array of dictionaries. -# list all the running boxes +def process_options(): + """ + List out servers that vagrant has running or print host details + """ -mapping = {} + if options.list: + list_running_boxes() + ssh_config = get_ssh_config() + meta = defaultdict(dict) + + for host in ssh_config: + meta['hostvars'][host] = ssh_config[host] + + print(json.dumps({_GROUP: list(mapping.values()), '_meta': meta}, indent=4)) + sys.exit(0) + + elif options.host: + list_running_boxes() + host_id = list(mapping.keys())[list(mapping.values()).index(options.host)] + print(json.dumps(get_a_ssh_config(host_id,options.host), indent=4)) + sys.exit(0) + + else: + sys.exit(0) def list_running_boxes(): """ - list all running vagrant boxes + List all running vagrant boxes """ + output = to_text(subprocess.check_output(["vagrant", "global-status", "--prune"])).split('\n') for line in output: @@ -83,7 +115,7 @@ def list_running_boxes(): def get_ssh_config(): """ - returns the ssh config for a box + Returns the ssh config for a box """ return dict((v, get_a_ssh_config(k,v)) for k,v in mapping.items()) @@ -91,7 +123,9 @@ def get_ssh_config(): # get the ssh config for a single box def get_a_ssh_config(box_id,box_name): - """Gives back a map of all the machine's ssh configurations""" + """ + Gives back a map of all the machine's ssh configurations + """ output = to_text(subprocess.check_output(["vagrant", "ssh-config", box_id])) config = SSHConfig() @@ -112,30 +146,5 @@ def get_a_ssh_config(box_id,box_name): return dict((v, host_config[k]) for k, v in _ssh_to_ansible) - -# List out servers that vagrant has running -# ------------------------------ -if options.list: - list_running_boxes() - ssh_config = get_ssh_config() - meta = defaultdict(dict) - - for host in ssh_config: - meta['hostvars'][host] = ssh_config[host] - - print(json.dumps({_GROUP: list(mapping.values()), '_meta': meta}, indent=4)) - sys.exit(0) - -# Get out the host details -# ------------------------------ -elif options.host: - list_running_boxes() - host_id = list(mapping.keys())[list(mapping.values()).index(options.host)] - print(json.dumps(get_a_ssh_config(host_id,options.host), indent=4)) - sys.exit(0) - -# Print out help -# ------------------------------ -else: - parser.print_help() - sys.exit(0) +if __name__ == "__main__": + main() \ No newline at end of file