Debian Codegraph @

ansible_collections/community/general/plugins/lookup/merge_variables.py

raw
1 # Copyright (c) 2020, Thales Netherlands
2 # Copyright (c) 2021, Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 author:
9 - Roy Lenferink (@rlenferink)
10 - Mark Ettema (@m-a-r-k-e)
11 - Alexander Petrenz (@alpex8)
12 - Christoph Fiehe (@cfiehe)
13 name: merge_variables
14 short_description: Merge variables whose names match a given pattern
15 description:
16 - This lookup returns the merged result of all variables in scope that match the given prefixes, suffixes, or regular expressions,
17 optionally.
18 version_added: 6.5.0
19 options:
20 _terms:
21 description:
22 - Depending on the value of O(pattern_type), this is a list of prefixes, suffixes, or regular expressions that is used
23 to match all variables that should be merged.
24 required: true
25 type: list
26 elements: str
27 pattern_type:
28 description:
29 - Change the way of searching for the specified pattern.
30 type: str
31 default: 'regex'
32 choices:
33 - prefix
34 - suffix
35 - regex
36 env:
37 - name: ANSIBLE_MERGE_VARIABLES_PATTERN_TYPE
38 ini:
39 - section: merge_variables_lookup
40 key: pattern_type
41 initial_value:
42 description:
43 - An initial value to start with.
44 type: raw
45 override:
46 description:
47 - Return an error, print a warning or ignore it when a key is overwritten.
48 - The default behavior V(error) makes the plugin fail when a key would be overwritten.
49 - When V(warn) and V(ignore) are used, note that it is important to know that the variables are sorted by name before
50 being merged. Keys for later variables in this order overwrite keys of the same name for variables earlier in this
51 order. To avoid potential confusion, better use O(override=error) whenever possible.
52 type: str
53 default: 'error'
54 choices:
55 - error
56 - warn
57 - ignore
58 env:
59 - name: ANSIBLE_MERGE_VARIABLES_OVERRIDE
60 ini:
61 - section: merge_variables_lookup
62 key: override
63 groups:
64 description:
65 - Search for variables across hosts that belong to the given groups. This allows to collect configuration pieces across
66 different hosts (for example a service on a host with its database on another host).
67 type: list
68 elements: str
69 version_added: 8.5.0
70 dict_merge:
71 description:
72 - Behavior when encountering dictionary values.
73 type: str
74 default: deep
75 choices:
76 deep: Merge dictionaries recursively.
77 shallow: Merge only top-level values.
78 replace: Overwrite existing dictionaries.
79 keep: Keep existing dictionaries.
80 version_added: 12.5.0
81 list_merge:
82 description:
83 - Behavior when encountering list values.
84 type: str
85 default: append
86 choices:
87 replace: Overwrite existing lists.
88 keep: Keep existing lists.
89 append: Append elements to the end of an existing list.
90 prepend: Insert elements at the beginning of an existing list.
91 merge: Take the index as key and merge each element.
92 version_added: 12.5.0
93 type_conflict_merge:
94 description:
95 - Merge strategy to apply on type conflicts.
96 - This value is only considered in case of O(override=warn) or O(override=ignore).
97 type: str
98 default: replace
99 choices:
100 replace: Overwrite existing values.
101 keep: Keep existing values.
102 version_added: 12.5.0
103 default_merge:
104 description:
105 - Merge strategy applied to other types.
106 - This value is only considered in case of O(override=warn) or O(override=ignore).
107 type: str
108 default: replace
109 choices:
110 replace: Overwrite existing values.
111 keep: Keep existing values.
112 version_added: 12.5.0
113 list_transformations:
114 description:
115 - List transformations applied to list types.
116 - The definition order corresponds to the order in which these transformations are applied.
117 - Elements can be a dict with the keys mentioned below or a string naming the transformation to apply.
118 type: list
119 elements: raw
120 suboptions:
121 name:
122 description:
123 - Name of the list transformation.
124 required: true
125 type: str
126 choices:
127 flatten: Flatten lists, converting nested lists into single lists. Does not support any additional options.
128 dedup: Remove duplicates from lists. Supported option is C(keep).
129 options:
130 description:
131 - Options as key value pairs.
132 type: dict
133 suboptions:
134 keep:
135 description:
136 - Determines which duplicates (if any) to keep.
137 - Only valid in combination with the O(list_transformations[].name=dedup) list transformation.
138 type: str
139 default: first
140 choices:
141 first: Drop duplicates except for the first occurrence.
142 last: Drop duplicates except for the last occurrence.
143 default: []
144 version_added: 12.5.0
145 """
146
147 EXAMPLES = r"""
148 # Some example variables, they can be defined anywhere as long as they are in scope
149 test_init_list:
150 - "list init item 1"
151 - "list init item 2"
152
153 testa__test_list:
154 - "test a item 1"
155
156 testb__test_list:
157 - "test b item 1"
158
159 testa__test_dict:
160 ports:
161 - 1
162
163 testb__test_dict:
164 ports:
165 - 3
166
167 testa_low_dict__test:
168 a:
169 a:
170 x: low_value
171 y: low_value
172 list:
173 - low_value
174 b:
175 - 1
176 - 1
177 - 2
178 - 3
179
180 testb_high_dict__test:
181 a:
182 a:
183 y: high_value
184 z: high_value
185 list:
186 - high_value
187 b:
188 - 3
189 - 4
190 - 4
191 - '5': value
192
193 # Merge variables that end with '__test_dict' and store the result in a variable 'example_a'
194 example_a: "{{ lookup('community.general.merge_variables', '__test_dict', pattern_type='suffix') }}"
195
196 # The variable example_a now contains:
197 # ports:
198 # - 1
199 # - 3
200
201 # Merge variables that match the '^.+__test_list$' regular expression, starting with an initial value and store the
202 # result in a variable 'example_b'
203 example_b: "{{ lookup('community.general.merge_variables', '^.+__test_list$', initial_value=test_init_list) }}"
204
205 # The variable example_b now contains:
206 # - "list init item 1"
207 # - "list init item 2"
208 # - "test a item 1"
209 # - "test b item 1"
210
211 # Shallow merge variables that end with '__test', insert list elements at the beginning of the list,
212 # remove duplicates from lists (keep the first occurrence), and store the result in a variable 'example_c'
213 example_c: "{{
214 lookup(
215 'community.general.merge_variables',
216 '^.+__test$',
217 dict_merge='shallow',
218 list_merge='prepend',
219 list_transformations=['dedup']) }}"
220
221 # The variable example_c now contains:
222 # a:
223 # a:
224 # y: high_value
225 # z: high_value
226 # list:
227 # - high_value
228 # b:
229 # - 3
230 # - 4
231 # - '5': value
232 # - 1
233 # - 2
234
235 # Deep merge variables that end with '__test', merge list elements by index, ignore overrides, apply the strategies
236 # 'keep' for type conflicts and 'replace' for other types, and store the result in a variable 'example_d'
237 example_d: "{{
238 lookup(
239 'community.general.merge_variables',
240 '^.+__test$',
241 dict_merge='deep',
242 list_merge='merge',
243 override='ignore',
244 type_conflict_merge='keep',
245 default_merge='replace') }}"
246
247 # The variable example_d now contains:
248 # a:
249 # a:
250 # x: low_value
251 # y: high_value
252 # list:
253 # - high_value
254 # z: high_value
255 # b:
256 # - 3
257 # - 4
258 # - 4
259 # - 3
260 """
261
262 RETURN = r"""
263 _raw:
264 description: In case the search matches list items, a list is returned. In case the search matches dicts, a dict is returned.
265 type: raw
266 elements: raw
267 """
268
269
270 import re
271 import typing as t
272 from abc import ABC, abstractmethod
273
274 from ansible.errors import AnsibleError
275 from ansible.plugins.lookup import LookupBase
276 from ansible.utils.display import Display
277
278 from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
279
280 if t.TYPE_CHECKING:
281 from collections.abc import Callable
282
283
284 display = Display()
285
286
287 def _verify_and_get_type(variable: t.Any) -> str:
288 if isinstance(variable, list):
289 return "list"
290 elif isinstance(variable, dict):
291 return "dict"
292 else:
293 raise AnsibleError(f"Not supported type detected, variable must be a list or a dict: '{variable}'")
294
295
296 class LookupModule(LookupBase):
297 def run(self, terms: list[str], variables: dict[str, t.Any], **kwargs) -> list[t.Any]:
298 self.set_options(direct=kwargs)
299 check_for_wrong_terms(self, direct=kwargs)
300 initial_value = self.get_option("initial_value", None)
301 self._override_behavior = self.get_option("override", "error")
302 self._pattern_type = self.get_option("pattern_type", "regex")
303 self._groups = self.get_option("groups", None)
304 self._dict_merge = self.get_option("dict_merge", "deep")
305 self._list_merge = self.get_option("list_merge", "append")
306 self._type_conflict_merge = self.get_option("type_conflict_merge", "replace")
307 self._default_merge = self.get_option("default_merge", "replace")
308 self._list_transformations = self.get_option("list_transformations", [])
309
310 ret = []
311 for term in terms:
312 if not isinstance(term, str):
313 raise AnsibleError(f"Non-string type '{type(term)}' passed, only 'str' types are allowed!")
314
315 if not self._groups: # consider only own variables
316 ret.append(self._merge_vars(term, initial_value, variables))
317 else: # consider variables of hosts in given groups
318 cross_host_merge_result = initial_value
319 for host in variables["hostvars"]:
320 if self._is_host_in_allowed_groups(variables["hostvars"][host]["group_names"]):
321 host_variables = dict(variables["hostvars"].raw_get(host))
322 host_variables["hostvars"] = variables["hostvars"] # re-add hostvars
323 cross_host_merge_result = self._merge_vars(term, cross_host_merge_result, host_variables)
324 ret.append(cross_host_merge_result)
325
326 return ret
327
328 def _is_host_in_allowed_groups(self, host_groups: list[str]) -> bool:
329 if "all" in self._groups:
330 return True
331
332 group_intersection = [host_group_name for host_group_name in host_groups if host_group_name in self._groups]
333 return bool(group_intersection)
334
335 def _var_matches(self, key: str, search_pattern: str) -> bool:
336 if self._pattern_type == "prefix":
337 return key.startswith(search_pattern)
338 elif self._pattern_type == "suffix":
339 return key.endswith(search_pattern)
340 elif self._pattern_type == "regex":
341 matcher = re.compile(search_pattern)
342 return matcher.search(key) is not None
343
344 return False
345
346 def _merge_vars(self, search_pattern: str, initial_value: t.Any, variables: dict[str, t.Any]) -> t.Any:
347 display.vvv(f"Merge variables with {self._pattern_type}: {search_pattern}")
348 var_merge_names = sorted([key for key in variables.keys() if self._var_matches(key, search_pattern)])
349 display.vvv(f"The following variables will be merged: {var_merge_names}")
350 prev_var_type = None
351 result = None
352
353 if initial_value is not None:
354 prev_var_type = _verify_and_get_type(initial_value)
355 result = initial_value
356
357 builder = (
358 MergerBuilder()
359 .with_type_strategy(list, ListMergeStrategies.from_name(self._list_merge))
360 .with_type_conflict_strategy(BaseMergeStrategies.from_name(self._type_conflict_merge))
361 .with_default_strategy(BaseMergeStrategies.from_name(self._default_merge))
362 .with_override_behavior(self._override_behavior)
363 )
364
365 if self._dict_merge == "deep":
366 builder.with_type_strategy(dict, DictMergeStrategies.Merge())
367 elif self._dict_merge == "shallow":
368 builder.with_shallow_merge()
369 else:
370 builder.with_type_strategy(dict, DictMergeStrategies.from_name(self._dict_merge))
371
372 for transformation in self._list_transformations:
373 if isinstance(transformation, str):
374 builder.with_transformation(list, ListTransformations.from_name(transformation))
375 elif isinstance(transformation, dict):
376 name = transformation["name"]
377 options = transformation.get("options", {})
378 builder.with_transformation(list, ListTransformations.from_name(name, **options))
379 else:
380 raise AnsibleError(
381 f"Transformations must be specified through values of type 'str' or 'dict', but a value of type '{type(transformation)}' was given"
382 )
383
384 merger = builder.build()
385
386 if self._templar is None:
387 raise AnsibleError("Templar is not available")
388
389 templar = self._templar.copy_with_new_env(available_variables=variables)
390
391 for var_name in var_merge_names:
392 var_value = templar.template(variables[var_name]) # Render jinja2 templates
393 var_type = _verify_and_get_type(var_value)
394
395 if prev_var_type is None:
396 prev_var_type = var_type
397 elif prev_var_type != var_type:
398 raise AnsibleError("Unable to merge, not all variables are of the same type")
399
400 if result is None:
401 result = var_value
402 continue
403
404 result = merger.merge(path=[var_name], left=result, right=var_value)
405
406 return result
407
408
409 class MergeStrategy(ABC):
410 @abstractmethod
411 def merge(self, merger: ObjectMerger, path: list[str], left: t.Any, right: t.Any) -> t.Any:
412 raise NotImplementedError
413
414
415 class MergeStrategies:
416 @classmethod
417 def from_name(cls, name: str, *args, **kwargs) -> MergeStrategy:
418 if name in cls.strategies:
419 return cls.strategies[name](*args, **kwargs)
420 else:
421 raise AnsibleError(f"Unknown merge strategy '{name}'")
422
423 strategies: dict[str, Callable[..., t.Any]] = {}
424
425
426 class BaseMergeStrategies(MergeStrategies):
427 class Replace(MergeStrategy):
428 def merge(self, merger: ObjectMerger, path: list[str], left: t.Any, right: t.Any) -> t.Any:
429 return right
430
431 class Keep(MergeStrategy):
432 def merge(self, merger: ObjectMerger, path: list[str], left: t.Any, right: t.Any) -> t.Any:
433 return left
434
435 strategies = {
436 "replace": Replace,
437 "keep": Keep,
438 }
439
440
441 class DictMergeStrategies(MergeStrategies):
442 class Merge(MergeStrategy):
443 def merge(
444 self, merger: ObjectMerger, path: list[str], left: dict[str, t.Any], right: dict[str, t.Any]
445 ) -> dict[str, t.Any]:
446 result = left
447 for key, value in right.items():
448 if key not in result:
449 result[key] = value
450 else:
451 path.append(key)
452 merged = merger.merge(path=path, left=result[key], right=value)
453 merger.before_override(path=path, old_value=result[key], new_value=merged)
454 result[key] = merged
455
456 return result
457
458 strategies = {
459 "merge": Merge,
460 "replace": BaseMergeStrategies.Replace,
461 "keep": BaseMergeStrategies.Keep,
462 }
463
464
465 class ListMergeStrategies(MergeStrategies):
466 class Append(MergeStrategy):
467 def merge(self, merger: ObjectMerger, path: list[str], left: list[t.Any], right: list[t.Any]) -> list[t.Any]:
468 return left + right
469
470 class Prepend(MergeStrategy):
471 def merge(self, merger: ObjectMerger, path: list[str], left: list[t.Any], right: list[t.Any]) -> list[t.Any]:
472 return right + left
473
474 class Merge(MergeStrategy):
475 def merge(self, merger: ObjectMerger, path: list[str], left: list[t.Any], right: list[t.Any]) -> list[t.Any]:
476 result = left
477 for i, value in enumerate(right):
478 if i >= len(result):
479 result.extend(right[i:])
480 break
481
482 path.append(str(i))
483 merged = merger.merge(path=path, left=result[i], right=value)
484 merger.before_override(path=path, old_value=result[i], new_value=merged)
485 result[i] = merged
486
487 return result
488
489 strategies = {
490 "append": Append,
491 "prepend": Prepend,
492 "merge": Merge,
493 "replace": BaseMergeStrategies.Replace,
494 "keep": BaseMergeStrategies.Keep,
495 }
496
497
498 class Transformation(ABC):
499 @abstractmethod
500 def transform(self, merger: ObjectMerger, value: t.Any) -> t.Any:
501 raise NotImplementedError
502
503
504 class Transformations:
505 @classmethod
506 def from_name(cls, name: str, *args, **kwargs) -> Transformation:
507 if name in cls.transformations:
508 return cls.transformations[name](*args, **kwargs)
509 else:
510 raise AnsibleError(f"Unknown transformation '{name}'")
511
512 transformations: dict[str, Callable[..., t.Any]] = {}
513
514
515 class ListTransformations(Transformations):
516 class Dedup(Transformation):
517 def __init__(self, keep: str = "first"):
518 self.keep = keep
519
520 def transform(self, merger: ObjectMerger, value: list[t.Any]) -> list[t.Any]:
521 result = []
522 if self.keep == "first":
523 for item in value:
524 if item not in result:
525 result.append(item)
526 elif self.keep == "last":
527 for item in reversed(value):
528 if item not in result:
529 result.insert(0, item)
530 else:
531 raise AnsibleError(
532 f"Unsupported 'keep' value for deduplication transformation. Given was '{self.keep}', but must be either 'first' or 'last'"
533 )
534
535 return result
536
537 class Flatten(Transformation):
538 def transform(self, merger: ObjectMerger, value: list[t.Any]) -> list[t.Any]:
539 result = []
540 for item in value:
541 if isinstance(item, list):
542 result.extend(self.transform(merger, item))
543 else:
544 result.append(item)
545 return result
546
547 transformations = {
548 "dedup": Dedup,
549 "flatten": Flatten,
550 }
551
552
553 class MergerBuilder:
554 def __init__(self) -> None:
555 self.type_strategies: list[tuple[type, MergeStrategy]] = []
556 self.type_conflict_strategy: MergeStrategy = BaseMergeStrategies.Replace()
557 self.default_strategy: MergeStrategy = BaseMergeStrategies.Replace()
558 self.transformations: list[tuple[type, Transformation]] = []
559 self.override_behavior: str = "error"
560 self.shallow_merge: bool = False
561
562 def with_shallow_merge(self, shallow_merge: bool = True) -> MergerBuilder:
563 self.shallow_merge = shallow_merge
564 return self
565
566 def with_override_behavior(self, override_behavior: str) -> MergerBuilder:
567 self.override_behavior = override_behavior
568 return self
569
570 def with_type_strategy(self, cls, merge_strategy: MergeStrategy) -> MergerBuilder:
571 self.type_strategies.append((cls, merge_strategy))
572 return self
573
574 def with_default_strategy(self, merge_strategy: MergeStrategy) -> MergerBuilder:
575 self.default_strategy = merge_strategy
576 return self
577
578 def with_type_conflict_strategy(self, merge_strategy: MergeStrategy) -> MergerBuilder:
579 self.type_conflict_strategy = merge_strategy
580 return self
581
582 def with_transformation(self, cls, *args: Transformation) -> MergerBuilder:
583 for transformation in args:
584 self.transformations.append((cls, transformation))
585 return self
586
587 def build(self) -> Merger:
588 merger = ObjectMerger(
589 type_strategies=self.type_strategies,
590 type_conflict_strategy=self.type_conflict_strategy,
591 default_strategy=self.default_strategy,
592 transformations=self.transformations,
593 override_behavior=self.override_behavior,
594 )
595
596 if self.shallow_merge:
597 return ShallowMerger(merger)
598
599 return merger
600
601
602 class Merger(ABC):
603 @abstractmethod
604 def merge(self, path: list[str], left: t.Any, right: t.Any) -> t.Any:
605 raise NotImplementedError
606
607
608 class ObjectMerger(Merger):
609 def __init__(
610 self,
611 type_strategies: list[tuple[type, MergeStrategy]],
612 type_conflict_strategy: MergeStrategy,
613 default_strategy: MergeStrategy,
614 transformations: list[tuple[type, Transformation]],
615 override_behavior: str,
616 ) -> None:
617 self.type_strategies = type_strategies
618 self.type_conflict_strategy = type_conflict_strategy
619 self.default_strategy = default_strategy
620 self.transformations = transformations
621 self.override_behavior = override_behavior
622
623 def before_override(self, path: list[str], old_value: t.Any, new_value: t.Any) -> None:
624 if (
625 not isinstance(old_value, type(new_value))
626 and not isinstance(new_value, type(old_value))
627 or not isinstance(new_value, dict)
628 and not isinstance(new_value, list)
629 and old_value != new_value
630 ):
631 # An override is regarded as a value type conflict or
632 # when both values are neither dicts nor lists and
633 # have different values
634 msg = f"The key '{path[-1]}' with value '{old_value}' will be overwritten with value '{new_value}' from '{'.'.join(path)}'"
635 if self.override_behavior == "error":
636 raise AnsibleError(msg)
637 elif self.override_behavior == "warn":
638 display.warning(msg)
639
640 def transform(self, value: t.Any) -> t.Any:
641 for cls, transformation in self.transformations:
642 if isinstance(value, cls):
643 value = transformation.transform(self, value)
644 return value
645
646 def lookup_merge_strategy(self, left: t.Any, right: t.Any) -> MergeStrategy:
647 for cls, merge_strategy in self.type_strategies:
648 if isinstance(left, cls) and isinstance(right, cls):
649 return merge_strategy
650
651 if not isinstance(left, type(right)) and not isinstance(right, type(left)):
652 return self.type_conflict_strategy
653
654 return self.default_strategy
655
656 def apply_merge_strategy(self, merge_strategy: MergeStrategy, path: list[str], left: t.Any, right: t.Any) -> t.Any:
657 return self.transform(merge_strategy.merge(self, path, left, right))
658
659 def merge(self, path: list[str], left: t.Any, right: t.Any) -> t.Any:
660 return self.apply_merge_strategy(self.lookup_merge_strategy(left, right), path, left, right)
661
662
663 class ShallowMerger(Merger):
664 def __init__(self, merger: ObjectMerger) -> None:
665 self.merger = merger
666
667 def merge(self, path: list[str], left: t.Any, right: t.Any) -> t.Any:
668 if isinstance(left, dict) and isinstance(right, dict):
669 return self.merger.apply_merge_strategy(DictMergeStrategies.Merge(), path, left, right)
670
671 return self.merger.merge(path, left, right)