Debian Codegraph @

lib/ansible/utils/vars.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 keyword
21 import secrets
22 import uuid
23 import typing as t
24
25 from collections.abc import MutableMapping, MutableSequence
26 from json import dumps
27
28 from ansible import constants as C
29 from ansible import context
30 from ansible._internal import _json
31 from ansible._internal._templating import _jinja_bits
32 from ansible.errors import AnsibleError, AnsibleOptionsError
33 from ansible.module_utils.datatag import native_type_name
34 from ansible.module_utils.common.text.converters import to_native, to_text
35 from ansible.parsing.splitter import parse_kv
36 from ansible.parsing.dataloader import DataLoader
37
38 _MAXSIZE = 2 ** 32
39 cur_id = 0
40 node_mac = ("%012x" % uuid.getnode())[:12]
41 random_int = ("%08x" % secrets.randbelow(_MAXSIZE))[:8]
42
43
44 def get_unique_id():
45 global cur_id
46 cur_id += 1
47 return "-".join([
48 node_mac[0:8],
49 node_mac[8:12],
50 random_int[0:4],
51 random_int[4:8],
52 ("%012x" % cur_id)[:12],
53 ])
54
55
56 def _validate_mutable_mappings(a, b):
57 """
58 Internal convenience function to ensure arguments are MutableMappings
59
60 This checks that all arguments are MutableMappings or raises an error
61
62 :raises AnsibleError: if one of the arguments is not a MutableMapping
63 """
64
65 # If this becomes generally needed, change the signature to operate on
66 # a variable number of arguments instead.
67
68 if not (isinstance(a, MutableMapping) and isinstance(b, MutableMapping)):
69 myvars = []
70 for x in [a, b]:
71 try:
72 myvars.append(dumps(x))
73 except Exception:
74 myvars.append(to_native(x))
75 raise AnsibleError(f"failed to combine variables, expected dicts but got a '{a.__class__.__name__}' and a '{b.__class__.__name__}'.")
76
77
78 def combine_vars(a, b, merge=None):
79 """
80 Return a copy of dictionaries of variables based on configured hash behavior
81 """
82
83 if merge or merge is None and C.DEFAULT_HASH_BEHAVIOUR == "merge":
84 return merge_hash(a, b)
85
86 # HASH_BEHAVIOUR == 'replace'
87 _validate_mutable_mappings(a, b)
88 result = a | b
89 return result
90
91
92 def merge_hash(x, y, recursive=True, list_merge='replace'):
93 """
94 Return a new dictionary result of the merges of y into x,
95 so that keys from y take precedence over keys from x.
96 (x and y aren't modified)
97 """
98 if list_merge not in ('replace', 'keep', 'append', 'prepend', 'append_rp', 'prepend_rp'):
99 raise AnsibleError("merge_hash: 'list_merge' argument can only be equal to 'replace', 'keep', 'append', 'prepend', 'append_rp' or 'prepend_rp'")
100
101 # verify x & y are dicts
102 _validate_mutable_mappings(x, y)
103
104 # to speed things up: if x is empty or equal to y, return y
105 # (this `if` can be remove without impact on the function
106 # except performance)
107 if x == {} or x == y:
108 return y.copy()
109 if y == {}:
110 return x
111
112 # in the following we will copy elements from y to x, but
113 # we don't want to modify x, so we create a copy of it
114 x = x.copy()
115
116 # to speed things up: use dict.update if possible
117 # (this `if` can be remove without impact on the function
118 # except performance)
119 if not recursive and list_merge == 'replace':
120 x.update(y)
121 return x
122
123 # insert each element of y in x, overriding the one in x
124 # (as y has higher priority)
125 # we copy elements from y to x instead of x to y because
126 # there is a high probability x will be the "default" dict the user
127 # want to "patch" with y
128 # therefore x will have much more elements than y
129 for key, y_value in y.items():
130 # if `key` isn't in x
131 # update x and move on to the next element of y
132 if key not in x:
133 x[key] = y_value
134 continue
135 # from this point we know `key` is in x
136
137 x_value = x[key]
138
139 # if both x's element and y's element are dicts
140 # recursively "combine" them or override x's with y's element
141 # depending on the `recursive` argument
142 # and move on to the next element of y
143 if isinstance(x_value, MutableMapping) and isinstance(y_value, MutableMapping):
144 if recursive:
145 x[key] = merge_hash(x_value, y_value, recursive, list_merge)
146 else:
147 x[key] = y_value
148 continue
149
150 # if both x's element and y's element are lists
151 # "merge" them depending on the `list_merge` argument
152 # and move on to the next element of y
153 if isinstance(x_value, MutableSequence) and isinstance(y_value, MutableSequence):
154 if list_merge == 'replace':
155 # replace x value by y's one as it has higher priority
156 x[key] = y_value
157 elif list_merge == 'append':
158 x[key] = x_value + y_value
159 elif list_merge == 'prepend':
160 x[key] = y_value + x_value
161 elif list_merge == 'append_rp':
162 # append all elements from y_value (high prio) to x_value (low prio)
163 # and remove x_value elements that are also in y_value
164 # we don't remove elements from x_value nor y_value that were already in double
165 # (we assume that there is a reason if there where such double elements)
166 # _rp stands for "remove present"
167 x[key] = [z for z in x_value if z not in y_value] + y_value
168 elif list_merge == 'prepend_rp':
169 # same as 'append_rp' but y_value elements are prepend
170 x[key] = y_value + [z for z in x_value if z not in y_value]
171 # else 'keep'
172 # keep x value even if y it's of higher priority
173 # it's done by not changing x[key]
174 continue
175
176 # else just override x's element with y's one
177 x[key] = y_value
178
179 return x
180
181
182 def load_extra_vars(loader: DataLoader) -> dict[str, t.Any]:
183
184 if not getattr(load_extra_vars, 'extra_vars', None):
185 extra_vars: dict[str, t.Any] = {}
186 for extra_vars_opt in context.CLIARGS.get('extra_vars', tuple()):
187 extra_vars_opt = to_text(extra_vars_opt, errors='surrogate_or_strict')
188 if extra_vars_opt is None or not extra_vars_opt:
189 continue
190
191 if extra_vars_opt.startswith(u"@"):
192 # Argument is a YAML file (JSON is a subset of YAML)
193 data = loader.load_from_file(extra_vars_opt[1:], trusted_as_template=True)
194 elif extra_vars_opt[0] in [u'/', u'.']:
195 raise AnsibleOptionsError("Please prepend extra_vars filename '%s' with '@'" % extra_vars_opt)
196 elif extra_vars_opt[0] in [u'[', u'{']:
197 # Arguments as YAML
198 data = loader.load(extra_vars_opt)
199 else:
200 # Arguments as Key-value
201 data = parse_kv(extra_vars_opt)
202
203 if isinstance(data, MutableMapping):
204 extra_vars = combine_vars(extra_vars, data)
205 else:
206 raise AnsibleOptionsError("Invalid extra vars data supplied. '%s' could not be made into a dictionary" % extra_vars_opt)
207
208 load_extra_vars.extra_vars = extra_vars
209
210 return load_extra_vars.extra_vars
211
212
213 def load_options_vars(version):
214
215 if not getattr(load_options_vars, 'options_vars', None):
216 if version is None:
217 version = 'Unknown'
218 options_vars = {'ansible_version': version}
219 attrs = {'check': 'check_mode',
220 'diff': 'diff_mode',
221 'forks': 'forks',
222 'inventory': 'inventory_sources',
223 'skip_tags': 'skip_tags',
224 'subset': 'limit',
225 'tags': 'run_tags',
226 'verbosity': 'verbosity'}
227
228 for attr, alias in attrs.items():
229 opt = context.CLIARGS.get(attr)
230 if opt is not None:
231 options_vars['ansible_%s' % alias] = opt
232
233 setattr(load_options_vars, 'options_vars', options_vars)
234
235 return load_options_vars.options_vars
236
237
238 def isidentifier(ident):
239 """Determine if string is valid identifier.
240
241 The purpose of this function is to be used to validate any variables created in
242 a play to be valid Python identifiers and to not conflict with Python keywords
243 to prevent unexpected behavior. Since Python 2 and Python 3 differ in what
244 a valid identifier is, this function unifies the validation so playbooks are
245 portable between the two. The following changes were made:
246
247 * disallow non-ascii characters (Python 3 allows for them as opposed to Python 2)
248
249 :arg ident: A text string of identifier to check. Note: It is callers
250 responsibility to convert ident to text if it is not already.
251
252 Originally posted at https://stackoverflow.com/a/29586366
253 """
254 # deprecated: description='Use validate_variable_name instead.' core_version='2.23'
255
256 if not isinstance(ident, str):
257 return False
258
259 if not ident.isascii():
260 return False
261
262 if not ident.isidentifier():
263 return False
264
265 if keyword.iskeyword(ident):
266 return False
267
268 return True
269
270
271 def validate_variable_name(name: object) -> None:
272 """Validate the given variable name is valid, raising an AnsibleError if it is not."""
273 if isinstance(name, str) and name.isidentifier() and name.isascii() and name not in _jinja_bits.JINJA_KEYWORDS:
274 return
275
276 if isinstance(name, (str, int, float, bool, type(None))):
277 key_description = f'name {str(name)!r}' # show common scalar key names as strings
278 else:
279 key_description = 'name'
280
281 if not isinstance(name, str):
282 key_description += f' of type {native_type_name(name)!r}' # show the type name of all non-string keys
283
284 raise AnsibleError(
285 message=f'Invalid variable {key_description}.',
286 help_text='Variable names must be strings starting with a letter or underscore character, and contain only letters, numbers and underscores.',
287 obj=name,
288 )
289
290
291 def transform_to_native_types(
292 value: object,
293 redact: bool = True,
294 ) -> t.Any:
295 """
296 Recursively transform the given value to Python native types.
297 Potentially sensitive values such as individually vaulted variables will be redacted unless ``redact=False`` is passed.
298 Which values are considered potentially sensitive may change in future releases.
299 Types which cannot be converted to Python native types will result in an error.
300 """
301 return _transform_to_native_types_for_callback(value=value, redact=redact, mask_values=False)
302
303
304 # deprecated: description='Remove and use transform_to_native_types once implicit callback is removed.' core_version='2.27'
305 def _transform_to_native_types_for_callback(
306 value: object,
307 redact: bool = True,
308 mask_values: bool = False,
309 ) -> t.Any:
310 """Temp function to transform values to native types with explicit masking for callback plugins."""
311 avv = _json.AnsibleVariableVisitor(
312 convert_mapping_to_dict=True,
313 convert_sequence_to_list=True,
314 convert_custom_scalars=True,
315 convert_to_native_values=True,
316 apply_transforms=True,
317 visit_keys=True, # ensure that keys are also converted
318 encrypted_string_behavior=_json.EncryptedStringBehavior.REDACT if redact else _json.EncryptedStringBehavior.DECRYPT,
319 mask_secret_values=mask_values,
320 )
321
322 return avv.visit(value)