From e154cdc122416f1db731468053a1d5fc73ef35a7 Mon Sep 17 00:00:00 2001 From: Arnold Bechtoldt Date: Tue, 3 Sep 2019 16:35:13 +0200 Subject: [PATCH] parse YAML inventory files with ansible-inventory Signed-off-by: Arnold Bechtoldt --- src/ansiblecmdb/ansible.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/ansiblecmdb/ansible.py b/src/ansiblecmdb/ansible.py index f1c22d2..169903b 100644 --- a/src/ansiblecmdb/ansible.py +++ b/src/ansiblecmdb/ansible.py @@ -103,6 +103,11 @@ def _handle_inventory(self, inventory_path): # It's a file and it's executable. Handle as dynamic inventory script self.log.debug("{} is a executable. Handle as dynamic inventory script".format(inventory_path)) self._parse_dyn_inventory(inventory_path) + if os.path.isfile(inventory_path) and \ + (inventory_path.endswith('.yml') or + inventory_path.endswith('.yaml')): + self.log.debug("{} is a YAML inventory file. Parsing it with ansible-inventory".format(inventory_path)) + self._parse_ansible_inventory(inventory_path) elif os.path.isfile(inventory_path): # Static inventory hosts file self.log.debug("{} is a file. Handle as static inventory file".format(inventory_path)) @@ -324,6 +329,29 @@ def _parse_dyn_inventory(self, script): sys.stderr.write("Exception while executing dynamic inventory script '{0}':\n\n".format(script)) sys.stderr.write(str(err) + '\n') + def _parse_ansible_inventory(self, filename): + try: + proc = subprocess.Popen(["ansible-inventory", '-i', filename, '--list'], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + close_fds=True) + stdout, stderr = proc.communicate(input) + if proc.returncode != 0: + sys.stderr.write("ansible-inventory with inventory file '{0}' returned " + "exitcode {1}\n".format(filename, + proc.returncode)) + for line in stderr: + sys.stderr.write(line) + + dyninv_parser = parser.DynInvParser(stdout.decode('utf8')) + for hostname, key_values in dyninv_parser.hosts.items(): + self.update_host(hostname, key_values) + except OSError as err: + sys.stderr.write("Exception while executing ansible-inventory with inventory file '{0}':\n\n".format(filename)) + sys.stderr.write(str(err) + '\n') + + + def update_host(self, hostname, key_values, overwrite=True): """ Update a hosts information. This is called by various collectors such