Debian Codegraph @

lib/ansible/playbook/role_include.py

raw
1 #
2 # This file is part of Ansible
3 #
4 # Ansible is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # Ansible is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
16
17 from __future__ import annotations
18
19 import ansible.constants as C
20 from ansible.errors import AnsibleError, AnsibleParserError
21 from ansible.playbook.attribute import NonInheritableFieldAttribute
22 from ansible.playbook.task_include import TaskInclude
23 from ansible.playbook.role import Role
24 from ansible.playbook.role.include import RoleInclude
25 from ansible.utils.display import Display
26 from ansible._internal._templating._engine import TemplateEngine
27
28 __all__ = ['IncludeRole']
29
30 display = Display()
31
32
33 class IncludeRole(TaskInclude):
34
35 """
36 A Role include is derived from a regular role to handle the special
37 circumstances related to the `- include_role: ...`
38 """
39
40 BASE = frozenset(('name', 'role')) # directly assigned
41 FROM_ARGS = frozenset(('tasks_from', 'vars_from', 'defaults_from', 'handlers_from')) # used to populate from dict in role
42 OTHER_ARGS = frozenset(('apply', 'public', 'allow_duplicates', 'rolespec_validate', 'rescuable')) # assigned to matching property
43 VALID_ARGS = BASE | FROM_ARGS | OTHER_ARGS # all valid args
44
45 # =================================================================================
46 # ATTRIBUTES
47 public = NonInheritableFieldAttribute(isa='bool', default=None, private=False, always_post_validate=True)
48
49 # private as this is a 'module options' vs a task property
50 allow_duplicates = NonInheritableFieldAttribute(isa='bool', default=True, private=True, always_post_validate=True)
51 rolespec_validate = NonInheritableFieldAttribute(isa='bool', default=True, private=True, always_post_validate=True)
52 rescuable = NonInheritableFieldAttribute(isa='bool', default=True, private=True, always_post_validate=True)
53
54 def __init__(self, block=None, role=None, task_include=None):
55
56 super(IncludeRole, self).__init__(block=block, role=role, task_include=task_include)
57
58 self._from_files = {}
59 self._parent_role = role
60 self._role_name = None
61 self._role_path = None
62
63 def get_name(self):
64 """ return the name of the task """
65 return self.name or "%s : %s" % (self.action, self._role_name)
66
67 def get_block_list(self, play=None, variable_manager=None, loader=None):
68
69 # only need play passed in when dynamic
70 if play is None:
71 myplay = self._parent._play
72 else:
73 myplay = play
74
75 try:
76 ri = RoleInclude.load(self._role_name, play=myplay, variable_manager=variable_manager, loader=loader, collection_list=self.collections)
77 except AnsibleError as e:
78 if not self.rescuable:
79 raise AnsibleParserError("Could not include role.") from e
80 raise
81
82 ri.vars |= self.vars
83
84 if variable_manager is not None:
85 available_variables = variable_manager.get_vars(play=myplay, task=self)
86 else:
87 available_variables = {}
88 templar = TemplateEngine(loader=loader, variables=available_variables)
89 from_files = templar.template(self._from_files)
90
91 # build role
92 actual_role = Role.load(ri, myplay, parent_role=self._parent_role, from_files=from_files, from_include=True,
93 validate=self.rolespec_validate, public=self.public, static=self.statically_loaded, rescuable=self.rescuable)
94 actual_role._metadata.allow_duplicates = self.allow_duplicates
95
96 # add role to play
97 myplay.roles.append(actual_role)
98
99 # save this for later use
100 self._role_path = actual_role._role_path
101
102 # compile role with parent roles as dependencies to ensure they inherit
103 # variables
104 dep_chain = actual_role.get_dep_chain()
105
106 p_block = self.build_parent_block()
107
108 # collections value is not inherited; override with the value we calculated during role setup
109 p_block.collections = actual_role.collections
110
111 blocks = actual_role.compile(play=myplay, dep_chain=dep_chain)
112 for b in blocks:
113 b._parent = p_block
114 # HACK: parent inheritance doesn't seem to have a way to handle this intermediate override until squashed/finalized
115 b.collections = actual_role.collections
116
117 # updated available handlers in play
118 handlers = actual_role.get_handler_blocks(play=myplay, dep_chain=dep_chain)
119 for h in handlers:
120 h._parent = p_block
121 myplay.handlers = myplay.handlers + handlers
122 return blocks, handlers
123
124 @staticmethod
125 def load(data, block=None, role=None, task_include=None, variable_manager=None, loader=None):
126
127 ir = IncludeRole(block, role, task_include=task_include).load_data(data, variable_manager=variable_manager, loader=loader)
128
129 # Validate options
130 my_arg_names = frozenset(ir.args.keys())
131
132 # name is needed, or use role as alias
133 ir._role_name = ir.args.get('name', ir.args.get('role'))
134 if ir._role_name is None:
135 raise AnsibleParserError("'name' is a required field for %s." % ir.action, obj=data)
136
137 # validate bad args, otherwise we silently ignore
138 bad_opts = my_arg_names.difference(IncludeRole.VALID_ARGS)
139 if bad_opts:
140 raise AnsibleParserError('Invalid options for %s: %s' % (ir.action, ','.join(list(bad_opts))), obj=data)
141
142 # build options for role include/import tasks
143 for key in my_arg_names.intersection(IncludeRole.FROM_ARGS):
144 from_key = key.removesuffix('_from')
145 args_value = ir.args.get(key)
146 if not isinstance(args_value, str):
147 raise AnsibleParserError('Expected a string for %s but got %s instead' % (key, type(args_value)))
148 ir._from_files[from_key] = args_value
149
150 # apply and rescuable are only valid for includes, not imports as they inherit directly
151 apply_attrs = ir.args.get('apply', {})
152 if apply_attrs and ir.action not in C._ACTION_INCLUDE_ROLE:
153 raise AnsibleParserError('Invalid options for %s: apply' % ir.action, obj=data)
154 elif not isinstance(apply_attrs, dict):
155 raise AnsibleParserError('Expected a dict for apply but got %s instead' % type(apply_attrs), obj=data)
156
157 resc_attr = ir.args.get('rescuable', None)
158 if resc_attr and ir.action not in C._ACTION_INCLUDE_ROLE:
159 raise AnsibleParserError(f'Invalid options for {ir.action}: rescuable', obj=data)
160
161 # manual list as otherwise the options would set other task parameters we don't want.
162 for option in my_arg_names.intersection(IncludeRole.OTHER_ARGS):
163 setattr(ir, option, ir.args.get(option))
164
165 return ir
166
167 def copy(self, exclude_parent=False, exclude_tasks=False):
168
169 new_me = super(IncludeRole, self).copy(exclude_parent=exclude_parent, exclude_tasks=exclude_tasks)
170 new_me.statically_loaded = self.statically_loaded
171 new_me._from_files = self._from_files.copy()
172 new_me._parent_role = self._parent_role
173 new_me._role_name = self._role_name
174 new_me._role_path = self._role_path
175
176 return new_me
177
178 def get_include_params(self):
179 v = super(IncludeRole, self).get_include_params()
180 if self._parent_role:
181 v |= self._parent_role.get_role_params()
182 v.setdefault('ansible_parent_role_names', []).insert(0, self._parent_role.get_name())
183 v.setdefault('ansible_parent_role_paths', []).insert(0, self._parent_role._role_path)
184 return v