| 1 |
# (c) 2012-2014, Michael DeHaan <[email protected]> |
| 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 |
|
| 18 |
############################################# |
| 19 |
from __future__ import annotations |
| 20 |
|
| 21 |
import fnmatch |
| 22 |
import functools |
| 23 |
import os |
| 24 |
import re |
| 25 |
import itertools |
| 26 |
import typing as t |
| 27 |
|
| 28 |
from operator import attrgetter |
| 29 |
from random import shuffle |
| 30 |
|
| 31 |
from ansible import constants as C |
| 32 |
from ansible._internal import _json, _wrapt |
| 33 |
from ansible._internal._json import EncryptedStringBehavior |
| 34 |
from ansible.errors import AnsibleError, AnsibleOptionsError |
| 35 |
from ansible.inventory.data import InventoryData |
| 36 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 37 |
from ansible.parsing.dataloader import DataLoader |
| 38 |
from ansible.parsing.utils.addresses import parse_address |
| 39 |
from ansible.plugins.loader import inventory_loader |
| 40 |
from ansible._internal._datatag._tags import Origin |
| 41 |
from ansible.utils.helpers import deduplicate_list |
| 42 |
from ansible.utils.path import unfrackpath |
| 43 |
from ansible.utils.display import Display |
| 44 |
from ansible.utils.vars import combine_vars |
| 45 |
from ansible.vars.plugins import get_vars_from_inventory_sources |
| 46 |
|
| 47 |
if t.TYPE_CHECKING: |
| 48 |
from ansible.plugins.inventory import BaseInventoryPlugin |
| 49 |
from ansible.inventory.host import Host |
| 50 |
from ansible._internal._task import AddHost, AddGroup |
| 51 |
|
| 52 |
display = Display() |
| 53 |
|
| 54 |
IGNORED_ALWAYS = [br"^\.", b"^host_vars$", b"^group_vars$", b"^vars_plugins$"] |
| 55 |
IGNORED_PATTERNS = [to_bytes(x) for x in C.INVENTORY_IGNORE_PATTERNS] |
| 56 |
IGNORED_EXTS = [b'%s$' % to_bytes(re.escape(x)) for x in C.INVENTORY_IGNORE_EXTS] |
| 57 |
|
| 58 |
IGNORED = re.compile(b'|'.join(IGNORED_ALWAYS + IGNORED_PATTERNS + IGNORED_EXTS)) |
| 59 |
|
| 60 |
PATTERN_WITH_SUBSCRIPT = re.compile( |
| 61 |
r"""^ |
| 62 |
(.+) # A pattern expression ending with... |
| 63 |
\[(?: # A [subscript] expression comprising: |
| 64 |
(-?[0-9]+)| # A single positive or negative number |
| 65 |
([0-9]+)([:-]) # Or an x:y or x: range. |
| 66 |
([0-9]*) |
| 67 |
)\] |
| 68 |
$ |
| 69 |
""", re.X |
| 70 |
) |
| 71 |
|
| 72 |
|
| 73 |
def order_patterns(patterns): |
| 74 |
""" takes a list of patterns and reorders them by modifier to apply them consistently """ |
| 75 |
|
| 76 |
# FIXME: this goes away if we apply patterns incrementally or by groups |
| 77 |
pattern_regular = [] |
| 78 |
pattern_intersection = [] |
| 79 |
pattern_exclude = [] |
| 80 |
for p in patterns: |
| 81 |
if not p: |
| 82 |
continue |
| 83 |
|
| 84 |
if p[0] == "!": |
| 85 |
pattern_exclude.append(p) |
| 86 |
elif p[0] == "&": |
| 87 |
pattern_intersection.append(p) |
| 88 |
else: |
| 89 |
pattern_regular.append(p) |
| 90 |
|
| 91 |
# if no regular pattern was given, hence only exclude and/or intersection |
| 92 |
# make that magically work |
| 93 |
if pattern_regular == []: |
| 94 |
pattern_regular = ['all'] |
| 95 |
|
| 96 |
# when applying the host selectors, run those without the "&" or "!" |
| 97 |
# first, then the &s, then the !s. |
| 98 |
return pattern_regular + pattern_intersection + pattern_exclude |
| 99 |
|
| 100 |
|
| 101 |
def split_host_pattern(pattern): |
| 102 |
""" |
| 103 |
Takes a string containing host patterns separated by commas (or a list |
| 104 |
thereof) and returns a list of single patterns (which may not contain |
| 105 |
commas). Whitespace is ignored. |
| 106 |
|
| 107 |
Also accepts ':' as a separator for backwards compatibility, but it is |
| 108 |
not recommended due to the conflict with IPv6 addresses and host ranges. |
| 109 |
|
| 110 |
Example: 'a,b[1], c[2:3] , d' -> ['a', 'b[1]', 'c[2:3]', 'd'] |
| 111 |
""" |
| 112 |
|
| 113 |
if isinstance(pattern, list): |
| 114 |
results = (split_host_pattern(p) for p in pattern) |
| 115 |
# flatten the results |
| 116 |
return list(itertools.chain.from_iterable(results)) |
| 117 |
elif not isinstance(pattern, str): |
| 118 |
pattern = to_text(pattern, errors='surrogate_or_strict') |
| 119 |
|
| 120 |
# If it's got commas in it, we'll treat it as a straightforward |
| 121 |
# comma-separated list of patterns. |
| 122 |
if u',' in pattern: |
| 123 |
patterns = pattern.split(u',') |
| 124 |
|
| 125 |
# If it doesn't, it could still be a single pattern. This accounts for |
| 126 |
# non-separator uses of colons: IPv6 addresses and [x:y] host ranges. |
| 127 |
else: |
| 128 |
try: |
| 129 |
(base, port) = parse_address(pattern, allow_ranges=True) |
| 130 |
patterns = [pattern] |
| 131 |
except Exception: |
| 132 |
# The only other case we accept is a ':'-separated list of patterns. |
| 133 |
# This mishandles IPv6 addresses, and is retained only for backwards |
| 134 |
# compatibility. |
| 135 |
patterns = re.findall( |
| 136 |
to_text(r"""(?: # We want to match something comprising: |
| 137 |
[^\s:\[\]] # (anything other than whitespace or ':[]' |
| 138 |
| # ...or... |
| 139 |
\[[^\]]*\] # a single complete bracketed expression) |
| 140 |
)+ # occurring once or more |
| 141 |
"""), pattern, re.X |
| 142 |
) |
| 143 |
|
| 144 |
return [p.strip() for p in patterns if p.strip()] |
| 145 |
|
| 146 |
|
| 147 |
class InventoryManager: |
| 148 |
""" Creates and manages inventory """ |
| 149 |
|
| 150 |
def __init__(self, loader: DataLoader, sources: list[str] | str | None = None, parse: bool = True, cache: bool = True) -> None: |
| 151 |
|
| 152 |
# base objects |
| 153 |
self._loader = loader |
| 154 |
self._inventory = InventoryData() |
| 155 |
|
| 156 |
# a list of host(names) to contain current inquiries to |
| 157 |
self._restriction = None |
| 158 |
self._subset = None |
| 159 |
|
| 160 |
# caches |
| 161 |
self._hosts_patterns_cache: dict[tuple[str, ...], list[Host]] = {} # resolved full patterns |
| 162 |
self._pattern_cache: dict[str, list[Host]] = {} # resolved individual patterns |
| 163 |
|
| 164 |
# the inventory dirs, files, script paths or lists of hosts |
| 165 |
if sources is None: |
| 166 |
self._sources = [] |
| 167 |
elif isinstance(sources, str): |
| 168 |
self._sources = [sources] |
| 169 |
else: |
| 170 |
self._sources = sources |
| 171 |
|
| 172 |
# get to work! |
| 173 |
if parse: |
| 174 |
self.parse_sources(cache=cache) |
| 175 |
|
| 176 |
self._cached_dynamic_hosts: list[AddHost] = [] |
| 177 |
self._cached_dynamic_grouping: list[tuple[str, AddGroup]] = [] |
| 178 |
|
| 179 |
@property |
| 180 |
def localhost(self): |
| 181 |
return self._inventory.get_host('localhost') |
| 182 |
|
| 183 |
@property |
| 184 |
def groups(self): |
| 185 |
return self._inventory.groups |
| 186 |
|
| 187 |
@property |
| 188 |
def hosts(self): |
| 189 |
return self._inventory.hosts |
| 190 |
|
| 191 |
def add_host(self, host, group=None, port=None): |
| 192 |
return self._inventory.add_host(host, group, port) |
| 193 |
|
| 194 |
def add_group(self, group): |
| 195 |
return self._inventory.add_group(group) |
| 196 |
|
| 197 |
def get_groups_dict(self): |
| 198 |
return self._inventory.get_groups_dict() |
| 199 |
|
| 200 |
def reconcile_inventory(self): |
| 201 |
self.clear_caches() |
| 202 |
return self._inventory.reconcile_inventory() |
| 203 |
|
| 204 |
def get_host(self, hostname): |
| 205 |
return self._inventory.get_host(hostname) |
| 206 |
|
| 207 |
def _fetch_inventory_plugins(self) -> list[BaseInventoryPlugin]: |
| 208 |
""" sets up loaded inventory plugins for usage """ |
| 209 |
|
| 210 |
display.vvvv('setting up inventory plugins') |
| 211 |
|
| 212 |
plugins: list[BaseInventoryPlugin] = [] |
| 213 |
for name in C.INVENTORY_ENABLED: |
| 214 |
plugin = inventory_loader.get(name) |
| 215 |
if plugin: |
| 216 |
plugins.append(plugin) |
| 217 |
else: |
| 218 |
display.warning('Failed to load inventory plugin, skipping %s' % name) |
| 219 |
|
| 220 |
if not plugins: |
| 221 |
raise AnsibleError("No inventory plugins available to generate inventory, make sure you have at least one enabled.") |
| 222 |
|
| 223 |
return plugins |
| 224 |
|
| 225 |
def parse_sources(self, cache=False): |
| 226 |
""" iterate over inventory sources and parse each one to populate it""" |
| 227 |
|
| 228 |
parsed = False |
| 229 |
# allow for multiple inventory parsing |
| 230 |
for source in self._sources: |
| 231 |
|
| 232 |
if source: |
| 233 |
if ',' not in source: |
| 234 |
source = unfrackpath(source, follow=False) |
| 235 |
parse = self.parse_source(source, cache=cache) |
| 236 |
if parse and not parsed: |
| 237 |
parsed = True |
| 238 |
|
| 239 |
if parsed: |
| 240 |
# do post processing |
| 241 |
self._inventory.reconcile_inventory() |
| 242 |
else: |
| 243 |
if C.INVENTORY_UNPARSED_IS_FAILED: |
| 244 |
raise AnsibleError("No inventory was parsed, please check your configuration and options.") |
| 245 |
elif C.INVENTORY_UNPARSED_WARNING: |
| 246 |
display.warning("No inventory was parsed, only implicit localhost is available") |
| 247 |
|
| 248 |
for group in self.groups.values(): |
| 249 |
group.vars = combine_vars(group.vars, get_vars_from_inventory_sources(self._loader, self._sources, [group], 'inventory')) |
| 250 |
for host in self.hosts.values(): |
| 251 |
host.vars = combine_vars(host.vars, get_vars_from_inventory_sources(self._loader, self._sources, [host], 'inventory')) |
| 252 |
|
| 253 |
def parse_source(self, source, cache=False): |
| 254 |
""" Generate or update inventory for the source provided """ |
| 255 |
|
| 256 |
parsed = False |
| 257 |
failures = [] |
| 258 |
display.debug(u'Examining possible inventory source: %s' % source) |
| 259 |
|
| 260 |
# use binary for path functions |
| 261 |
b_source = to_bytes(source) |
| 262 |
|
| 263 |
# process directories as a collection of inventories |
| 264 |
if os.path.isdir(b_source): |
| 265 |
display.debug(u'Searching for inventory files in directory: %s' % source) |
| 266 |
for i in sorted(os.listdir(b_source)): |
| 267 |
|
| 268 |
display.debug(u'Considering %s' % i) |
| 269 |
# Skip hidden files and stuff we explicitly ignore |
| 270 |
if IGNORED.search(i): |
| 271 |
continue |
| 272 |
|
| 273 |
# recursively deal with directory entries |
| 274 |
fullpath = to_text(os.path.join(b_source, i), errors='surrogate_or_strict') |
| 275 |
parsed_this_one = self.parse_source(fullpath, cache=cache) |
| 276 |
display.debug(u'parsed %s as %s' % (fullpath, parsed_this_one)) |
| 277 |
if not parsed: |
| 278 |
parsed = parsed_this_one |
| 279 |
else: |
| 280 |
# left with strings or files, let plugins figure it out |
| 281 |
|
| 282 |
# set so new hosts can use for inventory_file/dir vars |
| 283 |
self._inventory.current_source = source |
| 284 |
|
| 285 |
# try source with each plugin |
| 286 |
for plugin in self._fetch_inventory_plugins(): |
| 287 |
plugin_name = to_text(getattr(plugin, '_load_name', getattr(plugin, '_original_path', ''))) |
| 288 |
display.debug(u'Attempting to use plugin %s (%s)' % (plugin_name, plugin._original_path)) |
| 289 |
|
| 290 |
# initialize and figure out if plugin wants to attempt parsing this file |
| 291 |
try: |
| 292 |
plugin_wants = bool(plugin.verify_file(source)) |
| 293 |
except Exception: |
| 294 |
plugin_wants = False |
| 295 |
|
| 296 |
if plugin_wants: |
| 297 |
# have this tag ready to apply to errors or output; str-ify source since it is often tagged by the CLI |
| 298 |
origin = Origin(description=f'<inventory plugin {plugin_name!r} with source {str(source)!r}>') |
| 299 |
try: |
| 300 |
inventory_wrapper = _InventoryDataWrapper(self._inventory, target_plugin=plugin, origin=origin) |
| 301 |
|
| 302 |
# FUTURE: now that we have a wrapper around inventory, we can have it use ChainMaps to preview the in-progress inventory, |
| 303 |
# but be able to roll back partial inventory failures by discarding the outermost layer |
| 304 |
plugin.parse(inventory_wrapper, self._loader, source, cache=cache) |
| 305 |
try: |
| 306 |
plugin.update_cache_if_changed() |
| 307 |
except AttributeError: |
| 308 |
# some plugins might not implement caching |
| 309 |
pass |
| 310 |
parsed = True |
| 311 |
display.vvv('Parsed %s inventory source with %s plugin' % (source, plugin_name)) |
| 312 |
break |
| 313 |
except AnsibleError as ex: |
| 314 |
if not ex.obj: |
| 315 |
ex.obj = origin |
| 316 |
failures.append({'src': source, 'plugin': plugin_name, 'exc': ex}) |
| 317 |
except Exception as ex: |
| 318 |
# DTFIX-FUTURE: fix this error handling to correctly deal with messaging |
| 319 |
try: |
| 320 |
# omit line number to prevent contextual display of script or possibly sensitive info |
| 321 |
raise AnsibleError(str(ex), obj=origin) from ex |
| 322 |
except AnsibleError as ex: |
| 323 |
failures.append({'src': source, 'plugin': plugin_name, 'exc': ex}) |
| 324 |
else: |
| 325 |
display.vvv("%s declined parsing %s as it did not pass its verify_file() method" % (plugin_name, source)) |
| 326 |
|
| 327 |
if parsed: |
| 328 |
self._inventory.processed_sources.append(self._inventory.current_source) |
| 329 |
else: |
| 330 |
# only warn/error if NOT using the default or using it and the file is present |
| 331 |
# TODO: handle 'non file' inventory and detect vs hardcode default |
| 332 |
if source != '/etc/ansible/hosts' or os.path.exists(source): |
| 333 |
|
| 334 |
if failures: |
| 335 |
# only if no plugin processed files should we show errors. |
| 336 |
for fail in failures: |
| 337 |
# `obj` should always be set |
| 338 |
display.error_as_warning(msg=f'Failed to parse inventory with {fail["plugin"]!r} plugin.', exception=fail['exc']) |
| 339 |
|
| 340 |
# final error/warning on inventory source failure |
| 341 |
if C.INVENTORY_ANY_UNPARSED_IS_FAILED: |
| 342 |
raise AnsibleError(u'Completely failed to parse inventory source %s' % (source)) |
| 343 |
else: |
| 344 |
display.warning("Unable to parse %s as an inventory source" % source) |
| 345 |
|
| 346 |
# clear up, jic |
| 347 |
self._inventory.current_source = None |
| 348 |
|
| 349 |
return parsed |
| 350 |
|
| 351 |
def clear_caches(self): |
| 352 |
""" clear all caches """ |
| 353 |
self._hosts_patterns_cache = {} |
| 354 |
self._pattern_cache = {} |
| 355 |
|
| 356 |
def refresh_inventory(self): |
| 357 |
""" recalculate inventory """ |
| 358 |
|
| 359 |
self.clear_caches() |
| 360 |
self._inventory = InventoryData() |
| 361 |
self.parse_sources(cache=False) |
| 362 |
|
| 363 |
for add_host in self._cached_dynamic_hosts: |
| 364 |
self.add_dynamic_host(add_host, already_in_cache=True) |
| 365 |
|
| 366 |
for host_name, add_group in self._cached_dynamic_grouping: |
| 367 |
self.add_dynamic_group(host_name, add_group, already_in_cache=True) |
| 368 |
|
| 369 |
def _match_list(self, items, pattern_str): |
| 370 |
# compile patterns |
| 371 |
try: |
| 372 |
if not pattern_str[0] == '~': |
| 373 |
pattern = re.compile(fnmatch.translate(pattern_str)) |
| 374 |
else: |
| 375 |
pattern = re.compile(pattern_str[1:]) |
| 376 |
except Exception: |
| 377 |
raise AnsibleError('Invalid host list pattern: %s' % pattern_str) |
| 378 |
|
| 379 |
# apply patterns |
| 380 |
results = [] |
| 381 |
for item in items: |
| 382 |
if pattern.match(item): |
| 383 |
results.append(item) |
| 384 |
return results |
| 385 |
|
| 386 |
def get_hosts(self, pattern="all", ignore_limits=False, ignore_restrictions=False, order=None): |
| 387 |
""" |
| 388 |
Takes a pattern or list of patterns and returns a list of matching |
| 389 |
inventory host names, taking into account any active restrictions |
| 390 |
or applied subsets |
| 391 |
""" |
| 392 |
|
| 393 |
hosts = [] |
| 394 |
|
| 395 |
# Check if pattern already computed |
| 396 |
if isinstance(pattern, list): |
| 397 |
pattern_list = pattern[:] |
| 398 |
else: |
| 399 |
pattern_list = [pattern] |
| 400 |
|
| 401 |
if pattern_list: |
| 402 |
if not ignore_limits and self._subset: |
| 403 |
pattern_list.extend(self._subset) |
| 404 |
|
| 405 |
if not ignore_restrictions and self._restriction: |
| 406 |
pattern_list.extend(self._restriction) |
| 407 |
|
| 408 |
# This is only used as a hash key in the self._hosts_patterns_cache dict |
| 409 |
# a tuple is faster than stringifying |
| 410 |
pattern_hash = tuple(pattern_list) |
| 411 |
|
| 412 |
if pattern_hash not in self._hosts_patterns_cache: |
| 413 |
|
| 414 |
patterns = split_host_pattern(pattern) |
| 415 |
hosts = self._evaluate_patterns(patterns) |
| 416 |
|
| 417 |
# mainly useful for hostvars[host] access |
| 418 |
if not ignore_limits and self._subset: |
| 419 |
# exclude hosts not in a subset, if defined |
| 420 |
subset_uuids = set(s._uuid for s in self._evaluate_patterns(self._subset)) |
| 421 |
hosts = [h for h in hosts if h._uuid in subset_uuids] |
| 422 |
|
| 423 |
if not ignore_restrictions and self._restriction: |
| 424 |
# exclude hosts mentioned in any restriction (ex: failed hosts) |
| 425 |
hosts = [h for h in hosts if h.name in self._restriction] |
| 426 |
|
| 427 |
self._hosts_patterns_cache[pattern_hash] = deduplicate_list(hosts) |
| 428 |
|
| 429 |
# sort hosts list if needed (should only happen when called from strategy) |
| 430 |
if order in ['sorted', 'reverse_sorted']: |
| 431 |
hosts = sorted(self._hosts_patterns_cache[pattern_hash][:], key=attrgetter('name'), reverse=(order == 'reverse_sorted')) |
| 432 |
elif order == 'reverse_inventory': |
| 433 |
hosts = self._hosts_patterns_cache[pattern_hash][::-1] |
| 434 |
else: |
| 435 |
hosts = self._hosts_patterns_cache[pattern_hash][:] |
| 436 |
if order == 'shuffle': |
| 437 |
shuffle(hosts) |
| 438 |
elif order not in [None, 'inventory']: |
| 439 |
raise AnsibleOptionsError("Invalid 'order' specified for inventory hosts: %s" % order) |
| 440 |
|
| 441 |
return hosts |
| 442 |
|
| 443 |
def _evaluate_patterns(self, patterns): |
| 444 |
""" |
| 445 |
Takes a list of patterns and returns a list of matching host names, |
| 446 |
taking into account any negative and intersection patterns. |
| 447 |
""" |
| 448 |
|
| 449 |
patterns = order_patterns(patterns) |
| 450 |
hosts = [] |
| 451 |
|
| 452 |
for p in patterns: |
| 453 |
# avoid resolving a pattern that is a plain host |
| 454 |
if p in self._inventory.hosts: |
| 455 |
hosts.append(self._inventory.get_host(p)) |
| 456 |
else: |
| 457 |
that = self._match_one_pattern(p) |
| 458 |
if p[0] == "!": |
| 459 |
that = set(that) |
| 460 |
hosts = [h for h in hosts if h not in that] |
| 461 |
elif p[0] == "&": |
| 462 |
that = set(that) |
| 463 |
hosts = [h for h in hosts if h in that] |
| 464 |
else: |
| 465 |
existing_hosts = set(y.name for y in hosts) |
| 466 |
hosts.extend([h for h in that if h.name not in existing_hosts]) |
| 467 |
return hosts |
| 468 |
|
| 469 |
def _match_one_pattern(self, pattern): |
| 470 |
""" |
| 471 |
Takes a single pattern and returns a list of matching host names. |
| 472 |
Ignores intersection (&) and exclusion (!) specifiers. |
| 473 |
|
| 474 |
The pattern may be: |
| 475 |
|
| 476 |
1. A regex starting with ~, e.g. '~[abc]*' |
| 477 |
2. A shell glob pattern with ?/*/[chars]/[!chars], e.g. 'foo*' |
| 478 |
3. An ordinary word that matches itself only, e.g. 'foo' |
| 479 |
|
| 480 |
The pattern is matched using the following rules: |
| 481 |
|
| 482 |
1. If it's 'all', it matches all hosts in all groups. |
| 483 |
2. Otherwise, for each known group name: |
| 484 |
(a) if it matches the group name, the results include all hosts |
| 485 |
in the group or any of its children. |
| 486 |
(b) otherwise, if it matches any hosts in the group, the results |
| 487 |
include the matching hosts. |
| 488 |
|
| 489 |
This means that 'foo*' may match one or more groups (thus including all |
| 490 |
hosts therein) but also hosts in other groups. |
| 491 |
|
| 492 |
The built-in groups 'all' and 'ungrouped' are special. No pattern can |
| 493 |
match these group names (though 'all' behaves as though it matches, as |
| 494 |
described above). The word 'ungrouped' can match a host of that name, |
| 495 |
and patterns like 'ungr*' and 'al*' can match either hosts or groups |
| 496 |
other than all and ungrouped. |
| 497 |
|
| 498 |
If the pattern matches one or more group names according to these rules, |
| 499 |
it may have an optional range suffix to select a subset of the results. |
| 500 |
This is allowed only if the pattern is not a regex, i.e. '~foo[1]' does |
| 501 |
not work (the [1] is interpreted as part of the regex), but 'foo*[1]' |
| 502 |
would work if 'foo*' matched the name of one or more groups. |
| 503 |
|
| 504 |
Duplicate matches are always eliminated from the results. |
| 505 |
""" |
| 506 |
|
| 507 |
if pattern[0] in ("&", "!"): |
| 508 |
pattern = pattern[1:] |
| 509 |
|
| 510 |
if pattern not in self._pattern_cache: |
| 511 |
(expr, slice) = self._split_subscript(pattern) |
| 512 |
hosts = self._enumerate_matches(expr) |
| 513 |
try: |
| 514 |
hosts = self._apply_subscript(hosts, slice) |
| 515 |
except IndexError: |
| 516 |
raise AnsibleError("No hosts matched the subscripted pattern '%s'" % pattern) |
| 517 |
self._pattern_cache[pattern] = hosts |
| 518 |
|
| 519 |
return self._pattern_cache[pattern] |
| 520 |
|
| 521 |
def _split_subscript(self, pattern): |
| 522 |
""" |
| 523 |
Takes a pattern, checks if it has a subscript, and returns the pattern |
| 524 |
without the subscript and a (start,end) tuple representing the given |
| 525 |
subscript (or None if there is no subscript). |
| 526 |
|
| 527 |
Validates that the subscript is in the right syntax, but doesn't make |
| 528 |
sure the actual indices make sense in context. |
| 529 |
""" |
| 530 |
|
| 531 |
# Do not parse regexes for enumeration info |
| 532 |
if pattern[0] == '~': |
| 533 |
return (pattern, None) |
| 534 |
|
| 535 |
# We want a pattern followed by an integer or range subscript. |
| 536 |
# (We can't be more restrictive about the expression because the |
| 537 |
# fnmatch semantics permit [\[:\]] to occur.) |
| 538 |
|
| 539 |
subscript = None |
| 540 |
m = PATTERN_WITH_SUBSCRIPT.match(pattern) |
| 541 |
if m: |
| 542 |
(pattern, idx, start, sep, end) = m.groups() |
| 543 |
if idx: |
| 544 |
subscript = (int(idx), None) |
| 545 |
else: |
| 546 |
if not end: |
| 547 |
end = -1 |
| 548 |
subscript = (int(start), int(end)) |
| 549 |
if sep == '-': |
| 550 |
display.warning("Use [x:y] inclusive subscripts instead of [x-y] which has been removed") |
| 551 |
|
| 552 |
return (pattern, subscript) |
| 553 |
|
| 554 |
def _apply_subscript(self, hosts, subscript): |
| 555 |
""" |
| 556 |
Takes a list of hosts and a (start,end) tuple and returns the subset of |
| 557 |
hosts based on the subscript (which may be None to return all hosts). |
| 558 |
""" |
| 559 |
|
| 560 |
if not hosts or not subscript: |
| 561 |
return hosts |
| 562 |
|
| 563 |
(start, end) = subscript |
| 564 |
|
| 565 |
if end: |
| 566 |
if end == -1: |
| 567 |
end = len(hosts) - 1 |
| 568 |
return hosts[start:end + 1] |
| 569 |
else: |
| 570 |
return [hosts[start]] |
| 571 |
|
| 572 |
def _enumerate_matches(self, pattern): |
| 573 |
""" |
| 574 |
Returns a list of host names matching the given pattern according to the |
| 575 |
rules explained above in _match_one_pattern. |
| 576 |
""" |
| 577 |
|
| 578 |
results = [] |
| 579 |
# check if pattern matches group |
| 580 |
matching_groups = self._match_list(self._inventory.groups, pattern) |
| 581 |
if matching_groups: |
| 582 |
for groupname in matching_groups: |
| 583 |
results.extend(self._inventory.groups[groupname].get_hosts()) |
| 584 |
|
| 585 |
# check hosts if no groups matched or it is a regex/glob pattern |
| 586 |
if not matching_groups or pattern[0] == '~' or any(special in pattern for special in ('.', '?', '*', '[')): |
| 587 |
# pattern might match host |
| 588 |
matching_hosts = self._match_list(self._inventory.hosts, pattern) |
| 589 |
if matching_hosts: |
| 590 |
for hostname in matching_hosts: |
| 591 |
results.append(self._inventory.hosts[hostname]) |
| 592 |
|
| 593 |
if not results and pattern in C.LOCALHOST: |
| 594 |
# get_host autocreates implicit when needed |
| 595 |
implicit = self._inventory.get_host(pattern) |
| 596 |
if implicit: |
| 597 |
results.append(implicit) |
| 598 |
|
| 599 |
# Display warning if specified host pattern did not match any groups or hosts |
| 600 |
if not results and not matching_groups and pattern != 'all': |
| 601 |
msg = "Could not match supplied host pattern, ignoring: %s" % pattern |
| 602 |
display.debug(msg) |
| 603 |
if C.HOST_PATTERN_MISMATCH == 'warning': |
| 604 |
display.warning(msg) |
| 605 |
elif C.HOST_PATTERN_MISMATCH == 'error': |
| 606 |
raise AnsibleError(msg) |
| 607 |
# no need to write 'ignore' state |
| 608 |
|
| 609 |
return results |
| 610 |
|
| 611 |
def list_hosts(self, pattern="all"): |
| 612 |
""" return a list of hostnames for a pattern """ |
| 613 |
# FIXME: cache? |
| 614 |
result = self.get_hosts(pattern) |
| 615 |
|
| 616 |
# allow implicit localhost if pattern matches and no other results |
| 617 |
if len(result) == 0 and pattern in C.LOCALHOST: |
| 618 |
result = [pattern] |
| 619 |
|
| 620 |
return result |
| 621 |
|
| 622 |
def list_groups(self): |
| 623 |
# FIXME: cache? |
| 624 |
return sorted(self._inventory.groups.keys()) |
| 625 |
|
| 626 |
def restrict_to_hosts(self, restriction): |
| 627 |
""" |
| 628 |
Restrict list operations to the hosts given in restriction. This is used |
| 629 |
to batch serial operations in main playbook code, don't use this for other |
| 630 |
reasons. |
| 631 |
""" |
| 632 |
if restriction is None: |
| 633 |
return |
| 634 |
elif not isinstance(restriction, list): |
| 635 |
restriction = [restriction] |
| 636 |
self._restriction = set(to_text(h.name) for h in restriction) |
| 637 |
|
| 638 |
def subset(self, subset_pattern): |
| 639 |
""" |
| 640 |
Limits inventory results to a subset of inventory that matches a given |
| 641 |
pattern, such as to select a given geographic of numeric slice amongst |
| 642 |
a previous 'hosts' selection that only select roles, or vice versa. |
| 643 |
Corresponds to --limit parameter to ansible-playbook |
| 644 |
""" |
| 645 |
if subset_pattern is None: |
| 646 |
self._subset = None |
| 647 |
else: |
| 648 |
subset_patterns = split_host_pattern(subset_pattern) |
| 649 |
results = [] |
| 650 |
# allow Unix style @filename data |
| 651 |
for x in subset_patterns: |
| 652 |
if not x: |
| 653 |
continue |
| 654 |
|
| 655 |
if x[0] == "@": |
| 656 |
b_limit_file = to_bytes(x[1:]) |
| 657 |
if not os.path.exists(b_limit_file): |
| 658 |
raise AnsibleError(u'Unable to find limit file %s' % b_limit_file) |
| 659 |
if not os.path.isfile(b_limit_file): |
| 660 |
raise AnsibleError(u'Limit starting with "@" must be a file, not a directory: %s' % b_limit_file) |
| 661 |
with open(b_limit_file) as fd: |
| 662 |
results.extend([to_text(l.strip()) for l in fd.read().split("\n")]) |
| 663 |
else: |
| 664 |
results.append(to_text(x)) |
| 665 |
self._subset = results |
| 666 |
|
| 667 |
def remove_restriction(self): |
| 668 |
""" Do not restrict list operations """ |
| 669 |
self._restriction = None |
| 670 |
|
| 671 |
def clear_pattern_cache(self): |
| 672 |
self._pattern_cache = {} |
| 673 |
|
| 674 |
def add_dynamic_host(self, host_info: AddHost, already_in_cache: bool = False) -> bool: |
| 675 |
""" |
| 676 |
Helper function to add a new host to inventory based on a task result. |
| 677 |
""" |
| 678 |
changed = False |
| 679 |
|
| 680 |
if not already_in_cache: |
| 681 |
self._cached_dynamic_hosts.append(host_info) |
| 682 |
|
| 683 |
host_name = host_info.host_name |
| 684 |
|
| 685 |
# Check if host in inventory, add if not |
| 686 |
if host_name not in self.hosts: |
| 687 |
self.add_host(host_name, 'all') |
| 688 |
changed = True |
| 689 |
|
| 690 |
new_host = self.hosts.get(host_name) |
| 691 |
|
| 692 |
# Set/update the vars for this host |
| 693 |
new_host_vars = new_host.get_vars() |
| 694 |
new_host_combined_vars = combine_vars(new_host_vars, host_info.host_vars or {}) |
| 695 |
|
| 696 |
if new_host_vars != new_host_combined_vars: |
| 697 |
new_host.vars = new_host_combined_vars |
| 698 |
changed = True |
| 699 |
|
| 700 |
new_groups = host_info.parent_group_names or [] |
| 701 |
|
| 702 |
for group_name in new_groups: |
| 703 |
if group_name not in self.groups: |
| 704 |
group_name = self._inventory.add_group(group_name) |
| 705 |
changed = True |
| 706 |
|
| 707 |
new_group = self.groups[group_name] |
| 708 |
|
| 709 |
if new_group.add_host(self.hosts[host_name]): |
| 710 |
changed = True |
| 711 |
|
| 712 |
# reconcile inventory, ensures inventory rules are followed |
| 713 |
if changed: |
| 714 |
self.reconcile_inventory() |
| 715 |
|
| 716 |
return changed |
| 717 |
|
| 718 |
def add_dynamic_group(self, host_name: str, group_info: AddGroup, already_in_cache: bool = False) -> bool: |
| 719 |
""" |
| 720 |
Helper function to add a group (if it does not exist), and to assign the |
| 721 |
specified host to that group. |
| 722 |
""" |
| 723 |
changed = False |
| 724 |
|
| 725 |
if not already_in_cache: |
| 726 |
self._cached_dynamic_grouping.append((host_name, group_info)) |
| 727 |
|
| 728 |
# the host here is from the executor side, which means it was a |
| 729 |
# serialized/cloned copy and we'll need to look up the proper |
| 730 |
# host object from the master inventory |
| 731 |
real_host = self.hosts.get(host_name) |
| 732 |
|
| 733 |
if real_host is None: |
| 734 |
if host_name == self.localhost.name: |
| 735 |
real_host = self.localhost |
| 736 |
elif not already_in_cache: # RPFIX-5: BUG: pre-existing issue -- this error check probably needs to happen before mutation has already occurred |
| 737 |
raise AnsibleError('%s cannot be matched in inventory' % host_name) |
| 738 |
else: |
| 739 |
# host was removed from inventory during refresh, we should not process |
| 740 |
return False |
| 741 |
|
| 742 |
group_name = group_info.group_name |
| 743 |
|
| 744 |
if group_name not in self.groups: |
| 745 |
group_name = self.add_group(group_name) |
| 746 |
|
| 747 |
for name in group_info.parent_group_names or []: |
| 748 |
if name not in self.groups: |
| 749 |
# create the new group and add it to inventory |
| 750 |
self.add_group(name) |
| 751 |
changed = True |
| 752 |
|
| 753 |
group = self._inventory.groups[group_name] |
| 754 |
|
| 755 |
for parent_group_name in group_info.parent_group_names or []: |
| 756 |
parent_group = self.groups[parent_group_name] |
| 757 |
new = parent_group.add_child_group(group) |
| 758 |
|
| 759 |
if new and not changed: |
| 760 |
changed = True |
| 761 |
|
| 762 |
if real_host not in group.get_hosts(): |
| 763 |
changed = group.add_host(real_host) |
| 764 |
|
| 765 |
if group not in real_host.get_groups(): |
| 766 |
changed = real_host.add_group(group) |
| 767 |
|
| 768 |
if changed: |
| 769 |
self.reconcile_inventory() |
| 770 |
|
| 771 |
return changed |
| 772 |
|
| 773 |
|
| 774 |
class _InventoryDataWrapper(_wrapt.ObjectProxy): |
| 775 |
""" |
| 776 |
Proxy wrapper around InventoryData. |
| 777 |
Allows `set_variable` calls to automatically apply template trust for plugins that don't know how. |
| 778 |
""" |
| 779 |
|
| 780 |
# declared as class attrs to signal to ObjectProxy that we want them stored on the proxy, not the wrapped value |
| 781 |
_target_plugin = None |
| 782 |
_default_origin = None |
| 783 |
|
| 784 |
def __init__(self, referent: InventoryData, target_plugin: BaseInventoryPlugin, origin: Origin) -> None: |
| 785 |
super().__init__(referent) |
| 786 |
self._target_plugin = target_plugin |
| 787 |
# fallback origin to ensure that vars are tagged with at least the file they came from |
| 788 |
self._default_origin = origin |
| 789 |
|
| 790 |
@functools.cached_property |
| 791 |
def _inspector(self) -> _json.AnsibleVariableVisitor: |
| 792 |
""" |
| 793 |
Inventory plugins can delegate to other plugins (e.g. `auto`). |
| 794 |
This hack defers sampling the target plugin's `trusted_by_default` attr until `set_variable` is called, typically inside `parse`. |
| 795 |
Trust is then optionally applied based on the plugin's declared intent via `trusted_by_default`. |
| 796 |
""" |
| 797 |
return _json.AnsibleVariableVisitor( |
| 798 |
trusted_as_template=self._target_plugin.trusted_by_default, |
| 799 |
origin=self._default_origin, |
| 800 |
encrypted_string_behavior=EncryptedStringBehavior.PRESERVE, |
| 801 |
) |
| 802 |
|
| 803 |
def set_variable(self, entity: str, varname: str, value: t.Any) -> None: |
| 804 |
self.__wrapped__.set_variable(entity, varname, self._inspector.visit(value)) |