Debian Codegraph @

lib/ansible/playbook/task.py

raw
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 typing as t
21
22 from ansible import constants as C
23 from ansible.module_utils.common.sentinel import Sentinel
24 from ansible.errors import AnsibleError, AnsibleParserError, AnsibleUndefinedVariable, AnsibleAssertionError, AnsibleValueOmittedError
25 from ansible.executor.module_common import _get_action_arg_defaults
26 from ansible.module_utils.common.text.converters import to_native
27 from ansible.module_utils._internal._datatag import AnsibleTagHelper
28 from ansible.parsing.mod_args import ModuleArgsParser, RAW_PARAM_MODULES
29 from ansible.plugins.action import ActionBase
30 from ansible.plugins.loader import action_loader, module_loader, lookup_loader
31 from ansible.playbook.attribute import NonInheritableFieldAttribute
32 from ansible.playbook.base import Base
33 from ansible.playbook.block import Block
34 from ansible.playbook.collectionsearch import CollectionSearch
35 from ansible.playbook.conditional import Conditional
36 from ansible.playbook.delegatable import Delegatable
37 from ansible.playbook.loop_control import LoopControl
38 from ansible.playbook.notifiable import Notifiable
39 from ansible.playbook.taggable import Taggable
40 from ansible._internal import _task
41 from ansible._internal._templating import _marker_behaviors
42 from ansible._internal._templating._jinja_bits import is_possibly_all_template, is_possibly_template
43 from ansible._internal._templating._engine import TemplateEngine, TemplateOptions
44 from ansible.utils.collection_loader import AnsibleCollectionConfig
45 from ansible.utils.display import Display
46
47 from ansible.utils.vars import validate_variable_name
48
49 __all__ = ['Task']
50
51 display = Display()
52
53
54 class Task(Base, Conditional, Taggable, CollectionSearch, Notifiable, Delegatable):
55
56 """
57 A task is a language feature that represents a call to a module, with given arguments and other parameters.
58 A handler is a subclass of a task.
59
60 Usage:
61
62 Task.load(datastructure) -> Task
63 Task.something(...)
64 """
65
66 _post_validate_object = True
67
68 # =================================================================================
69 # ATTRIBUTES
70 # load_<attribute_name> and
71 # validate_<attribute_name>
72 # will be used if defined
73 # might be possible to define others
74
75 # NOTE: ONLY set defaults on task attributes that are not inheritable,
76 # inheritance is only triggered if the 'current value' is Sentinel,
77 # default can be set at play/top level object and inheritance will take it's course.
78
79 args = t.cast(dict, NonInheritableFieldAttribute(isa='dict', default=dict))
80 action = t.cast(str, NonInheritableFieldAttribute(isa='string'))
81
82 async_val = NonInheritableFieldAttribute(isa='int', default=0, alias='async')
83 changed_when = NonInheritableFieldAttribute(isa='list', default=list)
84 delay = NonInheritableFieldAttribute(isa='float', default=5)
85 failed_when = NonInheritableFieldAttribute(isa='list', default=list)
86 loop = NonInheritableFieldAttribute(isa='list')
87 loop_control = NonInheritableFieldAttribute(isa='class', class_type=LoopControl, default=LoopControl)
88 poll = NonInheritableFieldAttribute(isa='int', default=C.DEFAULT_POLL_INTERVAL)
89 register = NonInheritableFieldAttribute(static=True) # can be str or dict, manual validation required
90 retries = NonInheritableFieldAttribute(isa='int') # default is set in TaskExecutor
91 until = NonInheritableFieldAttribute(isa='list', default=list)
92
93 # deprecated, used to be loop and loop_args but loop has been repurposed
94 loop_with = NonInheritableFieldAttribute(isa='string', private=True)
95
96 def __init__(self, block=None, role=None, task_include=None) -> None:
97 """ constructors a task, without the Task.load classmethod, it will be pretty blank """
98
99 self._role = role
100 self._parent = None
101 self.implicit = False
102 self._resolved_action: str | None = None
103
104 if task_include:
105 self._parent = task_include
106 else:
107 self._parent = block
108
109 super(Task, self).__init__()
110
111 _resolved_action_warning = (
112 "A plugin is sampling the task's resolved_action when it is not resolved. "
113 "This can be caused by callback plugins using the resolved_action attribute too "
114 "early (such as in v2_playbook_on_task_start for a task using the action/local_action "
115 "keyword), or too late (such as in v2_runner_on_ok for a task with a loop). "
116 "To maximize compatibility with user features, callback plugins should "
117 "only use this attribute in v2_runner_on_ok/v2_runner_on_failed for tasks "
118 "without a loop, and v2_runner_item_on_ok/v2_runner_item_on_failed otherwise."
119 )
120
121 @property
122 def resolved_action(self) -> str | None:
123 """The templated and resolved FQCN of the task action or None.
124
125 If the action is a template, callback plugins can only use this value in certain methods.
126 - v2_runner_on_ok and v2_runner_on_failed if there's no task loop
127 - v2_runner_item_on_ok and v2_runner_item_on_failed if there is a task loop
128 """
129 # Consider deprecating this because it's difficult to use?
130 # Moving it to the task result would improve the no-loop limitation on v2_runner_on_ok
131 # but then wouldn't be accessible to v2_playbook_on_task_start, *_on_skipped, etc.
132 if self._resolved_action is not None:
133 return self._resolved_action
134 if not is_possibly_template(self.action):
135 try:
136 return self._resolve_action(self.action)
137 except AnsibleParserError:
138 display.warning(self._resolved_action_warning, obj=self.action)
139 else:
140 display.warning(self._resolved_action_warning, obj=self.action)
141 return None
142
143 def get_name(self, include_role_fqcn=True):
144 """ return the name of the task """
145
146 if self._role:
147 role_name = self._role.get_name(include_role_fqcn=include_role_fqcn)
148
149 if self._role and self.name:
150 return "%s : %s" % (role_name, self.name)
151 elif self.name:
152 return self.name
153 else:
154 if self._role:
155 return "%s : %s" % (role_name, self.action)
156 else:
157 return "%s" % (self.action,)
158
159 def _merge_kv(self, ds):
160 if ds is None:
161 return ""
162 elif isinstance(ds, str):
163 return ds
164 elif isinstance(ds, dict):
165 buf = ""
166 for (k, v) in ds.items():
167 if k.startswith('_'):
168 continue
169 buf = buf + "%s=%s " % (k, v)
170 buf = buf.strip()
171 return buf
172
173 @staticmethod
174 def load(data, block=None, role=None, task_include=None, variable_manager=None, loader=None):
175 task = Task(block=block, role=role, task_include=task_include)
176 return task.load_data(data, variable_manager=variable_manager, loader=loader)
177
178 def _post_validate_module_defaults(self, attr: str, value: t.Any, templar: TemplateEngine) -> t.Any:
179 """Override module_defaults post validation to disable templating, which is handled by args post validation."""
180 return value
181
182 def _post_validate_args(self, attr: str, value: t.Any, templar: TemplateEngine) -> dict[str, t.Any]:
183 try:
184 self.action = templar.template(self.action)
185 except AnsibleValueOmittedError:
186 # some strategies may trigger this error when templating task.action, but backstop here if not
187 raise AnsibleParserError("Omit is not valid for the `action` keyword.", obj=self.action) from None
188
189 action_context = action_loader.get_with_context(self.action, collection_list=self.collections, class_only=True)
190
191 if not action_context.plugin_load_context.resolved:
192 module_or_action_context = module_loader.find_plugin_with_context(self.action, collection_list=self.collections)
193
194 if not module_or_action_context.resolved:
195 raise AnsibleError(f"Cannot resolve {self.action!r} to an action or module.", obj=self.action)
196
197 action_context = action_loader.get_with_context('ansible.legacy.normal', collection_list=self.collections, class_only=True)
198 else:
199 module_or_action_context = action_context.plugin_load_context
200
201 self._resolved_action = module_or_action_context.resolved_fqcn
202
203 action_type: type[ActionBase] = action_context.object
204
205 vp = value.pop('_variable_params', None)
206
207 supports_raw_params = action_type.supports_raw_params or module_or_action_context.resolved_fqcn in RAW_PARAM_MODULES
208
209 if supports_raw_params:
210 raw_params_to_finalize = None
211 else:
212 raw_params_to_finalize = value.pop('_raw_params', None) # always str or None
213
214 # TaskArgsFinalizer performs more thorough type checking, but this provides a friendlier error message for a subset of detected cases.
215 if raw_params_to_finalize and not is_possibly_all_template(raw_params_to_finalize):
216 raise AnsibleError(f'Action {module_or_action_context.resolved_fqcn!r} does not support raw params.', obj=self.action)
217
218 args_finalizer = _task.TaskArgsFinalizer(
219 _get_action_arg_defaults(module_or_action_context.resolved_fqcn, self, templar),
220 vp,
221 raw_params_to_finalize,
222 value,
223 templar=templar,
224 )
225
226 try:
227 with action_type.get_finalize_task_args_context() as finalize_context:
228 args = args_finalizer.finalize(action_type.finalize_task_arg, context=finalize_context)
229 except Exception as ex:
230 raise AnsibleError(f'Finalization of task args for {module_or_action_context.resolved_fqcn!r} failed.', obj=self.action) from ex
231
232 if self._origin:
233 args = self._origin.tag(args)
234
235 return args
236
237 def _get_meta(self) -> str | None:
238 # FUTURE: validate meta and return an enum instead of a str
239 # meta currently does not support being templated, so we can cheat
240 if self.action in C._ACTION_META:
241 return self.args.get('_raw_params')
242
243 return None
244
245 def __repr__(self):
246 """ returns a human-readable representation of the task """
247 if meta := self._get_meta():
248 return f"TASK: meta ({meta})"
249 else:
250 return "TASK: %s" % self.get_name()
251
252 def _preprocess_with_loop(self, ds, new_ds, k, v):
253 """ take a lookup plugin name and store it correctly """
254
255 loop_name = k.removeprefix("with_")
256 if new_ds.get('loop') is not None or new_ds.get('loop_with') is not None:
257 raise AnsibleError("duplicate loop in task: %s" % loop_name, obj=ds)
258 if v is None:
259 raise AnsibleError("you must specify a value when using %s" % k, obj=ds)
260 new_ds['loop_with'] = loop_name
261 new_ds['loop'] = v
262
263 def preprocess_data(self, ds):
264 """
265 tasks are especially complex arguments so need pre-processing.
266 keep it short.
267 """
268
269 if not isinstance(ds, dict):
270 raise AnsibleAssertionError('ds (%s) should be a dict but was a %s' % (ds, type(ds)))
271
272 # the new, cleaned datastructure, which will have legacy items reduced to a standard structure suitable for the
273 # attributes of the task class; copy any tagged data to preserve things like origin
274 new_ds = AnsibleTagHelper.tag_copy(ds, {})
275
276 # since this affects the task action parsing, we have to resolve in preprocess instead of in typical validator
277 default_collection = AnsibleCollectionConfig.default_collection
278
279 collections_list = ds.get('collections')
280 if collections_list is None:
281 # use the parent value if our ds doesn't define it
282 collections_list = self.collections
283 else:
284 # Validate this untemplated field early on to guarantee we are dealing with a list.
285 # This is also done in CollectionSearch._load_collections() but this runs before that call.
286 collections_list = self.get_validated_value('collections', self.fattributes.get('collections'), collections_list, None)
287
288 if default_collection and not self._role: # FIXME: and not a collections role
289 if collections_list:
290 if default_collection not in collections_list:
291 collections_list.insert(0, default_collection)
292 else:
293 collections_list = [default_collection]
294
295 if collections_list and 'ansible.builtin' not in collections_list and 'ansible.legacy' not in collections_list:
296 collections_list.append('ansible.legacy')
297
298 if collections_list:
299 ds['collections'] = collections_list
300
301 # use the args parsing class to determine the action, args,
302 # and the delegate_to value from the various possible forms
303 # supported as legacy
304 args_parser = ModuleArgsParser(task_ds=ds, collection_list=collections_list)
305 try:
306 (action, args, delegate_to) = args_parser.parse()
307 except AnsibleParserError as ex:
308 # if the raises exception was created with obj=ds args, then it includes the detail
309 # so we dont need to add it so we can just re raise.
310 if ex.obj:
311 raise
312 # But if it wasn't, we can add the yaml object now to get more detail
313 raise AnsibleParserError("Error parsing task arguments.", obj=ds) from ex
314
315 if args_parser._resolved_action is not None:
316 self._resolved_action = args_parser._resolved_action
317
318 new_ds['action'] = action
319 new_ds['args'] = args
320 new_ds['delegate_to'] = delegate_to
321
322 # we handle any 'vars' specified in the ds here, as we may
323 # be adding things to them below (special handling for includes).
324 # When that deprecated feature is removed, this can be too.
325 if 'vars' in ds:
326 # _load_vars is defined in Base, and is used to load a dictionary
327 # or list of dictionaries in a standard way
328 new_ds['vars'] = self._load_vars(None, ds.get('vars'))
329 else:
330 new_ds['vars'] = dict()
331
332 for (k, v) in ds.items():
333 if k in ('action', 'local_action', 'args', 'delegate_to') or k == action or k == 'shell':
334 # we don't want to re-assign these values, which were determined by the ModuleArgsParser() above
335 continue
336 elif k.startswith('with_') and k.removeprefix("with_") in lookup_loader:
337 # transform into loop property
338 self._preprocess_with_loop(ds, new_ds, k, v)
339 elif C.INVALID_TASK_ATTRIBUTE_FAILED or k in self.fattributes:
340 new_ds[k] = v
341 else:
342 display.warning("Ignoring invalid attribute: %s" % k)
343
344 return super(Task, self).preprocess_data(new_ds)
345
346 def _load_loop_control(self, attr, ds):
347 if not isinstance(ds, dict):
348 raise AnsibleParserError(
349 "the `loop_control` value must be specified as a dictionary and cannot "
350 "be a variable itself (though it can contain variables)",
351 obj=ds,
352 )
353
354 return LoopControl.load(data=ds, variable_manager=self._variable_manager, loader=self._loader)
355
356 def _validate_attributes(self, ds):
357 try:
358 super(Task, self)._validate_attributes(ds)
359 except AnsibleParserError as e:
360 e.message += '\nThis error can be suppressed as a warning using the "invalid_task_attribute_failed" configuration'
361 raise e
362
363 def _validate_register(self, attr, name, value):
364 if value is None:
365 return
366
367 try:
368 if isinstance(value, dict):
369 any(validate_variable_name(k) for k in value.keys())
370 # RPFIX-5: UX: we've validated the keys, but need validation to ensure that dict values are non-template strings
371 else:
372 validate_variable_name(value)
373 setattr(self, name, {value: _task.POLYMORPHIC_RESULT_EXPRESSION}) # translate to a register projection
374 except Exception as ex:
375 raise AnsibleParserError("Invalid 'register' specified.", obj=value) from ex
376
377 def post_validate(self, templar):
378 """
379 Override of base class post_validate, to also do final validation on
380 the block and task include (if any) to which this task belongs.
381 """
382
383 if self._parent:
384 self._parent.post_validate(templar)
385
386 super(Task, self).post_validate(templar)
387
388 def _post_validate_loop(self, attr, value, templar):
389 """
390 Override post validation for the loop field, which is templated
391 specially in the TaskExecutor class when evaluating loops.
392 """
393 return value
394
395 def _post_validate_name(self, attr, value, templar):
396 """
397 Override post-validation behavior for `name` to be best-effort for the vars available.
398 Direct access via `post_validate_attribute` writes the value back to provide a stable value.
399 This value is individually post-validated early by strategies for the benefit of callbacks.
400 """
401 with _marker_behaviors.ReplacingMarkerBehavior.warning_context() as replacing_behavior:
402 self.name = templar.extend(marker_behavior=replacing_behavior).template(value, options=TemplateOptions(value_for_omit=None))
403
404 return self.name
405
406 def _post_validate_environment(self, attr, value, templar):
407 """
408 Override post validation of vars on the play, as we don't want to
409 template these too early.
410 """
411 env = {}
412
413 # FUTURE: kill this with fire
414 def _parse_env_kv(k, v):
415 try:
416 env[k] = templar.template(v)
417 except AnsibleValueOmittedError:
418 # skip this value
419 return
420 except AnsibleUndefinedVariable as e:
421 error = to_native(e)
422 if self.action in C._ACTION_FACT_GATHERING and 'ansible_facts.env' in error or 'ansible_env' in error:
423 # ignore as fact gathering is required for 'env' facts
424 return
425 raise
426
427 # NB: the environment FieldAttribute definition ensures that value is always a list
428 for env_item in value:
429 if isinstance(env_item, dict):
430 for k in env_item:
431 _parse_env_kv(k, env_item[k])
432 else:
433 try:
434 isdict = templar.template(env_item)
435 except AnsibleValueOmittedError:
436 continue
437
438 if isinstance(isdict, dict):
439 env |= isdict
440 else:
441 display.warning("could not parse environment value, skipping: %s" % value)
442
443 return env
444
445 def _post_validate_changed_when(self, attr, value, templar):
446 """
447 changed_when is evaluated after the execution of the task is complete,
448 and should not be templated during the regular post_validate step.
449 """
450 return value
451
452 def _post_validate_failed_when(self, attr, value, templar):
453 """
454 failed_when is evaluated after the execution of the task is complete,
455 and should not be templated during the regular post_validate step.
456 """
457 return value
458
459 def _post_validate_until(self, attr, value, templar):
460 """
461 until is evaluated after the execution of the task is complete,
462 and should not be templated during the regular post_validate step.
463 """
464 return value
465
466 def get_vars(self):
467 all_vars = dict()
468 if self._parent:
469 all_vars |= self._parent.get_vars()
470
471 all_vars |= self.vars
472
473 if 'tags' in all_vars:
474 del all_vars['tags']
475 if 'when' in all_vars:
476 del all_vars['when']
477
478 return all_vars
479
480 def get_include_params(self):
481 all_vars = dict()
482 if self._parent:
483 all_vars |= self._parent.get_include_params()
484 if self.action in C._ACTION_ALL_INCLUDES:
485 all_vars |= self.vars
486 return all_vars
487
488 def copy(self, exclude_parent: bool = False, exclude_tasks: bool = False) -> Task:
489 new_me = super(Task, self).copy()
490
491 new_me._parent = None
492 if self._parent and not exclude_parent:
493 new_me._parent = self._parent.copy(exclude_tasks=exclude_tasks)
494
495 new_me._role = None
496 if self._role:
497 new_me._role = self._role
498
499 new_me.implicit = self.implicit
500 new_me._resolved_action = self._resolved_action
501 new_me._uuid = self._uuid
502
503 return new_me
504
505 def set_loader(self, loader):
506 """
507 Sets the loader on this object and recursively on parent, child objects.
508 This is used primarily after the Task has been serialized/deserialized, which
509 does not preserve the loader.
510 """
511
512 self._loader = loader
513
514 if self._parent:
515 self._parent.set_loader(loader)
516
517 def _get_parent_attribute(self, attr, omit=False):
518 """
519 Generic logic to get the attribute or parent attribute for a task value.
520 """
521 fattr = self.fattributes[attr]
522
523 extend = fattr.extend
524 prepend = fattr.prepend
525
526 try:
527 # omit self, and only get parent values
528 if omit:
529 value = Sentinel
530 else:
531 value = getattr(self, f'_{attr}', Sentinel)
532
533 # If parent is static, we can grab attrs from the parent
534 # otherwise, defer to the grandparent
535 if getattr(self._parent, 'statically_loaded', True):
536 _parent = self._parent
537 else:
538 _parent = self._parent._parent
539
540 if _parent and (value is Sentinel or extend):
541 if getattr(_parent, 'statically_loaded', True):
542 # vars are always inheritable, other attributes might not be for the parent but still should be for other ancestors
543 if attr != 'vars' and hasattr(_parent, '_get_parent_attribute'):
544 parent_value = _parent._get_parent_attribute(attr)
545 else:
546 parent_value = getattr(_parent, f'_{attr}', Sentinel)
547
548 if extend:
549 value = self._extend_value(value, parent_value, prepend)
550 else:
551 value = parent_value
552 except KeyError:
553 pass
554
555 return value
556
557 def all_parents_static(self):
558 if self._parent:
559 return self._parent.all_parents_static()
560 return True
561
562 def get_first_parent_include(self):
563 from ansible.playbook.task_include import TaskInclude
564 if self._parent:
565 if isinstance(self._parent, TaskInclude):
566 return self._parent
567 return self._parent.get_first_parent_include()
568 return None
569
570 def get_play(self):
571 parent = self._parent
572 while not isinstance(parent, Block):
573 parent = parent._parent
574 return parent._play
575
576 def dump_attrs(self):
577 """Override to smuggle important non-FieldAttribute values back to the controller."""
578 attrs = super().dump_attrs()
579 attrs.update(_resolved_action=self._resolved_action)
580 return attrs
581
582 def from_attrs(self, attrs):
583 super().from_attrs(attrs)
584
585 # from_attrs is only used to create a finalized task
586 # from attrs from the Worker/TaskExecutor
587 # Those attrs are finalized and squashed in the TE
588 # and controller side use needs to reflect that
589 self._finalized = True
590 self._squashed = True
591
592 def _resolve_conditional(
593 self,
594 conditional: list[str | bool],
595 variables: dict[str, t.Any],
596 ) -> bool:
597 """Loops through the conditionals set on this object, returning False if any of them evaluate as such."""
598
599 return self._resolve_conditional_with_item(conditional, variables)[0]
600
601 def _resolve_conditional_with_item(
602 self,
603 conditional: list[str | bool],
604 variables: dict[str, t.Any],
605 ) -> tuple[bool, object]:
606 """Loops through the conditionals set on this object, returning False if any of them evaluate as such, as well as the condition that was False."""
607
608 # early bailout, True seems weird though...
609 if not conditional:
610 return True, None
611
612 engine = TemplateEngine(self._loader, variables=variables)
613
614 for item in conditional:
615 if not engine.evaluate_conditional(item):
616 return False, item
617
618 return True, None