Debian Codegraph @

lib/ansible/vars/clean.py

raw
1 # Copyright (c) 2017 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import annotations
5
6 import os
7 import re
8
9 from collections.abc import MutableMapping, Sequence, Mapping
10
11 from ansible import constants as C
12 from ansible.plugins.loader import connection_loader
13 from ansible.utils.display import Display
14
15 display = Display()
16
17
18 def module_response_deepcopy(v):
19 """Function to create a deep copy of module response data
20
21 Designed to be used within the Ansible "engine" to improve performance
22 issues where ``copy.deepcopy`` was used previously, largely with CPU
23 and memory contention.
24
25 This only supports the following data types, and was designed to only
26 handle specific workloads:
27
28 * ``dict``
29 * ``list``
30
31 The data we pass here will come from a serialization such
32 as JSON, so we shouldn't have need for other data types such as
33 ``set`` or ``tuple``.
34
35 Take note that this function should not be used extensively as a
36 replacement for ``deepcopy`` due to the naive way in which this
37 handles other data types.
38
39 Do not expect uses outside of those listed below to maintain
40 backwards compatibility, in case we need to extend this function
41 to handle our specific needs:
42
43 * ``ansible.executor.task_result._as_callback_task_result``
44 * ``ansible.vars.clean.clean_facts``
45 * ``ansible.vars.namespace_facts``
46 """
47 if isinstance(v, dict):
48 ret = v.copy()
49 items = ret.items()
50 elif isinstance(v, list):
51 ret = v[:]
52 items = enumerate(ret)
53 else:
54 return v
55
56 for key, value in items:
57 if isinstance(value, (dict, list)):
58 ret[key] = module_response_deepcopy(value)
59 else:
60 ret[key] = value
61
62 return ret
63
64
65 def strip_internal_keys[T: Sequence | MutableMapping](dirty: T, exceptions: set[str] | frozenset[str] = frozenset()) -> T:
66 """Recursively remove items from mappings whose keys start with `_ansible`, unless the key is in `exceptions`."""
67 match dirty:
68 case str():
69 return dirty
70 case Sequence():
71 for element in dirty:
72 strip_internal_keys(element, exceptions=exceptions)
73 case MutableMapping():
74 for key in list(dirty.keys()):
75 if isinstance(key, str) and key.startswith('_ansible_') and key not in exceptions:
76 del dirty[key]
77 else:
78 strip_internal_keys(dirty[key], exceptions=exceptions)
79
80 return dirty
81
82
83 def clean_facts(facts: Mapping[str, object]):
84 """ remove facts that can override internal keys or otherwise deemed unsafe """
85 data = module_response_deepcopy(facts)
86
87 remove_keys = set()
88 fact_keys = set(data.keys())
89 # first we add all of our magic variable names to the set of
90 # keys we want to remove from facts
91 # NOTE: these will eventually disappear in favor of others below
92 for magic_var in C.MAGIC_VARIABLE_MAPPING:
93 remove_keys.update(fact_keys.intersection(C.MAGIC_VARIABLE_MAPPING[magic_var]))
94
95 # remove common connection vars
96 remove_keys.update(fact_keys.intersection(C.COMMON_CONNECTION_VARS))
97
98 # next we remove any connection plugin specific vars
99 for conn_path in connection_loader.all(path_only=True):
100 conn_name = os.path.splitext(os.path.basename(conn_path))[0]
101 re_key = re.compile('^ansible_%s_' % re.escape(conn_name))
102 for fact_key in fact_keys:
103 # most lightweight VM or container tech creates devices with this pattern, this avoids filtering them out
104 if (re_key.match(fact_key) and not fact_key.endswith(('_bridge', '_gwbridge'))) or fact_key.startswith('ansible_become_'):
105 remove_keys.add(fact_key)
106
107 # remove some KNOWN keys
108 for hard in C.RESTRICTED_RESULT_KEYS:
109 if hard in fact_keys:
110 remove_keys.add(hard)
111
112 # finally, we search for interpreter keys to remove
113 re_interp = re.compile('^ansible_.*_interpreter$')
114 for fact_key in fact_keys:
115 if re_interp.match(fact_key):
116 remove_keys.add(fact_key)
117 # then we remove them (except for ssh host keys)
118 for r_key in remove_keys:
119 if not r_key.startswith('ansible_ssh_host_key_'):
120 display.warning("Removed restricted key from module data: %s" % (r_key))
121 del data[r_key]
122
123 return strip_internal_keys(data)
124
125
126 def namespace_facts(facts: Mapping[str, object]) -> dict[str, object]:
127 """ return all facts inside 'ansible_facts' w/o an ansible_ prefix """
128 deprefixed = {}
129 for k in facts:
130 if k.startswith('ansible_') and k not in ('ansible_local',):
131 deprefixed[k[8:]] = module_response_deepcopy(facts[k])
132 else:
133 deprefixed[k] = module_response_deepcopy(facts[k])
134
135 return {'ansible_facts': deprefixed}