Debian Codegraph @

lib/ansible/plugins/inventory/script.py

raw ◀ ▶
1 Debian patch touch this file
1 # Copyright (c) 2012-2014, Michael DeHaan <[email protected]>
2 # Copyright (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7 DOCUMENTATION = '''
8 name: script
9 version_added: "2.4"
10 short_description: Executes an inventory script that returns JSON
11 options:
12 always_show_stderr:
13 description: Toggle display of stderr even when script was successful
14 version_added: "2.5.1"
15 default: True
16 type: boolean
17 ini:
18 - section: inventory_plugin_script
19 key: always_show_stderr
20 env:
21 - name: ANSIBLE_INVENTORY_PLUGIN_SCRIPT_STDERR
22 description:
23 - The source provided must be an executable that returns Ansible inventory JSON
24 - The source must accept C(--list) and C(--host <hostname>) as arguments.
25 C(--host) will only be used if no C(_meta) key is present.
26 This is a performance optimization as the script would be called one additional time per host otherwise.
27 notes:
28 - Enabled in configuration by default.
29 - The plugin does not cache results because external inventory scripts are responsible for their own caching.
30 - To write your own inventory script see (R(Developing dynamic inventory,developing_inventory) from the documentation site.
31 - To find the scripts that used to be part of the code release, go to U(https://github.com/ansible-community/contrib-scripts/).
32 - Since 2.19 using a directory as an inventory source will no longer ignore .ini files by default,
33 but you can still update the configuration to do so.
34 '''
35
36 EXAMPLES = r'''# fmt: code
37
38 ### simple bash script
39
40 #!/usr/bin/env bash
41
42 if [ "$1" == "--list" ]; then
43 cat<<EOF
44 {
45 "bash_hosts": {
46 "hosts": [
47 "myhost.domain.com",
48 "myhost2.domain.com"
49 ],
50 "vars": {
51 "host_test": "test-value"
52 }
53 },
54 "_meta": {
55 "hostvars": {
56 "myhost.domain.com": {
57 "host_specific_test_var": "test-value"
58 }
59 }
60 }
61 }
62 EOF
63 elif [ "$1" == "--host" ]; then
64 # this should not normally be called by Ansible as we return _meta above
65 if [ "$2" == "myhost.domain.com" ]; then
66 echo '{"_meta": {"hostvars": {"myhost.domain.com": {"host_specific-test_var": "test-value"}}}}'
67 else
68 echo '{"_meta": {"hostvars": {}}}'
69 fi
70 else
71 echo "Invalid option: use --list or --host <hostname>"
72 exit 1
73 fi
74
75
76 ### python example with ini config
77
•78 #!/usr/bin/env python3
79 """
80 # ansible_inventory.py
81 """
82 import argparse
83 import json
84 import os.path
85 import sys
86 from configparser import ConfigParser
87 from inventories.custom import MyInventoryAPI
88
89 def load_config() -> ConfigParser:
90 cp = ConfigParser()
91 config_file = os.path.expanduser("~/.config/ansible_inventory_script.cfg")
92 cp.read(config_file)
93 if not cp.has_option('DEFAULT', 'namespace'):
94 raise ValueError("Missing configuration option: DEFAULT -> namespace")
95 return cp
96
97
98 def get_api_data(namespace: str, pretty=False) -> str:
99 """
100 :param namespace: parameter for our custom api
101 :param pretty: Human readable JSON vs machine readable
102 :return: JSON string
103 """
104 found_data = list(MyInventoryAPI(namespace))
105 hostvars = {}
106 data = { '_meta': { 'hostvars': {}},}
107
108 groups = found_data['groups'].keys()
109 for group in groups:
110 groups[group]['hosts'] = found_data[groups].get('host_list', [])
111 if group not in data:
112 data[group] = {}
113 data[group]['hosts'] = found_data[groups].get('host_list', [])
114 data[group]['vars'] = found_data[groups].get('info', [])
115 data[group]['children'] = found_data[group].get('subgroups', [])
116
117 for host_data in found_data['hosts']:
118 for name in host_data.items():
119 # turn info into vars
120 data['_meta'][name] = found_data[name].get('info', {})
121 # set ansible_host if possible
122 if 'address' in found_data[name]:
123 data[name]['_meta']['ansible_host'] = found_data[name]['address']
124 data['_meta']['hostvars'] = hostvars
125
126 return json.dumps(data, indent=pretty)
127
128 if __name__ == '__main__':
129
130 arg_parser = argparse.ArgumentParser( description=__doc__, prog=__file__)
131 arg_parser.add_argument('--pretty', action='store_true', default=False, help="Pretty JSON")
132 mandatory_options = arg_parser.add_mutually_exclusive_group()
133 mandatory_options.add_argument('--list', action='store', nargs="*", help="Get inventory JSON from our API")
134 mandatory_options.add_argument('--host', action='store',
135 help="Get variables for specific host, not used but kept for compatibility")
136
137 try:
138 config = load_config()
139 namespace = config.get('DEFAULT', 'namespace')
140
141 args = arg_parser.parse_args()
142 if args.host:
143 print('{"_meta":{}}')
144 sys.stderr.write('This script already provides _meta via --list, so this option is really ignored')
145 elif len(args.list) >= 0:
146 print(get_api_data(namespace, args.pretty))
147 else:
148 raise ValueError("Valid options are --list or --host <HOSTNAME>")
149
150 except ValueError:
151 raise
152
153 '''
154
155
156 import json
157 import os
158 import shlex
159 import subprocess
160 import typing as t
161
162 from ansible.errors import AnsibleError, AnsibleJSONParserError
163 from ansible.inventory.data import InventoryData
164 from ansible.module_utils.datatag import native_type_name
165 from ansible.module_utils.common.json import get_decoder
166 from ansible.parsing.dataloader import DataLoader
167 from ansible.plugins.inventory import BaseInventoryPlugin
168 from ansible._internal._datatag._tags import TrustedAsTemplate, Origin
169 from ansible.utils.display import Display
170 from ansible._internal._json._profiles import _legacy, _inventory_legacy
171
172 display = Display()
173
174
175 class InventoryModule(BaseInventoryPlugin):
176 """Host inventory parser for ansible using external inventory scripts."""
177
178 NAME = 'script'
179
180 def __init__(self) -> None:
181 super(InventoryModule, self).__init__()
182
183 self._hosts: set[str] = set()
184
185 def verify_file(self, path: str) -> bool:
186 return super(InventoryModule, self).verify_file(path) and os.access(path, os.X_OK)
187
188 def parse(self, inventory: InventoryData, loader: DataLoader, path: str, cache: bool = False) -> None:
189 super(InventoryModule, self).parse(inventory, loader, path)
190
191 self.set_options()
192
193 origin = Origin(description=f'<inventory script output from {path!r}>')
194
195 data, stderr, stderr_help_text = run_command(path, ['--list'], origin)
196
197 try:
198 profile_name = detect_profile_name(data)
199 decoder = get_decoder(profile_name)
200 except Exception as ex:
201 raise AnsibleError(
202 message="Unable to get JSON decoder for inventory script result.",
203 help_text=stderr_help_text,
204 # obj will be added by inventory manager
205 ) from ex
206
207 try:
208 try:
209 processed = json.loads(data, cls=decoder)
210 except Exception as json_ex:
211 AnsibleJSONParserError.handle_exception(json_ex, origin)
212 except Exception as ex:
213 raise AnsibleError(
214 message="Inventory script result could not be parsed as JSON.",
215 help_text=stderr_help_text,
216 # obj will be added by inventory manager
217 ) from ex
218
219 # if no other errors happened, and you want to force displaying stderr, do so now
220 if stderr and self.get_option('always_show_stderr'):
221 self.display.error(msg=stderr)
222
223 data_from_meta: dict | None = None
224
225 # A "_meta" subelement may contain a variable "hostvars" which contains a hash for each host
226 # if this "hostvars" exists at all then do not call --host for each # host.
227 # This is for efficiency and scripts should still return data
228 # if called with --host for backwards compat with 1.2 and earlier.
229 for (group, gdata) in processed.items():
230 if group == '_meta':
231 data_from_meta = gdata.get('hostvars')
232
233 if not isinstance(data_from_meta, dict):
234 raise TypeError(f"Value contains '_meta.hostvars' which is {native_type_name(data_from_meta)!r} instead of {native_type_name(dict)!r}.")
235 else:
236 self._parse_group(group, gdata, origin)
237
238 if data_from_meta is None:
239 display.deprecated(
240 msg="Inventory scripts should always provide 'meta.hostvars'. "
241 "Host variables will be collected by running the inventory script with the '--host' option for each host.",
242 version='2.23',
243 obj=origin,
244 )
245
246 for host in self._hosts:
247 if data_from_meta is None:
248 got = self.get_host_variables(path, host, origin)
249 else:
250 got = data_from_meta.get(host, {})
251
252 self._populate_host_vars([host], got)
253
254 def _parse_group(self, group: str, data: t.Any, origin: Origin) -> None:
255 """Normalize and ingest host/var information for the named group."""
256 group = self.inventory.add_group(group)
257
258 if not isinstance(data, dict):
259 original_type = native_type_name(data)
260 data = {'hosts': data}
261 display.deprecated(
262 msg=f"Group {group!r} was converted to {native_type_name(dict)!r} from {original_type!r}.",
263 version='2.23',
264 obj=origin,
265 )
266 elif not any(k in data for k in ('hosts', 'vars', 'children')):
267 data = {'hosts': [group], 'vars': data}
268 display.deprecated(
269 msg=f"Treating malformed group {group!r} as the sole host of that group. Variables provided in this manner cannot be templated.",
270 version='2.23',
271 obj=origin,
272 )
273
274 if (data_hosts := data.get('hosts', ...)) is not ...:
275 if not isinstance(data_hosts, list):
276 raise TypeError(f"Value contains '{group}.hosts' which is {native_type_name(data_hosts)!r} instead of {native_type_name(list)!r}.")
277
278 for hostname in data_hosts:
279 self._hosts.add(hostname)
280 self.inventory.add_host(hostname, group)
281
282 if (data_vars := data.get('vars', ...)) is not ...:
283 if not isinstance(data_vars, dict):
284 raise TypeError(f"Value contains '{group}.vars' which is {native_type_name(data_vars)!r} instead of {native_type_name(dict)!r}.")
285
286 for k, v in data_vars.items():
287 self.inventory.set_variable(group, k, v)
288
289 if group != '_meta' and isinstance(data, dict) and 'children' in data:
290 for child_name in data['children']:
291 child_name = self.inventory.add_group(child_name)
292 self.inventory.add_child(group, child_name)
293
294 @staticmethod
295 def get_host_variables(path: str, host: str, origin: Origin) -> dict:
296 """Runs <script> --host <hostname>, to determine additional host variables."""
297 origin = origin.replace(description=f'{origin.description} for host {host!r}')
298
299 data, stderr, stderr_help_text = run_command(path, ['--host', host], origin)
300
301 if not data.strip():
302 return {}
303
304 try:
305 try:
306 # Use standard legacy trust inversion here.
307 # Unlike the normal inventory output, everything here is considered a variable and thus supports trust (and trust inversion).
308 processed = json.loads(data, cls=_legacy.Decoder)
309 except Exception as json_ex:
310 AnsibleJSONParserError.handle_exception(json_ex, origin)
311 except Exception as ex:
312 raise AnsibleError(
313 message=f"Inventory script result for host {host!r} could not be parsed as JSON.",
314 help_text=stderr_help_text,
315 # obj will be added by inventory manager
316 ) from ex
317
318 return processed
319
320
321 def detect_profile_name(value: str) -> str:
322 """
323 Detect (optional) JSON profile name from an inventory JSON document.
324 Defaults to `inventory_legacy`.
325 """
326 try:
327 data = json.loads(value)
328 except Exception as ex:
329 raise ValueError('Value could not be parsed as JSON.') from ex
330
331 if not isinstance(data, dict):
332 raise TypeError(f'Value is {native_type_name(data)!r} instead of {native_type_name(dict)!r}.')
333
334 if (meta := data.get('_meta', ...)) is ...:
335 return _inventory_legacy.Decoder.profile_name
336
337 if not isinstance(meta, dict):
338 raise TypeError(f"Value contains '_meta' which is {native_type_name(meta)!r} instead of {native_type_name(dict)!r}.")
339
340 if (profile := meta.get('profile', ...)) is ...:
341 return _inventory_legacy.Decoder.profile_name
342
343 if not isinstance(profile, str):
344 raise TypeError(f"Value contains '_meta.profile' which is {native_type_name(profile)!r} instead of {native_type_name(str)!r}.")
345
346 if not profile.startswith('inventory_'):
347 raise ValueError(f"Non-inventory profile {profile!r} is not allowed.")
348
349 return profile
350
351
352 def run_command(path: str, options: list[str], origin: Origin) -> tuple[str, str, str]:
353 """Run an inventory script, normalize and validate output."""
354 cmd = [path] + options
355
356 try:
357 sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
358 except OSError as ex:
359 raise AnsibleError(
360 message=f"Failed to execute inventory script command {shlex.join(cmd)!r}.",
361 # obj will be added by inventory manager
362 ) from ex
363
364 stdout_bytes, stderr_bytes = sp.communicate()
365
366 stderr = stderr_bytes.decode(errors='surrogateescape')
367
368 if stderr and not stderr.endswith('\n'):
369 stderr += '\n'
370
371 # DTFIX-FUTURE: another use case for the "not quite help text, definitely not message" diagnostic output on errors
372 stderr_help_text = f'Standard error from inventory script:\n{stderr}' if stderr.strip() else None
373
374 if sp.returncode != 0:
375 raise AnsibleError(
376 message=f"Inventory script returned non-zero exit code {sp.returncode}.",
377 help_text=stderr_help_text,
378 # obj will be added by inventory manager
379 )
380
381 try:
382 data = stdout_bytes.decode()
383 except Exception as ex:
384 raise AnsibleError(
385 "Inventory script result contained characters that cannot be interpreted as UTF-8.",
386 help_text=stderr_help_text,
387 # obj will be added by inventory manager
388 ) from ex
389 else:
390 data = TrustedAsTemplate().tag(origin.tag(data))
391
392 return data, stderr, stderr_help_text