| 1 |
# (c) 2017, Red Hat, inc |
| 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 <https://www.gnu.org/licenses/>. |
| 17 |
|
| 18 |
from __future__ import annotations |
| 19 |
|
| 20 |
import functools |
| 21 |
import hashlib |
| 22 |
import os |
| 23 |
import string |
| 24 |
import typing as t |
| 25 |
|
| 26 |
from collections.abc import Mapping |
| 27 |
|
| 28 |
from ansible import template as _template |
| 29 |
from ansible.errors import AnsibleError, AnsibleParserError, AnsibleValueOmittedError |
| 30 |
from ansible.inventory.group import to_safe_group_name as original_safe |
| 31 |
from ansible.module_utils._internal import _plugin_info |
| 32 |
from ansible.parsing.utils.addresses import parse_address |
| 33 |
from ansible.parsing.dataloader import DataLoader |
| 34 |
from ansible.plugins import AnsiblePlugin, _ConfigurablePlugin |
| 35 |
from ansible.plugins.cache import CachePluginAdjudicator |
| 36 |
from ansible.module_utils.common.text.converters import to_bytes, to_native |
| 37 |
from ansible.utils.display import Display |
| 38 |
from ansible.utils.vars import combine_vars, load_extra_vars |
| 39 |
|
| 40 |
if t.TYPE_CHECKING: |
| 41 |
from ansible.inventory.data import InventoryData |
| 42 |
|
| 43 |
display = Display() |
| 44 |
|
| 45 |
|
| 46 |
# Helper methods |
| 47 |
def to_safe_group_name(name): |
| 48 |
# placeholder for backwards compat |
| 49 |
return original_safe(name, force=True, silent=True) |
| 50 |
|
| 51 |
|
| 52 |
def detect_range(line=None): |
| 53 |
""" |
| 54 |
A helper function that checks a given host line to see if it contains |
| 55 |
a range pattern described in the docstring above. |
| 56 |
|
| 57 |
Returns True if the given line contains a pattern, else False. |
| 58 |
""" |
| 59 |
return '[' in line |
| 60 |
|
| 61 |
|
| 62 |
def expand_hostname_range(line=None): |
| 63 |
""" |
| 64 |
A helper function that expands a given line that contains a pattern |
| 65 |
specified in top docstring, and returns a list that consists of the |
| 66 |
expanded version. |
| 67 |
|
| 68 |
The '[' and ']' characters are used to maintain the pseudo-code |
| 69 |
appearance. They are replaced in this function with '|' to ease |
| 70 |
string splitting. |
| 71 |
|
| 72 |
References: https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#hosts-and-groups |
| 73 |
""" |
| 74 |
all_hosts = [] |
| 75 |
if line: |
| 76 |
# A hostname such as db[1:6]-node is considered to consists |
| 77 |
# three parts: |
| 78 |
# head: 'db' |
| 79 |
# nrange: [1:6]; range() is a built-in. Can't use the name |
| 80 |
# tail: '-node' |
| 81 |
|
| 82 |
# Add support for multiple ranges in a host so: |
| 83 |
# db[01:10:3]node-[01:10] |
| 84 |
# - to do this we split off at the first [...] set, getting the list |
| 85 |
# of hosts and then repeat until none left. |
| 86 |
# - also add an optional third parameter which contains the step. (Default: 1) |
| 87 |
# so range can be [01:10:2] -> 01 03 05 07 09 |
| 88 |
|
| 89 |
(head, nrange, tail) = line.replace('[', '|', 1).replace(']', '|', 1).split('|') |
| 90 |
bounds = nrange.split(":") |
| 91 |
if len(bounds) != 2 and len(bounds) != 3: |
| 92 |
raise AnsibleError("host range must be begin:end or begin:end:step") |
| 93 |
beg = bounds[0] |
| 94 |
end = bounds[1] |
| 95 |
if len(bounds) == 2: |
| 96 |
step = 1 |
| 97 |
else: |
| 98 |
step = bounds[2] |
| 99 |
if not beg: |
| 100 |
beg = "0" |
| 101 |
if not end: |
| 102 |
raise AnsibleError("host range must specify end value") |
| 103 |
if beg[0] == '0' and len(beg) > 1: |
| 104 |
rlen = len(beg) # range length formatting hint |
| 105 |
if rlen != len(end): |
| 106 |
raise AnsibleError("host range must specify equal-length begin and end formats") |
| 107 |
|
| 108 |
def fill(x): |
| 109 |
return str(x).zfill(rlen) # range sequence |
| 110 |
|
| 111 |
else: |
| 112 |
fill = str |
| 113 |
|
| 114 |
try: |
| 115 |
i_beg = string.ascii_letters.index(beg) |
| 116 |
i_end = string.ascii_letters.index(end) |
| 117 |
if i_beg > i_end: |
| 118 |
raise AnsibleError("host range must have begin <= end") |
| 119 |
seq = list(string.ascii_letters[i_beg:i_end + 1:int(step)]) |
| 120 |
except ValueError: # not an alpha range |
| 121 |
seq = range(int(beg), int(end) + 1, int(step)) |
| 122 |
|
| 123 |
for rseq in seq: |
| 124 |
hname = ''.join((head, fill(rseq), tail)) |
| 125 |
|
| 126 |
if detect_range(hname): |
| 127 |
all_hosts.extend(expand_hostname_range(hname)) |
| 128 |
else: |
| 129 |
all_hosts.append(hname) |
| 130 |
|
| 131 |
return all_hosts |
| 132 |
|
| 133 |
|
| 134 |
def get_cache_plugin(plugin_name, **kwargs): |
| 135 |
if not plugin_name: |
| 136 |
raise AnsibleError("A cache plugin must be configured to use inventory caching.") |
| 137 |
|
| 138 |
try: |
| 139 |
cache = CachePluginAdjudicator(plugin_name, **kwargs) |
| 140 |
except AnsibleError as e: |
| 141 |
if 'fact_caching_connection' in to_native(e): |
| 142 |
raise AnsibleError("error, '%s' inventory cache plugin requires the one of the following to be set " |
| 143 |
"to a writeable directory path:\nansible.cfg:\n[default]: fact_caching_connection,\n" |
| 144 |
"[inventory]: cache_connection;\nEnvironment:\nANSIBLE_INVENTORY_CACHE_CONNECTION,\n" |
| 145 |
"ANSIBLE_CACHE_PLUGIN_CONNECTION." % plugin_name) |
| 146 |
else: |
| 147 |
raise |
| 148 |
|
| 149 |
if cache._plugin.ansible_name != 'ansible.builtin.memory' and kwargs and not getattr(cache._plugin, '_options', None): |
| 150 |
raise AnsibleError('Unable to use cache plugin {0} for inventory. Cache options were provided but may not reconcile ' |
| 151 |
'correctly unless set via set_options. Refer to the porting guide if the plugin derives user settings ' |
| 152 |
'from ansible.constants.'.format(plugin_name)) |
| 153 |
return cache |
| 154 |
|
| 155 |
|
| 156 |
class _BaseInventoryPlugin(AnsiblePlugin): |
| 157 |
""" |
| 158 |
Internal base implementation for inventory plugins. |
| 159 |
|
| 160 |
Do not inherit from this directly, use one of its public subclasses instead. |
| 161 |
Used to introduce an extra layer in the class hierarchy to allow Constructed to subclass this while remaining a mixin for existing inventory plugins. |
| 162 |
""" |
| 163 |
|
| 164 |
TYPE = 'generator' |
| 165 |
|
| 166 |
# 3rd party plugins redefine this to |
| 167 |
# use custom group name sanitization |
| 168 |
# since constructed features enforce |
| 169 |
# it by default. |
| 170 |
_sanitize_group_name = staticmethod(to_safe_group_name) |
| 171 |
|
| 172 |
def __init__(self) -> None: |
| 173 |
|
| 174 |
super().__init__() |
| 175 |
|
| 176 |
self._options = {} |
| 177 |
self.display = display |
| 178 |
|
| 179 |
# These attributes are set by the parse() method on this (base) class. |
| 180 |
self.loader: DataLoader | None = None |
| 181 |
self.inventory: InventoryData | None = None |
| 182 |
self._vars: dict[str, t.Any] | None = None |
| 183 |
|
| 184 |
trusted_by_default: bool = False |
| 185 |
"""Inventory plugins that only source templates from trusted sources can set this True to have trust automatically applied to all templates.""" |
| 186 |
|
| 187 |
@functools.cached_property |
| 188 |
def templar(self) -> _template.Templar: |
| 189 |
return _template.Templar(loader=self.loader) |
| 190 |
|
| 191 |
def parse(self, inventory: InventoryData, loader: DataLoader, path: str, cache: bool = True) -> None: |
| 192 |
""" Populates inventory from the given data. Raises an error on any parse failure |
| 193 |
:arg inventory: a copy of the previously accumulated inventory data, |
| 194 |
to be updated with any new data this plugin provides. |
| 195 |
The inventory can be empty if no other source/plugin ran successfully. |
| 196 |
:arg loader: a reference to the DataLoader, which can read in YAML and JSON files, |
| 197 |
it also has Vault support to automatically decrypt files. |
| 198 |
:arg path: the string that represents the 'inventory source', |
| 199 |
normally a path to a configuration file for this inventory, |
| 200 |
but it can also be a raw string for this plugin to consume |
| 201 |
:arg cache: a boolean that indicates if the plugin should use the cache or not |
| 202 |
you can ignore if this plugin does not implement caching. |
| 203 |
""" |
| 204 |
self.loader = loader |
| 205 |
self.inventory = inventory |
| 206 |
self._vars = load_extra_vars(loader) |
| 207 |
|
| 208 |
def verify_file(self, path): |
| 209 |
""" Verify if file is usable by this plugin, base does minimal accessibility check |
| 210 |
:arg path: a string that was passed as an inventory source, |
| 211 |
it normally is a path to a config file, but this is not a requirement, |
| 212 |
it can also be parsed itself as the inventory data to process. |
| 213 |
So only call this base class if you expect it to be a file. |
| 214 |
""" |
| 215 |
|
| 216 |
valid = False |
| 217 |
b_path = to_bytes(path, errors='surrogate_or_strict') |
| 218 |
if (os.path.exists(b_path) and os.access(b_path, os.R_OK)): |
| 219 |
valid = True |
| 220 |
else: |
| 221 |
self.display.vvv('Skipping due to inventory source not existing or not being readable by the current user') |
| 222 |
return valid |
| 223 |
|
| 224 |
def _populate_host_vars(self, hosts, variables, group=None, port=None): |
| 225 |
if not isinstance(variables, Mapping): |
| 226 |
raise AnsibleParserError("Invalid data from file, expected dictionary and got:\n\n%s" % to_native(variables)) |
| 227 |
|
| 228 |
for host in hosts: |
| 229 |
self.inventory.add_host(host, group=group, port=port) |
| 230 |
for k in variables: |
| 231 |
self.inventory.set_variable(host, k, variables[k]) |
| 232 |
|
| 233 |
def _read_config_data(self, path): |
| 234 |
""" validate config and set options as appropriate |
| 235 |
:arg path: path to common yaml format config file for this plugin |
| 236 |
""" |
| 237 |
|
| 238 |
try: |
| 239 |
# avoid loader cache so meta: refresh_inventory can pick up config changes |
| 240 |
# if we read more than once, fs cache should be good enough |
| 241 |
config = self.loader.load_from_file(path, cache='none', trusted_as_template=True) |
| 242 |
except Exception as e: |
| 243 |
raise AnsibleParserError(to_native(e)) |
| 244 |
|
| 245 |
# a plugin can be loaded via many different names with redirection- if so, we want to accept any of those names |
| 246 |
valid_names = getattr(self, '_redirected_names') or [self.NAME] |
| 247 |
|
| 248 |
if not config: |
| 249 |
# no data |
| 250 |
raise AnsibleParserError("%s is empty" % (to_native(path))) |
| 251 |
elif config.get('plugin') not in valid_names: |
| 252 |
# this is not my config file |
| 253 |
raise AnsibleParserError("Incorrect plugin name in file: %s" % config.get('plugin', 'none found')) |
| 254 |
elif not isinstance(config, Mapping): |
| 255 |
# configs are dictionaries |
| 256 |
raise AnsibleParserError('inventory source has invalid structure, it should be a dictionary, got: %s' % type(config)) |
| 257 |
|
| 258 |
self.set_options(direct=config, var_options=self._vars) |
| 259 |
if 'cache' in self._options and self.get_option('cache'): |
| 260 |
cache_option_keys = [('_uri', 'cache_connection'), ('_timeout', 'cache_timeout'), ('_prefix', 'cache_prefix')] |
| 261 |
cache_options = dict((opt[0], self.get_option(opt[1])) for opt in cache_option_keys if self.get_option(opt[1]) is not None) |
| 262 |
self._cache = get_cache_plugin(self.get_option('cache_plugin'), **cache_options) |
| 263 |
|
| 264 |
return config |
| 265 |
|
| 266 |
def _consume_options(self, data): |
| 267 |
""" update existing options from alternate configuration sources not normally used by Ansible. |
| 268 |
Many API libraries already have existing configuration sources, this allows plugin author to leverage them. |
| 269 |
:arg data: key/value pairs that correspond to configuration options for this plugin |
| 270 |
""" |
| 271 |
|
| 272 |
for k in self._options: |
| 273 |
if k in data: |
| 274 |
self._options[k] = data.pop(k) |
| 275 |
|
| 276 |
def _expand_hostpattern(self, hostpattern): |
| 277 |
""" |
| 278 |
Takes a single host pattern and returns a list of hostnames and an |
| 279 |
optional port number that applies to all of them. |
| 280 |
""" |
| 281 |
# Can the given hostpattern be parsed as a host with an optional port |
| 282 |
# specification? |
| 283 |
|
| 284 |
try: |
| 285 |
(pattern, port) = parse_address(hostpattern, allow_ranges=True) |
| 286 |
except Exception: |
| 287 |
# not a recognizable host pattern |
| 288 |
pattern = hostpattern |
| 289 |
port = None |
| 290 |
|
| 291 |
# Once we have separated the pattern, we expand it into list of one or |
| 292 |
# more hostnames, depending on whether it contains any [x:y] ranges. |
| 293 |
|
| 294 |
if detect_range(pattern): |
| 295 |
hostnames = expand_hostname_range(pattern) |
| 296 |
else: |
| 297 |
hostnames = [pattern] |
| 298 |
|
| 299 |
return (hostnames, port) |
| 300 |
|
| 301 |
|
| 302 |
class BaseInventoryPlugin(_BaseInventoryPlugin): |
| 303 |
""" Parses an Inventory Source """ |
| 304 |
|
| 305 |
|
| 306 |
class BaseFileInventoryPlugin(_BaseInventoryPlugin): |
| 307 |
""" Parses a File based Inventory Source""" |
| 308 |
|
| 309 |
TYPE = 'storage' |
| 310 |
|
| 311 |
def __init__(self): |
| 312 |
|
| 313 |
super(BaseFileInventoryPlugin, self).__init__() |
| 314 |
|
| 315 |
|
| 316 |
class Cacheable(_plugin_info.HasPluginInfo, _ConfigurablePlugin): |
| 317 |
"""Mixin for inventory plugins which support caching.""" |
| 318 |
|
| 319 |
_cache: CachePluginAdjudicator |
| 320 |
|
| 321 |
@property |
| 322 |
def cache(self) -> CachePluginAdjudicator: |
| 323 |
return self._cache |
| 324 |
|
| 325 |
def load_cache_plugin(self) -> None: |
| 326 |
plugin_name = self.get_option('cache_plugin') |
| 327 |
cache_option_keys = [('_uri', 'cache_connection'), ('_timeout', 'cache_timeout'), ('_prefix', 'cache_prefix')] |
| 328 |
cache_options = dict((opt[0], self.get_option(opt[1])) for opt in cache_option_keys if self.get_option(opt[1]) is not None) |
| 329 |
self._cache = get_cache_plugin(plugin_name, **cache_options) |
| 330 |
|
| 331 |
def get_cache_key(self, path: str) -> str: |
| 332 |
return f'{self.ansible_name}_{self._get_cache_prefix(path)}' |
| 333 |
|
| 334 |
def _get_cache_prefix(self, path: str) -> str: |
| 335 |
"""Return a predictable unique key based on the given path.""" |
| 336 |
return 'k' + hashlib.sha256(f'{self.ansible_name}{path}'.encode(), usedforsecurity=False).hexdigest()[:6] |
| 337 |
|
| 338 |
def clear_cache(self) -> None: |
| 339 |
self._cache.clear() |
| 340 |
|
| 341 |
def update_cache_if_changed(self) -> None: |
| 342 |
self._cache.update_cache_if_changed() |
| 343 |
|
| 344 |
def set_cache_plugin(self) -> None: |
| 345 |
self._cache.set_cache() |
| 346 |
|
| 347 |
|
| 348 |
class Constructable(_BaseInventoryPlugin): |
| 349 |
def _compose(self, template, variables, disable_lookups=...): |
| 350 |
""" helper method for plugins to compose variables for Ansible based on jinja2 expression and inventory vars""" |
| 351 |
if disable_lookups is not ...: |
| 352 |
self.display.deprecated("The disable_lookups arg has no effect.", version="2.23") |
| 353 |
|
| 354 |
try: |
| 355 |
use_extra = self.get_option('use_extra_vars') |
| 356 |
except Exception: |
| 357 |
use_extra = False |
| 358 |
|
| 359 |
if use_extra: |
| 360 |
self.templar.available_variables = combine_vars(variables, self._vars) |
| 361 |
else: |
| 362 |
self.templar.available_variables = variables |
| 363 |
|
| 364 |
return self.templar.evaluate_expression(template) |
| 365 |
|
| 366 |
def _set_composite_vars(self, compose, variables, host, strict=False): |
| 367 |
""" loops over compose entries to create vars for hosts """ |
| 368 |
if compose and isinstance(compose, dict): |
| 369 |
for varname in compose: |
| 370 |
try: |
| 371 |
composite = self._compose(compose[varname], variables) |
| 372 |
except Exception as e: |
| 373 |
if strict: |
| 374 |
raise AnsibleError("Could not set %s for host %s: %s" % (varname, host, to_native(e))) |
| 375 |
continue |
| 376 |
self.inventory.set_variable(host, varname, composite) |
| 377 |
|
| 378 |
def _add_host_to_composed_groups(self, groups, variables, host, strict=False, fetch_hostvars=True): |
| 379 |
""" helper to create complex groups for plugins based on jinja2 conditionals, hosts that meet the conditional are added to group""" |
| 380 |
# process each 'group entry' |
| 381 |
if groups and isinstance(groups, dict): |
| 382 |
if fetch_hostvars: |
| 383 |
variables = combine_vars(variables, self.inventory.get_host(host).get_vars()) |
| 384 |
self.templar.available_variables = variables |
| 385 |
for group_name in groups: |
| 386 |
conditional = groups[group_name] |
| 387 |
group_name = self._sanitize_group_name(group_name) |
| 388 |
try: |
| 389 |
result = self.templar.evaluate_conditional(conditional) |
| 390 |
except Exception as e: |
| 391 |
if strict: |
| 392 |
raise AnsibleParserError("Could not add host %s to group %s: %s" % (host, group_name, to_native(e))) |
| 393 |
continue |
| 394 |
|
| 395 |
if result: |
| 396 |
# ensure group exists, use sanitized name |
| 397 |
group_name = self.inventory.add_group(group_name) |
| 398 |
# add host to group |
| 399 |
self.inventory.add_child(group_name, host) |
| 400 |
|
| 401 |
def _add_host_to_keyed_groups(self, keys, variables, host, strict=False, fetch_hostvars=True): |
| 402 |
""" helper to create groups for plugins based on variable values and add the corresponding hosts to it""" |
| 403 |
should_default_value = (None, '') |
| 404 |
|
| 405 |
if keys and isinstance(keys, list): |
| 406 |
for keyed in keys: |
| 407 |
if keyed and isinstance(keyed, dict): |
| 408 |
|
| 409 |
if fetch_hostvars: |
| 410 |
variables = combine_vars(variables, self.inventory.get_host(host).get_vars()) |
| 411 |
try: |
| 412 |
key = self._compose(keyed.get('key'), variables) |
| 413 |
except Exception as e: |
| 414 |
if strict: |
| 415 |
raise AnsibleParserError("Could not generate group for host %s from %s entry: %s" % (host, keyed.get('key'), to_native(e))) |
| 416 |
continue |
| 417 |
default_value_name = keyed.get('default_value', None) |
| 418 |
trailing_separator = keyed.get('trailing_separator') |
| 419 |
if trailing_separator is not None and default_value_name is not None: |
| 420 |
raise AnsibleParserError("parameters are mutually exclusive for keyed groups: default_value|trailing_separator") |
| 421 |
|
| 422 |
use_default = key in should_default_value and default_value_name is not None |
| 423 |
if key or use_default: |
| 424 |
prefix = keyed.get('prefix', '') |
| 425 |
sep = keyed.get('separator', '_') |
| 426 |
raw_parent_name = keyed.get('parent_group', None) |
| 427 |
|
| 428 |
try: |
| 429 |
raw_parent_name = self.templar.template(raw_parent_name) |
| 430 |
except AnsibleValueOmittedError: |
| 431 |
raw_parent_name = None |
| 432 |
except Exception as ex: |
| 433 |
if strict: |
| 434 |
raise AnsibleParserError(f'Could not generate parent group {raw_parent_name!r} for group {key!r}: {ex}') from ex |
| 435 |
|
| 436 |
continue |
| 437 |
|
| 438 |
new_raw_group_names = [] |
| 439 |
if use_default: |
| 440 |
new_raw_group_names.append(default_value_name) |
| 441 |
elif isinstance(key, str): |
| 442 |
new_raw_group_names.append(key) |
| 443 |
elif isinstance(key, list): |
| 444 |
for name in key: |
| 445 |
# if list item is empty, 'default_value' will be used as group name |
| 446 |
if name in should_default_value and default_value_name is not None: |
| 447 |
new_raw_group_names.append(default_value_name) |
| 448 |
else: |
| 449 |
new_raw_group_names.append(name) |
| 450 |
elif isinstance(key, Mapping): |
| 451 |
for (gname, gval) in key.items(): |
| 452 |
bare_name = '%s%s%s' % (gname, sep, gval) |
| 453 |
if gval in should_default_value: |
| 454 |
# key's value is empty |
| 455 |
if default_value_name is not None: |
| 456 |
bare_name = '%s%s%s' % (gname, sep, default_value_name) |
| 457 |
elif trailing_separator is False: |
| 458 |
bare_name = gname |
| 459 |
new_raw_group_names.append(bare_name) |
| 460 |
else: |
| 461 |
raise AnsibleParserError("Invalid group name format, expected a string or a list of them or dictionary, got: %s" % type(key)) |
| 462 |
|
| 463 |
for bare_name in new_raw_group_names: |
| 464 |
if prefix == '' and self.get_option('leading_separator') is False: |
| 465 |
sep = '' |
| 466 |
gname = self._sanitize_group_name('%s%s%s' % (prefix, sep, bare_name)) |
| 467 |
result_gname = self.inventory.add_group(gname) |
| 468 |
self.inventory.add_host(host, result_gname) |
| 469 |
|
| 470 |
if raw_parent_name: |
| 471 |
parent_name = self._sanitize_group_name(raw_parent_name) |
| 472 |
self.inventory.add_group(parent_name) |
| 473 |
self.inventory.add_child(parent_name, result_gname) |
| 474 |
|
| 475 |
else: |
| 476 |
# exclude case of empty list and dictionary, because these are valid constructions |
| 477 |
# simply no groups need to be constructed, but are still falsy |
| 478 |
if strict and key not in ([], {}): |
| 479 |
raise AnsibleParserError("No key or key resulted empty for %s in host %s, invalid entry" % (keyed.get('key'), host)) |
| 480 |
else: |
| 481 |
raise AnsibleParserError("Invalid keyed group entry, it must be a dictionary: %s " % keyed) |