Skip to content
This repository was archived by the owner on Dec 3, 2020. It is now read-only.

Commit deef955

Browse files
committed
parse YAML inventory files with ansible-inventory, refs fboender#154
Signed-off-by: Arnold Bechtoldt <[email protected]>
1 parent ebd960a commit deef955

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/ansiblecmdb/ansible.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,11 @@ def _handle_inventory(self, inventory_path):
103103
# It's a file and it's executable. Handle as dynamic inventory script
104104
self.log.debug("{} is a executable. Handle as dynamic inventory script".format(inventory_path))
105105
self._parse_dyn_inventory(inventory_path)
106+
if os.path.isfile(inventory_path) and \
107+
(inventory_path.endswith('.yml') or
108+
inventory_path.endswith('.yaml')):
109+
self.log.debug("{} is a YAML inventory file. Parsing it with ansible-inventory".format(inventory_path))
110+
self._parse_ansible_inventory(inventory_path)
106111
elif os.path.isfile(inventory_path):
107112
# Static inventory hosts file
108113
self.log.debug("{} is a file. Handle as static inventory file".format(inventory_path))
@@ -324,6 +329,29 @@ def _parse_dyn_inventory(self, script):
324329
sys.stderr.write("Exception while executing dynamic inventory script '{0}':\n\n".format(script))
325330
sys.stderr.write(str(err) + '\n')
326331

332+
def _parse_ansible_inventory(self, filename):
333+
try:
334+
proc = subprocess.Popen(["ansible-inventory", '-i', filename, '--list'],
335+
stdout=subprocess.PIPE,
336+
stderr=subprocess.PIPE,
337+
close_fds=True)
338+
stdout, stderr = proc.communicate(input)
339+
if proc.returncode != 0:
340+
sys.stderr.write("ansible-inventory with inventory file '{0}' returned "
341+
"exitcode {1}\n".format(filename,
342+
proc.returncode))
343+
for line in stderr:
344+
sys.stderr.write(line)
345+
346+
dyninv_parser = parser.DynInvParser(stdout.decode('utf8'))
347+
for hostname, key_values in dyninv_parser.hosts.items():
348+
self.update_host(hostname, key_values)
349+
except OSError as err:
350+
sys.stderr.write("Exception while executing ansible-inventory with inventory file '{0}':\n\n".format(filename))
351+
sys.stderr.write(str(err) + '\n')
352+
353+
354+
327355
def update_host(self, hostname, key_values, overwrite=True):
328356
"""
329357
Update a hosts information. This is called by various collectors such

0 commit comments

Comments
 (0)