| 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 |
from __future__ import annotations |
| 19 |
|
| 20 |
import sys |
| 21 |
import typing as t |
| 22 |
|
| 23 |
from collections import defaultdict |
| 24 |
from collections.abc import Mapping, MutableMapping |
| 25 |
|
| 26 |
from ansible import constants as C |
| 27 |
from ansible.module_utils._internal import _deprecator |
| 28 |
from ansible.module_utils._internal._datatag import _tags |
| 29 |
from ansible.errors import (AnsibleError, AnsibleParserError, AnsibleUndefinedVariable, AnsibleFileNotFound, |
| 30 |
AnsibleAssertionError, AnsibleValueOmittedError) |
| 31 |
from ansible.inventory.host import Host |
| 32 |
from ansible.inventory.helpers import sort_groups, get_group_vars |
| 33 |
from ansible.inventory.manager import InventoryManager |
| 34 |
from ansible.module_utils.datatag import native_type_name |
| 35 |
from ansible.parsing.dataloader import DataLoader |
| 36 |
from ansible._internal._templating._engine import TemplateEngine |
| 37 |
from ansible.plugins.loader import cache_loader |
| 38 |
from ansible.utils.display import Display |
| 39 |
from ansible.utils.vars import combine_vars, load_extra_vars, load_options_vars |
| 40 |
from ansible.vars.clean import namespace_facts, clean_facts |
| 41 |
from ansible.vars.hostvars import HostVars |
| 42 |
from ansible.vars.plugins import get_vars_from_inventory_sources, get_vars_from_path |
| 43 |
from ansible.vars.reserved import warn_if_reserved |
| 44 |
|
| 45 |
if t.TYPE_CHECKING: |
| 46 |
from ansible.playbook import Play |
| 47 |
from ansible.playbook.task import Task |
| 48 |
|
| 49 |
display = Display() |
| 50 |
|
| 51 |
_DEPRECATE_TOP_LEVEL_FACT_TAG = _tags.Deprecated( |
| 52 |
msg='INJECT_FACTS_AS_VARS default to `True` is deprecated, top-level facts will not be auto injected after the change.', |
| 53 |
version='2.24', |
| 54 |
deprecator=_deprecator.ANSIBLE_CORE_DEPRECATOR, |
| 55 |
help_text='Use `ansible_facts["fact_name"]` (no `ansible_` prefix) instead.', |
| 56 |
) |
| 57 |
_DEPRECATE_VARS = _tags.Deprecated( |
| 58 |
msg='The internal "vars" dictionary is deprecated.', |
| 59 |
version='2.24', |
| 60 |
deprecator=_deprecator.ANSIBLE_CORE_DEPRECATOR, |
| 61 |
help_text='Use the `vars` and `varnames` lookups instead.', |
| 62 |
) |
| 63 |
|
| 64 |
|
| 65 |
def _deprecate_top_level_fact(value: t.Any) -> t.Any: |
| 66 |
""" |
| 67 |
Deprecate the given top-level fact value. |
| 68 |
The inner values are shared to aid in message de-duplication across hosts/values, and reduce intra-process memory usage. |
| 69 |
Unique tag instances are required to achieve the correct de-duplication within a top-level templating operation. |
| 70 |
""" |
| 71 |
return _DEPRECATE_TOP_LEVEL_FACT_TAG.tag(value) |
| 72 |
|
| 73 |
|
| 74 |
_INJECT_FACTS, _INJECT_FACTS_ORIGIN = C.config.get_config_value_and_origin('INJECT_FACTS_AS_VARS') |
| 75 |
|
| 76 |
|
| 77 |
def _clean_and_deprecate_top_level_facts(facts: Mapping[str, object]) -> dict[str, object]: |
| 78 |
if _INJECT_FACTS_ORIGIN == 'default': |
| 79 |
cleaned_facts = {k: _deprecate_top_level_fact(v) if k != 'ansible_local' else v for k, v in clean_facts(facts).items()} |
| 80 |
else: |
| 81 |
cleaned_facts = clean_facts(facts) |
| 82 |
|
| 83 |
return cleaned_facts |
| 84 |
|
| 85 |
|
| 86 |
def preprocess_vars(a): |
| 87 |
""" |
| 88 |
Ensures that vars contained in the parameter passed in are |
| 89 |
returned as a list of dictionaries, to ensure for instance |
| 90 |
that vars loaded from a file conform to an expected state. |
| 91 |
""" |
| 92 |
|
| 93 |
# FIXME: this does not properly handle omit, undefined, or dynamic structure from templated `vars` ; templating should be done earlier |
| 94 |
if a is None: |
| 95 |
return None |
| 96 |
elif not isinstance(a, list): |
| 97 |
data = [a] |
| 98 |
else: |
| 99 |
data = a |
| 100 |
|
| 101 |
for item in data: |
| 102 |
if not isinstance(item, MutableMapping): |
| 103 |
raise AnsibleParserError( |
| 104 |
message="Invalid variable file contents.", |
| 105 |
obj=item, |
| 106 |
help_text="Variable files must contain either a dictionary of variables, or a list of dictionaries.", |
| 107 |
) |
| 108 |
|
| 109 |
return data |
| 110 |
|
| 111 |
|
| 112 |
class VariableManager: |
| 113 |
|
| 114 |
_ALLOWED = frozenset(['plugins_by_group', 'groups_plugins_play', 'groups_plugins_inventory', 'groups_inventory', |
| 115 |
'all_plugins_play', 'all_plugins_inventory', 'all_inventory']) |
| 116 |
|
| 117 |
_PLAY_HOSTS_DEPRECATED_TAG = _tags.Deprecated( |
| 118 |
msg='The `play_hosts` magic variable is deprecated.', |
| 119 |
version='2.23', |
| 120 |
deprecator=_deprecator.ANSIBLE_CORE_DEPRECATOR, |
| 121 |
help_text='Use `ansible_play_batch` instead.', |
| 122 |
) |
| 123 |
|
| 124 |
def __init__(self, loader: DataLoader | None = None, inventory: InventoryManager | None = None, version_info: dict[str, str] | None = None) -> None: |
| 125 |
self._nonpersistent_fact_cache: defaultdict[str, dict] = defaultdict(dict) |
| 126 |
self._vars_cache: defaultdict[str, dict] = defaultdict(dict) |
| 127 |
self._inventory = inventory |
| 128 |
self._loader = loader |
| 129 |
self._hostvars: HostVars | None = None |
| 130 |
|
| 131 |
self._options_vars = load_options_vars(version_info) |
| 132 |
|
| 133 |
# If the basedir is specified as the empty string then it results in cwd being used. |
| 134 |
# This is not a safe location to load vars from. |
| 135 |
basedir = self._options_vars.get('basedir', False) |
| 136 |
self.safe_basedir = bool(basedir is False or basedir) |
| 137 |
|
| 138 |
# load extra vars |
| 139 |
self._extra_vars = load_extra_vars(loader=self._loader) |
| 140 |
|
| 141 |
# load fact cache |
| 142 |
try: |
| 143 |
self._fact_cache = cache_loader.get(C.CACHE_PLUGIN) |
| 144 |
except Exception as ex: |
| 145 |
# bad cache plugin is not fatal error |
| 146 |
# fallback to builtin memory cache plugin |
| 147 |
display.error_as_warning(None, ex) |
| 148 |
self._fact_cache = cache_loader.get('ansible.builtin.memory') # use FQCN to ensure the builtin version is used |
| 149 |
|
| 150 |
@property |
| 151 |
def extra_vars(self): |
| 152 |
return self._extra_vars |
| 153 |
|
| 154 |
def set_inventory(self, inventory): |
| 155 |
self._inventory = inventory |
| 156 |
|
| 157 |
def get_vars( |
| 158 |
self, |
| 159 |
play: Play | None = None, |
| 160 |
host: Host | None = None, |
| 161 |
task: Task | None = None, |
| 162 |
include_hostvars: bool = True, |
| 163 |
use_cache: bool = True, |
| 164 |
_hosts: list[str] | None = None, |
| 165 |
_hosts_all: list[str] | None = None, |
| 166 |
stage: str = 'task', |
| 167 |
) -> dict[str, t.Any]: |
| 168 |
""" |
| 169 |
Returns the variables, with optional "context" given via the parameters |
| 170 |
for the play, host, and task (which could possibly result in different |
| 171 |
sets of variables being returned due to the additional context). |
| 172 |
|
| 173 |
The order of precedence is: |
| 174 |
- play->roles->get_default_vars (if there is a play context) |
| 175 |
- group_vars_files[host] (if there is a host context) |
| 176 |
- host->get_vars (if there is a host context) |
| 177 |
- fact_cache[host] (if there is a host context) |
| 178 |
- play vars (if there is a play context) |
| 179 |
- play vars_files (if there's no host context, ignore |
| 180 |
file names that cannot be templated) |
| 181 |
- task->get_vars (if there is a task context) |
| 182 |
- vars_cache[host] (if there is a host context) |
| 183 |
- extra vars |
| 184 |
|
| 185 |
``_hosts`` and ``_hosts_all`` should be considered private args, with only internal trusted callers relying |
| 186 |
on the functionality they provide. These arguments may be removed at a later date without a deprecation |
| 187 |
period and without warning. |
| 188 |
""" |
| 189 |
|
| 190 |
display.debug("in VariableManager get_vars()") |
| 191 |
|
| 192 |
all_vars: dict[str, t.Any] = dict() |
| 193 |
magic_variables = self._get_magic_variables( |
| 194 |
play=play, |
| 195 |
host=host, |
| 196 |
task=task, |
| 197 |
include_hostvars=include_hostvars, |
| 198 |
_hosts=_hosts, |
| 199 |
_hosts_all=_hosts_all, |
| 200 |
) |
| 201 |
|
| 202 |
def _combine_and_track(data, new_data, source): |
| 203 |
# FIXME: this no longer does any tracking, only a slight optimization for empty new_data |
| 204 |
if new_data == {}: |
| 205 |
return data |
| 206 |
|
| 207 |
return combine_vars(data, new_data) |
| 208 |
|
| 209 |
# default for all cases |
| 210 |
basedirs = [] |
| 211 |
if self.safe_basedir: # avoid adhoc/console loading cwd |
| 212 |
basedirs = [self._loader.get_basedir()] |
| 213 |
|
| 214 |
if play: |
| 215 |
# get role defaults (lowest precedence) |
| 216 |
for role in play.roles: |
| 217 |
if role.public: |
| 218 |
all_vars = _combine_and_track(all_vars, role.get_default_vars(), "role '%s' defaults" % role.name) |
| 219 |
|
| 220 |
if task: |
| 221 |
# set basedirs |
| 222 |
if C.PLAYBOOK_VARS_ROOT == 'all': # should be default |
| 223 |
basedirs = task.get_search_path() |
| 224 |
elif C.PLAYBOOK_VARS_ROOT in ('bottom', 'playbook_dir'): # only option in 2.4.0 |
| 225 |
basedirs = [task.get_search_path()[0]] |
| 226 |
elif C.PLAYBOOK_VARS_ROOT != 'top': |
| 227 |
# preserves default basedirs, only option pre 2.3 |
| 228 |
raise AnsibleError('Unknown playbook vars logic: %s' % C.PLAYBOOK_VARS_ROOT) |
| 229 |
|
| 230 |
# if we have a task in this context, and that task has a role, make |
| 231 |
# sure it sees its defaults above any other roles, as we previously |
| 232 |
# (v1) made sure each task had a copy of its roles default vars |
| 233 |
# TODO: investigate why we need play or include_role check? |
| 234 |
if task._role is not None and (play or task.action in C._ACTION_INCLUDE_ROLE): |
| 235 |
all_vars = _combine_and_track(all_vars, task._role.get_default_vars(dep_chain=task.get_dep_chain()), "role '%s' defaults" % task._role.name) |
| 236 |
|
| 237 |
if host: |
| 238 |
# THE 'all' group and the rest of groups for a host, used below |
| 239 |
all_group = self._inventory.groups.get('all') |
| 240 |
host_groups = sort_groups([g for g in host.get_groups() if g.name != 'all']) |
| 241 |
|
| 242 |
# internal functions that actually do the work |
| 243 |
def _plugins_inventory(entities): |
| 244 |
""" merges all entities by inventory source """ |
| 245 |
return get_vars_from_inventory_sources(self._loader, self._inventory._sources, entities, stage) |
| 246 |
|
| 247 |
def _plugins_play(entities): |
| 248 |
""" merges all entities adjacent to play """ |
| 249 |
data = {} |
| 250 |
for path in basedirs: |
| 251 |
data = _combine_and_track(data, get_vars_from_path(self._loader, path, entities, stage), "path '%s'" % path) |
| 252 |
return data |
| 253 |
|
| 254 |
# configurable functions that are sortable via config, remember to add to _ALLOWED if expanding this list |
| 255 |
def all_inventory(): |
| 256 |
return all_group.get_vars() |
| 257 |
|
| 258 |
def all_plugins_inventory(): |
| 259 |
return _plugins_inventory([all_group]) |
| 260 |
|
| 261 |
def all_plugins_play(): |
| 262 |
return _plugins_play([all_group]) |
| 263 |
|
| 264 |
def groups_inventory(): |
| 265 |
""" gets group vars from inventory """ |
| 266 |
return get_group_vars(host_groups) |
| 267 |
|
| 268 |
def groups_plugins_inventory(): |
| 269 |
""" gets plugin sources from inventory for groups """ |
| 270 |
return _plugins_inventory(host_groups) |
| 271 |
|
| 272 |
def groups_plugins_play(): |
| 273 |
""" gets plugin sources from play for groups """ |
| 274 |
return _plugins_play(host_groups) |
| 275 |
|
| 276 |
def plugins_by_groups(): |
| 277 |
""" |
| 278 |
merges all plugin sources by group, |
| 279 |
This should be used instead, NOT in combination with the other groups_plugins* functions |
| 280 |
""" |
| 281 |
data = {} |
| 282 |
for group in host_groups: |
| 283 |
data[group] = _combine_and_track(data[group], _plugins_inventory(group), "inventory group_vars for '%s'" % group) |
| 284 |
data[group] = _combine_and_track(data[group], _plugins_play(group), "playbook group_vars for '%s'" % group) |
| 285 |
return data |
| 286 |
|
| 287 |
# Merge groups as per precedence config |
| 288 |
# only allow to call the functions we want exposed |
| 289 |
for entry in C.VARIABLE_PRECEDENCE: |
| 290 |
if entry in self._ALLOWED: |
| 291 |
display.debug('Calling %s to load vars for %s' % (entry, host.name)) |
| 292 |
all_vars = _combine_and_track(all_vars, locals()[entry](), "group vars, precedence entry '%s'" % entry) |
| 293 |
else: |
| 294 |
display.warning('Ignoring unknown variable precedence entry: %s' % (entry)) |
| 295 |
|
| 296 |
# host vars, from inventory, inventory adjacent and play adjacent via plugins |
| 297 |
all_vars = _combine_and_track(all_vars, host.get_vars(), "host vars for '%s'" % host) |
| 298 |
all_vars = _combine_and_track(all_vars, _plugins_inventory([host]), "inventory host_vars for '%s'" % host) |
| 299 |
all_vars = _combine_and_track(all_vars, _plugins_play([host]), "playbook host_vars for '%s'" % host) |
| 300 |
|
| 301 |
# finally, the facts caches for this host, if they exist |
| 302 |
try: |
| 303 |
try: |
| 304 |
facts = self._fact_cache.get(host.name) |
| 305 |
except KeyError: |
| 306 |
facts = {} |
| 307 |
|
| 308 |
all_vars |= namespace_facts(facts) |
| 309 |
|
| 310 |
# push facts to main namespace |
| 311 |
if _INJECT_FACTS: |
| 312 |
clean_top = _clean_and_deprecate_top_level_facts(facts) |
| 313 |
all_vars = _combine_and_track(all_vars, clean_top, "facts") |
| 314 |
else: |
| 315 |
# always 'promote' ansible_local, even if empty |
| 316 |
all_vars = _combine_and_track(all_vars, {'ansible_local': facts.get('ansible_local', {})}, "facts") |
| 317 |
except KeyError: |
| 318 |
pass |
| 319 |
|
| 320 |
if play: |
| 321 |
all_vars = _combine_and_track(all_vars, play.get_vars(), "play vars") |
| 322 |
|
| 323 |
vars_files = play.get_vars_files() |
| 324 |
|
| 325 |
for vars_file_item in vars_files: |
| 326 |
# create a set of temporary vars here, which incorporate the extra |
| 327 |
# and magic vars so we can properly template the vars_files entries |
| 328 |
# NOTE: this makes them depend on host vars/facts so things like |
| 329 |
# ansible_facts['os_distribution'] can be used, ala include_vars. |
| 330 |
# Consider DEPRECATING this in the future, since we have include_vars ... |
| 331 |
temp_vars = combine_vars(all_vars, self._extra_vars) |
| 332 |
temp_vars = combine_vars(temp_vars, magic_variables) |
| 333 |
templar = TemplateEngine(loader=self._loader, variables=temp_vars) |
| 334 |
|
| 335 |
# we assume each item in the list is itself a list, as we |
| 336 |
# support "conditional includes" for vars_files, which mimics |
| 337 |
# the with_first_found mechanism. |
| 338 |
vars_file_list = vars_file_item |
| 339 |
if not isinstance(vars_file_list, list): |
| 340 |
vars_file_list = [vars_file_list] |
| 341 |
|
| 342 |
# now we iterate through the (potential) files, and break out |
| 343 |
# as soon as we read one from the list. If none are found, we |
| 344 |
# raise an error, which is silently ignored at this point. |
| 345 |
try: |
| 346 |
for vars_file in vars_file_list: |
| 347 |
vars_file = templar.template(vars_file) |
| 348 |
if not (isinstance(vars_file, str)): |
| 349 |
raise AnsibleParserError( |
| 350 |
message=f"Invalid `vars_files` value of type {native_type_name(vars_file)!r}.", |
| 351 |
obj=vars_file, |
| 352 |
help_text="A `vars_files` value should either be a string or list of strings.", |
| 353 |
) |
| 354 |
try: |
| 355 |
play_search_stack = play.get_search_path() |
| 356 |
found_file = self._loader.path_dwim_relative_stack(play_search_stack, 'vars', vars_file) |
| 357 |
data = preprocess_vars(self._loader.load_from_file(found_file, unsafe=True, cache='vaulted', trusted_as_template=True)) |
| 358 |
if data is not None: |
| 359 |
for item in data: |
| 360 |
all_vars = _combine_and_track(all_vars, item, f"play vars_files from {vars_file!r}") |
| 361 |
display.vvv(f"Read `vars_file` {found_file!r}.") |
| 362 |
break |
| 363 |
except AnsibleFileNotFound: |
| 364 |
# we continue on loader failures |
| 365 |
continue |
| 366 |
except (AnsibleParserError, AnsibleUndefinedVariable): |
| 367 |
raise |
| 368 |
except AnsibleError as e: |
| 369 |
raise AnsibleError(f"Invalid vars_files file {found_file!r}.") from e |
| 370 |
|
| 371 |
except AnsibleUndefinedVariable as ex: |
| 372 |
if host is not None: |
| 373 |
try: |
| 374 |
facts = self._fact_cache.get(host.name) |
| 375 |
except KeyError: |
| 376 |
pass |
| 377 |
else: |
| 378 |
if facts.get('module_setup') and task is not None: |
| 379 |
raise AnsibleUndefinedVariable("an undefined variable was found when attempting to template the vars_files item '%s'" |
| 380 |
% vars_file_item, obj=vars_file_item) from ex |
| 381 |
|
| 382 |
display.warning("skipping vars_files item due to an undefined variable", obj=vars_file_item) |
| 383 |
continue |
| 384 |
|
| 385 |
# We now merge in all exported vars from all roles in the play (very high precedence) |
| 386 |
for role in play.roles: |
| 387 |
if role.public: |
| 388 |
all_vars = _combine_and_track(all_vars, role.get_vars(include_params=False, only_exports=True), "role '%s' exported vars" % role.name) |
| 389 |
|
| 390 |
# next, we merge in the vars from the role, which will specifically |
| 391 |
# follow the role dependency chain, and then we merge in the tasks |
| 392 |
# vars (which will look at parent blocks/task includes) |
| 393 |
if task: |
| 394 |
if task._role: |
| 395 |
all_vars = _combine_and_track(all_vars, task._role.get_vars(task.get_dep_chain(), include_params=False, only_exports=False), |
| 396 |
"role '%s' all vars" % task._role.name) |
| 397 |
all_vars = _combine_and_track(all_vars, task.get_vars(), "task vars") |
| 398 |
|
| 399 |
# next, we merge in the vars cache (include vars) and nonpersistent |
| 400 |
# facts cache (set_fact/register), in that order |
| 401 |
if host: |
| 402 |
# include_vars non-persistent cache |
| 403 |
all_vars = _combine_and_track(all_vars, self._vars_cache.get(host.get_name(), dict()), "include_vars") |
| 404 |
# fact non-persistent cache (this also includes registered variables and host variables set at runtime) |
| 405 |
all_vars = _combine_and_track(all_vars, self._nonpersistent_fact_cache.get(host.name, dict()), "set_fact") |
| 406 |
|
| 407 |
# next, we merge in role params and task include params |
| 408 |
if task: |
| 409 |
# special case for include tasks, where the include params |
| 410 |
# may be specified in the vars field for the task, which should |
| 411 |
# have higher precedence than the vars/np facts above |
| 412 |
if task._role: |
| 413 |
all_vars = _combine_and_track(all_vars, task._role.get_role_params(task.get_dep_chain()), "role params") |
| 414 |
all_vars = _combine_and_track(all_vars, task.get_include_params(), "include params") |
| 415 |
|
| 416 |
# extra vars |
| 417 |
all_vars = _combine_and_track(all_vars, self._extra_vars, "extra vars") |
| 418 |
|
| 419 |
# before we add 'reserved vars', check we didn't add any reserved vars |
| 420 |
warn_if_reserved(all_vars) |
| 421 |
|
| 422 |
# magic variables |
| 423 |
all_vars = _combine_and_track(all_vars, magic_variables, "magic vars") |
| 424 |
|
| 425 |
# special case for the 'environment' magic variable, as someone |
| 426 |
# may have set it as a variable and we don't want to stomp on it |
| 427 |
if task: |
| 428 |
all_vars['environment'] = task.environment |
| 429 |
|
| 430 |
# 'vars' magic var |
| 431 |
if task or play: |
| 432 |
all_vars['vars'] = _DEPRECATE_VARS.tag({}) |
| 433 |
for k, v in all_vars.items(): |
| 434 |
# has to be copy, otherwise recursive ref |
| 435 |
all_vars['vars'][k] = _DEPRECATE_VARS.tag(v) |
| 436 |
|
| 437 |
display.debug("done with get_vars()") |
| 438 |
return all_vars |
| 439 |
|
| 440 |
def _facts_gathered_for_host(self, hostname) -> bool: |
| 441 |
try: |
| 442 |
facts = self._fact_cache.get(hostname) |
| 443 |
except KeyError: |
| 444 |
facts = {} |
| 445 |
|
| 446 |
return bool(facts.get('_ansible_facts_gathered', False)) |
| 447 |
|
| 448 |
def _get_magic_variables(self, play, host, task, include_hostvars, _hosts=None, _hosts_all=None): |
| 449 |
""" |
| 450 |
Returns a dictionary of so-called "magic" variables in Ansible, |
| 451 |
which are special variables we set internally for use. |
| 452 |
""" |
| 453 |
|
| 454 |
variables = {} |
| 455 |
variables['playbook_dir'] = self._loader.get_basedir() |
| 456 |
variables['ansible_playbook_python'] = sys.executable |
| 457 |
variables['ansible_config_file'] = C.CONFIG_FILE |
| 458 |
|
| 459 |
if play: |
| 460 |
# using role_cache as play.roles only has 'public' roles for vars exporting |
| 461 |
dependency_role_names = list({d.get_name() for r in play.roles for d in r.get_all_dependencies()}) |
| 462 |
play_role_names = [r.get_name() for r in play.roles] |
| 463 |
|
| 464 |
# ansible_role_names includes all role names, dependent or directly referenced by the play |
| 465 |
variables['ansible_role_names'] = list(set(dependency_role_names + play_role_names)) |
| 466 |
# ansible_play_role_names includes the names of all roles directly referenced by this play |
| 467 |
# roles that are implicitly referenced via dependencies are not listed. |
| 468 |
variables['ansible_play_role_names'] = play_role_names |
| 469 |
# ansible_dependent_role_names includes the names of all roles that are referenced via dependencies |
| 470 |
# dependencies that are also explicitly named as roles are included in this list |
| 471 |
variables['ansible_dependent_role_names'] = dependency_role_names |
| 472 |
|
| 473 |
# TODO: data tagging!!! DEPRECATED: role_names should be deprecated in favor of ansible_ prefixed ones |
| 474 |
variables['role_names'] = variables['ansible_play_role_names'] |
| 475 |
|
| 476 |
variables['ansible_play_name'] = play.get_name() |
| 477 |
|
| 478 |
if task: |
| 479 |
if task._role: |
| 480 |
variables['role_name'] = task._role.get_name(include_role_fqcn=False) |
| 481 |
variables['role_path'] = task._role._role_path |
| 482 |
variables['role_uuid'] = str(task._role._uuid) |
| 483 |
variables['ansible_collection_name'] = task._role._role_collection |
| 484 |
variables['ansible_role_name'] = task._role.get_name() |
| 485 |
|
| 486 |
if self._inventory is not None: |
| 487 |
variables['groups'] = self._inventory.get_groups_dict() |
| 488 |
if play: |
| 489 |
# add the list of hosts in the play, as adjusted for limit/filters |
| 490 |
if not _hosts_all: |
| 491 |
if not play.finalized and TemplateEngine().is_template(play.hosts): |
| 492 |
pattern = 'all' |
| 493 |
else: |
| 494 |
pattern = play.hosts or 'all' |
| 495 |
|
| 496 |
_hosts_all = [h.name for h in self._inventory.get_hosts(pattern=pattern, ignore_restrictions=True)] |
| 497 |
if not _hosts: |
| 498 |
_hosts = [h.name for h in self._inventory.get_hosts()] |
| 499 |
|
| 500 |
variables['ansible_play_hosts_all'] = _hosts_all[:] |
| 501 |
variables['ansible_play_hosts'] = [x for x in variables['ansible_play_hosts_all'] if x not in play._removed_hosts] |
| 502 |
variables['ansible_play_batch'] = [x for x in _hosts if x not in play._removed_hosts] |
| 503 |
|
| 504 |
# use a static tag instead of `deprecate_value` to avoid stackwalk in a hot code path |
| 505 |
variables['play_hosts'] = self._PLAY_HOSTS_DEPRECATED_TAG.tag(variables['ansible_play_batch']) |
| 506 |
|
| 507 |
# Set options vars |
| 508 |
for option, option_value in self._options_vars.items(): |
| 509 |
variables[option] = option_value |
| 510 |
|
| 511 |
if self._hostvars is not None and include_hostvars: |
| 512 |
variables['hostvars'] = self._hostvars |
| 513 |
|
| 514 |
return variables |
| 515 |
|
| 516 |
def get_delegated_vars_and_hostname(self, templar, task, variables): |
| 517 |
"""Get the delegated_vars for an individual task invocation, which may be in the context |
| 518 |
of an individual loop iteration. |
| 519 |
|
| 520 |
Not used directly be VariableManager, but used primarily within TaskExecutor |
| 521 |
""" |
| 522 |
delegated_vars = {} |
| 523 |
delegated_host_name = ... # sentinel value distinct from empty/None, which are errors |
| 524 |
|
| 525 |
if task.delegate_to is not None: |
| 526 |
try: |
| 527 |
delegated_host_name = templar.template(task.delegate_to) |
| 528 |
except AnsibleValueOmittedError: |
| 529 |
pass |
| 530 |
|
| 531 |
# bypass for unspecified value/omit |
| 532 |
if delegated_host_name is ...: |
| 533 |
return delegated_vars, None |
| 534 |
|
| 535 |
if not delegated_host_name: |
| 536 |
raise AnsibleError('Empty hostname produced from delegate_to: "%s"' % task.delegate_to) |
| 537 |
|
| 538 |
delegated_host = self._inventory.get_host(delegated_host_name) |
| 539 |
if delegated_host is None: |
| 540 |
for h in self._inventory.get_hosts(ignore_limits=True, ignore_restrictions=True): |
| 541 |
# check if the address matches, or if both the delegated_to host |
| 542 |
# and the current host are in the list of localhost aliases |
| 543 |
if h.address == delegated_host_name: |
| 544 |
delegated_host = h |
| 545 |
break |
| 546 |
else: |
| 547 |
delegated_host = Host(name=delegated_host_name) |
| 548 |
|
| 549 |
delegated_vars['ansible_delegated_vars'] = { |
| 550 |
delegated_host_name: self.get_vars( |
| 551 |
play=task.get_play(), |
| 552 |
host=delegated_host, |
| 553 |
task=task, |
| 554 |
include_hostvars=True, |
| 555 |
) |
| 556 |
} |
| 557 |
delegated_vars['ansible_delegated_vars'][delegated_host_name]['inventory_hostname'] = variables.get('inventory_hostname') |
| 558 |
|
| 559 |
return delegated_vars, delegated_host_name |
| 560 |
|
| 561 |
def clear_facts(self, hostname): |
| 562 |
""" |
| 563 |
Clears the facts for a host |
| 564 |
""" |
| 565 |
try: |
| 566 |
self._fact_cache.delete(hostname) |
| 567 |
except KeyError: |
| 568 |
pass |
| 569 |
|
| 570 |
def set_host_facts(self, host, facts): |
| 571 |
""" |
| 572 |
Sets or updates the given facts for a host in the fact cache. |
| 573 |
""" |
| 574 |
|
| 575 |
if not isinstance(facts, Mapping): |
| 576 |
raise AnsibleAssertionError("the type of 'facts' to set for host_facts should be a Mapping but is a %s" % type(facts)) |
| 577 |
|
| 578 |
warn_if_reserved(facts) |
| 579 |
|
| 580 |
try: |
| 581 |
host_cache = self._fact_cache.get(host) |
| 582 |
except KeyError: |
| 583 |
# We get to set this as new |
| 584 |
host_cache = facts |
| 585 |
else: |
| 586 |
if not isinstance(host_cache, MutableMapping): |
| 587 |
raise TypeError('The object retrieved for {0} must be a MutableMapping but was' |
| 588 |
' a {1}'.format(host, type(host_cache))) |
| 589 |
# Update the existing facts |
| 590 |
host_cache |= facts |
| 591 |
|
| 592 |
# Save the facts back to the backing store |
| 593 |
self._fact_cache.set(host, host_cache) |
| 594 |
|
| 595 |
def set_nonpersistent_facts(self, host, facts): |
| 596 |
""" |
| 597 |
Sets or updates the given facts for a host in the fact cache. |
| 598 |
""" |
| 599 |
|
| 600 |
if not isinstance(facts, Mapping): |
| 601 |
raise AnsibleAssertionError("the type of 'facts' to set for nonpersistent_facts should be a Mapping but is a %s" % type(facts)) |
| 602 |
|
| 603 |
warn_if_reserved(facts) |
| 604 |
|
| 605 |
try: |
| 606 |
self._nonpersistent_fact_cache[host] |= facts |
| 607 |
except KeyError: |
| 608 |
self._nonpersistent_fact_cache[host] = facts |
| 609 |
|
| 610 |
def set_host_variable(self, host, varname, value): |
| 611 |
""" |
| 612 |
Sets a value in the vars_cache for a host. |
| 613 |
""" |
| 614 |
|
| 615 |
warn_if_reserved([varname]) |
| 616 |
|
| 617 |
if host not in self._vars_cache: |
| 618 |
self._vars_cache[host] = dict() |
| 619 |
|
| 620 |
if varname in self._vars_cache[host] and isinstance(self._vars_cache[host][varname], MutableMapping) and isinstance(value, MutableMapping): |
| 621 |
self._vars_cache[host] = combine_vars(self._vars_cache[host], {varname: value}) |
| 622 |
else: |
| 623 |
self._vars_cache[host][varname] = value |