Debian Codegraph @

ansible_collections/kubernetes/core/plugins/action/k8s_scale.py

raw symbols SCIP
1 # Copyright (c) 2012-2014, Michael DeHaan <[email protected]>
2 # Copyright (c) 2017, Toshio Kuratomi <[email protected]>
3 # Copyright (c) 2020, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10 import copy
11 import os
12 import platform
13 import traceback
14 from contextlib import contextmanager
15
16 from ansible.config.manager import ensure_type
17 from ansible.errors import (
18 AnsibleAction,
19 AnsibleActionFail,
20 AnsibleError,
21 AnsibleFileNotFound,
22 )
23 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
24 from ansible.module_utils.parsing.convert_bool import boolean
25 from ansible.plugins.action import ActionBase
26
27 try:
28 from ansible.template import trust_as_template
29 except ImportError:
30 trust_as_template = None
31
32
33 def _from_yaml_to_definition(buffer):
34 try:
35 import yaml
36 except ImportError:
37 raise AnsibleError("Failed to import the required Python library (PyYAML).")
38 return list(yaml.safe_load_all(buffer))
39
40
41 ENV_KUBECONFIG_PATH_SEPARATOR = ";" if platform.system() == "Windows" else ":"
42
43
44 class ActionModule(ActionBase):
45 TRANSFERS_FILES = True
46 DEFAULT_NEWLINE_SEQUENCE = "\n"
47
48 def _ensure_invocation(self, result):
49 # NOTE: adding invocation arguments here needs to be kept in sync with
50 # any no_log specified in the argument_spec in the module.
51 if "invocation" not in result:
52 if self._play_context.no_log:
53 result["invocation"] = "CENSORED: no_log is set"
54 else:
55 result["invocation"] = self._task.args.copy()
56 result["invocation"]["module_args"] = self._task.args.copy()
57
58 return result
59
60 @contextmanager
61 def get_template_data(self, template_path):
62 try:
63 source = self._find_needle("templates", template_path)
64 except AnsibleError as e:
65 raise AnsibleActionFail(to_text(e))
66
67 # Get vault decrypted tmp file
68 try:
69 tmp_source = self._loader.get_real_file(source)
70 except AnsibleFileNotFound as e:
71 raise AnsibleActionFail(
72 "could not find template=%s, %s" % (source, to_text(e))
73 )
74 b_tmp_source = to_bytes(tmp_source, errors="surrogate_or_strict")
75
76 try:
77 with open(b_tmp_source, "rb") as f:
78 try:
79 template_data = to_text(f.read(), errors="surrogate_or_strict")
80 except UnicodeError:
81 raise AnsibleActionFail(
82 "Template source files must be utf-8 encoded"
83 )
84 yield template_data
85 except AnsibleAction:
86 raise
87 except Exception as e:
88 raise AnsibleActionFail("%s: %s" % (type(e).__name__, to_text(e)))
89 finally:
90 self._loader.cleanup_tmp_file(b_tmp_source)
91
92 def get_template_args(self, template):
93 template_param = {
94 "newline_sequence": self.DEFAULT_NEWLINE_SEQUENCE,
95 "variable_start_string": None,
96 "variable_end_string": None,
97 "block_start_string": None,
98 "block_end_string": None,
99 "trim_blocks": True,
100 "lstrip_blocks": False,
101 }
102 if isinstance(template, str):
103 # treat this as raw_params
104 template_param["path"] = template
105 elif isinstance(template, dict):
106 template_args = template
107 template_path = template_args.get("path", None)
108 if not template_path:
109 raise AnsibleActionFail("Please specify path for template.")
110 template_param["path"] = template_path
111
112 # Options type validation strings
113 for s_type in (
114 "newline_sequence",
115 "variable_start_string",
116 "variable_end_string",
117 "block_start_string",
118 "block_end_string",
119 ):
120 if s_type in template_args:
121 value = ensure_type(template_args[s_type], "string")
122 if value is not None and not isinstance(value, str):
123 raise AnsibleActionFail(
124 "%s is expected to be a string, but got %s instead"
125 % (s_type, type(value))
126 )
127 try:
128 template_param.update(
129 {
130 "trim_blocks": boolean(
131 template_args.get("trim_blocks", True), strict=False
132 ),
133 "lstrip_blocks": boolean(
134 template_args.get("lstrip_blocks", False), strict=False
135 ),
136 }
137 )
138 except TypeError as e:
139 raise AnsibleActionFail(to_native(e))
140
141 template_param.update(
142 {
143 "newline_sequence": template_args.get(
144 "newline_sequence", self.DEFAULT_NEWLINE_SEQUENCE
145 ),
146 "variable_start_string": template_args.get(
147 "variable_start_string", None
148 ),
149 "variable_end_string": template_args.get(
150 "variable_end_string", None
151 ),
152 "block_start_string": template_args.get("block_start_string", None),
153 "block_end_string": template_args.get("block_end_string", None),
154 }
155 )
156 else:
157 raise AnsibleActionFail(
158 "Error while reading template file - "
159 "a string or dict for template expected, but got %s instead"
160 % type(template)
161 )
162 return template_param
163
164 def import_jinja2_lstrip(self, templates):
165 # Option `lstrip_blocks' was added in Jinja2 version 2.7.
166 if any(tmp["lstrip_blocks"] for tmp in templates):
167 try:
168 import jinja2.defaults
169 except ImportError:
170 raise AnsibleError(
171 "Unable to import Jinja2 defaults for determining Jinja2 features."
172 )
173
174 try:
175 jinja2.defaults.LSTRIP_BLOCKS
176 except AttributeError:
177 raise AnsibleError(
178 "Option `lstrip_blocks' is only available in Jinja2 versions >=2.7"
179 )
180
181 def load_template(self, template, new_module_args, task_vars):
182 # template is only supported by k8s module.
183 if self._task.action not in (
184 "k8s",
185 "kubernetes.core.k8s",
186 "community.okd.k8s",
187 "redhat.openshift.k8s",
188 "community.kubernetes.k8s",
189 "openshift_adm_groups_sync",
190 "community.okd.openshift_adm_groups_sync",
191 "redhat.openshift.openshift_adm_groups_sync",
192 ):
193 raise AnsibleActionFail(
194 "'template' is only a supported parameter for the 'k8s' module."
195 )
196
197 template_params = []
198 if isinstance(template, str) or isinstance(template, dict):
199 template_params.append(self.get_template_args(template))
200 elif isinstance(template, list):
201 for element in template:
202 template_params.append(self.get_template_args(element))
203 else:
204 raise AnsibleActionFail(
205 "Error while reading template file - "
206 "a string or dict for template expected, but got %s instead"
207 % type(template)
208 )
209
210 self.import_jinja2_lstrip(template_params)
211
212 wrong_sequences = ["\\n", "\\r", "\\r\\n"]
213 allowed_sequences = ["\n", "\r", "\r\n"]
214
215 result_template = []
216 old_vars = self._templar.available_variables
217
218 default_environment = {}
219 if trust_as_template is None:
220 for key in (
221 "newline_sequence",
222 "variable_start_string",
223 "variable_end_string",
224 "block_start_string",
225 "block_end_string",
226 "trim_blocks",
227 "lstrip_blocks",
228 ):
229 if hasattr(self._templar.environment, key):
230 default_environment[key] = getattr(self._templar.environment, key)
231 for template_item in template_params:
232 # We need to convert unescaped sequences to proper escaped sequences for Jinja2
233 newline_sequence = template_item["newline_sequence"]
234 if newline_sequence in wrong_sequences:
235 template_item["newline_sequence"] = allowed_sequences[
236 wrong_sequences.index(newline_sequence)
237 ]
238 elif newline_sequence not in allowed_sequences:
239 raise AnsibleActionFail(
240 "newline_sequence needs to be one of: \n, \r or \r\n"
241 )
242
243 # template the source data locally & get ready to transfer
244 with self.get_template_data(template_item["path"]) as template_data:
245 # add ansible 'template' vars
246 temp_vars = copy.deepcopy(task_vars)
247 overrides = {}
248 for key, value in template_item.items():
249 if hasattr(self._templar.environment, key):
250 if value is not None:
251 overrides[key] = value
252 if trust_as_template is None:
253 setattr(self._templar.environment, key, value)
254 elif trust_as_template is None:
255 setattr(
256 self._templar.environment,
257 key,
258 default_environment.get(key),
259 )
260 self._templar.available_variables = temp_vars
261 if trust_as_template:
262 template_data = trust_as_template(template_data)
263 result = self._templar.template(
264 template_data,
265 preserve_trailing_newlines=True,
266 escape_backslashes=False,
267 overrides=overrides,
268 )
269 else:
270 result = self._templar.do_template(
271 template_data,
272 preserve_trailing_newlines=True,
273 escape_backslashes=False,
274 )
275 result_template.extend(_from_yaml_to_definition(result))
276 self._templar.available_variables = old_vars
277 resource_definition = self._task.args.get("definition", None)
278 if not resource_definition:
279 new_module_args.pop("template")
280 new_module_args["definition"] = result_template
281
282 def get_file_realpath(self, local_path):
283 # local_path is only supported by k8s_cp module.
284 if self._task.action not in (
285 "k8s_cp",
286 "kubernetes.core.k8s_cp",
287 "community.kubernetes.k8s_cp",
288 ):
289 raise AnsibleActionFail(
290 "'local_path' is only supported parameter for 'k8s_cp' module."
291 )
292
293 if os.path.exists(local_path):
294 return local_path
295
296 try:
297 # find in expected paths
298 return self._find_needle("files", local_path)
299 except AnsibleError:
300 raise AnsibleActionFail(
301 "%s does not exist in local filesystem" % local_path
302 )
303
304 def get_kubeconfig(self, kubeconfig, remote_transport, new_module_args):
305 if isinstance(kubeconfig, str):
306 # find the kubeconfig in the expected search path
307 if not remote_transport:
308 # kubeconfig is local
309 # find in expected paths
310 configs = []
311 for config in kubeconfig.split(ENV_KUBECONFIG_PATH_SEPARATOR):
312 config = self._find_needle("files", config)
313
314 # decrypt kubeconfig found
315 configs.append(self._loader.get_real_file(config, decrypt=True))
316 new_module_args["kubeconfig"] = ENV_KUBECONFIG_PATH_SEPARATOR.join(
317 configs
318 )
319
320 elif isinstance(kubeconfig, dict):
321 new_module_args["kubeconfig"] = kubeconfig
322 else:
323 raise AnsibleActionFail(
324 "Error while reading kubeconfig parameter - "
325 "a string or dict expected, but got %s instead" % type(kubeconfig)
326 )
327
328 def run(self, tmp=None, task_vars=None):
329 """handler for k8s options"""
330 if task_vars is None:
331 task_vars = dict()
332
333 result = super(ActionModule, self).run(tmp, task_vars)
334 del tmp # tmp no longer has any effect
335
336 # Check current transport connection and depending upon
337 # look for kubeconfig and src
338 # 'local' => look files on Ansible Controller
339 # Transport other than 'local' => look files on remote node
340 remote_transport = self._connection.transport != "local"
341
342 new_module_args = copy.deepcopy(self._task.args)
343
344 kubeconfig = self._task.args.get("kubeconfig", None)
345 if kubeconfig:
346 try:
347 self.get_kubeconfig(kubeconfig, remote_transport, new_module_args)
348 except AnsibleError as e:
349 result["failed"] = True
350 result["msg"] = to_text(e)
351 result["exception"] = traceback.format_exc()
352 return result
353
354 # find the file in the expected search path
355 src = self._task.args.get("src", None)
356
357 if src and not src.startswith(("http://", "https://", "ftp://")):
358 if remote_transport:
359 # src is on remote node
360 result.update(
361 self._execute_module(
362 module_name=self._task.action, task_vars=task_vars
363 )
364 )
365 return self._ensure_invocation(result)
366
367 # src is local
368 try:
369 # find in expected paths
370 src = self._find_needle("files", src)
371 except AnsibleError as e:
372 result["failed"] = True
373 result["msg"] = to_text(e)
374 result["exception"] = traceback.format_exc()
375 return result
376
377 if src:
378 new_module_args["src"] = src
379
380 template = self._task.args.get("template", None)
381 if template:
382 self.load_template(template, new_module_args, task_vars)
383
384 local_path = self._task.args.get("local_path")
385 state = self._task.args.get("state", None)
386 if local_path and state == "to_pod" and not remote_transport:
387 new_module_args["local_path"] = self.get_file_realpath(local_path)
388
389 # Execute the k8s_* module.
390 module_return = self._execute_module(
391 module_name=self._task.action,
392 module_args=new_module_args,
393 task_vars=task_vars,
394 )
395
396 # Delete tmp path
397 self._remove_tmp_path(self._connection._shell.tmpdir)
398
399 result.update(module_return)
400
401 return self._ensure_invocation(result)