Debian Codegraph @

ansible_collections/community/sops/plugins/plugin_utils/action_module.py

raw
1 # Copyright (c) 2012-2013 Michael DeHaan <[email protected]>
2 # Copyright (c) 2016 Toshio Kuratomi <[email protected]>
3 # Copyright (c) 2019 Ansible Project
4 # Copyright (c) 2020 Felix Fontein <[email protected]>
5 # Copyright (c) 2021 Ansible Project
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 # Parts taken from ansible.module_utils.basic and ansible.module_utils.common.warnings.
10
11 # NOTE: THIS IS ONLY FOR ACTION PLUGINS!
12
13 from __future__ import annotations
14
15
16 import abc
17 import copy
18 import traceback
19 import typing as t
20
21 from ansible.errors import AnsibleError
22 from ansible.module_utils.basic import SEQUENCETYPE, remove_values
23 from collections.abc import Mapping
24 from ansible.plugins.action import ActionBase
25
26 from ansible.module_utils.common.arg_spec import ArgumentSpecValidator
27 from ansible.module_utils.errors import UnsupportedError
28
29 if t.TYPE_CHECKING:
30 from collections.abc import Callable
31
32
33 safe_eval: Callable[[t.Any, t.Any, t.Any], t.Any] | None
34
35 try:
36 from ansible.module_utils.common.validation import (
37 safe_eval,
38 )
39 except ImportError:
40 safe_eval = None
41
42
43 class _ModuleExitException(Exception):
44 def __init__(self, result):
45 super().__init__()
46 self.result = result
47
48
49 class AnsibleActionModule:
50 def __init__(self, action_plugin, argument_spec, bypass_checks=False,
51 mutually_exclusive=None, required_together=None,
52 required_one_of=None, supports_check_mode=False,
53 required_if=None, required_by=None):
54 # Internal data
55 self.__action_plugin = action_plugin
56 self.__warnings = []
57 self.__deprecations = []
58
59 # AnsibleModule data
60 self._name = self.__action_plugin._task.action
61 self.argument_spec = argument_spec
62 self.supports_check_mode = supports_check_mode
63 self.check_mode = self.__action_plugin._play_context.check_mode
64 self.bypass_checks = bypass_checks
65 self.no_log = self.__action_plugin._play_context.no_log
66
67 self.mutually_exclusive = mutually_exclusive
68 self.required_together = required_together
69 self.required_one_of = required_one_of
70 self.required_if = required_if
71 self.required_by = required_by
72 self._diff = self.__action_plugin._play_context.diff
73 self._verbosity = self.__action_plugin._display.verbosity
74
75 self.aliases = {}
76 self._legal_inputs = []
77 self._options_context = list()
78
79 self.params = copy.deepcopy(self.__action_plugin._task.args)
80 self.no_log_values = set()
81 self._validator = ArgumentSpecValidator(
82 self.argument_spec,
83 self.mutually_exclusive,
84 self.required_together,
85 self.required_one_of,
86 self.required_if,
87 self.required_by,
88 )
89 self._validation_result = self._validator.validate(self.params)
90 self.params.update(self._validation_result.validated_parameters)
91 self.no_log_values.update(self._validation_result._no_log_values)
92
93 try:
94 error = self._validation_result.errors[0]
95 except IndexError:
96 error = None
97
98 # We cannot use ModuleArgumentSpecValidator directly since it uses mechanisms for reporting
99 # warnings and deprecations that do not work in plugins. This is a copy of that code adjusted
100 # for our use-case:
101 for d in self._validation_result._deprecations:
102 # Before ansible-core 2.14.2, deprecations were always for aliases:
103 if 'name' in d:
104 self.deprecate(
105 "Alias '{name}' is deprecated. See the module docs for more information".format(name=d['name']),
106 version=d.get('version'), date=d.get('date'), collection_name=d.get('collection_name'))
107 # Since ansible-core 2.14.2, a message is present that can be directly printed:
108 if 'msg' in d:
109 self.deprecate(d['msg'], version=d.get('version'), date=d.get('date'), collection_name=d.get('collection_name'))
110
111 for w in self._validation_result._warnings:
112 self.warn('Both option {option} and its alias {alias} are set.'.format(option=w['option'], alias=w['alias']))
113
114 # Fail for validation errors, even in check mode
115 if error:
116 msg = self._validation_result.errors.msg
117 if isinstance(error, UnsupportedError):
118 msg = "Unsupported parameters for ({name}) {kind}: {msg}".format(name=self._name, kind='module', msg=msg)
119
120 self.fail_json(msg=msg)
121
122 def safe_eval(self, value, locals=None, include_exceptions=False):
123 if safe_eval is None:
124 raise ValueError("safe_eval is not available since ansible-core 2.21")
125 return safe_eval(value, locals, include_exceptions)
126
127 def warn(self, warning):
128 # Copied from ansible.module_utils.common.warnings:
129 if isinstance(warning, str):
130 self.__warnings.append(warning)
131 else:
132 raise TypeError("warn requires a string not a %s" % type(warning))
133
134 def deprecate(self, msg, version=None, date=None, collection_name=None):
135 if version is not None and date is not None:
136 raise AssertionError("implementation error -- version and date must not both be set")
137
138 # Copied from ansible.module_utils.common.warnings:
139 if isinstance(msg, str):
140 # For compatibility, we accept that neither version nor date is set,
141 # and treat that the same as if version would haven been set
142 if date is not None:
143 self.__deprecations.append({'msg': msg, 'date': date, 'collection_name': collection_name})
144 else:
145 self.__deprecations.append({'msg': msg, 'version': version, 'collection_name': collection_name})
146 else:
147 raise TypeError("deprecate requires a string not a %s" % type(msg))
148
149 def _return_formatted(self, kwargs):
150 if 'invocation' not in kwargs:
151 kwargs['invocation'] = {'module_args': self.params}
152
153 if 'warnings' in kwargs:
154 if isinstance(kwargs['warnings'], list):
155 for w in kwargs['warnings']:
156 self.warn(w)
157 else:
158 self.warn(kwargs['warnings'])
159
160 if self.__warnings:
161 kwargs['warnings'] = self.__warnings
162
163 if 'deprecations' in kwargs:
164 if isinstance(kwargs['deprecations'], list):
165 for d in kwargs['deprecations']:
166 if isinstance(d, SEQUENCETYPE) and len(d) == 2:
167 self.deprecate(d[0], version=d[1])
168 elif isinstance(d, Mapping):
169 self.deprecate(d['msg'], version=d.get('version'), date=d.get('date'),
170 collection_name=d.get('collection_name'))
171 else:
172 self.deprecate(d) # pylint: disable=ansible-deprecated-no-version
173 else:
174 self.deprecate(kwargs['deprecations']) # pylint: disable=ansible-deprecated-no-version
175
176 if self.__deprecations:
177 kwargs['deprecations'] = self.__deprecations
178
179 kwargs = remove_values(kwargs, self.no_log_values)
180 raise _ModuleExitException(kwargs)
181
182 def exit_json(self, **kwargs):
183 result = dict(kwargs)
184 if 'failed' not in result:
185 result['failed'] = False
186 self._return_formatted(result)
187
188 def fail_json(self, msg, **kwargs):
189 result = dict(kwargs)
190 result['failed'] = True
191 result['msg'] = msg
192 self._return_formatted(result)
193
194
195 class ActionModuleBase(ActionBase, metaclass=abc.ABCMeta):
196 @abc.abstractmethod
197 def setup_module(self):
198 """Return pair (ArgumentSpec, kwargs)."""
199 pass
200
201 @abc.abstractmethod
202 def run_module(self, module):
203 """Run module code"""
204 module.fail_json(msg='Not implemented.')
205
206 def run(self, tmp=None, task_vars=None):
207 if task_vars is None:
208 task_vars = dict()
209
210 result = super().run(tmp, task_vars)
211 del tmp # tmp no longer has any effect
212
213 try:
214 argument_spec, kwargs = self.setup_module()
215 module = argument_spec.create_ansible_module_helper(AnsibleActionModule, (self, ), **kwargs)
216 self.run_module(module)
217 raise AnsibleError('Internal error: action module did not call module.exit_json()') # pragma: no cover
218 except _ModuleExitException as mee:
219 result.update(mee.result)
220 return result
221 except Exception as dummy:
222 result['failed'] = True
223 result['msg'] = 'MODULE FAILURE'
224 result['exception'] = traceback.format_exc()
225 return result
226
227
228 class ArgumentSpec:
229 def __init__(self, argument_spec, mutually_exclusive=None, required_together=None, required_one_of=None, required_if=None, required_by=None):
230 self.argument_spec = argument_spec
231 self.mutually_exclusive = mutually_exclusive or []
232 self.required_together = required_together or []
233 self.required_one_of = required_one_of or []
234 self.required_if = required_if or []
235 self.required_by = required_by or {}
236
237 def create_ansible_module_helper(self, clazz, args, **kwargs):
238 return clazz(
239 *args,
240 argument_spec=self.argument_spec,
241 mutually_exclusive=self.mutually_exclusive,
242 required_together=self.required_together,
243 required_one_of=self.required_one_of,
244 required_if=self.required_if,
245 required_by=self.required_by,
246 **kwargs)