Debian Codegraph @

lib/ansible/playbook/play.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 functools as _functools
21 import pathlib as _pathlib
22
23 from ansible import constants as C
24 from ansible import context
25 from ansible.errors import AnsibleError
26 from ansible.errors import AnsibleParserError, AnsibleAssertionError, AnsibleValueOmittedError
27 from ansible.module_utils.common.collections import is_sequence
28 from ansible.module_utils.common.yaml import yaml_dump
29 from ansible.playbook.attribute import NonInheritableFieldAttribute
30 from ansible.playbook.base import Base
31 from ansible.playbook.block import Block
32 from ansible.playbook.collectionsearch import CollectionSearch
33 from ansible.playbook.helpers import load_list_of_blocks, load_list_of_roles
34 from ansible.playbook.role import Role
35 from ansible.playbook.task import Task
36 from ansible.playbook.taggable import Taggable
37 from ansible.parsing.vault import EncryptedString
38 from ansible.utils.display import Display
39
40 from ansible._internal._templating._engine import TemplateEngine as _TE
41
42 display = Display()
43
44
45 __all__ = ['Play']
46
47
48 class Play(Base, Taggable, CollectionSearch):
49
50 """
51 A play is a language feature that represents a list of roles and/or
52 task/handler blocks to execute on a given set of hosts.
53
54 Usage:
55
56 Play.load(datastructure) -> Play
57 Play.something(...)
58 """
59
60 # =================================================================================
61 hosts = NonInheritableFieldAttribute(isa='list', required=True, listof=(str,), always_post_validate=True, priority=-2)
62
63 # Facts
64 gather_facts = NonInheritableFieldAttribute(isa='bool', default=None, always_post_validate=True)
65 gather_subset = NonInheritableFieldAttribute(isa='list', default=None, listof=(str,), always_post_validate=True)
66 gather_timeout = NonInheritableFieldAttribute(isa='int', default=None, always_post_validate=True)
67 fact_path = NonInheritableFieldAttribute(isa='string', default=None)
68
69 # Variable Attributes
70 vars_files = NonInheritableFieldAttribute(isa='list', default=list, priority=99)
71 vars_prompt = NonInheritableFieldAttribute(isa='list', default=list, always_post_validate=False)
72
73 validate_argspec = NonInheritableFieldAttribute(isa='string', always_post_validate=True)
74
75 # Role Attributes
76 roles = NonInheritableFieldAttribute(isa='list', default=list, priority=90)
77
78 # Block (Task) Lists Attributes
79 handlers = NonInheritableFieldAttribute(isa='list', default=list, priority=-1)
80 pre_tasks = NonInheritableFieldAttribute(isa='list', default=list, priority=-1)
81 post_tasks = NonInheritableFieldAttribute(isa='list', default=list, priority=-1)
82 tasks = NonInheritableFieldAttribute(isa='list', default=list, priority=-1)
83
84 # Flag/Setting Attributes
85 force_handlers = NonInheritableFieldAttribute(isa='bool', default=context.cliargs_deferred_get('force_handlers'), always_post_validate=True)
86 max_fail_percentage = NonInheritableFieldAttribute(isa='percent', always_post_validate=True)
87 serial = NonInheritableFieldAttribute(isa='list', default=list, always_post_validate=True)
88 strategy = NonInheritableFieldAttribute(isa='string', default=C.DEFAULT_STRATEGY, always_post_validate=True)
89 order = NonInheritableFieldAttribute(isa='string', always_post_validate=True)
90
91 # =================================================================================
92
93 def __init__(self):
94 super(Play, self).__init__()
95
96 self._included_conditional = None
97 self._included_path = None
98 self._removed_hosts = []
99 self.role_cache = {}
100
101 self.only_tags = set(context.CLIARGS.get('tags', [])) or frozenset(('all',))
102 self.skip_tags = set(context.CLIARGS.get('skip_tags', []))
103
104 self._action_groups = {}
105 self._group_actions = {}
106
107 def __repr__(self):
108 return self.get_name()
109
110 def _get_cached_role(self, role):
111 role_path = role.get_role_path()
112 role_cache = self.role_cache[role_path]
113 try:
114 idx = role_cache.index(role)
115 return role_cache[idx]
116 except ValueError:
117 raise AnsibleError(f'Cannot locate {role.get_name()} in role cache')
118
119 def _validate_hosts(self, attribute, name, value):
120 # Only validate 'hosts' if a value was passed in to original data set.
121 if 'hosts' in self._ds:
122 if not value:
123 raise AnsibleParserError("Hosts list cannot be empty. Please check your playbook")
124
125 if is_sequence(value):
126 # Make sure each item in the sequence is a valid string
127 for entry in value:
128 if entry is None:
129 raise AnsibleParserError("Hosts list cannot contain values of 'None'. Please check your playbook")
130 elif not isinstance(entry, (bytes, str)):
131 raise AnsibleParserError("Hosts list contains an invalid host value: '{host!s}'".format(host=entry))
132
133 elif not isinstance(value, (bytes, str, EncryptedString)):
134 raise AnsibleParserError("Hosts list must be a sequence or string. Please check your playbook.")
135
136 def get_name(self):
137 """ return the name of the Play """
138 if self.name:
139 return self.name
140
141 if is_sequence(self.hosts):
142 self.name = ','.join(self.hosts)
143 else:
144 self.name = self.hosts or ''
145
146 return self.name
147
148 @staticmethod
149 def load(data, variable_manager=None, loader=None, vars=None):
150 p = Play()
151 if vars:
152 p.vars = vars.copy()
153 return p.load_data(data, variable_manager=variable_manager, loader=loader)
154
155 def preprocess_data(self, ds):
156 """
157 Adjusts play datastructure to cleanup old/legacy items
158 """
159
160 if not isinstance(ds, dict):
161 raise AnsibleAssertionError('while preprocessing data (%s), ds should be a dict but was a %s' % (ds, type(ds)))
162
163 # The use of 'user' in the Play datastructure was deprecated to
164 # line up with the same change for Tasks, due to the fact that
165 # 'user' conflicted with the user module.
166 if 'user' in ds:
167 # this should never happen, but error out with a helpful message
168 # to the user if it does...
169 if 'remote_user' in ds:
170 raise AnsibleParserError("both 'user' and 'remote_user' are set for this play. "
171 "The use of 'user' is deprecated, and should be removed", obj=ds)
172
173 ds['remote_user'] = ds['user']
174 del ds['user']
175
176 return super(Play, self).preprocess_data(ds)
177
178 def _load(self, attr: str, ds: object) -> list[Block]:
179 """
180 Loads a list of blocks from a list which may be mixed tasks/blocks.
181 Bare tasks outside of a block are given an implicit block.
182 """
183 try:
184 return load_list_of_blocks(ds=ds, play=self, variable_manager=self._variable_manager, loader=self._loader)
185 except AssertionError as ex:
186 raise AnsibleParserError(f"A malformed block was encountered while loading {attr}.", obj=self._ds) from ex
187
188 def _load_tasks(self, attr, ds):
189 return self._load(attr, ds)
190
191 def _load_pre_tasks(self, attr, ds):
192 return self._load(attr, ds)
193
194 def _load_post_tasks(self, attr, ds):
195 return self._load(attr, ds)
196
197 def _load_handlers(self, attr, ds):
198 """
199 Loads a list of blocks from a list which may be mixed handlers/blocks.
200 Bare handlers outside of a block are given an implicit block.
201 """
202 try:
203 return self._extend_value(
204 self.handlers,
205 load_list_of_blocks(ds=ds, play=self, use_handlers=True, variable_manager=self._variable_manager, loader=self._loader),
206 prepend=True
207 )
208 except AssertionError as ex:
209 raise AnsibleParserError("A malformed block was encountered while loading handlers.", obj=self._ds) from ex
210
211 def _load_roles(self, attr, ds):
212 """
213 Loads and returns a list of RoleInclude objects from the datastructure
214 list of role definitions and creates the Role from those objects
215 """
216
217 if ds is None:
218 ds = []
219
220 try:
221 role_includes = load_list_of_roles(ds, play=self, variable_manager=self._variable_manager,
222 loader=self._loader, collection_search_list=self.collections)
223 except AssertionError as ex:
224 raise AnsibleParserError("A malformed role declaration was encountered.", obj=self._ds) from ex
225
226 roles = []
227 for ri in role_includes:
228 roles.append(Role.load(ri, play=self))
229
230 self.roles[:0] = roles
231
232 return self.roles
233
234 def _load_vars_prompt(self, attr, ds):
235 # avoid circular dep
236 from ansible.vars.manager import preprocess_vars
237
238 new_ds = preprocess_vars(ds)
239 vars_prompts = []
240 if new_ds is not None:
241 for prompt_data in new_ds:
242 if 'name' not in prompt_data:
243 raise AnsibleParserError("Invalid vars_prompt data structure, missing 'name' key", obj=ds)
244 for key in prompt_data:
245 if key not in ('name', 'prompt', 'default', 'private', 'confirm', 'encrypt', 'salt_size', 'salt', 'unsafe'):
246 raise AnsibleParserError("Invalid vars_prompt data structure, found unsupported key '%s'" % key, obj=ds)
247 vars_prompts.append(prompt_data)
248 return vars_prompts
249
250 def _compile_roles(self):
251 """
252 Handles the role compilation step, returning a flat list of tasks
253 with the lowest level dependencies first. For example, if a role R
254 has a dependency D1, which also has a dependency D2, the tasks from
255 D2 are merged first, followed by D1, and lastly by the tasks from
256 the parent role R last. This is done for all roles in the Play.
257 """
258
259 block_list = []
260
261 if len(self.roles) > 0:
262 for r in self.roles:
263 # Don't insert tasks from ``import/include_role``, preventing
264 # duplicate execution at the wrong time
265 if r.from_include:
266 continue
267 block_list.extend(r.compile(play=self))
268
269 return block_list
270
271 def compile_roles_handlers(self):
272 """
273 Handles the role handler compilation step, returning a flat list of Handlers
274 This is done for all roles in the Play.
275 """
276
277 block_list = []
278
279 if len(self.roles) > 0:
280 for r in self.roles:
281 if r.from_include:
282 continue
283 block_list.extend(r.get_handler_blocks(play=self))
284
285 return block_list
286
287 def compile(self):
288 """
289 Compiles and returns the task list for this play, compiled from the
290 roles (which are themselves compiled recursively) and/or the list of
291 tasks specified in the play.
292 """
293 # create a block containing a single flush handlers meta
294 # task, so we can be sure to run handlers at certain points
295 # of the playbook execution
296 flush_block = Block(play=self)
297
298 t = Task(block=flush_block)
299 t.action = 'meta'
300 t._resolved_action = 'ansible.builtin.meta'
301 t.args['_raw_params'] = 'flush_handlers'
302 t.implicit = True
303 t.set_loader(self._loader)
304 t.tags = ['always']
305
306 flush_block.block = [t]
307
308 # NOTE keep flush_handlers tasks even if a section has no regular tasks,
309 # there may be notified handlers from the previous section
310 # (typically when a handler notifies a handler defined before)
311 block_list = []
312 if self.force_handlers:
313 noop_task = Task()
314 noop_task.action = 'meta'
315 noop_task.args['_raw_params'] = 'noop'
316 noop_task.implicit = True
317 noop_task.set_loader(self._loader)
318
319 b = Block(play=self)
320 if self.pre_tasks:
321 b.block = self.pre_tasks
322 else:
323 nt = noop_task.copy(exclude_parent=True)
324 nt._parent = b
325 b.block = [nt]
326 b.always = [flush_block]
327 block_list.append(b)
328
329 tasks = self._compile_roles() + self.tasks
330 b = Block(play=self)
331 if tasks:
332 b.block = tasks
333 else:
334 nt = noop_task.copy(exclude_parent=True)
335 nt._parent = b
336 b.block = [nt]
337 b.always = [flush_block]
338 block_list.append(b)
339
340 b = Block(play=self)
341 if self.post_tasks:
342 b.block = self.post_tasks
343 else:
344 nt = noop_task.copy(exclude_parent=True)
345 nt._parent = b
346 b.block = [nt]
347 b.always = [flush_block]
348 block_list.append(b)
349
350 return block_list
351
352 block_list.extend(self.pre_tasks)
353 block_list.append(flush_block)
354 block_list.extend(self._compile_roles())
355 block_list.extend(self.tasks)
356 block_list.append(flush_block)
357 block_list.extend(self.post_tasks)
358 block_list.append(flush_block)
359
360 return block_list
361
362 def get_vars(self):
363 return self.vars.copy()
364
365 def get_vars_files(self):
366 if self.vars_files is None:
367 return []
368 elif not isinstance(self.vars_files, list):
369 return [self.vars_files]
370 return self.vars_files
371
372 def get_handlers(self):
373 return self.handlers[:]
374
375 def get_roles(self):
376 return self.roles[:]
377
378 def get_tasks(self):
379 tasklist = []
380 for task in self.pre_tasks + self.tasks + self.post_tasks:
381 if isinstance(task, Block):
382 tasklist.append(task.block + task.rescue + task.always)
383 else:
384 tasklist.append(task)
385 return tasklist
386
387 def copy(self):
388 new_me = super(Play, self).copy()
389 new_me.role_cache = self.role_cache.copy()
390 new_me._included_conditional = self._included_conditional
391 new_me._included_path = self._included_path
392 new_me._action_groups = self._action_groups
393 new_me._group_actions = self._group_actions
394 return new_me
395
396 def _post_validate_validate_argspec(self, attr: NonInheritableFieldAttribute, value: object, templar: _TE) -> str | None:
397 """Validate user input is a bool or string, and return the corresponding argument spec name."""
398
399 # Ensure the configuration is valid
400 if isinstance(value, str):
401 try:
402 value = templar.template(value)
403 except AnsibleValueOmittedError:
404 value = False
405
406 if not isinstance(value, (str, bool)):
407 raise AnsibleParserError(f"validate_argspec must be a boolean or string, not {type(value)}", obj=value)
408
409 # Short-circuit if configuration is turned off or inapplicable
410 if not value or self._origin is None:
411 return None
412
413 # Use the requested argument spec or fall back to the play name
414 argspec_name = None
415 if isinstance(value, str):
416 argspec_name = value
417 elif self._ds.get("name"):
418 argspec_name = self.name
419
420 metadata_err = argspec_err = ""
421 if not argspec_name:
422 argspec_err = (
423 "A play name is required when validate_argspec is True. "
424 "Alternatively, set validate_argspec to the name of an argument spec."
425 )
426 if self._metadata_path is None:
427 metadata_err = "A playbook meta file is required. Considered:\n - "
428 metadata_err += "\n - ".join([path.as_posix() for path in self._metadata_candidate_paths])
429
430 if metadata_err or argspec_err:
431 error = f"{argspec_err + (' ' if argspec_err else '')}{metadata_err}"
432 raise AnsibleParserError(error, obj=self._origin)
433
434 metadata = self._loader.load_from_file(self._metadata_path)
435
436 try:
437 metadata = metadata['argument_specs']
438 metadata = metadata[argspec_name]
439 options = metadata['options']
440 except (TypeError, KeyError):
441 options = None
442
443 if not isinstance(options, dict):
444 raise AnsibleParserError(
445 f"No argument spec named '{argspec_name}' in {self._metadata_path}. Minimally expected:\n"
446 + yaml_dump({"argument_specs": {f"{argspec_name!s}": {"options": {}}}}),
447 obj=metadata,
448 )
449
450 return argspec_name
451
452 @property
453 def _metadata_candidate_paths(self) -> list[_pathlib.Path]:
454 """A list of possible playbook.meta paths in configured order."""
455 extensions = C.config.get_config_value("YAML_FILENAME_EXTENSIONS")
456 if self._origin.path.endswith(tuple(extensions)):
457 playbook_without_ext = self._origin.path.rsplit('.', 1)[0]
458 else:
459 playbook_without_ext = self._origin.path
460
461 return [_pathlib.Path(playbook_without_ext + ".meta" + ext) for ext in extensions + ['']]
462
463 @_functools.cached_property
464 def _metadata_path(self) -> str | None:
465 """Locate playbook meta path:
466
467 playbook{ext?} -> playbook.meta{ext?}
468 """
469 if self._origin is None:
470 # adhoc, ansible-console don't have an associated playbook
471 return None
472 for candidate in self._metadata_candidate_paths:
473 if candidate.is_file():
474 return candidate.as_posix()
475 return None
476
477 @property
478 def argument_spec(self) -> dict:
479 """Retrieve the argument spec if one is configured."""
480 if not self.validate_argspec:
481 return {}
482
483 return self._loader.load_from_file(self._metadata_path)['argument_specs'][self.validate_argspec]['options']