| 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 functools as _functools |
| 21 |
import os |
| 22 |
import typing as _t |
| 23 |
|
| 24 |
from collections.abc import Container, Mapping, Set, Sequence |
| 25 |
from types import MappingProxyType |
| 26 |
|
| 27 |
from ansible import constants as C |
| 28 |
from ansible.errors import AnsibleError, AnsibleParserError, AnsibleAssertionError, AnsibleActionFail |
| 29 |
from ansible.module_utils.common.sentinel import Sentinel |
| 30 |
from ansible.module_utils.common.text.converters import to_text |
| 31 |
from ansible.playbook.base import Base |
| 32 |
from ansible.playbook.collectionsearch import CollectionSearch |
| 33 |
from ansible.playbook.conditional import Conditional |
| 34 |
from ansible.playbook.delegatable import Delegatable |
| 35 |
from ansible.playbook.helpers import load_list_of_blocks |
| 36 |
from ansible.playbook.role.metadata import RoleMetadata |
| 37 |
from ansible.playbook.taggable import Taggable |
| 38 |
from ansible.plugins.loader import add_all_plugin_dirs |
| 39 |
from ansible.utils.collection_loader import AnsibleCollectionConfig |
| 40 |
from ansible.utils.display import Display |
| 41 |
from ansible.utils.path import is_subpath |
| 42 |
from ansible.utils.vars import combine_vars |
| 43 |
|
| 44 |
# NOTE: This import is only needed for the type-checking in __init__. While there's an alternative |
| 45 |
# available by using forward references this seems not to work well with commonly used IDEs. |
| 46 |
# Therefore the TYPE_CHECKING hack seems to be a more universal approach, even if not being very elegant. |
| 47 |
# References: |
| 48 |
# * https://stackoverflow.com/q/39740632/199513 |
| 49 |
# * https://peps.python.org/pep-0484/#forward-references |
| 50 |
if _t.TYPE_CHECKING: |
| 51 |
from ansible.playbook.block import Block |
| 52 |
from ansible.playbook.play import Play |
| 53 |
|
| 54 |
__all__ = ['Role', 'hash_params'] |
| 55 |
|
| 56 |
_display = Display() |
| 57 |
|
| 58 |
|
| 59 |
def hash_params(params): |
| 60 |
""" |
| 61 |
DEPRECATED |
| 62 |
Construct a data structure of parameters that is hashable. |
| 63 |
|
| 64 |
This requires changing any mutable data structures into immutable ones. |
| 65 |
We chose a frozenset because role parameters have to be unique. |
| 66 |
|
| 67 |
.. warning:: this does not handle unhashable scalars. Two things |
| 68 |
mitigate that limitation: |
| 69 |
|
| 70 |
1) There shouldn't be any unhashable scalars specified in the yaml |
| 71 |
2) Our only choice would be to return an error anyway. |
| 72 |
""" |
| 73 |
|
| 74 |
_display.deprecated( |
| 75 |
msg="The hash_params function is deprecated as its consumers have moved to internal alternatives", |
| 76 |
version='2.24', |
| 77 |
help_text='Contact the plugin author to update their code', |
| 78 |
) |
| 79 |
# Any container is unhashable if it contains unhashable items (for |
| 80 |
# instance, tuple() is a Hashable subclass but if it contains a dict, it |
| 81 |
# cannot be hashed) |
| 82 |
if isinstance(params, Container) and not isinstance(params, (str, bytes)): |
| 83 |
if isinstance(params, Mapping): |
| 84 |
try: |
| 85 |
# Optimistically hope the contents are all hashable |
| 86 |
new_params = frozenset(params.items()) |
| 87 |
except TypeError: |
| 88 |
new_params = set() |
| 89 |
for k, v in params.items(): |
| 90 |
# Hash each entry individually |
| 91 |
new_params.add((k, hash_params(v))) |
| 92 |
new_params = frozenset(new_params) |
| 93 |
|
| 94 |
elif isinstance(params, (Set, Sequence)): |
| 95 |
try: |
| 96 |
# Optimistically hope the contents are all hashable |
| 97 |
new_params = frozenset(params) |
| 98 |
except TypeError: |
| 99 |
new_params = set() |
| 100 |
for v in params: |
| 101 |
# Hash each entry individually |
| 102 |
new_params.add(hash_params(v)) |
| 103 |
new_params = frozenset(new_params) |
| 104 |
else: |
| 105 |
# This is just a guess. |
| 106 |
new_params = frozenset(params) |
| 107 |
return new_params |
| 108 |
|
| 109 |
# Note: We do not handle unhashable scalars but our only choice would be |
| 110 |
# to raise an error there anyway. |
| 111 |
return frozenset((params,)) |
| 112 |
|
| 113 |
|
| 114 |
class Role(Base, Conditional, Taggable, CollectionSearch, Delegatable): |
| 115 |
|
| 116 |
def __init__(self, |
| 117 |
play: Play = None, |
| 118 |
from_files: dict[str, list[str]] = None, |
| 119 |
from_include: bool = False, |
| 120 |
validate: bool = True, |
| 121 |
public: bool = None, |
| 122 |
static: bool = True, |
| 123 |
rescuable: bool = True) -> None: |
| 124 |
|
| 125 |
self._role_name: str = None |
| 126 |
self._role_path: str = None |
| 127 |
self._role_collection: str = None |
| 128 |
self._role_params: dict[str, dict[str, str]] = dict() |
| 129 |
self._loader = None |
| 130 |
self.static: bool = static |
| 131 |
self._rescuable: bool = rescuable |
| 132 |
|
| 133 |
# includes (static=false) default to private, while imports (static=true) default to public |
| 134 |
# but both can be overridden by global config if set |
| 135 |
if public is None: |
| 136 |
global_private, origin = C.config.get_config_value_and_origin('DEFAULT_PRIVATE_ROLE_VARS') |
| 137 |
if origin == 'default': |
| 138 |
self.public = static |
| 139 |
else: |
| 140 |
self.public = not global_private |
| 141 |
else: |
| 142 |
self.public = public |
| 143 |
|
| 144 |
self._metadata: RoleMetadata = RoleMetadata() |
| 145 |
self._play: Play = play |
| 146 |
self._parents: list[Role] = [] |
| 147 |
self._dependencies: list[Role] = [] |
| 148 |
self._all_dependencies: list[Role] | None = None |
| 149 |
self._task_blocks: list[Block] = [] |
| 150 |
self._handler_blocks: list[Block] = [] |
| 151 |
self._compiled_handler_blocks: list[Block] | None = None |
| 152 |
self._default_vars: dict[str, str] | None = dict() |
| 153 |
self._role_vars: dict[str, str] | None = dict() |
| 154 |
self._had_task_run: dict[str, bool] = dict() |
| 155 |
self._completed: dict[str, bool] = dict() |
| 156 |
self._should_validate: bool = validate |
| 157 |
|
| 158 |
if from_files is None: |
| 159 |
from_files = {} |
| 160 |
self._from_files: dict[str, list[str]] = from_files |
| 161 |
|
| 162 |
# Indicates whether this role was included via include/import_role |
| 163 |
self.from_include: bool = from_include |
| 164 |
|
| 165 |
self._hash = None |
| 166 |
|
| 167 |
super(Role, self).__init__() |
| 168 |
|
| 169 |
def __repr__(self): |
| 170 |
return self.get_name() |
| 171 |
|
| 172 |
@_functools.cached_property |
| 173 |
def _FAIL(self): |
| 174 |
return AnsibleActionFail if self._rescuable else AnsibleParserError |
| 175 |
|
| 176 |
def get_name(self, include_role_fqcn=True): |
| 177 |
if include_role_fqcn: |
| 178 |
return '.'.join(x for x in (self._role_collection, self._role_name) if x) |
| 179 |
return self._role_name |
| 180 |
|
| 181 |
def get_role_path(self): |
| 182 |
# Purposefully using realpath for canonical path |
| 183 |
return os.path.realpath(self._role_path) |
| 184 |
|
| 185 |
def _get_hash_dict(self): |
| 186 |
if self._hash: |
| 187 |
return self._hash |
| 188 |
self._hash = MappingProxyType( |
| 189 |
{ |
| 190 |
'name': self.get_name(), |
| 191 |
'path': self.get_role_path(), |
| 192 |
'params': MappingProxyType(self.get_role_params()), |
| 193 |
'when': self.when, |
| 194 |
'tags': self.tags, |
| 195 |
'from_files': MappingProxyType(self._from_files), |
| 196 |
'vars': MappingProxyType(self.vars), |
| 197 |
'from_include': self.from_include, |
| 198 |
} |
| 199 |
) |
| 200 |
return self._hash |
| 201 |
|
| 202 |
def __eq__(self, other): |
| 203 |
if not isinstance(other, Role): |
| 204 |
return False |
| 205 |
|
| 206 |
return self._get_hash_dict() == other._get_hash_dict() |
| 207 |
|
| 208 |
@staticmethod |
| 209 |
def load(role_include, play, parent_role=None, from_files=None, from_include=False, validate=True, public=None, static=True, rescuable=True): |
| 210 |
if from_files is None: |
| 211 |
from_files = {} |
| 212 |
try: |
| 213 |
# TODO: need to fix cycle detection in role load (maybe use an empty dict |
| 214 |
# for the in-flight in role cache as a sentinel that we're already trying to load |
| 215 |
# that role?) |
| 216 |
# see https://github.com/ansible/ansible/issues/61527 |
| 217 |
r = Role(play=play, from_files=from_files, from_include=from_include, validate=validate, public=public, static=static, rescuable=rescuable) |
| 218 |
r._load_role_data(role_include, parent_role=parent_role) |
| 219 |
|
| 220 |
role_path = r.get_role_path() |
| 221 |
if role_path not in play.role_cache: |
| 222 |
play.role_cache[role_path] = [] |
| 223 |
|
| 224 |
# Using the role path as a cache key is done to improve performance when a large number of roles |
| 225 |
# are in use in the play |
| 226 |
if r not in play.role_cache[role_path]: |
| 227 |
play.role_cache[role_path].append(r) |
| 228 |
|
| 229 |
return r |
| 230 |
|
| 231 |
except RecursionError as ex: |
| 232 |
raise AnsibleError("A recursion loop was detected with the roles specified. Make sure child roles do not have dependencies on parent roles", |
| 233 |
obj=role_include._ds) from ex |
| 234 |
|
| 235 |
def _load_role_data(self, role_include, parent_role=None): |
| 236 |
self._role_name = role_include.role |
| 237 |
self._role_path = role_include.get_role_path() |
| 238 |
self._role_collection = role_include._role_collection |
| 239 |
self._role_params = role_include.get_role_params() |
| 240 |
self._variable_manager = role_include.get_variable_manager() |
| 241 |
self._loader = role_include.get_loader() |
| 242 |
|
| 243 |
if parent_role: |
| 244 |
self.add_parent(parent_role) |
| 245 |
|
| 246 |
# copy over all field attributes from the RoleInclude |
| 247 |
# update self._attr directly, to avoid squashing |
| 248 |
for attr_name in self.fattributes: |
| 249 |
setattr(self, f'_{attr_name}', getattr(role_include, f'_{attr_name}', Sentinel)) |
| 250 |
|
| 251 |
# vars and default vars are regular dictionaries |
| 252 |
self._role_vars = self._load_role_yaml('vars', main=self._from_files.get('vars'), allow_dir=True) |
| 253 |
if self._role_vars is None: |
| 254 |
self._role_vars = {} |
| 255 |
elif not isinstance(self._role_vars, Mapping): |
| 256 |
raise AnsibleParserError("The vars/main.yml file for role '%s' must contain a dictionary of variables" % self._role_name) |
| 257 |
|
| 258 |
self._default_vars = self._load_role_yaml('defaults', main=self._from_files.get('defaults'), allow_dir=True) |
| 259 |
if self._default_vars is None: |
| 260 |
self._default_vars = {} |
| 261 |
elif not isinstance(self._default_vars, Mapping): |
| 262 |
raise AnsibleParserError("The defaults/main.yml file for role '%s' must contain a dictionary of variables" % self._role_name) |
| 263 |
|
| 264 |
# load the role's other files, if they exist |
| 265 |
metadata = self._load_role_yaml('meta') |
| 266 |
if metadata: |
| 267 |
self._metadata = RoleMetadata.load(metadata, owner=self, variable_manager=self._variable_manager, loader=self._loader) |
| 268 |
self._dependencies = self._load_dependencies() |
| 269 |
|
| 270 |
# reset collections list; roles do not inherit collections from parents, just use the defaults |
| 271 |
# FUTURE: use a private config default for this so we can allow it to be overridden later |
| 272 |
self.collections = [] |
| 273 |
|
| 274 |
# configure plugin/collection loading; either prepend the current role's collection or configure legacy plugin loading |
| 275 |
# FIXME: need exception for explicit ansible.legacy? |
| 276 |
if self._role_collection: # this is a collection-hosted role |
| 277 |
self.collections.insert(0, self._role_collection) |
| 278 |
else: # this is a legacy role, but set the default collection if there is one |
| 279 |
default_collection = AnsibleCollectionConfig.default_collection |
| 280 |
if default_collection: |
| 281 |
self.collections.insert(0, default_collection) |
| 282 |
# legacy role, ensure all plugin dirs under the role are added to plugin search path |
| 283 |
add_all_plugin_dirs(self._role_path) |
| 284 |
|
| 285 |
# collections can be specified in metadata for legacy or collection-hosted roles |
| 286 |
if self._metadata.collections: |
| 287 |
self.collections.extend((c for c in self._metadata.collections if c not in self.collections)) |
| 288 |
|
| 289 |
# if any collections were specified, ensure that core or legacy synthetic collections are always included |
| 290 |
if self.collections: |
| 291 |
# default append collection is core for collection-hosted roles, legacy for others |
| 292 |
default_append_collection = 'ansible.builtin' if self._role_collection else 'ansible.legacy' |
| 293 |
if 'ansible.builtin' not in self.collections and 'ansible.legacy' not in self.collections: |
| 294 |
self.collections.append(default_append_collection) |
| 295 |
|
| 296 |
task_data = self._load_role_yaml('tasks', main=self._from_files.get('tasks')) |
| 297 |
|
| 298 |
if self._should_validate: |
| 299 |
role_argspecs = self._get_role_argspecs() |
| 300 |
task_data = self._prepend_validation_task(task_data, role_argspecs) |
| 301 |
|
| 302 |
if task_data: |
| 303 |
try: |
| 304 |
self._task_blocks = load_list_of_blocks(task_data, play=self._play, role=self, loader=self._loader, variable_manager=self._variable_manager) |
| 305 |
except AssertionError as ex: |
| 306 |
raise AnsibleParserError(f"The tasks/main.yml file for role {self._role_name!r} must contain a list of tasks.", obj=task_data) from ex |
| 307 |
|
| 308 |
handler_data = self._load_role_yaml('handlers', main=self._from_files.get('handlers')) |
| 309 |
if handler_data: |
| 310 |
try: |
| 311 |
self._handler_blocks = load_list_of_blocks(handler_data, play=self._play, role=self, use_handlers=True, loader=self._loader, |
| 312 |
variable_manager=self._variable_manager) |
| 313 |
except AssertionError as ex: |
| 314 |
raise AnsibleParserError(f"The handlers/main.yml file for role {self._role_name!r} must contain a list of tasks.", |
| 315 |
obj=handler_data) from ex |
| 316 |
|
| 317 |
def _get_role_argspecs(self): |
| 318 |
"""Get the role argument spec data. |
| 319 |
|
| 320 |
Role arg specs can be in one of two files in the role meta subdir: argument_specs.yml |
| 321 |
or main.yml. The former has precedence over the latter. Data is not combined |
| 322 |
between the files. |
| 323 |
|
| 324 |
:returns: A dict of all data under the top-level ``argument_specs`` YAML key |
| 325 |
in the argument spec file. An empty dict is returned if there is no |
| 326 |
argspec data. |
| 327 |
""" |
| 328 |
base_argspec_path = os.path.join(self._role_path, 'meta', 'argument_specs') |
| 329 |
|
| 330 |
for ext in C.YAML_FILENAME_EXTENSIONS: |
| 331 |
full_path = base_argspec_path + ext |
| 332 |
if self._loader.path_exists(full_path): |
| 333 |
# Note: _load_role_yaml() takes care of rebuilding the path. |
| 334 |
argument_specs = self._load_role_yaml('meta', main='argument_specs') |
| 335 |
try: |
| 336 |
return argument_specs.get('argument_specs') or {} |
| 337 |
except AttributeError: |
| 338 |
return {} |
| 339 |
|
| 340 |
# We did not find the meta/argument_specs.[yml|yaml] file, so use the spec |
| 341 |
# dict from the role meta data, if it exists. Ansible 2.11 and later will |
| 342 |
# have the 'argument_specs' attribute, but earlier versions will not. |
| 343 |
return getattr(self._metadata, 'argument_specs', {}) |
| 344 |
|
| 345 |
def _prepend_validation_task(self, task_data, argspecs): |
| 346 |
"""Insert a role validation task if we have a role argument spec. |
| 347 |
|
| 348 |
This method will prepend a validation task to the front of the role task |
| 349 |
list to perform argument spec validation before any other tasks, if an arg spec |
| 350 |
exists for the entry point. Entry point defaults to `main`. |
| 351 |
|
| 352 |
:param task_data: List of tasks loaded from the role. |
| 353 |
:param argspecs: The role argument spec data dict. |
| 354 |
|
| 355 |
:returns: The (possibly modified) task list. |
| 356 |
""" |
| 357 |
if argspecs: |
| 358 |
# Determine the role entry point so we can retrieve the correct argument spec. |
| 359 |
# This comes from the `tasks_from` value to include_role or import_role. |
| 360 |
entrypoint = self._from_files.get('tasks', 'main') |
| 361 |
entrypoint_arg_spec = argspecs.get(entrypoint) |
| 362 |
|
| 363 |
if entrypoint_arg_spec: |
| 364 |
validation_task = self._create_validation_task(entrypoint_arg_spec, entrypoint) |
| 365 |
|
| 366 |
# Prepend our validate_argument_spec action to happen before any tasks provided by the role. |
| 367 |
# 'any tasks' can and does include 0 or None tasks, in which cases we create a list of tasks and add our |
| 368 |
# validate_argument_spec task |
| 369 |
if not task_data: |
| 370 |
task_data = [] |
| 371 |
task_data.insert(0, validation_task) |
| 372 |
return task_data |
| 373 |
|
| 374 |
def _create_validation_task(self, argument_spec, entrypoint_name): |
| 375 |
"""Create a new task data structure that uses the validate_argument_spec action plugin. |
| 376 |
|
| 377 |
:param argument_spec: The arg spec definition for a particular role entry point. |
| 378 |
This will be the entire arg spec for the entry point as read from the input file. |
| 379 |
:param entrypoint_name: The name of the role entry point associated with the |
| 380 |
supplied `argument_spec`. |
| 381 |
""" |
| 382 |
|
| 383 |
# If the arg spec provides a short description, use it to flesh out the validation task name |
| 384 |
task_name = "Validating arguments against arg spec '%s'" % entrypoint_name |
| 385 |
if 'short_description' in argument_spec: |
| 386 |
task_name = task_name + ' - ' + argument_spec['short_description'] |
| 387 |
|
| 388 |
return { |
| 389 |
'action': 'ansible.builtin.validate_argument_spec', |
| 390 |
'args': { |
| 391 |
# Pass only the 'options' portion of the arg spec to the module. |
| 392 |
'argument_spec': argument_spec.get('options', {}), |
| 393 |
'provided_arguments': self._role_params, |
| 394 |
'validate_args_context': { |
| 395 |
'type': 'role', |
| 396 |
'name': self._role_name, |
| 397 |
'argument_spec_name': entrypoint_name, |
| 398 |
'path': self._role_path |
| 399 |
}, |
| 400 |
}, |
| 401 |
'name': task_name, |
| 402 |
'tags': ['always'], |
| 403 |
} |
| 404 |
|
| 405 |
def _load_role_yaml(self, subdir, main=None, allow_dir=False): |
| 406 |
""" |
| 407 |
Find and load role YAML files and return data found. |
| 408 |
:param subdir: subdir of role to search (vars, files, tasks, handlers, defaults) |
| 409 |
:type subdir: string |
| 410 |
:param main: filename to match, will default to 'main.<ext>' if not provided. |
| 411 |
:type main: string |
| 412 |
:param allow_dir: If true we combine results of multiple matching files found. |
| 413 |
If false, highlander rules. Only for vars(dicts) and not tasks(lists). |
| 414 |
:type allow_dir: bool |
| 415 |
|
| 416 |
:returns: data from the matched file(s), type can be dict or list depending on vars or tasks. |
| 417 |
""" |
| 418 |
data = None |
| 419 |
file_path = os.path.join(self._role_path, subdir) |
| 420 |
if self._loader.path_exists(file_path) and self._loader.is_directory(file_path): |
| 421 |
# Valid extensions and ordering for roles is hard-coded to maintain portability |
| 422 |
extensions = ['.yml', '.yaml', '.json'] # same as default for YAML_FILENAME_EXTENSIONS |
| 423 |
|
| 424 |
# look for files w/o extensions before/after bare name depending on it being set or not |
| 425 |
# keep 'main' as original to figure out errors if no files found |
| 426 |
if main is None: |
| 427 |
_main = 'main' |
| 428 |
extensions.append('') |
| 429 |
else: |
| 430 |
_main = main |
| 431 |
extensions.insert(0, '') |
| 432 |
|
| 433 |
# not really 'find_vars_files' but find_files_with_extensions_default_to_yaml_filename_extensions |
| 434 |
found_files = self._loader.find_vars_files(file_path, _main, extensions, allow_dir) |
| 435 |
if found_files: |
| 436 |
for found in found_files: |
| 437 |
|
| 438 |
if not is_subpath(found, file_path): |
| 439 |
raise self._FAIL(f"Failed loading '{found!r}' for role ({self._role_name}) " |
| 440 |
f"as it is not inside the expected role path: {file_path!r}") |
| 441 |
|
| 442 |
new_data = self._loader.load_from_file(found, trusted_as_template=True) |
| 443 |
if new_data: |
| 444 |
if data is not None and isinstance(new_data, Mapping): |
| 445 |
data = combine_vars(data, new_data) |
| 446 |
else: |
| 447 |
data = new_data |
| 448 |
|
| 449 |
# found data so no need to continue unless we want to merge |
| 450 |
if not allow_dir: |
| 451 |
break |
| 452 |
|
| 453 |
elif main is not None: |
| 454 |
# this won't trigger with default only when <subdir>_from is specified |
| 455 |
raise self._FAIL(f"Could not find specified file in role: {subdir}/{main}") |
| 456 |
elif main is not None: |
| 457 |
# this won't trigger with default only when <subdir>_from is specified |
| 458 |
raise self._FAIL(f"Could not find specified file in role, its '{subdir}/' is not usable.") |
| 459 |
|
| 460 |
return data |
| 461 |
|
| 462 |
def _load_dependencies(self): |
| 463 |
""" |
| 464 |
Recursively loads role dependencies from the metadata list of |
| 465 |
dependencies, if it exists |
| 466 |
""" |
| 467 |
|
| 468 |
deps = [] |
| 469 |
for role_include in self._metadata.dependencies: |
| 470 |
r = Role.load(role_include, play=self._play, parent_role=self, static=self.static) |
| 471 |
deps.append(r) |
| 472 |
|
| 473 |
return deps |
| 474 |
|
| 475 |
# other functions |
| 476 |
|
| 477 |
def add_parent(self, parent_role): |
| 478 |
""" adds a role to the list of this roles parents """ |
| 479 |
if not isinstance(parent_role, Role): |
| 480 |
raise AnsibleAssertionError() |
| 481 |
|
| 482 |
if parent_role not in self._parents: |
| 483 |
self._parents.append(parent_role) |
| 484 |
|
| 485 |
def get_parents(self): |
| 486 |
return self._parents |
| 487 |
|
| 488 |
def get_dep_chain(self): |
| 489 |
dep_chain = [] |
| 490 |
for parent in self._parents: |
| 491 |
dep_chain.extend(parent.get_dep_chain()) |
| 492 |
dep_chain.append(parent) |
| 493 |
return dep_chain |
| 494 |
|
| 495 |
def get_default_vars(self, dep_chain=None): |
| 496 |
dep_chain = [] if dep_chain is None else dep_chain |
| 497 |
|
| 498 |
default_vars = dict() |
| 499 |
for dep in self.get_all_dependencies(): |
| 500 |
default_vars = combine_vars(default_vars, dep.get_default_vars()) |
| 501 |
if dep_chain: |
| 502 |
for parent in dep_chain: |
| 503 |
default_vars = combine_vars(default_vars, parent._default_vars) |
| 504 |
default_vars = combine_vars(default_vars, self._default_vars) |
| 505 |
return default_vars |
| 506 |
|
| 507 |
def get_inherited_vars(self, dep_chain=None, only_exports=False): |
| 508 |
dep_chain = [] if dep_chain is None else dep_chain |
| 509 |
|
| 510 |
inherited_vars = dict() |
| 511 |
|
| 512 |
if dep_chain: |
| 513 |
for parent in dep_chain: |
| 514 |
if not only_exports: |
| 515 |
inherited_vars = combine_vars(inherited_vars, parent.vars) |
| 516 |
inherited_vars = combine_vars(inherited_vars, parent._role_vars) |
| 517 |
return inherited_vars |
| 518 |
|
| 519 |
def get_role_params(self, dep_chain=None): |
| 520 |
dep_chain = [] if dep_chain is None else dep_chain |
| 521 |
|
| 522 |
params = {} |
| 523 |
if dep_chain: |
| 524 |
for parent in dep_chain: |
| 525 |
params = combine_vars(params, parent._role_params) |
| 526 |
params = combine_vars(params, self._role_params) |
| 527 |
return params |
| 528 |
|
| 529 |
def get_vars(self, dep_chain=None, include_params=True, only_exports=False): |
| 530 |
dep_chain = [] if dep_chain is None else dep_chain |
| 531 |
|
| 532 |
all_vars = {} |
| 533 |
|
| 534 |
# get role_vars: from parent objects |
| 535 |
# TODO: is this right precedence for inherited role_vars? |
| 536 |
all_vars = self.get_inherited_vars(dep_chain, only_exports=only_exports) |
| 537 |
|
| 538 |
# get exported variables from meta/dependencies |
| 539 |
seen = [] |
| 540 |
for dep in self.get_all_dependencies(): |
| 541 |
# Avoid rerunning dupe deps since they can have vars from previous invocations and they accumulate in deps |
| 542 |
# TODO: re-examine dep loading to see if we are somehow improperly adding the same dep too many times |
| 543 |
if dep not in seen: |
| 544 |
# only take 'exportable' vars from deps |
| 545 |
all_vars = combine_vars(all_vars, dep.get_vars(include_params=False, only_exports=True)) |
| 546 |
seen.append(dep) |
| 547 |
|
| 548 |
# role_vars come from vars/ in a role |
| 549 |
all_vars = combine_vars(all_vars, self._role_vars) |
| 550 |
|
| 551 |
if not only_exports: |
| 552 |
# include_params are 'inline variables' in role invocation. - {role: x, varname: value} |
| 553 |
if include_params: |
| 554 |
# TODO: add deprecation notice |
| 555 |
all_vars = combine_vars(all_vars, self.get_role_params(dep_chain=dep_chain)) |
| 556 |
|
| 557 |
# these come from vars: keyword in role invocation. - {role: x, vars: {varname: value}} |
| 558 |
all_vars = combine_vars(all_vars, self.vars) |
| 559 |
|
| 560 |
return all_vars |
| 561 |
|
| 562 |
def get_direct_dependencies(self): |
| 563 |
return self._dependencies[:] |
| 564 |
|
| 565 |
def get_all_dependencies(self): |
| 566 |
""" |
| 567 |
Returns a list of all deps, built recursively from all child dependencies, |
| 568 |
in the proper order in which they should be executed or evaluated. |
| 569 |
""" |
| 570 |
if self._all_dependencies is None: |
| 571 |
|
| 572 |
self._all_dependencies = [] |
| 573 |
for dep in self.get_direct_dependencies(): |
| 574 |
for child_dep in dep.get_all_dependencies(): |
| 575 |
self._all_dependencies.append(child_dep) |
| 576 |
self._all_dependencies.append(dep) |
| 577 |
|
| 578 |
return self._all_dependencies |
| 579 |
|
| 580 |
def get_task_blocks(self): |
| 581 |
return self._task_blocks[:] |
| 582 |
|
| 583 |
def get_handler_blocks(self, play, dep_chain=None): |
| 584 |
# Do not recreate this list each time ``get_handler_blocks`` is called. |
| 585 |
# Cache the results so that we don't potentially overwrite with copied duplicates |
| 586 |
# |
| 587 |
# ``get_handler_blocks`` may be called when handling ``import_role`` during parsing |
| 588 |
# as well as with ``Play.compile_roles_handlers`` from ``TaskExecutor`` |
| 589 |
if self._compiled_handler_blocks: |
| 590 |
return self._compiled_handler_blocks |
| 591 |
|
| 592 |
self._compiled_handler_blocks = block_list = [] |
| 593 |
|
| 594 |
# update the dependency chain here |
| 595 |
if dep_chain is None: |
| 596 |
dep_chain = [] |
| 597 |
new_dep_chain = dep_chain + [self] |
| 598 |
|
| 599 |
for dep in self.get_direct_dependencies(): |
| 600 |
dep_blocks = dep.get_handler_blocks(play=play, dep_chain=new_dep_chain) |
| 601 |
block_list.extend(dep_blocks) |
| 602 |
|
| 603 |
for task_block in self._handler_blocks: |
| 604 |
new_task_block = task_block.copy() |
| 605 |
new_task_block._dep_chain = new_dep_chain |
| 606 |
new_task_block._play = play |
| 607 |
block_list.append(new_task_block) |
| 608 |
|
| 609 |
return block_list |
| 610 |
|
| 611 |
def has_run(self, host): |
| 612 |
""" |
| 613 |
Returns true if this role has been iterated over completely and |
| 614 |
at least one task was run |
| 615 |
""" |
| 616 |
|
| 617 |
return host.name in self._completed |
| 618 |
|
| 619 |
def compile(self, play, dep_chain=None): |
| 620 |
""" |
| 621 |
Returns the task list for this role, which is created by first |
| 622 |
recursively compiling the tasks for all direct dependencies, and |
| 623 |
then adding on the tasks for this role. |
| 624 |
|
| 625 |
The role compile() also remembers and saves the dependency chain |
| 626 |
with each task, so tasks know by which route they were found, and |
| 627 |
can correctly take their parent's tags/conditionals into account. |
| 628 |
""" |
| 629 |
from ansible.playbook.block import Block |
| 630 |
from ansible.playbook.task import Task |
| 631 |
|
| 632 |
block_list = [] |
| 633 |
|
| 634 |
# update the dependency chain here |
| 635 |
if dep_chain is None: |
| 636 |
dep_chain = [] |
| 637 |
new_dep_chain = dep_chain + [self] |
| 638 |
|
| 639 |
deps = self.get_direct_dependencies() |
| 640 |
for dep in deps: |
| 641 |
dep_blocks = dep.compile(play=play, dep_chain=new_dep_chain) |
| 642 |
block_list.extend(dep_blocks) |
| 643 |
|
| 644 |
for task_block in self._task_blocks: |
| 645 |
new_task_block = task_block.copy() |
| 646 |
new_task_block._dep_chain = new_dep_chain |
| 647 |
new_task_block._play = play |
| 648 |
block_list.append(new_task_block) |
| 649 |
|
| 650 |
eor_block = Block(play=play) |
| 651 |
eor_block._loader = self._loader |
| 652 |
eor_block._role = self |
| 653 |
eor_block._variable_manager = self._variable_manager |
| 654 |
eor_block.run_once = False |
| 655 |
|
| 656 |
eor_task = Task(block=eor_block) |
| 657 |
eor_task._role = self |
| 658 |
eor_task.action = 'meta' |
| 659 |
eor_task.args = {'_raw_params': 'role_complete'} |
| 660 |
eor_task.implicit = True |
| 661 |
eor_task.tags = ['always'] |
| 662 |
eor_task.when = True |
| 663 |
|
| 664 |
eor_block.block = [eor_task] |
| 665 |
block_list.append(eor_block) |
| 666 |
|
| 667 |
return block_list |
| 668 |
|
| 669 |
def set_loader(self, loader): |
| 670 |
self._loader = loader |
| 671 |
for parent in self._parents: |
| 672 |
parent.set_loader(loader) |
| 673 |
for dep in self.get_direct_dependencies(): |
| 674 |
dep.set_loader(loader) |