1#!/usr/local/bin/python3.8 2 3# (c) 2014, Jonathan Lestrelin <jonathan.lestrelin@gmail.com> 4# 5# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) 6 7from __future__ import (absolute_import, division, print_function) 8__metaclass__ = type 9 10""" 11Nagios NDO external inventory script. 12======================================== 13 14Returns hosts and hostgroups from Nagios NDO. 15 16Configuration is read from `nagios_ndo.ini`. 17""" 18 19import os 20import argparse 21import sys 22from ansible.module_utils.six.moves import configparser 23import json 24 25try: 26 from sqlalchemy import text 27 from sqlalchemy.engine import create_engine 28except ImportError: 29 sys.exit("Error: SQLAlchemy is needed. Try something like: pip install sqlalchemy") 30 31 32class NagiosNDOInventory(object): 33 34 def read_settings(self): 35 config = configparser.SafeConfigParser() 36 config.read(os.path.dirname(os.path.realpath(__file__)) + '/nagios_ndo.ini') 37 if config.has_option('ndo', 'database_uri'): 38 self.ndo_database_uri = config.get('ndo', 'database_uri') 39 40 def read_cli(self): 41 parser = argparse.ArgumentParser() 42 parser.add_argument('--host', nargs=1) 43 parser.add_argument('--list', action='store_true') 44 self.options = parser.parse_args() 45 46 def get_hosts(self): 47 engine = create_engine(self.ndo_database_uri) 48 connection = engine.connect() 49 select_hosts = text("SELECT display_name \ 50 FROM nagios_hosts") 51 select_hostgroups = text("SELECT alias \ 52 FROM nagios_hostgroups") 53 select_hostgroup_hosts = text("SELECT h.display_name \ 54 FROM nagios_hostgroup_members hgm, nagios_hosts h, nagios_hostgroups hg \ 55 WHERE hgm.hostgroup_id = hg.hostgroup_id \ 56 AND hgm.host_object_id = h.host_object_id \ 57 AND hg.alias =:hostgroup_alias") 58 59 hosts = connection.execute(select_hosts) 60 self.result['all']['hosts'] = [host['display_name'] for host in hosts] 61 62 for hostgroup in connection.execute(select_hostgroups): 63 hostgroup_alias = hostgroup['alias'] 64 self.result[hostgroup_alias] = {} 65 hosts = connection.execute(select_hostgroup_hosts, hostgroup_alias=hostgroup_alias) 66 self.result[hostgroup_alias]['hosts'] = [host['display_name'] for host in hosts] 67 68 def __init__(self): 69 70 self.defaultgroup = 'group_all' 71 self.ndo_database_uri = None 72 self.options = None 73 74 self.read_settings() 75 self.read_cli() 76 77 self.result = {} 78 self.result['all'] = {} 79 self.result['all']['hosts'] = [] 80 self.result['_meta'] = {} 81 self.result['_meta']['hostvars'] = {} 82 83 if self.ndo_database_uri: 84 self.get_hosts() 85 if self.options.host: 86 print(json.dumps({})) 87 elif self.options.list: 88 print(json.dumps(self.result)) 89 else: 90 sys.exit("usage: --list or --host HOSTNAME") 91 else: 92 sys.exit("Error: Database configuration is missing. See nagios_ndo.ini.") 93 94 95NagiosNDOInventory() 96