Debian Codegraph @

lib/ansible/playbook/role/definition.py

raw
1 # (c) 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, AnsibleAssertionError
24 from ansible.module_utils._internal._datatag import AnsibleTagHelper
25 from ansible.playbook.attribute import NonInheritableFieldAttribute
26 from ansible.playbook.base import Base
27 from ansible.playbook.collectionsearch import CollectionSearch
28 from ansible.playbook.conditional import Conditional
29 from ansible.playbook.taggable import Taggable
30 from ansible._internal._templating._engine import TemplateEngine
31 from ansible.utils.collection_loader import AnsibleCollectionRef
32 from ansible.utils.collection_loader._collection_finder import _get_collection_role_path
33 from ansible.utils.path import unfrackpath
34 from ansible.utils.display import Display
35
36 __all__ = ['RoleDefinition']
37
38 display = Display()
39
40
41 class RoleDefinition(Base, Conditional, Taggable, CollectionSearch):
42
43 role = NonInheritableFieldAttribute(isa='string')
44
45 def __init__(self, play=None, role_basedir=None, variable_manager=None, loader=None, collection_list=None):
46
47 super(RoleDefinition, self).__init__()
48
49 self._play = play
50 self._variable_manager = variable_manager
51 self._loader = loader
52
53 self._role_path = None
54 self._role_collection = None
55 self._role_basedir = role_basedir
56 self._role_params = dict()
57 self._collection_list = collection_list
58
59 # def __repr__(self):
60 # return 'ROLEDEF: ' + self._attributes.get('role', '<no name set>')
61
62 @staticmethod
63 def load(data, variable_manager=None, loader=None):
64 raise AnsibleError("not implemented")
65
66 def preprocess_data(self, ds):
67 # role names that are simply numbers can be parsed by PyYAML
68 # as integers even when quoted, so turn it into a string type
69 if isinstance(ds, int):
70 ds = "%s" % ds
71
72 if not isinstance(ds, dict) and not isinstance(ds, str):
73 raise AnsibleAssertionError()
74
75 if isinstance(ds, dict):
76 ds = super(RoleDefinition, self).preprocess_data(ds)
77
78 # save the original ds for use later
79 self._ds = ds
80
81 # the new, cleaned datastructure, which will have legacy items reduced to a standard structure suitable for the
82 # attributes of the task class; copy any tagged data to preserve things like origin
83 new_ds = AnsibleTagHelper.tag_copy(ds, {})
84
85 # first we pull the role name out of the data structure,
86 # and then use that to determine the role path (which may
87 # result in a new role name, if it was a file path)
88 role_name = self._load_role_name(ds)
89 (role_name, role_path) = self._load_role_path(role_name)
90
91 # next, we split the role params out from the valid role
92 # attributes and update the new datastructure with that
93 # result and the role name
94 if isinstance(ds, dict):
95 (new_role_def, role_params) = self._split_role_params(ds)
96 new_ds |= new_role_def
97 self._role_params = role_params
98
99 # set the role name in the new ds
100 new_ds['role'] = role_name
101
102 # we store the role path internally
103 self._role_path = role_path
104
105 # and return the cleaned-up data structure
106 return new_ds
107
108 def _load_role_name(self, ds):
109 """
110 Returns the role name (either the role: or name: field) from
111 the role definition, or (when the role definition is a simple
112 string), just that string
113 """
114
115 if isinstance(ds, str):
116 return ds
117
118 role_name = ds.get('role', ds.get('name'))
119 if not role_name or not isinstance(role_name, str):
120 raise AnsibleError('role definitions must contain a role name', obj=ds)
121
122 # if we have the required datastructures, and if the role_name
123 # contains a variable, try and template it now
124 if self._variable_manager:
125 all_vars = self._variable_manager.get_vars(play=self._play)
126 templar = TemplateEngine(loader=self._loader, variables=all_vars)
127 role_name = templar.template(role_name)
128
129 return role_name
130
131 def _load_role_path(self, role_name):
132 """
133 the 'role', as specified in the ds (or as a bare string), can either
134 be a simple name or a full path. If it is a full path, we use the
135 basename as the role name, otherwise we take the name as-given and
136 append it to the default role path
137 """
138
139 # create a templar class to template the dependency names, in
140 # case they contain variables
141 if self._variable_manager is not None:
142 all_vars = self._variable_manager.get_vars(play=self._play)
143 else:
144 all_vars = dict()
145
146 templar = TemplateEngine(loader=self._loader, variables=all_vars)
147 role_name = templar.template(role_name)
148
149 role_tuple = None
150
151 # try to load as a collection-based role first
152 if self._collection_list or AnsibleCollectionRef.is_valid_fqcr(role_name):
153 role_tuple = _get_collection_role_path(role_name, self._collection_list)
154
155 if role_tuple:
156 # we found it, stash collection data and return the name/path tuple
157 self._role_collection = role_tuple[2]
158 return role_tuple[0:2]
159
160 # We didn't find a collection role, look in defined role paths
161 # FUTURE: refactor this to be callable from internal so we can properly order
162 # ansible.legacy searches with the collections keyword
163
164 # we always start the search for roles in the base directory of the playbook
165 role_search_paths = [
166 os.path.join(self._loader.get_basedir(), u'roles'),
167 ]
168
169 # also search in the configured roles path
170 if C.DEFAULT_ROLES_PATH:
171 role_search_paths.extend(C.DEFAULT_ROLES_PATH)
172
173 # next, append the roles basedir, if it was set, so we can
174 # search relative to that directory for dependent roles
175 if self._role_basedir:
176 role_search_paths.append(self._role_basedir)
177
178 # finally as a last resort we look in the current basedir as set
179 # in the loader (which should be the playbook dir itself) but without
180 # the roles/ dir appended
181 role_search_paths.append(self._loader.get_basedir())
182
183 # now iterate through the possible paths and return the first one we find
184 for path in role_search_paths:
185 path = templar.template(path)
186 role_path = unfrackpath(os.path.join(path, role_name))
187 if self._loader.path_exists(role_path):
188 return (role_name, role_path)
189
190 # if not found elsewhere try to extract path from name
191 role_path = unfrackpath(role_name)
192 if self._loader.path_exists(role_path):
193 role_name = os.path.basename(role_name)
194 return (role_name, role_path)
195
196 searches = (self._collection_list or []) + role_search_paths
197
198 raise AnsibleError(f"The role {role_name!r} was not found in: {':'.join(searches)}", obj=self._ds)
199
200 def _split_role_params(self, ds):
201 """
202 Splits any random role params off from the role spec and store
203 them in a dictionary of params for parsing later
204 """
205
206 role_def = dict()
207 role_params = dict()
208 base_attribute_names = frozenset(self.fattributes)
209 for (key, value) in ds.items():
210 # use the list of FieldAttribute values to determine what is and is not
211 # an extra parameter for this role (or sub-class of this role)
212 # FIXME: hard-coded list of exception key names here corresponds to the
213 # connection fields in the Base class. There may need to be some
214 # other mechanism where we exclude certain kinds of field attributes,
215 # or make this list more automatic in some way so we don't have to
216 # remember to update it manually.
217 if key not in base_attribute_names:
218 # this key does not match a field attribute, so it must be a role param
219 role_params[key] = value
220 else:
221 # this is a field attribute, so copy it over directly
222 role_def[key] = value
223
224 return (role_def, role_params)
225
226 def get_role_params(self):
227 return self._role_params.copy()
228
229 def get_role_path(self):
230 return self._role_path
231
232 def get_name(self, include_role_fqcn=True):
233 if include_role_fqcn:
234 return '.'.join(x for x in (self._role_collection, self.role) if x)
235 return self.role