1#!/usr/bin/env python
2#
3# (c) 2018, Red Hat, Inc.
4#
5# This file is part of Ansible
6#
7# Ansible is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# Ansible is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
19#
20import os
21import sys
22import json
23import argparse
24
25from ansible.parsing.dataloader import DataLoader
26from ansible.module_utils.six import iteritems
27from ansible.module_utils._text import to_text
28from ansible.module_utils.net_tools.nios.api import WapiInventory
29from ansible.module_utils.net_tools.nios.api import normalize_extattrs, flatten_extattrs
30
31
32CONFIG_FILES = [
33    '/usr/local/etc/ansible/infoblox.yaml',
34    '/usr/local/etc/ansible/infoblox.yml'
35]
36
37
38def parse_args():
39    parser = argparse.ArgumentParser()
40
41    parser.add_argument('--list', action='store_true',
42                        help='List host records from NIOS for use in Ansible')
43
44    parser.add_argument('--host',
45                        help='List meta data about single host (not used)')
46
47    return parser.parse_args()
48
49
50def main():
51    args = parse_args()
52
53    for config_file in CONFIG_FILES:
54        if os.path.exists(config_file):
55            break
56    else:
57        sys.stdout.write('unable to locate config file at /usr/local/etc/ansible/infoblox.yaml\n')
58        sys.exit(-1)
59
60    try:
61        loader = DataLoader()
62        config = loader.load_from_file(config_file)
63        provider = config.get('provider') or {}
64        wapi = WapiInventory(provider)
65    except Exception as exc:
66        sys.stdout.write(to_text(exc))
67        sys.exit(-1)
68
69    if args.host:
70        host_filter = {'name': args.host}
71    else:
72        host_filter = {}
73
74    config_filters = config.get('filters')
75
76    if config_filters.get('view') is not None:
77        host_filter['view'] = config_filters['view']
78
79    if config_filters.get('extattrs'):
80        extattrs = normalize_extattrs(config_filters['extattrs'])
81    else:
82        extattrs = {}
83
84    hostvars = {}
85    inventory = {
86        '_meta': {
87            'hostvars': hostvars
88        }
89    }
90
91    return_fields = ['name', 'view', 'extattrs', 'ipv4addrs']
92
93    hosts = wapi.get_object('record:host',
94                            host_filter,
95                            extattrs=extattrs,
96                            return_fields=return_fields)
97
98    if hosts:
99        for item in hosts:
100            view = item['view']
101            name = item['name']
102
103            if view not in inventory:
104                inventory[view] = {'hosts': []}
105
106            inventory[view]['hosts'].append(name)
107
108            hostvars[name] = {
109                'view': view
110            }
111
112            if item.get('extattrs'):
113                for key, value in iteritems(flatten_extattrs(item['extattrs'])):
114                    if key.startswith('ansible_'):
115                        hostvars[name][key] = value
116                    else:
117                        if 'extattrs' not in hostvars[name]:
118                            hostvars[name]['extattrs'] = {}
119                        hostvars[name]['extattrs'][key] = value
120
121    sys.stdout.write(json.dumps(inventory, indent=4))
122    sys.exit(0)
123
124
125if __name__ == '__main__':
126    main()
127