Debian Codegraph @

bin/ansible-inventory

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Copyright: (c) 2017, Brian Coca <[email protected]>
3 # Copyright: (c) 2018, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # PYTHON_ARGCOMPLETE_OK
6
7 from __future__ import annotations
8
9 # ansible.cli needs to be imported first, to ensure the source bin/* scripts run that code first
10 from ansible.cli import CLI
11
12 import json
13 import sys
14 import typing as t
15
16 import argparse
17
18 from ansible import constants as C
19 from ansible import context
20 from ansible.cli.arguments import option_helpers as opt_help
21 from ansible.errors import AnsibleError, AnsibleOptionsError, AnsibleRuntimeError
22 from ansible.module_utils.common.text.converters import to_bytes, to_text
23 from ansible._internal._json._profiles import _inventory_legacy
24 from ansible.utils.vars import combine_vars
25 from ansible.utils.display import Display
26 from ansible.vars.plugins import get_vars_from_inventory_sources, get_vars_from_path
27
28 display = Display()
29
30
31 class InventoryCLI(CLI):
32 """ used to display or dump the configured inventory as Ansible sees it """
33
34 name = 'ansible-inventory'
35
36 ARGUMENTS = {'group': 'The name of a group in the inventory, relevant when using --graph', }
37
38 def __init__(self, args):
39
40 super(InventoryCLI, self).__init__(args)
41 self.vm = None
42 self.loader = None
43 self.inventory = None
44
45 def init_parser(self):
46 super(InventoryCLI, self).init_parser(
47 desc='Show Ansible inventory information, by default it uses the inventory script JSON format')
48
49 opt_help.add_inventory_options(self.parser)
50 opt_help.add_vault_options(self.parser)
51 opt_help.add_basedir_options(self.parser)
52 opt_help.add_runtask_options(self.parser)
53
54 # remove unused default options
55 self.parser.add_argument('--list-hosts', help=argparse.SUPPRESS, action=opt_help.UnrecognizedArgument)
56
57 self.parser.add_argument('args', metavar='group', nargs='?', help='The name of a group in the inventory, relevant when using --graph')
58
59 # Actions
60 action_group = self.parser.add_argument_group("Actions", "One of following must be used on invocation, ONLY ONE!")
61 action_group.add_argument("--list", action="store_true", default=False, dest='list', help='Output all hosts info, works as inventory script')
62 action_group.add_argument("--host", action="store", default=None, dest='host',
63 help='Output specific host info, works as inventory script. It will ignore limit')
64 action_group.add_argument("--graph", action="store_true", default=False, dest='graph',
65 help='create inventory graph, if supplying pattern it must be a valid group name. It will ignore limit')
66 self.parser.add_argument_group(action_group)
67
68 # graph
69 self.parser.add_argument("-y", "--yaml", action="store_true", default=False, dest='yaml',
70 help='Use YAML format instead of default JSON, ignored for --graph')
71 self.parser.add_argument('--toml', action='store_true', default=False, dest='toml',
72 help='Use TOML format instead of default JSON, ignored for --graph')
73 self.parser.add_argument("--vars", action="store_true", default=False, dest='show_vars',
74 help='Add vars to graph display, ignored unless used with --graph')
75
76 # list
77 self.parser.add_argument("--export", action="store_true", default=C.INVENTORY_EXPORT, dest='export',
78 help="When doing --list, represent in a way that is optimized for export,"
79 "not as an accurate representation of how Ansible has processed it")
80 self.parser.add_argument('--output', default=None, dest='output_file',
81 help="When doing --list, send the inventory to a file instead of to the screen")
82 # self.parser.add_argument("--ignore-vars-plugins", action="store_true", default=False, dest='ignore_vars_plugins',
83 # help="When doing --list, skip vars data from vars plugins, by default, this would include group_vars/ and host_vars/")
84
85 def post_process_args(self, options):
86 options = super(InventoryCLI, self).post_process_args(options)
87
88 display.verbosity = options.verbosity
89 self.validate_conflicts(options)
90
91 # there can be only one! and, at least, one!
92 used = 0
93 for opt in (options.list, options.host, options.graph):
94 if opt:
95 used += 1
96 if used == 0:
97 raise AnsibleOptionsError("No action selected, at least one of --host, --graph or --list needs to be specified.")
98 elif used > 1:
99 raise AnsibleOptionsError("Conflicting options used, only one of --host, --graph or --list can be used at the same time.")
100
101 # set host pattern to default if not supplied
102 if options.args:
103 options.pattern = options.args
104 else:
105 options.pattern = 'all'
106
107 return options
108
109 def run(self):
110
111 super(InventoryCLI, self).run()
112
113 # Initialize needed objects
114 self.loader, self.inventory, self.vm = self._play_prereqs()
115
116 results = None
117 if context.CLIARGS['host']:
118 hosts = self.inventory.get_hosts(context.CLIARGS['host'])
119 if len(hosts) != 1:
120 raise AnsibleOptionsError("You must pass a single valid host to --host parameter")
121
122 myvars = self._get_host_variables(host=hosts[0])
123
124 # FIXME: should we template first?
125 results = self.dump(myvars)
126
127 else:
128 if context.CLIARGS['subset']:
129 # not doing single host, set limit in general if given
130 self.inventory.subset(context.CLIARGS['subset'])
131
132 if context.CLIARGS['graph']:
133 results = self.inventory_graph()
134 elif context.CLIARGS['list']:
135 top = self._get_group('all')
136 if context.CLIARGS['yaml']:
137 results = self.yaml_inventory(top)
138 elif context.CLIARGS['toml']:
139 results = self.toml_inventory(top)
140 else:
141 results = self.json_inventory(top)
142 results = self.dump(results)
143
144 if results:
145 outfile = context.CLIARGS['output_file']
146 if outfile is None:
147 # FIXME: pager?
148 display.display(results)
149 else:
150 try:
151 with open(to_bytes(outfile), 'wb') as f:
152 f.write(to_bytes(results))
153 except OSError as ex:
154 raise AnsibleError(f'Unable to write to destination file {outfile!r}.') from ex
155 sys.exit(0)
156
157 sys.exit(1)
158
159 @staticmethod
160 def dump(stuff):
161 if context.CLIARGS['yaml']:
162 import yaml
163
164 from ansible.parsing.yaml.dumper import AnsibleDumper
165
166 results = to_text(yaml.dump(stuff, Dumper=AnsibleDumper, default_flow_style=False, allow_unicode=True))
167 elif context.CLIARGS['toml']:
168 results = toml_dumps(stuff)
169 else:
170 results = json.dumps(stuff, cls=_inventory_legacy.Encoder, sort_keys=True, indent=4)
171
172 return results
173
174 def _get_group_variables(self, group):
175
176 # get info from inventory source
177 res = group.get_vars()
178
179 # Always load vars plugins
180 res = combine_vars(res, get_vars_from_inventory_sources(self.loader, self.inventory._sources, [group], 'all'))
181 if context.CLIARGS['basedir']:
182 res = combine_vars(res, get_vars_from_path(self.loader, context.CLIARGS['basedir'], [group], 'all'))
183
184 if group.priority != 1:
185 res['ansible_group_priority'] = group.priority
186
187 return self._remove_internal(res)
188
189 def _get_host_variables(self, host):
190
191 if context.CLIARGS['export']:
192 # only get vars defined directly host
193 hostvars = host.get_vars()
194
195 # Always load vars plugins
196 hostvars = combine_vars(hostvars, get_vars_from_inventory_sources(self.loader, self.inventory._sources, [host], 'all'))
197 if context.CLIARGS['basedir']:
198 hostvars = combine_vars(hostvars, get_vars_from_path(self.loader, context.CLIARGS['basedir'], [host], 'all'))
199 else:
200 # get all vars flattened by host, but skip magic hostvars
201 hostvars = self.vm.get_vars(host=host, include_hostvars=False, stage='all')
202
203 return self._remove_internal(hostvars)
204
205 def _get_group(self, gname):
206 group = self.inventory.groups.get(gname)
207 return group
208
209 @staticmethod
210 def _remove_internal(dump):
211
212 for internal in C.INTERNAL_STATIC_VARS:
213 if internal in dump:
214 del dump[internal]
215
216 return dump
217
218 @staticmethod
219 def _remove_empty_keys(dump):
220 # remove empty keys
221 for x in ('hosts', 'vars', 'children'):
222 if x in dump and not dump[x]:
223 del dump[x]
224
225 @staticmethod
226 def _show_vars(dump, depth):
227 result = []
228 for (name, val) in sorted(dump.items()):
229 result.append(InventoryCLI._graph_name('{%s = %s}' % (name, val), depth))
230 return result
231
232 @staticmethod
233 def _graph_name(name, depth=0):
234 if depth:
235 name = " |" * (depth) + "--%s" % name
236 return name
237
238 def _graph_group(self, group, depth=0):
239
240 result = [self._graph_name('@%s:' % group.name, depth)]
241 depth = depth + 1
242 for kid in group.child_groups:
243 result.extend(self._graph_group(kid, depth))
244
245 if group.name != 'all':
246 for host in group.hosts:
247 result.append(self._graph_name(host.name, depth))
248 if context.CLIARGS['show_vars']:
249 result.extend(self._show_vars(self._get_host_variables(host), depth + 1))
250
251 if context.CLIARGS['show_vars']:
252 result.extend(self._show_vars(self._get_group_variables(group), depth))
253
254 return result
255
256 def inventory_graph(self):
257
258 start_at = self._get_group(context.CLIARGS['pattern'])
259 if start_at:
260 return '\n'.join(self._graph_group(start_at))
261 else:
262 raise AnsibleOptionsError("Pattern must be valid group name when using --graph")
263
264 def json_inventory(self, top):
265
266 seen_groups = set()
267
268 def format_group(group, available_hosts):
269 results = {}
270 results[group.name] = {}
271 if group.name != 'all':
272 results[group.name]['hosts'] = [h.name for h in group.hosts if h.name in available_hosts]
273 results[group.name]['children'] = []
274 for subgroup in group.child_groups:
275 results[group.name]['children'].append(subgroup.name)
276 if subgroup.name not in seen_groups:
277 results.update(format_group(subgroup, available_hosts))
278 seen_groups.add(subgroup.name)
279 if context.CLIARGS['export']:
280 results[group.name]['vars'] = self._get_group_variables(group)
281
282 self._remove_empty_keys(results[group.name])
283 # remove empty groups
284 if not results[group.name]:
285 del results[group.name]
286
287 return results
288
289 hosts = self.inventory.get_hosts(top.name)
290 results = format_group(top, frozenset(h.name for h in hosts))
291
292 # populate meta
293 results['_meta'] = {
294 'hostvars': {},
295 'profile': _inventory_legacy.Encoder.profile_name,
296 }
297
298 for host in hosts:
299 hvars = self._get_host_variables(host)
300 if hvars:
301 results['_meta']['hostvars'][host.name] = hvars
302
303 return results
304
305 def yaml_inventory(self, top):
306
307 seen_hosts = set()
308 seen_groups = set()
309
310 def format_group(group, available_hosts):
311 results = {}
312
313 # initialize group + vars
314 results[group.name] = {}
315
316 # subgroups
317 results[group.name]['children'] = {}
318 for subgroup in group.child_groups:
319 if subgroup.name != 'all':
320 if subgroup.name in seen_groups:
321 results[group.name]['children'].update({subgroup.name: {}})
322 else:
323 results[group.name]['children'].update(format_group(subgroup, available_hosts))
324 seen_groups.add(subgroup.name)
325
326 # hosts for group
327 results[group.name]['hosts'] = {}
328 if group.name != 'all':
329 for h in group.hosts:
330 if h.name not in available_hosts:
331 continue # observe limit
332 myvars = {}
333 if h.name not in seen_hosts: # avoid defining host vars more than once
334 seen_hosts.add(h.name)
335 myvars = self._get_host_variables(host=h)
336 results[group.name]['hosts'][h.name] = myvars
337
338 if context.CLIARGS['export']:
339 gvars = self._get_group_variables(group)
340 if gvars:
341 results[group.name]['vars'] = gvars
342
343 self._remove_empty_keys(results[group.name])
344 # remove empty groups
345 if not results[group.name]:
346 del results[group.name]
347
348 return results
349
350 available_hosts = frozenset(h.name for h in self.inventory.get_hosts(top.name))
351 return format_group(top, available_hosts)
352
353 def toml_inventory(self, top):
354 seen_hosts = set()
355 seen_hosts = set()
356 has_ungrouped = bool(next(g.hosts for g in top.child_groups if g.name == 'ungrouped'))
357
358 def format_group(group, available_hosts):
359 results = {}
360 results[group.name] = {}
361
362 results[group.name]['children'] = []
363 for subgroup in group.child_groups:
364 if subgroup.name == 'ungrouped' and not has_ungrouped:
365 continue
366 if group.name != 'all':
367 results[group.name]['children'].append(subgroup.name)
368 results.update(format_group(subgroup, available_hosts))
369
370 if group.name != 'all':
371 for host in group.hosts:
372 if host.name not in available_hosts:
373 continue
374 if host.name not in seen_hosts:
375 seen_hosts.add(host.name)
376 host_vars = self._get_host_variables(host=host)
377 else:
378 host_vars = {}
379 try:
380 results[group.name]['hosts'][host.name] = host_vars
381 except KeyError:
382 results[group.name]['hosts'] = {host.name: host_vars}
383
384 if context.CLIARGS['export']:
385 results[group.name]['vars'] = self._get_group_variables(group)
386
387 self._remove_empty_keys(results[group.name])
388 # remove empty groups
389 if not results[group.name]:
390 del results[group.name]
391
392 return results
393
394 available_hosts = frozenset(h.name for h in self.inventory.get_hosts(top.name))
395 results = format_group(top, available_hosts)
396
397 return results
398
399
400 def toml_dumps(data: t.Any) -> str:
401 try:
402 from tomli_w import dumps as _tomli_w_dumps
403 except ImportError:
404 pass
405 else:
406 return _tomli_w_dumps(data)
407
408 raise AnsibleRuntimeError('The Python library "tomli-w" is required when using the TOML output format.')
409
410
411 def main(args=None):
412 InventoryCLI.cli_executor(args)
413
414
415 if __name__ == '__main__':
416 main()