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

Commit

Permalink
parse YAML inventory files with ansible-inventory, refs fboender#154
Browse files Browse the repository at this point in the history
Signed-off-by: Arnold Bechtoldt <arnold.bechtoldt@inovex.de>
  • Loading branch information
arnisoph committed Sep 3, 2019
1 parent ebd960a commit deef955
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/ansiblecmdb/ansible.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit deef955

Please sign in to comment.