Debian Codegraph @

lib/ansible/module_utils/basic.py

raw
1 # Copyright (c), Michael DeHaan <[email protected]>, 2012-2013
2 # Copyright (c), Toshio Kuratomi <[email protected]> 2016
3 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
4
5 from __future__ import annotations
6
7 import copy
8 import json
9 import sys
10 import typing as t
11
12 # Used for determining if the system is running a new enough python version
13 # and should only restrict on our documented minimum versions
14 _PY_MIN = (3, 9)
15
16 if sys.version_info < _PY_MIN:
17 print(json.dumps(dict(
18 failed=True,
19 msg=f"Ansible requires Python {'.'.join(map(str, _PY_MIN))} or newer on the target. "
20 f"Current version: {''.join(sys.version.splitlines())}",
21 )))
22 sys.exit(1)
23
24 # Ansible modules can be written in any language.
25 # The functions available here can be used to do many common tasks,
26 # to simplify development of Python modules.
27
28 import __main__
29 import atexit
30 import dataclasses as _dataclasses
31 import errno
32 import grp
33 import fcntl
34 import locale
35 import os
36 import pwd
37 import platform
38 import re
39 import select
40 import selectors
41 import shlex
42 import shutil
43 import stat
44 import subprocess
45 import tempfile
46 import time
47 import traceback
48
49 from . import secrets as _secrets
50
51 from collections.abc import (
52 KeysView,
53 Mapping,
54 MutableMapping,
55 Sequence,
56 MutableSequence,
57 Set,
58 MutableSet,
59 )
60 from functools import reduce
61
62 _UNSET = t.cast(t.Any, object())
63
64 HAVE_SELINUX = False
65 try:
66 from ansible.module_utils.compat import selinux
67 HAVE_SELINUX = True
68 except ImportError:
69 pass
70
71 # Python2 & 3 way to get NoneType
72 NoneType = type(None)
73
74 from ._internal import _traceback, _errors, _debugging, _deprecator, _messages, _logging
75 # Re-export logging capability flags as public API for backward compatibility
76 from ._internal._logging import HAS_SYSLOG, has_journal
77
78 from .common.text.converters import (
79 to_native,
80 to_bytes,
81 to_text,
82 jsonify,
83 container_to_bytes as json_dict_unicode_to_bytes,
84 container_to_text as json_dict_bytes_to_unicode,
85 )
86
87 from ansible.module_utils.common.arg_spec import ModuleArgumentSpecValidator
88
89 from ansible.module_utils.common.text.formatters import (
90 lenient_lowercase,
91 bytes_to_human,
92 human_to_bytes,
93 SIZE_RANGES,
94 )
95
96 from ansible.module_utils.common import json as _common_json
97
98 import hashlib
99
100
101 def _get_available_hash_algorithms():
102 """Return a dictionary of available hash function names and their associated function."""
103 algorithms = {}
104 for algorithm_name in hashlib.algorithms_available:
105 algorithm_func = getattr(hashlib, algorithm_name, None)
106 if algorithm_func:
107 try:
108 # Make sure the algorithm is actually available for use.
109 # Not all algorithms listed as available are actually usable.
110 # For example, md5 is not available in FIPS mode.
111 algorithm_func()
112 except Exception:
113 pass
114 else:
115 algorithms[algorithm_name] = algorithm_func
116
117 return algorithms
118
119
120 AVAILABLE_HASH_ALGORITHMS = _get_available_hash_algorithms()
121
122 from ansible.module_utils.common import json as _json
123 from ansible.module_utils.common.locale import get_best_parsable_locale
124 from ansible.module_utils.common.process import get_bin_path
125 from ansible.module_utils.common.file import (
126 _PERM_BITS as PERM_BITS,
127 _DEFAULT_PERM as DEFAULT_PERM,
128 is_executable,
129 format_attributes,
130 get_flags_from_attributes,
131 FILE_ATTRIBUTES,
132 S_IXANY,
133 S_IRWU_RWG_RWO,
134 )
135 from ansible.module_utils.common.sys_info import (
136 get_distribution,
137 get_distribution_version,
138 get_platform_subclass,
139 )
140 from ansible.module_utils.common.parameters import (
141 env_fallback,
142 remove_values,
143 sanitize_keys,
144 DEFAULT_TYPE_VALIDATORS,
145 PASS_VARS,
146 PASS_BOOLS,
147 )
148
149 from ansible.module_utils.errors import AnsibleFallbackNotFound, AnsibleValidationErrorMultiple, UnsupportedError
150 from ansible.module_utils.common.validation import (
151 check_missing_parameters,
152 )
153 from ansible.module_utils.common._utils import get_all_subclasses as _get_all_subclasses
154 from ansible.module_utils.parsing.convert_bool import BOOLEANS, BOOLEANS_FALSE, BOOLEANS_TRUE, boolean
155 from ansible.module_utils.common.warnings import (
156 deprecate,
157 error_as_warning,
158 get_deprecations,
159 get_warnings,
160 warn,
161 )
162
163 from ansible.module_utils._internal import _debug
164
165 # Note: When getting Sequence from collections, it matches with strings. If
166 # this matters, make sure to check for strings before checking for sequencetype
167 SEQUENCETYPE = frozenset, KeysView, Sequence
168
169 PASSWORD_MATCH = re.compile(r'^(?:.+[-_\s])?pass(?:[-_\s]?(?:word|phrase|wrd|wd)?)(?:[-_\s].+)?$', re.I)
170
171 imap = map
172
173 # Internal global holding passed in params. This is consulted in case
174 # multiple AnsibleModules are created. Otherwise each AnsibleModule would
175 # attempt to read from stdin. Other code should not use this directly as it
176 # is an internal implementation detail
177 _ANSIBLE_ARGS: bytes | None = None
178 _ANSIBLE_PROFILE: str | None = None
179 _PARSED_MODULE_ARGS: dict[str, t.Any] | None = None
180
181
182 FILE_COMMON_ARGUMENTS = dict(
183 # These are things we want. About setting metadata (mode, ownership, permissions in general) on
184 # created files (these are used by set_fs_attributes_if_different and included in
185 # load_file_common_arguments)
186 mode=dict(type='raw'),
187 owner=dict(type='str'),
188 group=dict(type='str'),
189 seuser=dict(type='str'),
190 serole=dict(type='str'),
191 selevel=dict(type='str'),
192 setype=dict(type='str'),
193 attributes=dict(type='str', aliases=['attr']),
194 unsafe_writes=dict(type='bool', default=False, fallback=(env_fallback, ['ANSIBLE_UNSAFE_WRITES'])), # should be available to any module using atomic_move
195 )
196
197 PASSWD_ARG_RE = re.compile(r'^[-]{0,2}pass[-]?(word|wd)?')
198
199 # Used for parsing symbolic file perms
200 MODE_OPERATOR_RE = re.compile(r'[+=-]')
201 USERS_RE = re.compile(r'^[ugo]+$')
202 PERMS_RE = re.compile(r'^[rwxXstugo]*$')
203
204
205 def get_platform():
206 """
207 :returns: Name of the platform the module is running on in a native string
208
209 Returns a native string that labels the platform ("Linux", "Solaris", etc). Currently, this is
210 the result of calling :py:func:`platform.system`.
211 """
212 deprecate(
213 msg="The `get_platform()` function from `ansible.module_utils.basic` is deprecated.",
214 version="2.24",
215 help_text="Use `platform.system()` from the Python standard library instead.",
216 )
217 return platform.system()
218
219
220 def load_platform_subclass(cls, *args, **kwargs):
221 deprecate(
222 msg="The `load_platform_subclass()` function from `ansible.module_utils.basic` is deprecated.",
223 version="2.24",
224 help_text="Use `get_platform_subclass()` from `ansible.module_utils.common.sys_info` instead.",
225 )
226 platform_cls = get_platform_subclass(cls)
227 return super(cls, platform_cls).__new__(platform_cls)
228
229
230 def get_all_subclasses(cls):
231 deprecate(
232 msg="The `get_all_subclasses()` function from `ansible.module_utils.basic` is deprecated.",
233 version="2.24",
234 help_text="Use `get_all_subclasses()` from `ansible.module_utils.common._utils` instead.",
235 )
236 return list(_get_all_subclasses(cls))
237
238
239 def heuristic_log_sanitize(data, no_log_values=None):
240 """ Remove strings that look like passwords from log messages """
241 deprecate(
242 msg="The `heuristic_log_sanitize()` function from `ansible.module_utils.basic` is deprecated.",
243 version="2.25",
244 help_text="Secret values are now masked automatically. Use functions from `ansible.module_utils.secrets` if you need to handle secrets manually.",
245 )
246 # Currently filters:
247 # user:pass@foo/whatever and http://username:pass@wherever/foo
248 # This code has false positives and consumes parts of logs that are
249 # not passwds
250
251 # begin: start of a passwd containing string
252 # end: end of a passwd containing string
253 # sep: char between user and passwd
254 # prev_begin: where in the overall string to start a search for
255 # a passwd
256 # sep_search_end: where in the string to end a search for the sep
257 data = to_native(data)
258
259 output = []
260 begin = len(data)
261 prev_begin = begin
262 sep = 1
263 while sep:
264 # Find the potential end of a passwd
265 try:
266 end = data.rindex('@', 0, begin)
267 except ValueError:
268 # No passwd in the rest of the data
269 output.insert(0, data[0:begin])
270 break
271
272 # Search for the beginning of a passwd
273 sep = None
274 sep_search_end = end
275 while not sep:
276 # URL-style username+password
277 try:
278 begin = data.rindex('://', 0, sep_search_end)
279 except ValueError:
280 # No url style in the data, check for ssh style in the
281 # rest of the string
282 begin = 0
283 # Search for separator
284 try:
285 sep = data.index(':', begin + 3, end)
286 except ValueError:
287 # No separator; choices:
288 if begin == 0:
289 # Searched the whole string so there's no password
290 # here. Return the remaining data
291 output.insert(0, data[0:prev_begin])
292 break
293 # Search for a different beginning of the password field.
294 sep_search_end = begin
295 continue
296 if sep:
297 # Password was found; remove it.
298 output.insert(0, data[end:prev_begin])
299 output.insert(0, '********')
300 output.insert(0, data[begin:sep + 1])
301 prev_begin = begin
302
303 output = ''.join(output)
304 if no_log_values:
305 output = remove_values(output, no_log_values)
306 return output
307
308
309 def _load_params():
310 """ read the modules parameters and store them globally.
311
312 This function may be needed for certain very dynamic custom modules which
313 want to process the parameters that are being handed the module. Since
314 this is so closely tied to the implementation of modules we cannot
315 guarantee API stability for it (it may change between versions) however we
316 will try not to break it gratuitously. It is certainly more future-proof
317 to call this function and consume its outputs than to implement the logic
318 inside it as a copy in your own code.
319 """
320 global _ANSIBLE_ARGS, _ANSIBLE_PROFILE
321
322 if _ANSIBLE_ARGS is None:
323 _ANSIBLE_ARGS, _ANSIBLE_PROFILE = _debugging.load_params()
324
325 buffer = _ANSIBLE_ARGS
326 profile = _ANSIBLE_PROFILE
327
328 if not profile:
329 raise Exception("No serialization profile was specified.")
330
331 try:
332 decoder = _json.get_module_decoder(profile, _json.Direction.CONTROLLER_TO_MODULE)
333 params = json.loads(buffer.decode(), cls=decoder)
334 except Exception as ex:
335 raise Exception("Failed to decode JSON module parameters.") from ex
336
337 if (ansible_module_args := params.get('ANSIBLE_MODULE_ARGS', _UNSET)) is _UNSET:
338 raise Exception("ANSIBLE_MODULE_ARGS not provided.")
339
340 global _PARSED_MODULE_ARGS
341
342 _PARSED_MODULE_ARGS = copy.deepcopy(ansible_module_args) # AnsibleModule mutates the returned dict, so a copy is needed
343
344 return ansible_module_args
345
346
347 def missing_required_lib(library, reason=None, url=None):
348 hostname = platform.node()
349 msg = "Failed to import the required Python library (%s) on %s's Python %s." % (library, hostname, sys.executable)
350 if reason:
351 msg += " This is required %s." % reason
352 if url:
353 msg += " See %s for more info." % url
354
355 msg += (" Please read the module documentation and install it in the appropriate location."
356 " If the required library is installed, but Ansible is using the wrong Python interpreter,"
357 " please consult the documentation on ansible_python_interpreter")
358 return msg
359
360
361 class AnsibleModule(object):
362 def __init__(self, argument_spec, bypass_checks=False, no_log=False,
363 mutually_exclusive=None, required_together=None,
364 required_one_of=None, add_file_common_args=False,
365 supports_check_mode=False, required_if=None, required_by=None):
366
367 """
368 Common code for quickly building an ansible module in Python
369 (although you can write modules with anything that can return JSON).
370
371 See :ref:`developing_modules_general` for a general introduction
372 and :ref:`developing_program_flow_modules` for more detailed explanation.
373 """
374
375 self._name = os.path.basename(__file__) # initialize name until we can parse from options
376 self.argument_spec = argument_spec
377 self.supports_check_mode = supports_check_mode
378 self.check_mode = False
379 self.bypass_checks = bypass_checks
380 self.no_log = no_log
381
382 self.mutually_exclusive = mutually_exclusive
383 self.required_together = required_together
384 self.required_one_of = required_one_of
385 self.required_if = required_if
386 self.required_by = required_by
387 self.cleanup_files = []
388 self._debug = False
389 self._diff = False
390 self._socket_path = None
391 self._shell = None
392 self._syslog_facility = 'LOG_USER'
393 self._verbosity = 0
394 # May be used to set modifications to the environment for any
395 # run_command invocation
396 self.run_command_environ_update = {}
397 self._clean = {}
398
399 self.aliases = {}
400 self._legal_inputs = []
401 self._options_context = list()
402 self._tmpdir = None
403 self._new_secrets = _secrets._secret_masker.track_new_secrets()
404
405 if add_file_common_args:
406 for k, v in FILE_COMMON_ARGUMENTS.items():
407 if k not in self.argument_spec:
408 self.argument_spec[k] = v
409
410 # Save parameter values that should never be logged
411 self.no_log_values = set()
412
413 # check the locale as set by the current environment, and reset to
414 # a known valid (LANG=C) if it's an invalid/unavailable locale
415 self._check_locale()
416
417 self._load_params()
418 self._set_internal_properties()
419
420 self.validator = ModuleArgumentSpecValidator(self.argument_spec,
421 self.mutually_exclusive,
422 self.required_together,
423 self.required_one_of,
424 self.required_if,
425 self.required_by,
426 )
427
428 self.validation_result = self.validator.validate(self.params)
429 self.params.update(self.validation_result.validated_parameters)
430 self.no_log_values.update(self.validation_result._no_log_values)
431 self.aliases.update(self.validation_result._aliases)
432
433 try:
434 error = self.validation_result.errors[0]
435 if isinstance(error, UnsupportedError) and self._ignore_unknown_opts:
436 error = None
437 except IndexError:
438 error = None
439
440 # Fail for validation errors, even in check mode
441 if error:
442 msg = self.validation_result.errors.msg
443 if isinstance(error, UnsupportedError):
444 msg = "Unsupported parameters for ({name}) {kind}: {msg}".format(name=self._name, kind='module', msg=msg)
445
446 self.fail_json(msg=msg)
447
448 if self.check_mode and not self.supports_check_mode:
449 self.exit_json(
450 skipped=True, # deprecated: description='remove this skipped return', core_version='2.25'
451 msg="remote module (%s) does not support check mode" % self._name,
452 )
453
454 # This is for backwards compatibility only.
455 self._CHECK_ARGUMENT_TYPES_DISPATCHER = DEFAULT_TYPE_VALIDATORS
456
457 if not self.no_log:
458 self._log_invocation()
459
460 # selinux state caching
461 self._selinux_enabled = None
462 self._selinux_mls_enabled = None
463 self._selinux_initial_context = None
464
465 # finally, make sure we're in a logical working dir
466 self._set_cwd()
467
468 # Use system temp dir for module-level stacktraces. Using remote_tmp gets complicated with tasks
469 # as different or unprivileged users.
470 _debug.register_for_stacktrace()
471
472 @property
473 def tmpdir(self):
474 # if _ansible_tmpdir was not set and we have a remote_tmp,
475 # the module needs to create it and clean it up once finished.
476 # otherwise we create our own module tmp dir from the system defaults
477 if self._tmpdir is None:
478 basedir = None
479
480 if self._remote_tmp is not None:
481 basedir = os.path.expanduser(os.path.expandvars(self._remote_tmp))
482
483 if basedir is not None and not os.path.exists(basedir):
484 try:
485 os.makedirs(basedir, mode=0o700)
486 except OSError as ex:
487 self.error_as_warning(
488 msg=f"Unable to use {basedir!r} as temporary directory, falling back to system default.",
489 exception=ex,
490 )
491 basedir = None
492 else:
493 self.warn("Module remote_tmp %s did not exist and was "
494 "created with a mode of 0700, this may cause"
495 " issues when running as another user. To "
496 "avoid this, create the remote_tmp dir with "
497 "the correct permissions manually" % basedir)
498
499 basefile = "ansible-moduletmp-%s-" % time.time()
500 try:
501 tmpdir = tempfile.mkdtemp(prefix=basefile, dir=basedir)
502 except OSError as ex:
503 raise Exception(
504 f"Failed to create remote module tmp path at dir {basedir!r} "
505 f"with prefix {basefile!r}.",
506 ) from ex
507 if not self._keep_remote_files:
508 atexit.register(shutil.rmtree, tmpdir)
509 self._tmpdir = tmpdir
510
511 return self._tmpdir
512
513 def warn(
514 self,
515 warning: str,
516 *,
517 help_text: str | None = None,
518 ) -> None:
519 _skip_stackwalk = True
520
521 warn(
522 warning=warning,
523 help_text=help_text,
524 )
525
526 def error_as_warning(
527 self,
528 msg: str | None,
529 exception: BaseException,
530 *,
531 help_text: str | None = None,
532 ) -> None:
533 """Display an exception as a warning."""
534 _skip_stackwalk = True
535
536 error_as_warning(
537 msg=msg,
538 exception=exception,
539 help_text=help_text,
540 )
541
542 def deprecate(
543 self,
544 msg: str,
545 version: str | None = None,
546 date: str | None = None,
547 collection_name: str | None = None,
548 *,
549 deprecator: _messages.PluginInfo | None = None,
550 help_text: str | None = None,
551 ) -> None:
552 """
553 Record a deprecation warning to be returned with the module result.
554 Most callers do not need to provide `collection_name` or `deprecator` -- but provide only one if needed.
555 Specify `version` or `date`, but not both.
556 If `date` is a string, it must be in the form `YYYY-MM-DD`.
557 """
558 _skip_stackwalk = True
559
560 deprecate( # pylint: disable=ansible-deprecated-date-not-permitted,ansible-deprecated-unnecessary-collection-name
561 msg=msg,
562 version=version,
563 date=date,
564 deprecator=_deprecator.get_best_deprecator(deprecator=deprecator, collection_name=collection_name),
565 help_text=help_text,
566 )
567
568 def load_file_common_arguments(self, params, path=None):
569 """
570 many modules deal with files, this encapsulates common
571 options that the file module accepts such that it is directly
572 available to all modules and they can share code.
573
574 Allows to overwrite the path/dest module argument by providing path.
575 """
576
577 if path is None:
578 path = params.get('path', params.get('dest', None))
579 if path is None:
580 return {}
581 else:
582 path = os.path.expanduser(os.path.expandvars(path))
583
584 b_path = to_bytes(path, errors='surrogate_or_strict')
585 # if the path is a symlink, and we're following links, get
586 # the target of the link instead for testing
587 if params.get('follow', False) and os.path.islink(b_path):
588 b_path = os.path.realpath(b_path)
589 path = to_native(b_path)
590
591 mode = params.get('mode', None)
592 owner = params.get('owner', None)
593 group = params.get('group', None)
594
595 # selinux related options
596 seuser = params.get('seuser', None)
597 serole = params.get('serole', None)
598 setype = params.get('setype', None)
599 selevel = params.get('selevel', None)
600 secontext = [seuser, serole, setype]
601
602 if self.selinux_mls_enabled():
603 secontext.append(selevel)
604
605 default_secontext = self.selinux_default_context(path)
606 for i in range(len(default_secontext)):
607 if i is not None and secontext[i] == '_default':
608 secontext[i] = default_secontext[i]
609
610 attributes = params.get('attributes', None)
611 return dict(
612 path=path, mode=mode, owner=owner, group=group,
613 seuser=seuser, serole=serole, setype=setype,
614 selevel=selevel, secontext=secontext, attributes=attributes,
615 )
616
617 # Detect whether using selinux that is MLS-aware.
618 # While this means you can set the level/range with
619 # selinux.lsetfilecon(), it may or may not mean that you
620 # will get the selevel as part of the context returned
621 # by selinux.lgetfilecon().
622
623 def selinux_mls_enabled(self):
624 if self._selinux_mls_enabled is None:
625 self._selinux_mls_enabled = HAVE_SELINUX and selinux.is_selinux_mls_enabled() == 1
626
627 return self._selinux_mls_enabled
628
629 def selinux_enabled(self):
630 if self._selinux_enabled is None:
631 self._selinux_enabled = HAVE_SELINUX and selinux.is_selinux_enabled() == 1
632
633 return self._selinux_enabled
634
635 # Determine whether we need a placeholder for selevel/mls
636 def selinux_initial_context(self):
637 if self._selinux_initial_context is None:
638 self._selinux_initial_context = [None, None, None]
639 if self.selinux_mls_enabled():
640 self._selinux_initial_context.append(None)
641
642 return self._selinux_initial_context
643
644 # If selinux fails to find a default, return an array of None
645 def selinux_default_context(self, path, mode=0):
646 context = self.selinux_initial_context()
647 if not self.selinux_enabled():
648 return context
649 try:
650 ret = selinux.matchpathcon(to_native(path, errors='surrogate_or_strict'), mode)
651 except OSError:
652 return context
653 if ret[0] == -1:
654 return context
655 # Limit split to 4 because the selevel, the last in the list,
656 # may contain ':' characters
657 context = ret[1].split(':', 3)
658 return context
659
660 def selinux_context(self, path):
661 context = self.selinux_initial_context()
662 if not self.selinux_enabled():
663 return context
664 try:
665 ret = selinux.lgetfilecon_raw(to_native(path, errors='surrogate_or_strict'))
666 except OSError as ex:
667 self.fail_json(path=path, msg='Failed to retrieve selinux context.', exception=ex)
668 if ret[0] == -1:
669 return context
670 # Limit split to 4 because the selevel, the last in the list,
671 # may contain ':' characters
672 context = ret[1].split(':', 3)
673 return context
674
675 def user_and_group(self, path, expand=True):
676 b_path = to_bytes(path, errors='surrogate_or_strict')
677 if expand:
678 b_path = os.path.expanduser(os.path.expandvars(b_path))
679 st = os.lstat(b_path)
680 uid = st.st_uid
681 gid = st.st_gid
682 return (uid, gid)
683
684 def find_mount_point(self, path):
685 """
686 Takes a path and returns its mount point
687
688 :param path: a string type with a filesystem path
689 :returns: the path to the mount point as a text type
690 """
691
692 b_path = os.path.realpath(to_bytes(os.path.expanduser(os.path.expandvars(path)), errors='surrogate_or_strict'))
693 while not os.path.ismount(b_path):
694 b_path = os.path.dirname(b_path)
695
696 return to_text(b_path, errors='surrogate_or_strict')
697
698 def is_special_selinux_path(self, path):
699 """
700 Returns a tuple containing (True, selinux_context) if the given path is on a
701 NFS or other 'special' fs mount point, otherwise the return will be (False, None).
702 """
703 try:
704 with open('/proc/mounts', 'r') as f:
705 mount_data = f.readlines()
706 except Exception:
707 return (False, None)
708
709 path_mount_point = self.find_mount_point(path)
710
711 for line in mount_data:
712 (device, mount_point, fstype, options, rest) = line.split(' ', 4)
713 if to_bytes(path_mount_point) == to_bytes(mount_point):
714 for fs in self._selinux_special_fs:
715 if fs in fstype:
716 special_context = self.selinux_context(path_mount_point)
717 return (True, special_context)
718
719 return (False, None)
720
721 def set_default_selinux_context(self, path, changed):
722 if not self.selinux_enabled():
723 return changed
724 context = self.selinux_default_context(path)
725 return self.set_context_if_different(path, context, False)
726
727 def set_context_if_different(self, path, context, changed, diff=None):
728
729 if not self.selinux_enabled():
730 return changed
731
732 if self.check_file_absent_if_check_mode(path):
733 return True
734
735 cur_context = self.selinux_context(path)
736 new_context = list(cur_context)
737 # Iterate over the current context instead of the
738 # argument context, which may have selevel.
739
740 (is_special_se, sp_context) = self.is_special_selinux_path(path)
741 if is_special_se:
742 new_context = sp_context
743 else:
744 for i in range(len(cur_context)):
745 if len(context) > i:
746 if context[i] is not None and context[i] != cur_context[i]:
747 new_context[i] = context[i]
748 elif context[i] is None:
749 new_context[i] = cur_context[i]
750
751 if cur_context != new_context:
752 if diff is not None:
753 if 'before' not in diff:
754 diff['before'] = {}
755 diff['before']['secontext'] = cur_context
756 if 'after' not in diff:
757 diff['after'] = {}
758 diff['after']['secontext'] = new_context
759
760 try:
761 if self.check_mode:
762 return True
763 rc = selinux.lsetfilecon(to_native(path), ':'.join(new_context))
764 except OSError as e:
765 self.fail_json(path=path, msg='invalid selinux context: %s' % to_native(e),
766 new_context=new_context, cur_context=cur_context, input_was=context)
767 if rc != 0:
768 self.fail_json(path=path, msg='set selinux context failed')
769 changed = True
770 return changed
771
772 def set_owner_if_different(self, path, owner, changed, diff=None, expand=True):
773
774 if owner is None:
775 return changed
776
777 b_path = to_bytes(path, errors='surrogate_or_strict')
778 if expand:
779 b_path = os.path.expanduser(os.path.expandvars(b_path))
780
781 if self.check_file_absent_if_check_mode(b_path):
782 return True
783
784 orig_uid, orig_gid = self.user_and_group(b_path, expand)
785 try:
786 uid = int(owner)
787 except ValueError:
788 try:
789 uid = pwd.getpwnam(owner).pw_uid
790 except KeyError:
791 path = to_text(b_path)
792 self.fail_json(path=path, msg='chown failed: failed to look up user %s' % owner)
793
794 if orig_uid != uid:
795 if diff is not None:
796 if 'before' not in diff:
797 diff['before'] = {}
798 diff['before']['owner'] = orig_uid
799 if 'after' not in diff:
800 diff['after'] = {}
801 diff['after']['owner'] = uid
802
803 if self.check_mode:
804 return True
805 try:
806 os.lchown(b_path, uid, -1)
807 except OSError as ex:
808 path = to_text(b_path)
809 self.fail_json(path=path, msg='chown failed', exception=ex)
810 changed = True
811 return changed
812
813 def set_group_if_different(self, path, group, changed, diff=None, expand=True):
814
815 if group is None:
816 return changed
817
818 b_path = to_bytes(path, errors='surrogate_or_strict')
819 if expand:
820 b_path = os.path.expanduser(os.path.expandvars(b_path))
821
822 if self.check_file_absent_if_check_mode(b_path):
823 return True
824
825 orig_uid, orig_gid = self.user_and_group(b_path, expand)
826 try:
827 gid = int(group)
828 except ValueError:
829 try:
830 gid = grp.getgrnam(group).gr_gid
831 except KeyError:
832 path = to_text(b_path)
833 self.fail_json(path=path, msg='chgrp failed: failed to look up group %s' % group)
834
835 if orig_gid != gid:
836 if diff is not None:
837 if 'before' not in diff:
838 diff['before'] = {}
839 diff['before']['group'] = orig_gid
840 if 'after' not in diff:
841 diff['after'] = {}
842 diff['after']['group'] = gid
843
844 if self.check_mode:
845 return True
846 try:
847 os.lchown(b_path, -1, gid)
848 except OSError:
849 path = to_text(b_path)
850 self.fail_json(path=path, msg='chgrp failed')
851 changed = True
852 return changed
853
854 def set_mode_if_different(self, path, mode, changed, diff=None, expand=True):
855
856 if mode is None:
857 return changed
858
859 b_path = to_bytes(path, errors='surrogate_or_strict')
860 if expand:
861 b_path = os.path.expanduser(os.path.expandvars(b_path))
862
863 if self.check_file_absent_if_check_mode(b_path):
864 return True
865
866 path_stat = os.lstat(b_path)
867
868 if not isinstance(mode, int):
869 try:
870 mode = int(mode, 8)
871 except Exception:
872 try:
873 mode = self._symbolic_mode_to_octal(path_stat, mode)
874 except Exception as e:
875 path = to_text(b_path)
876 self.fail_json(path=path,
877 msg="mode must be in octal or symbolic form",
878 details=to_native(e))
879
880 if mode != stat.S_IMODE(mode):
881 # prevent mode from having extra info or being invalid long number
882 path = to_text(b_path)
883 self.fail_json(path=path, msg="Invalid mode supplied, only permission info is allowed", details=mode)
884
885 prev_mode = stat.S_IMODE(path_stat.st_mode)
886
887 if prev_mode != mode:
888
889 if diff is not None:
890 if 'before' not in diff:
891 diff['before'] = {}
892 diff['before']['mode'] = '0%03o' % prev_mode
893 if 'after' not in diff:
894 diff['after'] = {}
895 diff['after']['mode'] = '0%03o' % mode
896
897 if self.check_mode:
898 return True
899 # FIXME: comparison against string above will cause this to be executed
900 # every time
901 try:
902 if hasattr(os, 'lchmod'):
903 os.lchmod(b_path, mode)
904 else:
905 if not os.path.islink(b_path):
906 os.chmod(b_path, mode)
907 else:
908 # Attempt to set the perms of the symlink but be
909 # careful not to change the perms of the underlying
910 # file while trying
911 underlying_stat = os.stat(b_path)
912 os.chmod(b_path, mode)
913 new_underlying_stat = os.stat(b_path)
914 if underlying_stat.st_mode != new_underlying_stat.st_mode:
915 os.chmod(b_path, stat.S_IMODE(underlying_stat.st_mode))
916 except OSError as e:
917 if os.path.islink(b_path) and e.errno in (
918 errno.EACCES, # can't access symlink in sticky directory (stat)
919 errno.EPERM, # can't set mode on symbolic links (chmod)
920 errno.EROFS, # can't set mode on read-only filesystem
921 ):
922 pass
923 elif e.errno in (errno.ENOENT, errno.ELOOP): # Can't set mode on broken symbolic links
924 pass
925 else:
926 raise
927 except Exception as e:
928 path = to_text(b_path)
929 self.fail_json(path=path, msg='chmod failed', details=to_native(e))
930
931 path_stat = os.lstat(b_path)
932 new_mode = stat.S_IMODE(path_stat.st_mode)
933
934 if new_mode != prev_mode:
935 changed = True
936 return changed
937
938 def set_attributes_if_different(self, path, attributes, changed, diff=None, expand=True):
939
940 if attributes is None:
941 return changed
942
943 b_path = to_bytes(path, errors='surrogate_or_strict')
944 if expand:
945 b_path = os.path.expanduser(os.path.expandvars(b_path))
946
947 if self.check_file_absent_if_check_mode(b_path):
948 return True
949
950 existing = self.get_file_attributes(b_path, include_version=False)
951
952 attr_mod = '='
953 if attributes.startswith(('-', '+')):
954 attr_mod = attributes[0]
955 attributes = attributes[1:]
956
957 if attributes and (existing.get('attr_flags', '') != attributes or attr_mod == '-'):
958 attrcmd = self.get_bin_path('chattr')
959 if attrcmd:
960 attrcmd = [attrcmd, '%s%s' % (attr_mod, attributes), b_path]
961 changed = True
962
963 if diff is not None:
964 if 'before' not in diff:
965 diff['before'] = {}
966 diff['before']['attributes'] = existing.get('attr_flags')
967 if 'after' not in diff:
968 diff['after'] = {}
969 diff['after']['attributes'] = '%s%s' % (attr_mod, attributes)
970
971 if not self.check_mode:
972 try:
973 rc, out, err = self.run_command(attrcmd)
974 if rc != 0 or err:
975 raise Exception("Error while setting attributes: %s" % (out + err))
976 except Exception as e:
977 self.fail_json(path=to_text(b_path), msg='chattr failed', details=to_native(e))
978 return changed
979
980 def get_file_attributes(self, path, include_version=True):
981 output = {}
982 attrcmd = self.get_bin_path('lsattr', False)
983 if attrcmd:
984 flags = '-vd' if include_version else '-d'
985 attrcmd = [attrcmd, flags, path]
986 try:
987 rc, out, err = self.run_command(attrcmd)
988 if rc == 0:
989 res = out.split()
990 attr_flags_idx = 0
991 if include_version:
992 attr_flags_idx = 1
993 output['version'] = res[0].strip()
994 output['attr_flags'] = res[attr_flags_idx].replace('-', '').strip()
995 output['attributes'] = format_attributes(output['attr_flags'])
996 except Exception:
997 pass
998 return output
999
1000 @classmethod
1001 def _symbolic_mode_to_octal(cls, path_stat, symbolic_mode):
1002 """
1003 This enables symbolic chmod string parsing as stated in the chmod man-page
1004
1005 This includes things like: "u=rw-x+X,g=r-x+X,o=r-x+X"
1006 """
1007
1008 new_mode = stat.S_IMODE(path_stat.st_mode)
1009
1010 # Now parse all symbolic modes
1011 for mode in symbolic_mode.split(','):
1012 # Per single mode. This always contains a '+', '-' or '='
1013 # Split it on that
1014 permlist = MODE_OPERATOR_RE.split(mode)
1015
1016 # And find all the operators
1017 opers = MODE_OPERATOR_RE.findall(mode)
1018
1019 # The user(s) where it's all about is the first element in the
1020 # 'permlist' list. Take that and remove it from the list.
1021 # An empty user or 'a' means 'all'.
1022 users = permlist.pop(0)
1023 use_umask = (users == '')
1024 if users == 'a' or users == '':
1025 users = 'ugo'
1026
1027 # Check if there are illegal characters in the user list
1028 # They can end up in 'users' because they are not split
1029 if not USERS_RE.match(users):
1030 raise ValueError("bad symbolic permission for mode: %s" % mode)
1031
1032 # Now we have two list of equal length, one contains the requested
1033 # permissions and one with the corresponding operators.
1034 for idx, perms in enumerate(permlist):
1035 # Check if there are illegal characters in the permissions
1036 if not PERMS_RE.match(perms):
1037 raise ValueError("bad symbolic permission for mode: %s" % mode)
1038
1039 for user in users:
1040 mode_to_apply = cls._get_octal_mode_from_symbolic_perms(path_stat, user, perms, use_umask, new_mode)
1041 new_mode = cls._apply_operation_to_mode(user, opers[idx], mode_to_apply, new_mode)
1042
1043 return new_mode
1044
1045 @staticmethod
1046 def _apply_operation_to_mode(user, operator, mode_to_apply, current_mode):
1047 if operator == '=':
1048 if user == 'u':
1049 mask = stat.S_IRWXU | stat.S_ISUID
1050 elif user == 'g':
1051 mask = stat.S_IRWXG | stat.S_ISGID
1052 elif user == 'o':
1053 mask = stat.S_IRWXO | stat.S_ISVTX
1054
1055 # mask out u, g, or o permissions from current_mode and apply new permissions
1056 inverse_mask = mask ^ PERM_BITS
1057 new_mode = (current_mode & inverse_mask) | mode_to_apply
1058 elif operator == '+':
1059 new_mode = current_mode | mode_to_apply
1060 elif operator == '-':
1061 new_mode = current_mode - (current_mode & mode_to_apply)
1062 return new_mode
1063
1064 @staticmethod
1065 def _get_octal_mode_from_symbolic_perms(path_stat, user, perms, use_umask, prev_mode=None):
1066 if prev_mode is None:
1067 prev_mode = stat.S_IMODE(path_stat.st_mode)
1068 is_directory = stat.S_ISDIR(path_stat.st_mode)
1069 has_x_permissions = (prev_mode & S_IXANY) > 0
1070 apply_X_permission = is_directory or has_x_permissions
1071
1072 # Get the umask, if the 'user' part is empty, the effect is as if (a) were
1073 # given, but bits that are set in the umask are not affected.
1074 # We also need the "reversed umask" for masking
1075 umask = os.umask(0)
1076 os.umask(umask)
1077 rev_umask = umask ^ PERM_BITS
1078
1079 # Permission bits constants documented at:
1080 # https://docs.python.org/3/library/stat.html#stat.S_ISUID
1081 if apply_X_permission:
1082 X_perms = {
1083 'u': {'X': stat.S_IXUSR},
1084 'g': {'X': stat.S_IXGRP},
1085 'o': {'X': stat.S_IXOTH},
1086 }
1087 else:
1088 X_perms = {
1089 'u': {'X': 0},
1090 'g': {'X': 0},
1091 'o': {'X': 0},
1092 }
1093
1094 user_perms_to_modes = {
1095 'u': {
1096 'r': rev_umask & stat.S_IRUSR if use_umask else stat.S_IRUSR,
1097 'w': rev_umask & stat.S_IWUSR if use_umask else stat.S_IWUSR,
1098 'x': rev_umask & stat.S_IXUSR if use_umask else stat.S_IXUSR,
1099 's': stat.S_ISUID,
1100 't': 0,
1101 'u': prev_mode & stat.S_IRWXU,
1102 'g': (prev_mode & stat.S_IRWXG) << 3,
1103 'o': (prev_mode & stat.S_IRWXO) << 6},
1104 'g': {
1105 'r': rev_umask & stat.S_IRGRP if use_umask else stat.S_IRGRP,
1106 'w': rev_umask & stat.S_IWGRP if use_umask else stat.S_IWGRP,
1107 'x': rev_umask & stat.S_IXGRP if use_umask else stat.S_IXGRP,
1108 's': stat.S_ISGID,
1109 't': 0,
1110 'u': (prev_mode & stat.S_IRWXU) >> 3,
1111 'g': prev_mode & stat.S_IRWXG,
1112 'o': (prev_mode & stat.S_IRWXO) << 3},
1113 'o': {
1114 'r': rev_umask & stat.S_IROTH if use_umask else stat.S_IROTH,
1115 'w': rev_umask & stat.S_IWOTH if use_umask else stat.S_IWOTH,
1116 'x': rev_umask & stat.S_IXOTH if use_umask else stat.S_IXOTH,
1117 's': 0,
1118 't': stat.S_ISVTX,
1119 'u': (prev_mode & stat.S_IRWXU) >> 6,
1120 'g': (prev_mode & stat.S_IRWXG) >> 3,
1121 'o': prev_mode & stat.S_IRWXO},
1122 }
1123
1124 # Insert X_perms into user_perms_to_modes
1125 for key, value in X_perms.items():
1126 user_perms_to_modes[key].update(value)
1127
1128 def or_reduce(mode, perm):
1129 return mode | user_perms_to_modes[user][perm]
1130
1131 return reduce(or_reduce, perms, 0)
1132
1133 def set_fs_attributes_if_different(self, file_args, changed, diff=None, expand=True):
1134 # set modes owners and context as needed
1135 changed = self.set_context_if_different(
1136 file_args['path'], file_args['secontext'], changed, diff
1137 )
1138 changed = self.set_owner_if_different(
1139 file_args['path'], file_args['owner'], changed, diff, expand
1140 )
1141 changed = self.set_group_if_different(
1142 file_args['path'], file_args['group'], changed, diff, expand
1143 )
1144 changed = self.set_mode_if_different(
1145 file_args['path'], file_args['mode'], changed, diff, expand
1146 )
1147 changed = self.set_attributes_if_different(
1148 file_args['path'], file_args['attributes'], changed, diff, expand
1149 )
1150 return changed
1151
1152 def check_file_absent_if_check_mode(self, file_path):
1153 return self.check_mode and not os.path.exists(file_path)
1154
1155 def set_directory_attributes_if_different(self, file_args, changed, diff=None, expand=True):
1156 return self.set_fs_attributes_if_different(file_args, changed, diff, expand)
1157
1158 def set_file_attributes_if_different(self, file_args, changed, diff=None, expand=True):
1159 return self.set_fs_attributes_if_different(file_args, changed, diff, expand)
1160
1161 def add_path_info(self, kwargs):
1162 """
1163 for results that are files, supplement the info about the file
1164 in the return path with stats about the file path.
1165 """
1166
1167 path = kwargs.get('path', kwargs.get('dest', None))
1168 if path is None:
1169 return kwargs
1170 b_path = to_bytes(path, errors='surrogate_or_strict')
1171 if os.path.exists(b_path):
1172 (uid, gid) = self.user_and_group(path)
1173 kwargs['uid'] = uid
1174 kwargs['gid'] = gid
1175 try:
1176 user = pwd.getpwuid(uid)[0]
1177 except KeyError:
1178 user = str(uid)
1179 try:
1180 group = grp.getgrgid(gid)[0]
1181 except KeyError:
1182 group = str(gid)
1183 kwargs['owner'] = user
1184 kwargs['group'] = group
1185 st = os.lstat(b_path)
1186 kwargs['mode'] = '0%03o' % stat.S_IMODE(st[stat.ST_MODE])
1187 # secontext not yet supported
1188 if os.path.islink(b_path):
1189 kwargs['state'] = 'link'
1190 elif os.path.isdir(b_path):
1191 kwargs['state'] = 'directory'
1192 elif os.stat(b_path).st_nlink > 1:
1193 kwargs['state'] = 'hard'
1194 else:
1195 kwargs['state'] = 'file'
1196 if self.selinux_enabled():
1197 kwargs['secontext'] = ':'.join(self.selinux_context(path))
1198 kwargs['size'] = st[stat.ST_SIZE]
1199 return kwargs
1200
1201 def _check_locale(self):
1202 """
1203 Uses the locale module to test the currently set locale
1204 (per the LANG and LC_CTYPE environment settings)
1205 """
1206 try:
1207 # setting the locale to '' uses the default locale
1208 # as it would be returned by locale.getdefaultlocale()
1209 locale.setlocale(locale.LC_ALL, '')
1210 except locale.Error:
1211 # fallback to the 'best' locale, per the function
1212 # final fallback is 'C', which may cause unicode issues
1213 # but is preferable to simply failing on unknown locale
1214 best_locale = get_best_parsable_locale(self)
1215
1216 # need to set several since many tools choose to ignore documented precedence and scope
1217 locale.setlocale(locale.LC_ALL, best_locale)
1218 os.environ['LANG'] = best_locale
1219 os.environ['LC_ALL'] = best_locale
1220 os.environ['LC_MESSAGES'] = best_locale
1221 except Exception as e:
1222 self.fail_json(msg="An unknown error was encountered while attempting to validate the locale: %s" % to_native(e))
1223
1224 def _set_internal_properties(self, argument_spec=None, module_parameters=None):
1225 if argument_spec is None:
1226 argument_spec = self.argument_spec
1227 if module_parameters is None:
1228 module_parameters = self.params
1229
1230 for k in PASS_VARS:
1231 # handle setting internal properties from internal ansible vars
1232 param_key = '_ansible_%s' % k
1233 if param_key in module_parameters:
1234 if k in PASS_BOOLS:
1235 setattr(self, PASS_VARS[k][0], self.boolean(module_parameters[param_key]))
1236 else:
1237 setattr(self, PASS_VARS[k][0], module_parameters[param_key])
1238
1239 # clean up internal top level params:
1240 if param_key in self.params:
1241 del self.params[param_key]
1242 else:
1243 # use defaults if not already set
1244 if not hasattr(self, PASS_VARS[k][0]):
1245 setattr(self, PASS_VARS[k][0], PASS_VARS[k][1])
1246
1247 def _load_params(self):
1248 """ read the input and set the params attribute.
1249
1250 This method is for backwards compatibility. The guts of the function
1251 were moved out in 2.1 so that custom modules could read the parameters.
1252 """
1253 # debug overrides to read args from file or cmdline
1254 self.params = _load_params()
1255
1256 def debug(self, msg):
1257 if self._debug:
1258 self.log('[debug] %s' % msg)
1259
1260 def log(self, msg, log_args=None):
1261
1262 if self.no_log:
1263 return
1264
1265 if not isinstance(msg, (bytes, str)):
1266 raise TypeError("msg should be a string (got %s)" % type(msg))
1267
1268 if isinstance(msg, bytes):
1269 msg = msg.decode('utf-8', 'replace')
1270
1271 if log_args:
1272 log_args = {k: _secrets.mask_secrets(str(v)) for k, v in log_args.items()}
1273
1274 msg = _secrets.mask_secrets(msg)
1275
1276 try:
1277 _logging.log_to_system(
1278 msg,
1279 module_name=self._name,
1280 log_args=log_args,
1281 syslog_facility=self._syslog_facility,
1282 target_log_info=self._target_log_info,
1283 )
1284 except (TypeError, ValueError) as e:
1285 self.fail_json(
1286 msg='Failed to log to syslog (%s). To proceed anyway, '
1287 'disable syslog logging by setting no_target_syslog '
1288 'to True in your Ansible config.' % to_native(e),
1289 msg_to_log=msg,
1290 )
1291
1292 def _redact_no_log_params(
1293 self,
1294 argument_spec: Mapping[str, Mapping[str, t.Any]],
1295 params: Mapping[str, t.Any],
1296 prefix: str = '',
1297 ) -> dict[str, t.Any]:
1298 """Return a copy of ``params`` suitable for logging with ``no_log`` values replaced by a placeholder.
1299
1300 Values are redacted by their position in ``argument_spec`` rather than by matching their content, so
1301 ``no_log`` values that are too short or not a string to be registered as a secret are still hidden.
1302 Sub options are processed recursively using the same rules as the top level parameters.
1303 """
1304 aliases = {alias: name for name, opts in argument_spec.items() for alias in opts.get('aliases') or ()}
1305 redacted: dict[str, t.Any] = {}
1306
1307 for param, value in params.items():
1308 arg_opts = argument_spec.get(aliases.get(param, param), {})
1309 no_log = arg_opts.get('no_log', None)
1310
1311 # try to proactively capture password/passphrase fields
1312 if no_log is None and PASSWORD_MATCH.search(param):
1313 value = '$REDACTED$'
1314 self.warn(f'Module did not set no_log for {prefix}{param}')
1315 elif self.boolean(no_log):
1316 # We don't rely on the secret masker here because the value
1317 # may have been set to anything (non-string/too short, etc) and
1318 # historically we've always just blocked it out.
1319 value = '$REDACTED$'
1320 elif (sub_spec := arg_opts.get('options')) and value is not None:
1321 wanted_type = arg_opts.get('type')
1322
1323 if wanted_type == 'dict' and isinstance(value, Mapping):
1324 value = self._redact_no_log_params(
1325 argument_spec=sub_spec,
1326 params=value,
1327 prefix=f'{prefix}{param}.',
1328 )
1329 elif wanted_type == 'list' and arg_opts.get('elements') == 'dict' and isinstance(value, list):
1330 value = [
1331 self._redact_no_log_params(
1332 argument_spec=sub_spec,
1333 params=elem,
1334 prefix=f'{prefix}{param}[{idx}].'
1335 ) if isinstance(elem, Mapping) else elem
1336 for idx, elem in enumerate(value)
1337 ]
1338
1339 redacted[param] = value
1340
1341 return redacted
1342
1343 def _log_invocation(self) -> None:
1344 """ log that ansible ran the module """
1345 # TODO: generalize a separate log function and make log_invocation use it
1346 # These log args will be masked in log() if they contain any secrets.
1347 log_args = {key: to_text(value) for key, value in self._redact_no_log_params(self.argument_spec, self.params).items()}
1348
1349 if log_args:
1350 msg = f"Invoked with {' '.join([f'{k}={v}' for k, v in log_args.items()])}"
1351 else:
1352 msg = 'Invoked'
1353
1354 self.log(msg, log_args=log_args)
1355
1356 def _set_cwd(self):
1357 try:
1358 cwd = os.getcwd()
1359 if not os.access(cwd, os.F_OK | os.R_OK):
1360 raise Exception()
1361 return cwd
1362 except Exception:
1363 # we don't have access to the cwd, probably because of sudo.
1364 # Try and move to a neutral location to prevent errors
1365 for cwd in [self.tmpdir, os.path.expandvars('$HOME'), tempfile.gettempdir()]:
1366 try:
1367 if os.access(cwd, os.F_OK | os.R_OK):
1368 os.chdir(cwd)
1369 return cwd
1370 except Exception:
1371 pass
1372 # we won't error here, as it may *not* be a problem,
1373 # and we don't want to break modules unnecessarily
1374 return None
1375
1376 def get_bin_path(self, arg, required=False, opt_dirs=None):
1377 """
1378 Find system executable in PATH.
1379
1380 :param arg: The executable to find.
1381 :param required: if the executable is not found and required is ``True``, fail_json
1382 :param opt_dirs: optional list of directories to search in addition to ``PATH``
1383 :returns: if found return full path; otherwise return original arg, unless 'warning' then return None
1384 :raises: Sysexit: if arg is not found and required=True (via fail_json)
1385 """
1386
1387 bin_path = None
1388 try:
1389 bin_path = get_bin_path(arg=arg, opt_dirs=opt_dirs)
1390 except ValueError as e:
1391 if required:
1392 self.fail_json(msg=to_text(e))
1393
1394 return bin_path
1395
1396 def boolean(self, arg):
1397 """Convert the argument to a boolean"""
1398 if arg is None:
1399 return arg
1400
1401 try:
1402 return boolean(arg)
1403 except TypeError as e:
1404 self.fail_json(msg=to_native(e))
1405
1406 def jsonify(self, data):
1407 # deprecated: description='deprecate AnsibleModule.jsonify()' core_version='2.23'
1408 # deprecate(
1409 # msg="The `AnsibleModule.jsonify' method is deprecated.",
1410 # version="2.27",
1411 # # help_text="", # DTFIX-FUTURE: fill in this help text
1412 # )
1413
1414 try:
1415 return json.dumps(data, cls=_common_json._get_legacy_encoder())
1416 except UnicodeError as e:
1417 self.fail_json(msg=to_text(e))
1418
1419 def from_json(self, data):
1420 return json.loads(data)
1421
1422 def add_cleanup_file(self, path):
1423 if path not in self.cleanup_files:
1424 self.cleanup_files.append(path)
1425
1426 def do_cleanup_files(self):
1427 for path in self.cleanup_files:
1428 self.cleanup(path)
1429
1430 def _return_formatted(self, kwargs):
1431 _skip_stackwalk = True
1432
1433 if flushed := self._new_secrets.flush():
1434 kwargs['_ansible_new_secrets'] = list(flushed)
1435
1436 # Technically process end is the same but in case this is ever run in
1437 # a persisted process worker or multiple times in the same process we
1438 # detach our secret tracker.
1439 self._new_secrets.unregister()
1440
1441 self.add_path_info(kwargs)
1442
1443 if _PARSED_MODULE_ARGS.get('_ansible_inject_invocation', False):
1444 if 'invocation' not in kwargs:
1445 kwargs['invocation'] = {'module_args': self.params}
1446 else:
1447 kwargs.pop('invocation', None)
1448
1449 if 'warnings' in kwargs:
1450 self.deprecate( # pylint: disable=ansible-deprecated-unnecessary-collection-name
1451 msg='Passing `warnings` to `exit_json` or `fail_json` is deprecated.',
1452 version='2.23',
1453 help_text='Use `AnsibleModule.warn` instead.',
1454 deprecator=_deprecator.ANSIBLE_CORE_DEPRECATOR,
1455 )
1456
1457 if isinstance(kwargs['warnings'], list):
1458 for w in kwargs['warnings']:
1459 self.warn(w)
1460 else:
1461 self.warn(kwargs['warnings'])
1462
1463 warnings = get_warnings()
1464 if warnings:
1465 kwargs['warnings'] = warnings
1466
1467 if 'deprecations' in kwargs:
1468 self.deprecate( # pylint: disable=ansible-deprecated-unnecessary-collection-name
1469 msg='Passing `deprecations` to `exit_json` or `fail_json` is deprecated.',
1470 version='2.23',
1471 help_text='Use `AnsibleModule.deprecate` instead.',
1472 deprecator=_deprecator.ANSIBLE_CORE_DEPRECATOR,
1473 )
1474
1475 if isinstance(kwargs['deprecations'], list):
1476 for d in kwargs['deprecations']:
1477 if isinstance(d, (KeysView, Sequence)) and len(d) == 2:
1478 self.deprecate( # pylint: disable=ansible-deprecated-unnecessary-collection-name,ansible-invalid-deprecated-version
1479 msg=d[0],
1480 version=d[1],
1481 deprecator=_deprecator.get_best_deprecator(),
1482 )
1483 elif isinstance(d, Mapping):
1484 self.deprecate( # pylint: disable=ansible-deprecated-date-not-permitted,ansible-deprecated-unnecessary-collection-name
1485 msg=d['msg'],
1486 version=d.get('version'),
1487 date=d.get('date'),
1488 deprecator=_deprecator.get_best_deprecator(collection_name=d.get('collection_name')),
1489 )
1490 else:
1491 self.deprecate( # pylint: disable=ansible-deprecated-unnecessary-collection-name,ansible-deprecated-no-version
1492 msg=d,
1493 deprecator=_deprecator.get_best_deprecator(),
1494 )
1495 else:
1496 self.deprecate( # pylint: disable=ansible-deprecated-unnecessary-collection-name,ansible-deprecated-no-version
1497 msg=kwargs['deprecations'],
1498 deprecator=_deprecator.get_best_deprecator(),
1499 )
1500
1501 deprecations = get_deprecations()
1502 if deprecations:
1503 kwargs['deprecations'] = deprecations
1504
1505 self._record_module_result(kwargs)
1506
1507 def _record_module_result(self, o: dict[str, t.Any]) -> None:
1508 """
1509 Temporary internal hook to enable modification/bypass of module result serialization.
1510
1511 Monkeypatched by ansible.netcommon for direct in-worker module execution.
1512 """
1513 encoder = _json.get_module_encoder(_ANSIBLE_PROFILE, _json.Direction.MODULE_TO_CONTROLLER)
1514 print('\n%s' % json.dumps(o, cls=encoder))
1515
1516 def exit_json(self, **kwargs) -> t.NoReturn:
1517 """ return from the module, without error """
1518 _skip_stackwalk = True
1519
1520 self.do_cleanup_files()
1521 self._return_formatted(kwargs)
1522 sys.exit(0)
1523
1524 def fail_json(self, msg: str, *, exception: BaseException | str | None = _UNSET, **kwargs) -> t.NoReturn:
1525 """
1526 Return from the module with an error message and optional exception/traceback detail.
1527 A traceback will only be included in the result if error traceback capturing has been enabled.
1528
1529 When `exception` is an exception object, its message chain will be automatically combined with `msg` to create the final error message.
1530 The message chain includes the exception's message as well as messages from any __cause__ exceptions.
1531 The traceback from `exception` will be used for the formatted traceback.
1532
1533 When `exception` is a string, it will be used as the formatted traceback.
1534
1535 When `exception` is set to `None`, the current call stack will be used for the formatted traceback.
1536
1537 When `exception` is not specified, a formatted traceback will be retrieved from the current exception.
1538 If no exception is pending, the current call stack will be used instead.
1539 """
1540 _skip_stackwalk = True
1541
1542 msg = str(msg) # coerce to str instead of raising an error due to an invalid type
1543
1544 kwargs.update(
1545 failed=True,
1546 msg=msg,
1547 )
1548
1549 if isinstance(exception, BaseException):
1550 # Include a `_messages.Event` in the result.
1551 # The `msg` is included in the chain to ensure it is not lost when looking only at `exception` from the result.
1552
1553 kwargs.update(
1554 exception=_messages.ErrorSummary(
1555 event=_messages.Event(
1556 msg=msg,
1557 formatted_traceback=_traceback.maybe_capture_traceback(msg, _traceback.TracebackEvent.ERROR),
1558 chain=_messages.EventChain(
1559 msg_reason=_errors.MSG_REASON_DIRECT_CAUSE,
1560 traceback_reason="The above exception was the direct cause of the following error:",
1561 event=_errors.EventFactory.from_exception(exception, _traceback.is_traceback_enabled(_traceback.TracebackEvent.ERROR)),
1562 ),
1563 ),
1564 ),
1565 )
1566 elif _traceback.is_traceback_enabled(_traceback.TracebackEvent.ERROR):
1567 # Include only a formatted traceback string in the result.
1568 # The controller will combine this with `msg` to create an `_messages.ErrorSummary`.
1569
1570 formatted_traceback: str | None
1571
1572 if isinstance(exception, str):
1573 formatted_traceback = exception
1574 elif exception is _UNSET and (current_exception := t.cast(t.Optional[BaseException], sys.exc_info()[1])):
1575 formatted_traceback = _traceback.maybe_extract_traceback(current_exception, _traceback.TracebackEvent.ERROR)
1576 else:
1577 formatted_traceback = _traceback.maybe_capture_traceback(msg, _traceback.TracebackEvent.ERROR)
1578
1579 if formatted_traceback:
1580 kwargs.update(exception=formatted_traceback)
1581
1582 self.do_cleanup_files()
1583 self._return_formatted(kwargs)
1584
1585 sys.exit(1)
1586
1587 def fail_on_missing_params(self, required_params=None):
1588 if not required_params:
1589 return
1590 try:
1591 check_missing_parameters(self.params, required_params)
1592 except TypeError as e:
1593 self.fail_json(msg=to_native(e))
1594
1595 def digest_from_file(self, filename, algorithm):
1596 """ Return hex digest of local file for a digest_method specified by name, or None if file is not present. """
1597 b_filename = to_bytes(filename, errors='surrogate_or_strict')
1598
1599 if not os.path.exists(b_filename):
1600 return None
1601 if os.path.isdir(b_filename):
1602 self.fail_json(msg="attempted to take checksum of directory: %s" % filename)
1603
1604 # preserve old behaviour where the third parameter was a hash algorithm object
1605 if hasattr(algorithm, 'hexdigest'):
1606 digest_method = algorithm
1607 else:
1608 try:
1609 digest_method = AVAILABLE_HASH_ALGORITHMS[algorithm]()
1610 except KeyError:
1611 self.fail_json(msg="Could not hash file '%s' with algorithm '%s'. Available algorithms: %s" %
1612 (filename, algorithm, ', '.join(AVAILABLE_HASH_ALGORITHMS)))
1613
1614 blocksize = 64 * 1024
1615 infile = open(os.path.realpath(b_filename), 'rb')
1616 block = infile.read(blocksize)
1617 while block:
1618 digest_method.update(block)
1619 block = infile.read(blocksize)
1620 infile.close()
1621 return digest_method.hexdigest()
1622
1623 def md5(self, filename):
1624 """ Return MD5 hex digest of local file using digest_from_file().
1625
1626 Do not use this function unless you have no other choice for:
1627 1) Optional backwards compatibility
1628 2) Compatibility with a third party protocol
1629
1630 This function will not work on systems complying with FIPS-140-2.
1631
1632 Most uses of this function can use the module.sha1 function instead.
1633 """
1634 if 'md5' not in AVAILABLE_HASH_ALGORITHMS:
1635 raise ValueError('MD5 not available. Possibly running in FIPS mode')
1636 return self.digest_from_file(filename, 'md5')
1637
1638 def sha1(self, filename):
1639 """ Return SHA1 hex digest of local file using digest_from_file(). """
1640 return self.digest_from_file(filename, 'sha1')
1641
1642 def sha256(self, filename):
1643 """ Return SHA-256 hex digest of local file using digest_from_file(). """
1644 return self.digest_from_file(filename, 'sha256')
1645
1646 def backup_local(self, fn):
1647 """make a date-marked backup of the specified file, return True or False on success or failure"""
1648
1649 backupdest = ''
1650 if os.path.exists(fn):
1651 # backups named basename.PID.YYYY-MM-DD@HH:MM:SS~
1652 ext = time.strftime("%Y-%m-%d@%H:%M:%S~", time.localtime(time.time()))
1653 backupdest = '%s.%s.%s' % (fn, os.getpid(), ext)
1654
1655 if not self.check_mode:
1656 try:
1657 self.preserved_copy(fn, backupdest)
1658 except (shutil.Error, IOError) as ex:
1659 raise Exception(f'Could not make backup of {fn!r} to {backupdest!r}.') from ex
1660
1661 return backupdest
1662
1663 def cleanup(self, tmpfile):
1664 if os.path.exists(tmpfile):
1665 try:
1666 os.unlink(tmpfile)
1667 except OSError as e:
1668 sys.stderr.write("could not cleanup %s: %s" % (tmpfile, to_native(e)))
1669
1670 def preserved_copy(self, src, dest):
1671 """Copy a file with preserved ownership, permissions and context"""
1672
1673 # shutil.copy2(src, dst)
1674 # Similar to shutil.copy(), but metadata is copied as well - in fact,
1675 # this is just shutil.copy() followed by copystat(). This is similar
1676 # to the Unix command cp -p.
1677
1678 # shutil.copystat(src, dst)
1679 # Copy the permission bits, last access time, last modification time,
1680 # and flags from src to dst. The file contents, owner, and group are
1681 # unaffected. src and dst are path names given as strings.
1682
1683 shutil.copy2(src, dest)
1684
1685 # Set the context
1686 if self.selinux_enabled():
1687 context = self.selinux_context(src)
1688 self.set_context_if_different(dest, context, False)
1689
1690 # chown it
1691 try:
1692 dest_stat = os.stat(src)
1693 tmp_stat = os.stat(dest)
1694 if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid):
1695 os.chown(dest, dest_stat.st_uid, dest_stat.st_gid)
1696 except OSError as e:
1697 if e.errno != errno.EPERM:
1698 raise
1699
1700 # Set the attributes
1701 current_attribs = self.get_file_attributes(src, include_version=False)
1702 current_attribs = current_attribs.get('attr_flags', '')
1703 self.set_attributes_if_different(dest, current_attribs, True)
1704
1705 def atomic_move(self, src, dest, unsafe_writes=False, keep_dest_attrs=True):
1706 """atomically move src to dest, copying attributes from dest, returns true on success
1707 it uses os.rename to ensure this as it is an atomic operation, rest of the function is
1708 to work around limitations, corner cases and ensure selinux context is saved if possible"""
1709 context = None
1710 dest_stat = None
1711 b_src = to_bytes(src, errors='surrogate_or_strict')
1712 b_dest = to_bytes(dest, errors='surrogate_or_strict')
1713 if os.path.exists(b_dest) and keep_dest_attrs:
1714 try:
1715 dest_stat = os.stat(b_dest)
1716 os.chown(b_src, dest_stat.st_uid, dest_stat.st_gid)
1717 shutil.copystat(b_dest, b_src)
1718 os.utime(b_src, times=(time.time(), time.time()))
1719 except OSError as e:
1720 if e.errno != errno.EPERM:
1721 raise
1722 if self.selinux_enabled():
1723 context = self.selinux_context(dest)
1724 else:
1725 if self.selinux_enabled():
1726 context = self.selinux_default_context(dest)
1727
1728 creating = not os.path.exists(b_dest)
1729
1730 try:
1731 # Optimistically try a rename, solves some corner cases and can avoid useless work, throws exception if not atomic.
1732 os.rename(b_src, b_dest)
1733 except OSError as ex:
1734 if ex.errno in (errno.EPERM, errno.EXDEV, errno.EACCES, errno.ETXTBSY, errno.EBUSY):
1735 # only try workarounds for errno 18 (cross device), 1 (not permitted), 13 (permission denied)
1736 # and 26 (text file busy) which happens on vagrant synced folders and other 'exotic' non posix file systems
1737 # Use bytes here. In the shippable CI, this fails with
1738 # a UnicodeError with surrogateescape'd strings for an unknown
1739 # reason (doesn't happen in a local Ubuntu16.04 VM)
1740 b_dest_dir = os.path.dirname(b_dest)
1741 b_suffix = os.path.basename(b_dest)
1742 tmp_dest_name = None
1743 try:
1744 tmp_dest_fd, tmp_dest_name = tempfile.mkstemp(prefix=b'.ansible_tmp', dir=b_dest_dir, suffix=b_suffix)
1745 except OSError as ex:
1746 if unsafe_writes:
1747 self._unsafe_writes(b_src, b_dest)
1748 else:
1749 raise Exception(
1750 f'The destination directory {os.path.dirname(dest)!r} is not writable by the current user.'
1751 ) from ex
1752
1753 if tmp_dest_name:
1754 b_tmp_dest_name = to_bytes(tmp_dest_name, errors='surrogate_or_strict')
1755
1756 try:
1757 try:
1758 # close tmp file handle before file operations to prevent text file busy errors on vboxfs synced folders (windows host)
1759 os.close(tmp_dest_fd)
1760 # leaves tmp file behind when sudo and not root
1761 try:
1762 shutil.move(b_src, b_tmp_dest_name, copy_function=shutil.copy if keep_dest_attrs else shutil.copy2)
1763 except OSError:
1764 # cleanup will happen by 'rm' of tmpdir
1765 # copy2 will preserve some metadata
1766 if keep_dest_attrs:
1767 shutil.copy(b_src, b_tmp_dest_name)
1768 else:
1769 shutil.copy2(b_src, b_tmp_dest_name)
1770
1771 if self.selinux_enabled():
1772 self.set_context_if_different(
1773 b_tmp_dest_name, context, False)
1774 try:
1775 tmp_stat = os.stat(b_tmp_dest_name)
1776 if keep_dest_attrs:
1777 if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid):
1778 os.chown(b_tmp_dest_name, dest_stat.st_uid, dest_stat.st_gid)
1779 os.utime(b_tmp_dest_name, times=(time.time(), time.time()))
1780 except OSError as ex:
1781 if ex.errno != errno.EPERM:
1782 raise
1783 try:
1784 os.rename(b_tmp_dest_name, b_dest)
1785 except (shutil.Error, OSError) as ex:
1786 if unsafe_writes and ex.errno == errno.EBUSY:
1787 self._unsafe_writes(b_tmp_dest_name, b_dest)
1788 else:
1789 raise Exception(
1790 f'Unable to make {src!r} into to {dest!r}, failed final rename from {to_text(b_tmp_dest_name)!r}.'
1791 ) from ex
1792 except (shutil.Error, OSError) as ex:
1793 if unsafe_writes:
1794 self._unsafe_writes(b_src, b_dest)
1795 else:
1796 raise Exception(f'Failed to replace {dest!r} with {src!r}.') from ex
1797 finally:
1798 self.cleanup(b_tmp_dest_name)
1799 else:
1800 raise Exception(f'Could not replace {dest!r} with {src!r}.') from ex
1801
1802 if creating:
1803 # make sure the file has the correct permissions
1804 # based on the current value of umask
1805 umask = os.umask(0)
1806 os.umask(umask)
1807 os.chmod(b_dest, S_IRWU_RWG_RWO & ~umask)
1808 dest_dir_stat = os.stat(os.path.dirname(b_dest))
1809 try:
1810 if dest_dir_stat.st_mode & stat.S_ISGID:
1811 os.chown(b_dest, os.geteuid(), dest_dir_stat.st_gid)
1812 else:
1813 os.chown(b_dest, os.geteuid(), os.getegid())
1814 except OSError:
1815 # We're okay with trying our best here. If the user is not
1816 # root (or old Unices) they won't be able to chown.
1817 pass
1818
1819 if self.selinux_enabled():
1820 # rename might not preserve context
1821 self.set_context_if_different(dest, context, False)
1822
1823 def _unsafe_writes(self, src, dest):
1824 # sadly there are some situations where we cannot ensure atomicity, but only if
1825 # the user insists and we get the appropriate error we update the file unsafely
1826 try:
1827 with open(dest, 'wb') as out_dest:
1828 with open(src, 'rb') as in_src:
1829 shutil.copyfileobj(in_src, out_dest)
1830 except (shutil.Error, OSError) as ex:
1831 raise Exception(f'Could not write data to file {dest!r} from {src!r}.') from ex
1832
1833 def run_command(self, args, check_rc=False, close_fds=True, executable=None, data=None, binary_data=False, path_prefix=None, cwd=None,
1834 use_unsafe_shell=False, prompt_regex=None, environ_update=None, umask=None, encoding='utf-8', errors='surrogate_or_strict',
1835 expand_user_and_vars=True, pass_fds=None, before_communicate_callback=None, ignore_invalid_cwd=True, handle_exceptions=True):
1836 """
1837 Execute a command, returns rc, stdout, and stderr.
1838
1839 The mechanism of this method for reading stdout and stderr differs from
1840 that of CPython subprocess.Popen.communicate, in that this method will
1841 stop reading once the spawned command has exited and stdout and stderr
1842 have been consumed, as opposed to waiting until stdout/stderr are
1843 closed. This can be an important distinction, when taken into account
1844 that a forked or backgrounded process may hold stdout or stderr open
1845 for longer than the spawned command.
1846
1847 :arg args: is the command to run
1848 * If args is a list, the command will be run with shell=False.
1849 * If args is a string and use_unsafe_shell=False it will split args to a list and run with shell=False
1850 * If args is a string and use_unsafe_shell=True it runs with shell=True.
1851 :kw check_rc: Whether to call fail_json in case of non zero RC.
1852 Default False
1853 :kw close_fds: See documentation for subprocess.Popen(). Default True
1854 :kw executable: See documentation for subprocess.Popen(). Default None
1855 :kw data: If given, information to write to the stdin of the command
1856 :kw binary_data: If False, append a newline to the data. Default False
1857 :kw path_prefix: If given, additional path to find the command in.
1858 This adds to the PATH environment variable so helper commands in
1859 the same directory can also be found
1860 :kw cwd: If given, working directory to run the command inside
1861 :kw use_unsafe_shell: See `args` parameter. Default False
1862 :kw prompt_regex: Regex string (not a compiled regex) which can be
1863 used to detect prompts in the stdout which would otherwise cause
1864 the execution to hang (especially if no input data is specified)
1865 :kw environ_update: dictionary to *update* environ variables with
1866 :kw umask: Umask to be used when running the command. Default None
1867 :kw encoding: Since we return strings, we need to
1868 know the encoding to use to transform from bytes to text. If you
1869 want to always get bytes back, use encoding=None. The default is
1870 "utf-8". This does not affect transformation of strings given as
1871 args.
1872 :kw errors: Since we return strings, we need to
1873 transform stdout and stderr from bytes to text. If the bytes are
1874 undecodable in the ``encoding`` specified, then use this error
1875 handler to deal with them. The default is ``surrogate_or_strict``
1876 which means that the bytes will be decoded using the
1877 surrogateescape error handler if available (available on all
1878 Python versions we support) otherwise a UnicodeError traceback
1879 will be raised. This does not affect transformations of strings
1880 given as args.
1881 :kw expand_user_and_vars: When ``use_unsafe_shell=False`` this argument
1882 dictates whether ``~`` is expanded in paths and environment variables
1883 are expanded before running the command. When ``True`` a string such as
1884 ``$SHELL`` will be expanded regardless of escaping. When ``False`` and
1885 ``use_unsafe_shell=False`` no path or variable expansion will be done.
1886 :kw pass_fds: This argument dictates which file descriptors should be passed
1887 to an underlying ``Popen`` constructor.
1888 :kw before_communicate_callback: This function will be called
1889 after ``Popen`` object will be created
1890 but before communicating to the process.
1891 (``Popen`` object will be passed to callback as a first argument)
1892 :kw ignore_invalid_cwd: This flag indicates whether an invalid ``cwd``
1893 (non-existent or not a directory) should be ignored or should raise
1894 an exception.
1895 :kw handle_exceptions: This flag indicates whether an exception will
1896 be handled inline and issue a failed_json or if the caller should
1897 handle it.
1898 :returns: A 3-tuple of return code (int), stdout (str), and stderr (str).
1899 stdout and stderr are text strings converted according to the encoding
1900 and errors parameters. If you want byte strings, use encoding=None
1901 to turn decoding to text off.
1902 """
1903 # used by clean args later on
1904 self._clean = None
1905
1906 if not isinstance(args, (list, bytes, str)):
1907 msg = "Argument 'args' to run_command must be list or string"
1908 self.fail_json(rc=257, cmd=args, msg=msg)
1909
1910 shell = False
1911 if use_unsafe_shell:
1912
1913 # stringify args for unsafe/direct shell usage
1914 if isinstance(args, list):
1915 args = b" ".join([to_bytes(shlex.quote(x), errors='surrogate_or_strict') for x in args])
1916 else:
1917 args = to_bytes(args, errors='surrogate_or_strict')
1918
1919 # not set explicitly, check if set by controller
1920 if executable:
1921 executable = to_bytes(executable, errors='surrogate_or_strict')
1922 args = [executable, b'-c', args]
1923 elif self._shell not in (None, '/bin/sh'):
1924 args = [to_bytes(self._shell, errors='surrogate_or_strict'), b'-c', args]
1925 else:
1926 shell = True
1927 else:
1928 # ensure args are a list
1929 if isinstance(args, (bytes, str)):
1930 try:
1931 args = shlex.split(to_text(args, errors='surrogateescape'))
1932 except ValueError as e:
1933 self.fail_json(msg="Invalid command syntax in run_command", exception=e)
1934
1935 # expand ``~`` in paths, and all environment vars
1936 if expand_user_and_vars:
1937 args = [to_bytes(os.path.expanduser(os.path.expandvars(x)), errors='surrogate_or_strict') for x in args if x is not None]
1938 else:
1939 args = [to_bytes(x, errors='surrogate_or_strict') for x in args if x is not None]
1940
1941 prompt_re = None
1942 if prompt_regex:
1943 if isinstance(prompt_regex, str):
1944 prompt_regex = to_bytes(prompt_regex, errors='surrogateescape')
1945 try:
1946 prompt_re = re.compile(prompt_regex, re.MULTILINE)
1947 except re.error:
1948 self.fail_json(msg="invalid prompt regular expression given to run_command")
1949
1950 rc = 0
1951 msg = None
1952 st_in = None
1953
1954 env = os.environ.copy()
1955 # We can set this from both an attribute and per call
1956 env.update(self.run_command_environ_update or {})
1957 env.update(environ_update or {})
1958 if path_prefix:
1959 path = env.get('PATH', '')
1960 if path:
1961 env['PATH'] = "%s:%s" % (path_prefix, path)
1962 else:
1963 env['PATH'] = path_prefix
1964
1965 # If using test-module.py and explode, the remote lib path will resemble:
1966 # /tmp/test_module_scratch/debug_dir/ansible/module_utils/basic.py
1967 # If using ansible or ansible-playbook with a remote system:
1968 # /tmp/ansible_vmweLQ/ansible_modlib.zip/ansible/module_utils/basic.py
1969
1970 # Clean out python paths set by ansiballz
1971 if 'PYTHONPATH' in env:
1972 pypaths = [x for x in env['PYTHONPATH'].split(':')
1973 if x and
1974 not x.endswith('/ansible_modlib.zip') and
1975 not x.endswith('/debug_dir')]
1976 if pypaths and any(pypaths):
1977 env['PYTHONPATH'] = ':'.join(pypaths)
1978
1979 if data:
1980 st_in = subprocess.PIPE
1981
1982 def preexec():
1983 if umask:
1984 os.umask(umask)
1985
1986 kwargs = dict(
1987 executable=executable,
1988 shell=shell,
1989 close_fds=close_fds,
1990 stdin=st_in,
1991 stdout=subprocess.PIPE,
1992 stderr=subprocess.PIPE,
1993 preexec_fn=preexec,
1994 env=env,
1995 )
1996 if pass_fds:
1997 kwargs["pass_fds"] = pass_fds
1998
1999 # make sure we're in the right working directory
2000 if cwd:
2001 cwd = to_bytes(os.path.abspath(os.path.expanduser(cwd)), errors='surrogate_or_strict')
2002 if os.path.isdir(cwd):
2003 kwargs['cwd'] = cwd
2004 elif not ignore_invalid_cwd:
2005 self.fail_json(msg="Provided cwd is not a valid directory: %s" % cwd)
2006
2007 try:
2008 if self._debug:
2009 # `args` is bytes (shell) or a list of bytes (non-shell) at this point;
2010 # render a printable command line. log() masks any secrets in it.
2011 printable_args = b' '.join(args) if isinstance(args, list) else args
2012 self.log('Executing: ' + to_native(printable_args, errors='surrogate_or_strict'))
2013 cmd = subprocess.Popen(args, **kwargs)
2014 if before_communicate_callback:
2015 before_communicate_callback(cmd)
2016
2017 stdout = b''
2018 stderr = b''
2019
2020 # Mirror the CPython subprocess logic and preference for the selector to use.
2021 # poll/select have the advantage of not requiring any extra file
2022 # descriptor, contrarily to epoll/kqueue (also, they require a single
2023 # syscall).
2024 if hasattr(selectors, 'PollSelector'):
2025 selector = selectors.PollSelector()
2026 else:
2027 selector = selectors.SelectSelector()
2028
2029 if data:
2030 if not binary_data:
2031 data += '\n'
2032 if isinstance(data, str):
2033 data = to_bytes(data)
2034
2035 selector.register(cmd.stdout, selectors.EVENT_READ)
2036 selector.register(cmd.stderr, selectors.EVENT_READ)
2037
2038 if os.name == 'posix':
2039 fcntl.fcntl(cmd.stdout.fileno(), fcntl.F_SETFL, fcntl.fcntl(cmd.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK)
2040 fcntl.fcntl(cmd.stderr.fileno(), fcntl.F_SETFL, fcntl.fcntl(cmd.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK)
2041
2042 if data:
2043 cmd.stdin.write(data)
2044 cmd.stdin.close()
2045
2046 while True:
2047 # A timeout of 1 is both a little short and a little long.
2048 # With None we could deadlock, with a lower value we would
2049 # waste cycles. As it is, this is a mild inconvenience if
2050 # we need to exit, and likely doesn't waste too many cycles
2051 events = selector.select(1)
2052 stdout_changed = False
2053 for key, event in events:
2054 b_chunk = key.fileobj.read(32768)
2055 if b_chunk is None:
2056 # Non-blocking read returned None (no data currently available).
2057 # This can happen with certain file-like objects or in edge cases.
2058 # Skip this chunk and try again on next select iteration.
2059 continue
2060 if not b_chunk:
2061 # Empty bytes received, EOF reached
2062 selector.unregister(key.fileobj)
2063 elif key.fileobj == cmd.stdout:
2064 stdout += b_chunk
2065 stdout_changed = True
2066 elif key.fileobj == cmd.stderr:
2067 stderr += b_chunk
2068
2069 # if we're checking for prompts, do it now, but only if stdout
2070 # actually changed since the last loop
2071 if prompt_re and stdout_changed and prompt_re.search(stdout) and not data:
2072 if encoding:
2073 stdout = to_native(stdout, encoding=encoding, errors=errors)
2074 return (257, stdout, "A prompt was encountered while running a command, but no input data was specified")
2075
2076 # break out if no pipes are left to read or the pipes are completely read
2077 # and the process is terminated
2078 if (not events or not selector.get_map()) and cmd.poll() is not None:
2079 break
2080
2081 # No pipes are left to read but process is not yet terminated
2082 # Only then it is safe to wait for the process to be finished
2083 # NOTE: Actually cmd.poll() is always None here if no selectors are left
2084 elif not selector.get_map() and cmd.poll() is None:
2085 cmd.wait()
2086 # The process is terminated. Since no pipes to read from are
2087 # left, there is no need to call select() again.
2088 break
2089
2090 cmd.stdout.close()
2091 cmd.stderr.close()
2092 selector.close()
2093
2094 rc = cmd.returncode
2095 except OSError as ex:
2096 if handle_exceptions:
2097 self.fail_json(rc=ex.errno, stdout='', stderr='', msg="Error executing command.", cmd=args, exception=ex)
2098 else:
2099 raise
2100 except Exception as ex:
2101 if handle_exceptions:
2102 self.fail_json(rc=257, stdout='', stderr='', msg="Error executing command.", cmd=args, exception=ex)
2103 else:
2104 raise
2105
2106 if rc != 0 and check_rc:
2107 self.fail_json(cmd=args, rc=rc, stdout=stdout, stderr=stderr, msg=to_native(stderr.rstrip(), errors='surrogate_or_strict'))
2108
2109 if encoding is not None:
2110 return (rc, to_native(stdout, encoding=encoding, errors=errors),
2111 to_native(stderr, encoding=encoding, errors=errors))
2112
2113 return (rc, stdout, stderr)
2114
2115 def append_to_file(self, filename, str):
2116 filename = os.path.expandvars(os.path.expanduser(filename))
2117 with open(filename, 'a') as fh:
2118 fh.write(str)
2119
2120 @staticmethod
2121 def bytes_to_human(size: int) -> str:
2122 return bytes_to_human(size)
2123
2124 # for backwards compatibility
2125 pretty_bytes = bytes_to_human
2126
2127 @staticmethod
2128 def human_to_bytes(number: str, isbits: bool = False) -> int:
2129 return human_to_bytes(number, isbits=isbits)
2130
2131 #
2132 # Backwards compat
2133 #
2134
2135 # In 2.0, moved from inside the module to the toplevel
2136 is_executable = is_executable
2137
2138 @staticmethod
2139 def get_buffer_size(fd):
2140 try:
2141 # 1032 == FZ_GETPIPE_SZ
2142 buffer_size = fcntl.fcntl(fd, 1032)
2143 except Exception:
2144 try:
2145 # not as exact as above, but should be good enough for most platforms that fail the previous call
2146 buffer_size = select.PIPE_BUF
2147 except Exception:
2148 buffer_size = 9000 # use logical default JIC
2149
2150 return buffer_size
2151
2152
2153 def get_module_path():
2154 return os.path.dirname(os.path.realpath(__file__))
2155
2156
2157 _mini_six = {
2158 "b": lambda s: s.encode("latin-1"),
2159 "PY2": False,
2160 "PY3": True,
2161 "text_type": str,
2162 "binary_type": bytes,
2163 "string_types": (str,),
2164 "integer_types": (int,),
2165 "iteritems": lambda d, **kw: iter(d.items(**kw)),
2166 }
2167
2168
2169 def __getattr__(importable_name):
2170 """Inject import-time deprecation warnings."""
2171 if (importable := _mini_six.get(importable_name, ...)) is ...:
2172 raise AttributeError(f"module {__name__!r} has no attribute {importable_name!r}")
2173
2174 deprecate(
2175 msg=f"Importing '{importable_name}' from '{__name__}' is deprecated.",
2176 version="2.24",
2177 )
2178 return importable