Debian Codegraph @

lib/ansible/playbook/helpers.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 os
21
22 from ansible import constants as C
23 from ansible.errors import AnsibleParserError, AnsibleUndefinedVariable, AnsibleAssertionError
24 from ansible.parsing.mod_args import ModuleArgsParser
25 from ansible.utils.display import Display
26 from ansible._internal._templating._engine import TemplateEngine
27
28 display = Display()
29
30
31 def load_list_of_blocks(ds, play, parent_block=None, role=None, task_include=None, use_handlers=False, variable_manager=None, loader=None):
32 """
33 Given a list of mixed task/block data (parsed from YAML),
34 return a list of Block() objects, where implicit blocks
35 are created for each bare Task.
36 """
37
38 # we import here to prevent a circular dependency with imports
39 from ansible.playbook.block import Block
40
41 if not isinstance(ds, (list, type(None))):
42 raise AnsibleAssertionError('%s should be a list or None but is %s' % (ds, type(ds)))
43
44 block_list = []
45 if ds:
46 count = iter(range(len(ds)))
47 for i in count:
48 block_ds = ds[i]
49 # Implicit blocks are created by bare tasks listed in a play without
50 # an explicit block statement. If we have two implicit blocks in a row,
51 # squash them down to a single block to save processing time later.
52 implicit_blocks = []
53 while block_ds is not None and not Block.is_block(block_ds):
54 implicit_blocks.append(block_ds)
55 i += 1
56 # Advance the iterator, so we don't repeat
57 next(count, None)
58 try:
59 block_ds = ds[i]
60 except IndexError:
61 block_ds = None
62
63 # Loop both implicit blocks and block_ds as block_ds is the next in the list
64 for b in (implicit_blocks, block_ds):
65 if b:
66 block_list.append(
67 Block.load(
68 b,
69 play=play,
70 parent_block=parent_block,
71 role=role,
72 task_include=task_include,
73 use_handlers=use_handlers,
74 variable_manager=variable_manager,
75 loader=loader,
76 )
77 )
78
79 return block_list
80
81
82 def load_list_of_tasks(ds, play, block=None, role=None, task_include=None, use_handlers=False, variable_manager=None, loader=None):
83 """
84 Given a list of task datastructures (parsed from YAML),
85 return a list of Task() or TaskInclude() objects.
86 """
87
88 # we import here to prevent a circular dependency with imports
89 from ansible.playbook.block import Block
90 from ansible.playbook.handler import Handler
91 from ansible.playbook.task import Task
92 from ansible.playbook.task_include import TaskInclude
93 from ansible.playbook.role_include import IncludeRole
94 from ansible.playbook.handler_task_include import HandlerTaskInclude
95
96 if not isinstance(ds, list):
97 raise AnsibleAssertionError('The ds (%s) should be a list but was a %s' % (ds, type(ds)))
98
99 task_list = []
100 for task_ds in ds:
101 if not isinstance(task_ds, dict):
102 raise AnsibleAssertionError('The ds (%s) should be a dict but was a %s' % (ds, type(ds)))
103
104 if 'block' in task_ds:
105 if use_handlers:
106 raise AnsibleParserError("Using a block as a handler is not supported.", obj=task_ds)
107 task = Block.load(
108 task_ds,
109 play=play,
110 parent_block=block,
111 role=role,
112 task_include=task_include,
113 use_handlers=use_handlers,
114 variable_manager=variable_manager,
115 loader=loader,
116 )
117 task_list.append(task)
118 else:
119 args_parser = ModuleArgsParser(task_ds)
120 try:
121 (action, args, delegate_to) = args_parser.parse(skip_action_validation=True)
122 except AnsibleParserError as ex:
123 # if the raises exception was created with obj=ds args, then it includes the detail
124 # so we dont need to add it so we can just re raise.
125 if ex.obj is not None:
126 raise
127 # But if it wasn't, we can add the yaml object now to get more detail
128 # DTFIX-FUTURE: this *should* be unnecessary- check code coverage.
129 # Will definitely be unnecessary once we have proper contexts to consult.
130 raise AnsibleParserError("Error loading tasks.", obj=task_ds) from ex
131
132 if action in C._ACTION_ALL_INCLUDE_IMPORT_TASKS:
133
134 if use_handlers:
135 include_class = HandlerTaskInclude
136 else:
137 include_class = TaskInclude
138
139 task = include_class.load(
140 task_ds,
141 block=block,
142 role=role,
143 task_include=None,
144 variable_manager=variable_manager,
145 loader=loader
146 )
147
148 all_vars = variable_manager.get_vars(play=play, task=task)
149 templar = TemplateEngine(loader=loader, variables=all_vars)
150
151 # check to see if this include is dynamic or static:
152 if action in C._ACTION_IMPORT_TASKS:
153 if task.loop is not None:
154 raise AnsibleParserError("You cannot use loops on 'import_tasks' statements. You should use 'include_tasks' instead.", obj=task_ds)
155
156 # we set a flag to indicate this include was static
157 task.statically_loaded = True
158
159 # handle relative includes by walking up the list of parent include
160 # tasks and checking the relative result to see if it exists
161 parent_include = block
162 cumulative_path = None
163
164 found = False
165 subdir = 'tasks'
166 if use_handlers:
167 subdir = 'handlers'
168 try:
169 include_target = templar.template(task.args['_raw_params'])
170 except AnsibleUndefinedVariable as ex:
171 raise AnsibleParserError(
172 message=f"Error when evaluating variable in import path {task.args['_raw_params']!r}.",
173 help_text="When using static imports, ensure that any variables used in their names are defined in vars/vars_files\n"
174 "or extra-vars passed in from the command line. Static imports cannot use variables from facts or inventory\n"
175 "sources like group or host vars.",
176 obj=task_ds,
177 ) from ex
178 # FIXME this appears to be (almost?) duplicate code as in IncludedFile for include_tasks
179 while parent_include is not None:
180 if not isinstance(parent_include, TaskInclude):
181 parent_include = parent_include._parent
182 continue
183 if isinstance(parent_include, IncludeRole):
184 parent_include_dir = parent_include._role_path
185 else:
186 parent_include_dir = os.path.dirname(templar.template(parent_include.args.get('_raw_params')))
187 if cumulative_path is None:
188 cumulative_path = parent_include_dir
189 elif not os.path.isabs(cumulative_path):
190 cumulative_path = os.path.join(parent_include_dir, cumulative_path)
191 if task._role:
192 new_basedir = os.path.join(task._role._role_path, subdir, cumulative_path)
193 include_file = loader.path_dwim_relative(new_basedir, subdir, include_target)
194 else:
195 include_file = loader.path_dwim_relative(loader.get_basedir(), cumulative_path, include_target)
196
197 if os.path.exists(include_file):
198 found = True
199 break
200 else:
201 parent_include = parent_include._parent
202
203 if not found:
204 if task._role:
205 include_file = loader.path_dwim_relative(task._role._role_path, subdir, include_target)
206 else:
207 include_file = loader.path_dwim(include_target)
208
209 data = loader.load_from_file(include_file, trusted_as_template=True)
210 if not data:
211 display.warning('file %s is empty and had no tasks to include' % include_file)
212 continue
213 elif not isinstance(data, list):
214 raise AnsibleParserError("included task files must contain a list of tasks", obj=data)
215
216 # since we can't send callbacks here, we display a message directly in
217 # the same fashion used by the on_include callback. We also do it here,
218 # because the recursive nature of helper methods means we may be loading
219 # nested includes, and we want the include order printed correctly
220 display.vv("statically imported: %s" % include_file)
221
222 ti_copy = task.copy(exclude_parent=True)
223 ti_copy._parent = block
224 included_blocks = load_list_of_blocks(
225 data,
226 play=play,
227 parent_block=None,
228 task_include=ti_copy,
229 role=role,
230 use_handlers=use_handlers,
231 loader=loader,
232 variable_manager=variable_manager,
233 )
234
235 # FIXME: handlers shouldn't need this special handling, but do
236 # right now because they don't iterate blocks correctly
237 if use_handlers:
238 for b in included_blocks:
239 task_list.extend(b.block)
240 else:
241 task_list.extend(included_blocks)
242 else:
243 task_list.append(task)
244
245 elif action in C._ACTION_ALL_PROPER_INCLUDE_IMPORT_ROLES:
246 if use_handlers:
247 raise AnsibleParserError(f"Using '{action}' as a handler is not supported.", obj=task_ds)
248
249 ir = IncludeRole.load(
250 task_ds,
251 block=block,
252 role=role,
253 task_include=None,
254 variable_manager=variable_manager,
255 loader=loader,
256 )
257
258 if action in C._ACTION_IMPORT_ROLE:
259 if ir.loop is not None:
260 raise AnsibleParserError("You cannot use loops on 'import_role' statements. You should use 'include_role' instead.", obj=task_ds)
261
262 # we set a flag to indicate this include was static
263 ir.statically_loaded = True
264
265 # template the role name now, if needed
266 all_vars = variable_manager.get_vars(play=play, task=ir)
267 templar = TemplateEngine(loader=loader, variables=all_vars)
268 ir.post_validate(templar=templar)
269 ir._role_name = templar.template(ir._role_name)
270
271 # uses compiled list from object
272 blocks, dummy = ir.get_block_list(variable_manager=variable_manager, loader=loader)
273 task_list.extend(blocks)
274 else:
275 # passes task object itself for latter generation of list
276 task_list.append(ir)
277 else:
278 if use_handlers:
279 task = Handler.load(task_ds, block=block, role=role, task_include=task_include, variable_manager=variable_manager, loader=loader)
280 if task._get_meta() == "end_role":
281 raise AnsibleParserError("Cannot execute 'end_role' from a handler", obj=task)
282 else:
283 task = Task.load(task_ds, block=block, role=role, task_include=task_include, variable_manager=variable_manager, loader=loader)
284 if task._get_meta() == "end_role" and role is None:
285 raise AnsibleParserError("Cannot execute 'end_role' from outside of a role", obj=task)
286
287 task_list.append(task)
288
289 return task_list
290
291
292 def load_list_of_roles(ds, play, current_role_path=None, variable_manager=None, loader=None, collection_search_list=None):
293 """
294 Loads and returns a list of RoleInclude objects from the ds list of role definitions
295 :param ds: list of roles to load
296 :param play: calling Play object
297 :param current_role_path: path of the owning role, if any
298 :param variable_manager: varmgr to use for templating
299 :param loader: loader to use for DS parsing/services
300 :param collection_search_list: list of collections to search for unqualified role names
301 :return:
302 """
303 # we import here to prevent a circular dependency with imports
304 from ansible.playbook.role.include import RoleInclude
305
306 if not isinstance(ds, list):
307 raise AnsibleAssertionError('ds (%s) should be a list but was a %s' % (ds, type(ds)))
308
309 roles = []
310 for role_def in ds:
311 i = RoleInclude.load(role_def, play=play, current_role_path=current_role_path, variable_manager=variable_manager,
312 loader=loader, collection_list=collection_search_list)
313 roles.append(i)
314
315 return roles