Debian Codegraph @

lib/ansible/playbook/included_file.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 AnsibleError
24 from ansible._internal._task import HostTaskResult
25 from ansible.inventory.host import Host
26 from ansible.module_utils.common.text.converters import to_text
27 from ansible.parsing.dataloader import DataLoader
28 from ansible.playbook.handler import Handler
29 from ansible.playbook.task_include import TaskInclude
30 from ansible.playbook.role_include import IncludeRole
31 from ansible._internal._templating._engine import TemplateEngine
32 from ansible.utils.display import Display
33 from ansible.vars.manager import VariableManager
34
35 display = Display()
36
37
38 class IncludedFile:
39 """Recombines include task results from multiple hosts into consolidated IncludedFile objects.
40
41 TaskExecutor processes include tasks per-host in workers, returning include metadata without loading
42 the included file. Strategy plugins collect these per-host results and call process_include_results()
43 to consolidate them: hosts with identical (filename, args, vars, task) are merged into a single
44 IncludedFile, allowing the strategy to load and process the included tasks once for all affected hosts.
45 """
46
47 def __init__(self, filename, args, vars, task, is_role: bool = False) -> None:
48 self._filename = filename
49 self._args = args
50 self._vars = vars
51 self._task = task
52 self._hosts: list[Host] = []
53 self._is_role = is_role
54 self._results: list[HostTaskResult] = []
55
56 def add_host(self, host: Host) -> None:
57 if host not in self._hosts:
58 self._hosts.append(host)
59 return
60
61 raise ValueError()
62
63 def __eq__(self, other):
64 if not isinstance(other, IncludedFile):
65 return False
66
67 return (other._filename == self._filename and
68 other._args == self._args and
69 other._vars == self._vars and
70 other._task._uuid == self._task._uuid and
71 other._task._parent._uuid == self._task._parent._uuid)
72
73 def __repr__(self):
74 return "%s (args=%s vars=%s): %s" % (self._filename, self._args, self._vars, self._hosts)
75
76 @staticmethod
77 def process_include_results(
78 results: list[HostTaskResult],
79 iterator,
80 loader: DataLoader,
81 variable_manager: VariableManager,
82 ) -> list[IncludedFile]:
83 included_files: list[IncludedFile] = []
84 task_vars_cache: dict[tuple, dict] = {}
85
86 for res in results:
87
88 original_host = res.host
89 original_task = res.task
90
91 if original_task.action in C._ACTION_ALL_INCLUDES:
92
93 if original_task.loop:
94 if res.utr.loop_results is None:
95 continue
96
97 include_utrs = res.utr.loop_results
98 else:
99 include_utrs = [res.utr]
100
101 for include_utr in include_utrs:
102 # if the task result was skipped or failed, continue
103 if include_utr.skipped or include_utr.failed:
104 continue
105
106 cache_key = (iterator._play, original_host, original_task)
107 try:
108 task_vars = task_vars_cache[cache_key]
109 except KeyError:
110 task_vars = task_vars_cache[cache_key] = variable_manager.get_vars(play=iterator._play, host=original_host, task=original_task)
111
112 include_args = include_utr.include_args or {} # This shouldn't be necessary, we should always have include_args -- avoid type complaints.
113 special_vars = {}
114
115 # Since includes aren't run through workers, task_vars with the same internal state keys as result dicts with current item metadata
116 # are abused to allow callback infra like _get_item_label to transparently work on both.
117 if include_utr.loop_var is not None:
118 task_vars[include_utr.loop_var] = special_vars[include_utr.loop_var] = include_utr.loop_item
119 task_vars['ansible_loop_var'] = special_vars['ansible_loop_var'] = include_utr.loop_var
120 if include_utr.loop_index_var is not None:
121 task_vars[include_utr.loop_index_var] = special_vars[include_utr.loop_index_var] = include_utr.loop_index
122 task_vars['ansible_index_var'] = special_vars['ansible_index_var'] = include_utr.loop_index_var
123 if include_utr.loop_item_label is not None:
124 task_vars['_ansible_item_label'] = special_vars['_ansible_item_label'] = include_utr.loop_item_label
125 if include_utr.loop_extended is not None:
126 task_vars['ansible_loop'] = special_vars['ansible_loop'] = include_utr.loop_extended
127 if original_task.no_log and '_ansible_no_log' not in include_args:
128 task_vars['_ansible_no_log'] = special_vars['_ansible_no_log'] = original_task.no_log
129
130 # get search path for this task to pass to lookup plugins that may be used in pathing to
131 # the included file
132 task_vars['ansible_search_path'] = original_task.get_search_path()
133
134 # ensure basedir is always in (dwim already searches here but we need to display it)
135 if loader.get_basedir() not in task_vars['ansible_search_path']:
136 task_vars['ansible_search_path'].append(loader.get_basedir())
137
138 templar = TemplateEngine(loader=loader, variables=task_vars)
139
140 if original_task.action in C._ACTION_INCLUDE_TASKS:
141 include_file = None
142
143 if original_task._parent:
144 # handle relative includes by walking up the list of parent include
145 # tasks and checking the relative result to see if it exists
146 parent_include = original_task._parent
147 cumulative_path = None
148 while parent_include is not None:
149 if not isinstance(parent_include, TaskInclude):
150 parent_include = parent_include._parent
151 continue
152 if isinstance(parent_include, IncludeRole):
153 parent_include_dir = parent_include._role_path
154 else:
155 try:
156 # FUTURE: Since the parent include path has already been resolved, it should be used here.
157 # Unfortunately it's not currently stored anywhere, so it must be calculated again.
158 parent_include_dir = os.path.dirname(templar.template(parent_include.args.get('_raw_params')))
159 except AnsibleError as e:
160 parent_include_dir = ''
161 display.warning(
162 'Templating the path of the parent %s failed. The path to the '
163 'included file may not be found. '
164 'The error was: %s.' % (original_task.action, to_text(e))
165 )
166 if cumulative_path is not None and not os.path.isabs(cumulative_path):
167 cumulative_path = os.path.join(parent_include_dir, cumulative_path)
168 else:
169 cumulative_path = parent_include_dir
170 include_target = include_utr.include_file
171 if original_task._role:
172 dirname = 'handlers' if isinstance(original_task, Handler) else 'tasks'
173 new_basedir = os.path.join(original_task._role._role_path, dirname, cumulative_path)
174 candidates = [
175 loader.path_dwim_relative(original_task._role._role_path, dirname, include_target, is_role=True),
176 loader.path_dwim_relative(new_basedir, dirname, include_target, is_role=True)
177 ]
178 for include_file in candidates:
179 try:
180 # may throw OSError
181 os.stat(include_file)
182 # or select the task file if it exists
183 break
184 except OSError:
185 pass
186 else:
187 include_file = loader.path_dwim_relative(loader.get_basedir(), cumulative_path, include_target)
188
189 if os.path.exists(include_file):
190 break
191 else:
192 parent_include = parent_include._parent
193
194 if include_file is None:
195 if original_task._role:
196 include_target = include_utr.include_file
197 include_file = loader.path_dwim_relative(
198 original_task._role._role_path,
199 'handlers' if isinstance(original_task, Handler) else 'tasks',
200 include_target,
201 is_role=True)
202 else:
203 include_file = loader.path_dwim(include_utr.include_file)
204
205 inc_file = IncludedFile(include_file, include_args, special_vars, original_task)
206 else:
207 # template the included role's name here
208 role_name = include_args.pop('name', include_args.pop('role', None))
209 new_task = original_task.copy()
210 new_task.post_validate(templar=templar)
211 new_task._role_name = role_name
212 for from_arg in new_task.FROM_ARGS:
213 if from_arg in include_args:
214 from_key = from_arg.removesuffix('_from')
215 new_task._from_files[from_key] = include_args.get(from_arg)
216
217 inc_file = IncludedFile(role_name, include_args, special_vars, new_task, is_role=True)
218
219 # Deduplication loop handles multiple facets:
220 # 1. Cross-host consolidation: merge hosts with same (filename, args, vars, task) into one IncludedFile
221 # 2. Loop iteration tracking: each loop item creates distinct execution context per-host
222 # 3. Duplicate loop items: loop=[a,b,a] means 3 executions; same host+context creates NEW IncludedFile
223 # 4. Order preservation: execution order depends on IncludedFile list order
224 # If host already exists in matched IncludedFile (ValueError from add_host), advance idx to find/create next occurrence
225 idx = 0
226 orig_inc_file = inc_file
227 while 1:
228 try:
229 pos = included_files[idx:].index(orig_inc_file)
230 # pos is relative to idx since we are slicing
231 # use idx + pos due to relative indexing
232 inc_file = included_files[idx + pos]
233 except ValueError:
234 included_files.append(orig_inc_file)
235 inc_file = orig_inc_file
236
237 try:
238 inc_file.add_host(original_host)
239 inc_file._results.append(res)
240 except ValueError:
241 # The host already exists for this include, advance forward, this is a new include
242 idx += pos + 1
243 else:
244 break
245
246 return included_files