1#!/usr/bin/env python 2 3# This file is part of Ansible 4# 5# Ansible is free software: you can redistribute it and/or modify 6# it under the terms of the GNU General Public License as published by 7# the Free Software Foundation, either version 3 of the License, or 8# (at your option) any later version. 9# 10# Ansible is distributed in the hope that it will be useful, 11# but WITHOUT ANY WARRANTY; without even the implied warranty of 12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13# GNU General Public License for more details. 14# 15# You should have received a copy of the GNU General Public License 16# along with Ansible. If not, see <http://www.gnu.org/licenses/>. 17 18import json 19import os 20import requests 21import argparse 22 23RACKHD_URL = 'http://localhost:8080' 24 25 26class RackhdInventory(object): 27 def __init__(self, nodeids): 28 self._inventory = {} 29 for nodeid in nodeids: 30 self._load_inventory_data(nodeid) 31 inventory = {} 32 for (nodeid, info) in self._inventory.items(): 33 inventory[nodeid] = (self._format_output(nodeid, info)) 34 print(json.dumps(inventory)) 35 36 def _load_inventory_data(self, nodeid): 37 info = {} 38 info['ohai'] = RACKHD_URL + '/api/common/nodes/{0}/catalogs/ohai'.format(nodeid) 39 info['lookup'] = RACKHD_URL + '/api/common/lookups/?q={0}'.format(nodeid) 40 41 results = {} 42 for (key, url) in info.items(): 43 r = requests.get(url, verify=False) 44 results[key] = r.text 45 self._inventory[nodeid] = results 46 47 def _format_output(self, nodeid, info): 48 try: 49 node_info = json.loads(info['lookup']) 50 ipaddress = '' 51 if len(node_info) > 0: 52 ipaddress = node_info[0]['ipAddress'] 53 output = {'hosts': [ipaddress], 'vars': {}} 54 for (key, result) in info.items(): 55 output['vars'][key] = json.loads(result) 56 output['vars']['ansible_ssh_user'] = 'monorail' 57 except KeyError: 58 pass 59 return output 60 61 62def parse_args(): 63 parser = argparse.ArgumentParser() 64 parser.add_argument('--host') 65 parser.add_argument('--list', action='store_true') 66 return parser.parse_args() 67 68 69try: 70 # check if rackhd url(ie:10.1.1.45:8080) is specified in the environment 71 RACKHD_URL = 'http://' + str(os.environ['RACKHD_URL']) 72except Exception: 73 # use default values 74 pass 75 76# Use the nodeid specified in the environment to limit the data returned 77# or return data for all available nodes 78nodeids = [] 79 80if (parse_args().host): 81 try: 82 nodeids += parse_args().host.split(',') 83 RackhdInventory(nodeids) 84 except Exception: 85 pass 86if (parse_args().list): 87 try: 88 url = RACKHD_URL + '/api/common/nodes' 89 r = requests.get(url, verify=False) 90 data = json.loads(r.text) 91 for entry in data: 92 if entry['type'] == 'compute': 93 nodeids.append(entry['id']) 94 RackhdInventory(nodeids) 95 except Exception: 96 pass 97