| 1 |
# coding: utf-8 |
| 2 |
# Copyright: (c) 2012-2014, Michael DeHaan <[email protected]> |
| 3 |
# Copyright: (c) 2018, 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 annotations |
| 7 |
|
| 8 |
import base64 |
| 9 |
import contextlib |
| 10 |
import json |
| 11 |
import os |
| 12 |
import re |
| 13 |
import secrets |
| 14 |
import shlex |
| 15 |
import stat |
| 16 |
import tempfile |
| 17 |
import typing as t |
| 18 |
|
| 19 |
from abc import ABC, abstractmethod |
| 20 |
from collections.abc import Callable |
| 21 |
|
| 22 |
from ansible import constants as C |
| 23 |
from ansible.errors import AnsibleError, AnsibleConnectionFailure, AnsibleActionSkip, AnsibleActionFail, AnsibleAuthenticationFailure |
| 24 |
from ansible.executor.module_common import modify_module, _BuiltModule |
| 25 |
from ansible.executor.interpreter_discovery import discover_interpreter, InterpreterDiscoveryRequiredError |
| 26 |
from ansible.module_utils._internal import _traceback |
| 27 |
from ansible.module_utils.common.arg_spec import ArgumentSpecValidator |
| 28 |
from ansible.module_utils.errors import UnsupportedError |
| 29 |
from ansible.module_utils.json_utils import _filter_non_json_lines |
| 30 |
from ansible.module_utils.common.json import Direction, get_module_encoder, get_module_decoder |
| 31 |
from ansible.module_utils.common.text.converters import to_native, to_text |
| 32 |
from ansible.release import __version__ |
| 33 |
from ansible.utils.collection_loader import resource_from_fqcr |
| 34 |
from ansible.utils.display import Display |
| 35 |
from ansible.utils.plugin_docs import get_versioned_doclink |
| 36 |
from ansible import _internal |
| 37 |
from ansible._internal._templating import _engine |
| 38 |
from ansible._internal import _task |
| 39 |
from .. import _AnsiblePluginInfoMixin |
| 40 |
|
| 41 |
display = Display() |
| 42 |
|
| 43 |
if t.TYPE_CHECKING: |
| 44 |
from ansible.parsing.dataloader import DataLoader |
| 45 |
from ansible.playbook.play_context import PlayContext |
| 46 |
from ansible.playbook.task import Task |
| 47 |
from ansible.plugins.connection import ConnectionBase |
| 48 |
from ansible.template import Templar |
| 49 |
|
| 50 |
VariableLayer = _task.VariableLayer # public API |
| 51 |
|
| 52 |
|
| 53 |
def _validate_utf8_json(d): |
| 54 |
if isinstance(d, str): |
| 55 |
# Purposefully not using to_bytes here for performance reasons |
| 56 |
d.encode(encoding='utf-8', errors='strict') |
| 57 |
elif isinstance(d, dict): |
| 58 |
for o in d.items(): |
| 59 |
_validate_utf8_json(o) |
| 60 |
elif isinstance(d, (list, tuple)): |
| 61 |
for o in d: |
| 62 |
_validate_utf8_json(o) |
| 63 |
|
| 64 |
|
| 65 |
class LowLevelExecuteCommandResult(t.TypedDict): |
| 66 |
rc: int |
| 67 |
stdout: str |
| 68 |
stdout_lines: list[str] |
| 69 |
stderr: str |
| 70 |
stderr_lines: list[str] |
| 71 |
|
| 72 |
|
| 73 |
class ActionBase(ABC, _AnsiblePluginInfoMixin): |
| 74 |
""" |
| 75 |
This class is the base class for all action plugins, and defines |
| 76 |
code common to all actions. The base class handles the connection |
| 77 |
by putting/getting files and executing commands based on the current |
| 78 |
action in use. |
| 79 |
""" |
| 80 |
|
| 81 |
# A set of valid arguments |
| 82 |
_VALID_ARGS = frozenset([]) # type: frozenset[str] |
| 83 |
|
| 84 |
# behavioral attributes |
| 85 |
BYPASS_HOST_LOOP = False |
| 86 |
TRANSFERS_FILES = False |
| 87 |
_requires_connection = True |
| 88 |
_supports_check_mode = True |
| 89 |
_supports_async = False |
| 90 |
supports_raw_params = False |
| 91 |
|
| 92 |
def __init__(self, task: Task, connection: ConnectionBase, play_context: PlayContext, loader: DataLoader, templar: Templar, shared_loader_obj=None): |
| 93 |
self._task = task |
| 94 |
self._connection = connection |
| 95 |
self._play_context = play_context |
| 96 |
self._loader = loader |
| 97 |
self._templar = templar |
| 98 |
|
| 99 |
from ansible.plugins import loader as plugin_loaders # avoid circular global import since PluginLoader needs ActionBase |
| 100 |
|
| 101 |
self._shared_loader_obj = plugin_loaders # shared_loader_obj was just a ref to `ansible.plugins.loader` anyway; this lets us inherit its type |
| 102 |
self._cleanup_remote_tmp = False |
| 103 |
|
| 104 |
# interpreter discovery state |
| 105 |
self._discovered_interpreter_key: str | None = None |
| 106 |
self._discovered_interpreter = False |
| 107 |
self._used_interpreter: str | None = None |
| 108 |
|
| 109 |
# Backwards compat: self._display isn't really needed, just import the global display and use that. |
| 110 |
self._display = display |
| 111 |
|
| 112 |
@abstractmethod |
| 113 |
def run(self, tmp: str | None = None, task_vars: dict[str, t.Any] | None = None) -> dict[str, t.Any]: |
| 114 |
""" Action Plugins should implement this method to perform their |
| 115 |
tasks. Everything else in this base class is a helper method for the |
| 116 |
action plugin to do that. |
| 117 |
|
| 118 |
:kwarg tmp: Deprecated parameter. This is no longer used. An action plugin that calls |
| 119 |
another one and wants to use the same remote tmp for both should set |
| 120 |
self._connection._shell.tmpdir rather than this parameter. |
| 121 |
:kwarg task_vars: The variables (host vars, group vars, config vars, |
| 122 |
etc) associated with this task. |
| 123 |
:returns: dictionary of results from the module |
| 124 |
|
| 125 |
Implementers of action modules may find the following variables especially useful: |
| 126 |
|
| 127 |
* Module parameters. These are stored in self._task.args |
| 128 |
""" |
| 129 |
# does not default to {'changed': False, 'failed': False}, as it used to break async |
| 130 |
result: dict[str, t.Any] = {} |
| 131 |
|
| 132 |
if tmp is not None: |
| 133 |
display.warning('ActionModule.run() no longer honors the tmp parameter. Action' |
| 134 |
' plugins should set self._connection._shell.tmpdir to share' |
| 135 |
' the tmpdir.') |
| 136 |
del tmp |
| 137 |
|
| 138 |
if self._task.async_val and not self._supports_async: |
| 139 |
raise AnsibleActionFail('This action (%s) does not support async.' % self._task.action) |
| 140 |
elif self._task.check_mode and not self._supports_check_mode: |
| 141 |
# deprecated: description='switch to AnsibleActionNoCheckMode' core_version='2.25' |
| 142 |
raise AnsibleActionSkip(f'This action ({self._task.action}) does not support check mode.') |
| 143 |
# raise AnsibleActionNoCheckMode(f'This action ({self._task.action}) does not support check mode.') |
| 144 |
|
| 145 |
# Error if invalid argument is passed |
| 146 |
if self._VALID_ARGS: |
| 147 |
task_opts = frozenset(self._task.args.keys()) |
| 148 |
bad_opts = task_opts.difference(self._VALID_ARGS) |
| 149 |
if bad_opts: |
| 150 |
raise AnsibleActionFail('Invalid options for %s: %s' % (self._task.action, ','.join(list(bad_opts)))) |
| 151 |
|
| 152 |
if self._connection._shell.tmpdir is None and self._early_needs_tmp_path(): |
| 153 |
self._make_tmp_path() |
| 154 |
|
| 155 |
return result |
| 156 |
|
| 157 |
def validate_argument_spec(self, argument_spec=None, |
| 158 |
mutually_exclusive=None, |
| 159 |
required_together=None, |
| 160 |
required_one_of=None, |
| 161 |
required_if=None, |
| 162 |
required_by=None, |
| 163 |
): |
| 164 |
"""Validate an argument spec against the task args |
| 165 |
|
| 166 |
This will return a tuple of (ValidationResult, dict) where the dict |
| 167 |
is the validated, coerced, and normalized task args. |
| 168 |
|
| 169 |
Be cautious when directly passing ``new_module_args`` directly to a |
| 170 |
module invocation, as it will contain the defaults, and not only |
| 171 |
the args supplied from the task. If you do this, the module |
| 172 |
should not define ``mutually_exclusive`` or similar. |
| 173 |
|
| 174 |
This code is roughly copied from the ``validate_argument_spec`` |
| 175 |
action plugin for use by other action plugins. |
| 176 |
""" |
| 177 |
|
| 178 |
new_module_args = self._task.args.copy() |
| 179 |
|
| 180 |
validator = ArgumentSpecValidator( |
| 181 |
argument_spec, |
| 182 |
mutually_exclusive=mutually_exclusive, |
| 183 |
required_together=required_together, |
| 184 |
required_one_of=required_one_of, |
| 185 |
required_if=required_if, |
| 186 |
required_by=required_by, |
| 187 |
) |
| 188 |
validation_result = validator.validate(new_module_args) |
| 189 |
|
| 190 |
new_module_args.update(validation_result.validated_parameters) |
| 191 |
|
| 192 |
try: |
| 193 |
error = validation_result.errors[0] |
| 194 |
except IndexError: |
| 195 |
error = None |
| 196 |
|
| 197 |
# Fail for validation errors, even in check mode |
| 198 |
if error: |
| 199 |
msg = validation_result.errors.msg |
| 200 |
if isinstance(error, UnsupportedError): |
| 201 |
msg = f"Unsupported parameters for ({self._load_name}) module: {msg}" |
| 202 |
|
| 203 |
raise AnsibleActionFail(msg, obj=self._task.args) |
| 204 |
|
| 205 |
return validation_result, new_module_args |
| 206 |
|
| 207 |
def cleanup(self, force=False): |
| 208 |
"""Method to perform a clean up at the end of an action plugin execution |
| 209 |
|
| 210 |
By default this is designed to clean up the shell tmpdir, and is toggled based on whether |
| 211 |
async is in use |
| 212 |
|
| 213 |
Action plugins may override this if they deem necessary, but should still call this method |
| 214 |
via super |
| 215 |
""" |
| 216 |
if force or not self._task.async_val: |
| 217 |
self._remove_tmp_path(self._connection._shell.tmpdir) |
| 218 |
|
| 219 |
@_internal.experimental |
| 220 |
def add_host( |
| 221 |
self, |
| 222 |
host_name: str, |
| 223 |
*, |
| 224 |
host_vars: dict[str, object] | None = None, |
| 225 |
parent_group_names: list[str] | None = None, |
| 226 |
) -> bool: |
| 227 |
""" |
| 228 |
EXPERIMENTAL: Unstable API subject to change at any time without notice. |
| 229 |
Add the given host to inventory. |
| 230 |
""" |
| 231 |
return _task.TaskContext.current().inventory_rpc_client.add_host(_task.AddHost( |
| 232 |
host_name=host_name, |
| 233 |
host_vars=host_vars, |
| 234 |
parent_group_names=parent_group_names, |
| 235 |
)) |
| 236 |
|
| 237 |
@_internal.experimental |
| 238 |
def add_group( |
| 239 |
self, |
| 240 |
group_name: str, |
| 241 |
*, |
| 242 |
parent_group_names: list[str] | None = None, |
| 243 |
) -> bool: |
| 244 |
""" |
| 245 |
EXPERIMENTAL: Unstable API subject to change at any time without notice. |
| 246 |
Add the given group to inventory. |
| 247 |
""" |
| 248 |
task_ctx = _task.TaskContext.current() |
| 249 |
host_name = task_ctx.host_name |
| 250 |
|
| 251 |
return task_ctx.inventory_rpc_client.add_group(host_name, _task.AddGroup( |
| 252 |
group_name=group_name, |
| 253 |
parent_group_names=parent_group_names, |
| 254 |
)) |
| 255 |
|
| 256 |
def register_host_variables(self, variables: dict[str, object], layer: VariableLayer = VariableLayer.REGISTER_VARS) -> None: |
| 257 |
""" |
| 258 |
Register the given variables for the current host at the specified variable precedence layer. |
| 259 |
Calling this method more than once for the same layer will override any previous value for the currently executing action. |
| 260 |
""" |
| 261 |
self.__get_pending_changes().register_host_variables[layer] = variables |
| 262 |
|
| 263 |
def __get_pending_changes(self) -> _task.PendingChanges: |
| 264 |
if self._supports_async: |
| 265 |
raise RuntimeError('Actions that support async cannot record pending changes.') |
| 266 |
|
| 267 |
return _task.TaskContext.current().pending_changes |
| 268 |
|
| 269 |
@classmethod |
| 270 |
@contextlib.contextmanager |
| 271 |
@_internal.experimental |
| 272 |
def get_finalize_task_args_context(cls) -> t.Any: |
| 273 |
""" |
| 274 |
EXPERIMENTAL: Unstable API subject to change at any time without notice. |
| 275 |
Wraps task arg finalization with (optional) stateful context. |
| 276 |
The context manager is entered during `Task.post_validate_args, and may yield a single value to be passed |
| 277 |
as `context` to Task.finalize_task_arg for each task arg. |
| 278 |
""" |
| 279 |
yield None |
| 280 |
|
| 281 |
@classmethod |
| 282 |
@_internal.experimental |
| 283 |
def finalize_task_arg(cls, name: str, value: t.Any, templar: _engine.TemplateEngine, context: t.Any) -> t.Any: |
| 284 |
""" |
| 285 |
EXPERIMENTAL: Unstable API subject to change at any time without notice. |
| 286 |
Called for each task arg to allow for custom templating. |
| 287 |
The optional `context` value is sourced from `Task.get_finalize_task_args_context`. |
| 288 |
""" |
| 289 |
return templar.template(value) |
| 290 |
|
| 291 |
def get_plugin_option(self, plugin, option, default=None): |
| 292 |
"""Helper to get an option from a plugin without having to use |
| 293 |
the try/except dance everywhere to set a default |
| 294 |
""" |
| 295 |
try: |
| 296 |
return plugin.get_option(option) |
| 297 |
except (AttributeError, KeyError): |
| 298 |
return default |
| 299 |
|
| 300 |
def get_become_option(self, option, default=None): |
| 301 |
return self.get_plugin_option(self._connection.become, option, default=default) |
| 302 |
|
| 303 |
def get_connection_option(self, option, default=None): |
| 304 |
return self.get_plugin_option(self._connection, option, default=default) |
| 305 |
|
| 306 |
def get_shell_option(self, option, default=None): |
| 307 |
return self.get_plugin_option(self._connection._shell, option, default=default) |
| 308 |
|
| 309 |
def _remote_file_exists(self, path): |
| 310 |
cmd = self._connection._shell.exists(path) |
| 311 |
result = self._low_level_execute_command(cmd=cmd, sudoable=True) |
| 312 |
if result['rc'] == 0: |
| 313 |
return True |
| 314 |
return False |
| 315 |
|
| 316 |
def _configure_module(self, module_name, module_args, task_vars) -> tuple[_BuiltModule, str]: |
| 317 |
""" |
| 318 |
Handles the loading and templating of the module code through the |
| 319 |
modify_module() function. |
| 320 |
""" |
| 321 |
if self._task.delegate_to: |
| 322 |
use_vars = task_vars.get('ansible_delegated_vars')[self._task.delegate_to] |
| 323 |
else: |
| 324 |
use_vars = task_vars |
| 325 |
|
| 326 |
split_module_name = module_name.split('.') |
| 327 |
collection_name = '.'.join(split_module_name[0:2]) if len(split_module_name) > 2 else '' |
| 328 |
leaf_module_name = resource_from_fqcr(module_name) |
| 329 |
|
| 330 |
# Search module path(s) for named module. |
| 331 |
for mod_type in self._connection.module_implementation_preferences: |
| 332 |
# Check to determine if PowerShell modules are supported, and apply |
| 333 |
# some fixes (hacks) to module name + args. |
| 334 |
if mod_type == '.ps1': |
| 335 |
# FIXME: This should be temporary and moved to an exec subsystem plugin where we can define the mapping |
| 336 |
# for each subsystem. |
| 337 |
win_collection = 'ansible.windows' |
| 338 |
rewrite_collection_names = ['ansible.builtin', 'ansible.legacy', ''] |
| 339 |
# async_status, win_stat, win_file, win_copy, and win_ping are not just like their |
| 340 |
# python counterparts but they are compatible enough for our |
| 341 |
# internal usage |
| 342 |
# NB: we only rewrite the module if it's not being called by the user (eg, an action calling something else) |
| 343 |
# and if it's unqualified or FQ to a builtin |
| 344 |
if leaf_module_name in ('stat', 'file', 'copy', 'ping') and \ |
| 345 |
collection_name in rewrite_collection_names and self._task.action != module_name: |
| 346 |
module_name = '%s.win_%s' % (win_collection, leaf_module_name) |
| 347 |
elif leaf_module_name == 'async_status' and collection_name in rewrite_collection_names: |
| 348 |
module_name = '%s.%s' % (win_collection, leaf_module_name) |
| 349 |
|
| 350 |
result = self._shared_loader_obj.module_loader.find_plugin_with_context(module_name, mod_type, collection_list=self._task.collections) |
| 351 |
|
| 352 |
if not result.resolved: |
| 353 |
if result.redirect_list and len(result.redirect_list) > 1: |
| 354 |
# take the last one in the redirect list, we may have successfully jumped through N other redirects |
| 355 |
target_module_name = result.redirect_list[-1] |
| 356 |
|
| 357 |
raise AnsibleError("The module {0} was redirected to {1}, which could not be loaded.".format(module_name, target_module_name)) |
| 358 |
|
| 359 |
module_path = result.plugin_resolved_path |
| 360 |
if module_path: |
| 361 |
break |
| 362 |
else: # This is a for-else: http://bit.ly/1ElPkyg |
| 363 |
raise AnsibleError("The module %s was not found in configured module paths" % (module_name)) |
| 364 |
|
| 365 |
# insert shared code and arguments into the module |
| 366 |
final_environment: dict[str, t.Any] = {} |
| 367 |
self._compute_environment_string(final_environment) |
| 368 |
|
| 369 |
# modify_module will exit early if interpreter discovery is required; re-run after if necessary |
| 370 |
for _dummy in (1, 2): |
| 371 |
try: |
| 372 |
module_bits = modify_module( |
| 373 |
module_name=module_name, |
| 374 |
module_path=module_path, |
| 375 |
module_args=module_args, |
| 376 |
templar=self._templar, |
| 377 |
task_vars=use_vars, |
| 378 |
module_compression=C.config.get_config_value('DEFAULT_MODULE_COMPRESSION', variables=task_vars), |
| 379 |
async_timeout=self._task.async_val, |
| 380 |
environment=final_environment, |
| 381 |
remote_is_local=bool(getattr(self._connection, '_remote_is_local', False)), |
| 382 |
become_plugin=self._connection.become, |
| 383 |
shell_plugin=self._connection._shell, |
| 384 |
) |
| 385 |
|
| 386 |
break |
| 387 |
except InterpreterDiscoveryRequiredError as idre: |
| 388 |
self._discovered_interpreter = discover_interpreter(action=self, interpreter_name=idre.interpreter_name, |
| 389 |
discovery_mode=idre.discovery_mode, task_vars=use_vars) |
| 390 |
|
| 391 |
# update the local task_vars with the discovered interpreter (which might be None); |
| 392 |
# we'll propagate back to the controller in the task result |
| 393 |
discovered_key = 'discovered_interpreter_%s' % idre.interpreter_name |
| 394 |
|
| 395 |
# update the local vars copy for the retry |
| 396 |
use_vars['ansible_facts'][discovered_key] = self._discovered_interpreter |
| 397 |
|
| 398 |
# TODO: this condition prevents 'wrong host' from being updated |
| 399 |
# but in future we would want to be able to update 'delegated host facts' |
| 400 |
# irrespective of task settings |
| 401 |
if not self._task.delegate_to or self._task.delegate_facts: |
| 402 |
# store in local task_vars facts collection for the retry and any other usages in this worker |
| 403 |
task_vars['ansible_facts'][discovered_key] = self._discovered_interpreter |
| 404 |
# preserve this so _execute_module can propagate back to controller as a fact |
| 405 |
self._discovered_interpreter_key = discovered_key |
| 406 |
else: |
| 407 |
task_vars['ansible_delegated_vars'][self._task.delegate_to]['ansible_facts'][discovered_key] = self._discovered_interpreter |
| 408 |
|
| 409 |
return module_bits, module_path |
| 410 |
|
| 411 |
def _compute_environment_string(self, raw_environment_out=None) -> str: |
| 412 |
""" |
| 413 |
Builds the environment string to be used when executing the remote task. |
| 414 |
""" |
| 415 |
|
| 416 |
final_environment = dict() |
| 417 |
if self._task.environment is not None: |
| 418 |
environments = self._task.environment |
| 419 |
if not isinstance(environments, list): |
| 420 |
environments = [environments] |
| 421 |
|
| 422 |
# The order of environments matters to make sure we merge |
| 423 |
# in the parent's values first so those in the block then |
| 424 |
# task 'win' in precedence |
| 425 |
for environment in environments: |
| 426 |
if environment is None or len(environment) == 0: |
| 427 |
continue |
| 428 |
temp_environment = self._templar.template(environment) |
| 429 |
if not isinstance(temp_environment, dict): |
| 430 |
raise AnsibleError("environment must be a dictionary, received %s (%s)" % (temp_environment, type(temp_environment))) |
| 431 |
# very deliberately using update here instead of combine_vars, as |
| 432 |
# these environment settings should not need to merge sub-dicts |
| 433 |
final_environment.update(temp_environment) |
| 434 |
|
| 435 |
if len(final_environment) > 0: |
| 436 |
final_environment = self._templar.template(final_environment) |
| 437 |
|
| 438 |
if isinstance(raw_environment_out, dict): |
| 439 |
raw_environment_out.clear() |
| 440 |
raw_environment_out.update(final_environment) |
| 441 |
|
| 442 |
return self._connection._shell.env_prefix(**final_environment) |
| 443 |
|
| 444 |
def _early_needs_tmp_path(self): |
| 445 |
""" |
| 446 |
Determines if a tmp path should be created before the action is executed. |
| 447 |
""" |
| 448 |
|
| 449 |
return getattr(self, 'TRANSFERS_FILES', False) |
| 450 |
|
| 451 |
def _is_pipelining_enabled(self, module_style: str, wrap_async: bool = False) -> bool: |
| 452 |
""" |
| 453 |
Determines if we are required and can do pipelining, only 'new' style modules can support pipelining |
| 454 |
""" |
| 455 |
# FUTURE: Move async checks from connection.is_pipelining_enabled here |
| 456 |
# as async and pipelining is a property on the execution layer and not |
| 457 |
# the capabilities of the connection itself. |
| 458 |
conditions = [ |
| 459 |
module_style == 'new', |
| 460 |
not C.DEFAULT_KEEP_REMOTE_FILES, # user doesn't want to keep remote files |
| 461 |
self._connection.is_pipelining_enabled(wrap_async), # connection/become supports pipelining and is enabled |
| 462 |
] |
| 463 |
return all(conditions) |
| 464 |
|
| 465 |
def _get_admin_users(self): |
| 466 |
""" |
| 467 |
Returns a list of admin users that are configured for the current shell |
| 468 |
plugin |
| 469 |
""" |
| 470 |
|
| 471 |
return self.get_shell_option('admin_users', ['root']) |
| 472 |
|
| 473 |
def _get_remote_addr(self, tvars): |
| 474 |
""" consistently get the 'remote_address' for the action plugin """ |
| 475 |
remote_addr = tvars.get('delegated_vars', {}).get('ansible_host', tvars.get('ansible_host', tvars.get('inventory_hostname', None))) |
| 476 |
for variation in ('remote_addr', 'host'): |
| 477 |
try: |
| 478 |
remote_addr = self._connection.get_option(variation) |
| 479 |
except KeyError: |
| 480 |
continue |
| 481 |
break |
| 482 |
else: |
| 483 |
# plugin does not have, fallback to play_context |
| 484 |
remote_addr = self._play_context.remote_addr |
| 485 |
return remote_addr |
| 486 |
|
| 487 |
def _get_remote_user(self): |
| 488 |
""" consistently get the 'remote_user' for the action plugin """ |
| 489 |
# TODO: use 'current user running ansible' as fallback when moving away from play_context |
| 490 |
# pwd.getpwuid(os.getuid()).pw_name |
| 491 |
remote_user = None |
| 492 |
try: |
| 493 |
remote_user = self._connection.get_option('remote_user') |
| 494 |
except KeyError: |
| 495 |
# plugin does not have remote_user option, fallback to default and/play_context |
| 496 |
remote_user = getattr(self._connection, 'default_user', None) or self._play_context.remote_user |
| 497 |
except AttributeError: |
| 498 |
# plugin does not use config system, fallback to old play_context |
| 499 |
remote_user = self._play_context.remote_user |
| 500 |
return remote_user |
| 501 |
|
| 502 |
def _is_become_unprivileged(self): |
| 503 |
""" |
| 504 |
The user is not the same as the connection user and is not part of the |
| 505 |
shell configured admin users |
| 506 |
""" |
| 507 |
# if we don't use become then we know we aren't switching to a |
| 508 |
# different unprivileged user |
| 509 |
if not self._connection.become: |
| 510 |
return False |
| 511 |
|
| 512 |
# if we use become and the user is not an admin (or same user) then |
| 513 |
# we need to return become_unprivileged as True |
| 514 |
admin_users = self._get_admin_users() |
| 515 |
remote_user = self._get_remote_user() |
| 516 |
become_user = self.get_become_option('become_user') |
| 517 |
return bool(become_user and become_user not in admin_users + [remote_user]) |
| 518 |
|
| 519 |
def _make_tmp_path(self, remote_user: str | None = None) -> str: |
| 520 |
""" |
| 521 |
Create and return a temporary path on a remote box. |
| 522 |
""" |
| 523 |
|
| 524 |
# Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host. |
| 525 |
# As such, we want to avoid using remote_user for paths as remote_user may not line up with the local user |
| 526 |
# This is a hack and should be solved by more intelligent handling of remote_tmp in 2.7 |
| 527 |
if getattr(self._connection, '_remote_is_local', False): |
| 528 |
tmpdir = C.DEFAULT_LOCAL_TMP |
| 529 |
else: |
| 530 |
# NOTE: shell plugins should populate this setting anyways, but they dont do remote expansion, which |
| 531 |
# we need for 'non posix' systems like cloud-init and solaris |
| 532 |
tmpdir = self._remote_expand_user(self.get_shell_option('remote_tmp', default='~/.ansible/tmp'), sudoable=False) |
| 533 |
|
| 534 |
become_unprivileged = self._is_become_unprivileged() |
| 535 |
basefile = self._connection._shell._generate_temp_dir_name() |
| 536 |
|
| 537 |
cmd = None |
| 538 |
in_data = None |
| 539 |
if self._connection.is_pipelining_enabled(wrap_async=False): |
| 540 |
cmd_details = self._connection._shell._mkdtemp2(basefile=basefile, system=become_unprivileged, tmpdir=tmpdir) |
| 541 |
cmd = cmd_details.command |
| 542 |
in_data = cmd_details.input_data |
| 543 |
else: |
| 544 |
cmd = self._connection._shell.mkdtemp(basefile=basefile, system=become_unprivileged, tmpdir=tmpdir) |
| 545 |
result = self._low_level_execute_command(cmd, in_data=in_data, sudoable=False) |
| 546 |
|
| 547 |
# error handling on this seems a little aggressive? |
| 548 |
if result['rc'] != 0: |
| 549 |
if result['rc'] == 5: |
| 550 |
output = 'Authentication failure.' |
| 551 |
elif result['rc'] == 255 and self._connection.transport in ('ssh',): |
| 552 |
|
| 553 |
if display.verbosity > 3: |
| 554 |
output = u'SSH encountered an unknown error. The output was:\n%s%s' % (result['stdout'], result['stderr']) |
| 555 |
else: |
| 556 |
output = (u'SSH encountered an unknown error during the connection. ' |
| 557 |
'We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue') |
| 558 |
|
| 559 |
elif u'No space left on device' in result['stderr']: |
| 560 |
output = result['stderr'] |
| 561 |
else: |
| 562 |
output = ('Failed to create temporary directory. ' |
| 563 |
'In some cases, you may have been able to authenticate and did not have permissions on the target directory. ' |
| 564 |
'Consider changing the remote tmp path in ansible.cfg to a path rooted in "/tmp", for more error information use -vvv. ' |
| 565 |
'Failed command was: %s, exited with result %d' % (cmd, result['rc'])) |
| 566 |
if 'stdout' in result and result['stdout'] != u'': |
| 567 |
output = output + u", stdout output: %s" % result['stdout'] |
| 568 |
if display.verbosity > 3 and 'stderr' in result and result['stderr'] != u'': |
| 569 |
output += u", stderr output: %s" % result['stderr'] |
| 570 |
raise AnsibleConnectionFailure(output) |
| 571 |
else: |
| 572 |
self._cleanup_remote_tmp = True |
| 573 |
|
| 574 |
try: |
| 575 |
stdout_parts = result['stdout'].strip().split('%s=' % basefile, 1) |
| 576 |
rc = self._connection._shell.join_path(stdout_parts[-1], u'').splitlines()[-1] |
| 577 |
except IndexError: |
| 578 |
# stdout was empty or just space, set to / to trigger error in next if |
| 579 |
rc = '/' |
| 580 |
|
| 581 |
# Catch failure conditions, files should never be |
| 582 |
# written to locations in /. |
| 583 |
if rc == '/': |
| 584 |
raise AnsibleError('failed to resolve remote temporary directory from %s: `%s` returned empty string' % (basefile, cmd)) |
| 585 |
|
| 586 |
self._connection._shell.tmpdir = rc |
| 587 |
|
| 588 |
return rc |
| 589 |
|
| 590 |
def _should_remove_tmp_path(self, tmp_path): |
| 591 |
"""Determine if temporary path should be deleted or kept by user request/config""" |
| 592 |
return tmp_path and self._cleanup_remote_tmp and not C.DEFAULT_KEEP_REMOTE_FILES and "-tmp-" in tmp_path |
| 593 |
|
| 594 |
def _remove_tmp_path(self, tmp_path, force=False): |
| 595 |
"""Remove a temporary path we created. """ |
| 596 |
|
| 597 |
if tmp_path is None and self._connection._shell.tmpdir: |
| 598 |
tmp_path = self._connection._shell.tmpdir |
| 599 |
|
| 600 |
if force or self._should_remove_tmp_path(tmp_path): |
| 601 |
cmd = self._connection._shell.remove(tmp_path, recurse=True) |
| 602 |
# If we have gotten here we have a working connection configuration. |
| 603 |
# If the connection breaks we could leave tmp directories out on the remote system. |
| 604 |
tmp_rm_res = self._low_level_execute_command(cmd, sudoable=False) |
| 605 |
|
| 606 |
if tmp_rm_res.get('rc', 0) != 0: |
| 607 |
display.warning('Error deleting remote temporary files (rc: %s, stderr: %s})' |
| 608 |
% (tmp_rm_res.get('rc'), tmp_rm_res.get('stderr', 'No error string available.'))) |
| 609 |
else: |
| 610 |
self._connection._shell.tmpdir = None |
| 611 |
|
| 612 |
def _transfer_file(self, local_path: str, remote_path: str) -> str: |
| 613 |
""" |
| 614 |
Copy a file from the controller to a remote path |
| 615 |
|
| 616 |
:arg local_path: Path on controller to transfer |
| 617 |
:arg remote_path: Path on the remote system to transfer into |
| 618 |
|
| 619 |
.. warning:: |
| 620 |
* When you use this function you likely want to use use fixup_perms2() on the |
| 621 |
remote_path to make sure that the remote file is readable when the user becomes |
| 622 |
a non-privileged user. |
| 623 |
* If you use fixup_perms2() on the file and copy or move the file into place, you will |
| 624 |
need to then remove filesystem acls on the file once it has been copied into place by |
| 625 |
the module. See how the copy module implements this for help. |
| 626 |
""" |
| 627 |
self._connection.put_file(local_path, remote_path) |
| 628 |
return remote_path |
| 629 |
|
| 630 |
def _transfer_data(self, remote_path: str, data: str | bytes) -> str: |
| 631 |
""" |
| 632 |
Copies the module data out to the temporary module path. |
| 633 |
""" |
| 634 |
|
| 635 |
if isinstance(data, str): |
| 636 |
data = data.encode(errors='surrogateescape') |
| 637 |
elif not isinstance(data, bytes): |
| 638 |
raise TypeError('data must be either a string or bytes') |
| 639 |
|
| 640 |
afd, afile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP) |
| 641 |
afo = os.fdopen(afd, 'wb') |
| 642 |
try: |
| 643 |
afo.write(data) |
| 644 |
except Exception as e: |
| 645 |
raise AnsibleError("failure writing module data to temporary file for transfer: %s" % to_native(e)) |
| 646 |
|
| 647 |
afo.flush() |
| 648 |
afo.close() |
| 649 |
|
| 650 |
try: |
| 651 |
self._transfer_file(afile, remote_path) |
| 652 |
finally: |
| 653 |
os.unlink(afile) |
| 654 |
|
| 655 |
return remote_path |
| 656 |
|
| 657 |
def _fixup_perms2(self, remote_paths, remote_user=None, execute=True): |
| 658 |
""" |
| 659 |
We need the files we upload to be readable (and sometimes executable) |
| 660 |
by the user being sudo'd to but we want to limit other people's access |
| 661 |
(because the files could contain passwords or other private |
| 662 |
information. We achieve this in one of these ways: |
| 663 |
|
| 664 |
* If no sudo is performed or the remote_user is sudo'ing to |
| 665 |
themselves, we don't have to change permissions. |
| 666 |
* If the remote_user sudo's to a privileged user (for instance, root), |
| 667 |
we don't have to change permissions |
| 668 |
* If the remote_user sudo's to an unprivileged user then we attempt to |
| 669 |
grant the unprivileged user access via file system acls. |
| 670 |
* If granting file system acls fails we try to change the owner of the |
| 671 |
file with chown which only works in case the remote_user is |
| 672 |
privileged or the remote systems allows chown calls by unprivileged |
| 673 |
users (e.g. HP-UX) |
| 674 |
* If the above fails, we next try 'chmod +a' which is a macOS way of |
| 675 |
setting ACLs on files. |
| 676 |
* If the above fails, we check if ansible_common_remote_group is set. |
| 677 |
If it is, we attempt to chgrp the file to its value. This is useful |
| 678 |
if the remote_user has a group in common with the become_user. As the |
| 679 |
remote_user, we can chgrp the file to that group and allow the |
| 680 |
become_user to read it. |
| 681 |
* If (the chown fails AND ansible_common_remote_group is not set) OR |
| 682 |
(ansible_common_remote_group is set AND the chgrp (or following chmod) |
| 683 |
returned non-zero), we can set the file to be world readable so that |
| 684 |
the second unprivileged user can read the file. |
| 685 |
Since this could allow other users to get access to private |
| 686 |
information we only do this if ansible is configured with |
| 687 |
"allow_world_readable_tmpfiles" in the ansible.cfg. Also note that |
| 688 |
when ansible_common_remote_group is set this final fallback is very |
| 689 |
unlikely to ever be triggered, so long as chgrp was successful. But |
| 690 |
just because the chgrp was successful, does not mean Ansible can |
| 691 |
necessarily access the files (if, for example, the variable was set |
| 692 |
to a group that remote_user is in, and can chgrp to, but does not have |
| 693 |
in common with become_user). |
| 694 |
""" |
| 695 |
if remote_user is None: |
| 696 |
remote_user = self._get_remote_user() |
| 697 |
|
| 698 |
# Step 1: Are we on windows? |
| 699 |
if getattr(self._connection._shell, "_IS_WINDOWS", False): |
| 700 |
# This won't work on Powershell as-is, so we'll just completely |
| 701 |
# skip until we have a need for it, at which point we'll have to do |
| 702 |
# something different. |
| 703 |
return remote_paths |
| 704 |
|
| 705 |
# Step 2: If we're not becoming an unprivileged user, we are roughly |
| 706 |
# done. Make the files +x if we're asked to, and return. |
| 707 |
if not self._is_become_unprivileged(): |
| 708 |
if execute: |
| 709 |
# Can't depend on the file being transferred with required permissions. |
| 710 |
# Only need user perms because no become was used here |
| 711 |
res = self._remote_chmod(remote_paths, 'u+rwx') |
| 712 |
if res['rc'] != 0: |
| 713 |
raise AnsibleError( |
| 714 |
'Failed to set permissions on remote files ' |
| 715 |
'(rc: {0}, err: {1})'.format( |
| 716 |
res['rc'], |
| 717 |
to_native(res['stderr']))) |
| 718 |
return remote_paths |
| 719 |
|
| 720 |
# If we're still here, we have an unprivileged user that's different |
| 721 |
# than the ssh user. |
| 722 |
become_user = self.get_become_option('become_user') |
| 723 |
|
| 724 |
# Try to use file system acls to make the files readable for sudo'd |
| 725 |
# user |
| 726 |
if execute: |
| 727 |
chmod_mode = 'rx' |
| 728 |
setfacl_mode = 'r-x' |
| 729 |
# Apple patches their "file_cmds" chmod with ACL support |
| 730 |
chmod_acl_mode = '{0} allow read,execute'.format(become_user) |
| 731 |
# POSIX-draft ACL specification. Solaris, maybe others. |
| 732 |
# See chmod(1) on something Solaris-based for syntax details. |
| 733 |
posix_acl_mode = 'A+user:{0}:rx:allow'.format(become_user) |
| 734 |
else: |
| 735 |
chmod_mode = 'rX' |
| 736 |
# TODO: this form fails silently on freebsd. We currently |
| 737 |
# never call _fixup_perms2() with execute=False but if we |
| 738 |
# start to we'll have to fix this. |
| 739 |
setfacl_mode = 'r-X' |
| 740 |
# Apple |
| 741 |
chmod_acl_mode = '{0} allow read'.format(become_user) |
| 742 |
# POSIX-draft |
| 743 |
posix_acl_mode = 'A+user:{0}:r:allow'.format(become_user) |
| 744 |
|
| 745 |
# Step 3a: Are we able to use setfacl to add user ACLs to the file? |
| 746 |
res = self._remote_set_user_facl( |
| 747 |
remote_paths, |
| 748 |
become_user, |
| 749 |
setfacl_mode) |
| 750 |
|
| 751 |
match res.get('rc'): |
| 752 |
case 0: |
| 753 |
return remote_paths |
| 754 |
case 2: |
| 755 |
# invalid syntax (for example, missing user, missing colon) |
| 756 |
self._display.debug(f"setfacl command failed with an invalid syntax. Trying chmod instead. Err: {res!r}") |
| 757 |
case 127: |
| 758 |
# setfacl binary does not exists or we don't have permission to use it. |
| 759 |
self._display.debug(f"setfacl binary does not exist or does not have permission to use it. Trying chmod instead. Err: {res!r}") |
| 760 |
case _: |
| 761 |
# generic debug message |
| 762 |
self._display.debug(f'Failed to set facl {setfacl_mode}, got:{res!r}') |
| 763 |
|
| 764 |
# Step 3b: Set execute if we need to. We do this before anything else |
| 765 |
# because some of the methods below might work but not let us set |
| 766 |
# permissions as part of them. |
| 767 |
if execute: |
| 768 |
res = self._remote_chmod(remote_paths, 'u+rwx') |
| 769 |
if res['rc'] != 0: |
| 770 |
raise AnsibleError( |
| 771 |
'Failed to set file mode or acl on remote temporary files ' |
| 772 |
'(rc: {0}, err: {1})'.format( |
| 773 |
res['rc'], |
| 774 |
to_native(res['stderr']))) |
| 775 |
|
| 776 |
# Step 3c: File system ACLs failed above; try falling back to chown. |
| 777 |
res = self._remote_chown(remote_paths, become_user) |
| 778 |
if res['rc'] == 0: |
| 779 |
return remote_paths |
| 780 |
|
| 781 |
# Check if we are an admin/root user. If we are and got here, it means |
| 782 |
# we failed to chown as root and something weird has happened. |
| 783 |
if remote_user in self._get_admin_users(): |
| 784 |
raise AnsibleError( |
| 785 |
'Failed to change ownership of the temporary files Ansible ' |
| 786 |
'(via chmod nor setfacl) needs to create despite connecting as a ' |
| 787 |
'privileged user. Unprivileged become user would be unable to read' |
| 788 |
' the file.') |
| 789 |
|
| 790 |
# Step 3d: Try macOS's special chmod + ACL |
| 791 |
# macOS chmod's +a flag takes its own argument. As a slight hack, we |
| 792 |
# pass that argument as the first element of remote_paths. So we end |
| 793 |
# up running `chmod +a [that argument] [file 1] [file 2] ...` |
| 794 |
try: |
| 795 |
res = self._remote_chmod([chmod_acl_mode] + list(remote_paths), '+a') |
| 796 |
except AnsibleAuthenticationFailure as e: |
| 797 |
# Solaris-based chmod will return 5 when it sees an invalid mode, |
| 798 |
# and +a is invalid there. Because it returns 5, which is the same |
| 799 |
# thing sshpass returns on auth failure, our sshpass code will |
| 800 |
# assume that auth failed. If we don't handle that case here, none |
| 801 |
# of the other logic below will get run. This is fairly hacky and a |
| 802 |
# corner case, but probably one that shows up pretty often in |
| 803 |
# Solaris-based environments (and possibly others). |
| 804 |
pass |
| 805 |
else: |
| 806 |
if res['rc'] == 0: |
| 807 |
return remote_paths |
| 808 |
|
| 809 |
# Step 3e: Try Solaris/OpenSolaris/OpenIndiana-sans-setfacl chmod |
| 810 |
# Similar to macOS above, Solaris 11.4 drops setfacl and takes file ACLs |
| 811 |
# via chmod instead. OpenSolaris and illumos-based distros allow for |
| 812 |
# using either setfacl or chmod, and compatibility depends on filesystem. |
| 813 |
# It should be possible to debug this branch by installing OpenIndiana |
| 814 |
# (use ZFS) and going unpriv -> unpriv. |
| 815 |
res = self._remote_chmod(remote_paths, posix_acl_mode) |
| 816 |
if res['rc'] == 0: |
| 817 |
return remote_paths |
| 818 |
|
| 819 |
# we'll need this down here |
| 820 |
become_link = get_versioned_doclink('playbook_guide/playbooks_privilege_escalation.html') |
| 821 |
# Step 3f: Common group |
| 822 |
# Otherwise, we're a normal user. We failed to chown the paths to the |
| 823 |
# unprivileged user, but if we have a common group with them, we should |
| 824 |
# be able to chown it to that. |
| 825 |
# |
| 826 |
# Note that we have no way of knowing if this will actually work... just |
| 827 |
# because chgrp exits successfully does not mean that Ansible will work. |
| 828 |
# We could check if the become user is in the group, but this would |
| 829 |
# create an extra round trip. |
| 830 |
# |
| 831 |
# Also note that due to the above, this can prevent the |
| 832 |
# world_readable_temp logic below from ever getting called. We |
| 833 |
# leave this up to the user to rectify if they have both of these |
| 834 |
# features enabled. |
| 835 |
group = self.get_shell_option('common_remote_group') |
| 836 |
if group is not None: |
| 837 |
res = self._remote_chgrp(remote_paths, group) |
| 838 |
if res['rc'] == 0: |
| 839 |
# warn user that something might go weirdly here. |
| 840 |
if self.get_shell_option('world_readable_temp'): |
| 841 |
display.warning( |
| 842 |
'Both common_remote_group and ' |
| 843 |
'allow_world_readable_tmpfiles are set. chgrp was ' |
| 844 |
'successful, but there is no guarantee that Ansible ' |
| 845 |
'will be able to read the files after this operation, ' |
| 846 |
'particularly if common_remote_group was set to a ' |
| 847 |
'group of which the unprivileged become user is not a ' |
| 848 |
'member. In this situation, ' |
| 849 |
'allow_world_readable_tmpfiles is a no-op. See this ' |
| 850 |
'URL for more details: %s' |
| 851 |
'#risks-of-becoming-an-unprivileged-user' % become_link) |
| 852 |
if execute: |
| 853 |
group_mode = 'g+rwx' |
| 854 |
else: |
| 855 |
group_mode = 'g+rw' |
| 856 |
res = self._remote_chmod(remote_paths, group_mode) |
| 857 |
if res['rc'] == 0: |
| 858 |
return remote_paths |
| 859 |
|
| 860 |
# Step 4: World-readable temp directory |
| 861 |
if self.get_shell_option('world_readable_temp'): |
| 862 |
# chown and fs acls failed -- do things this insecure way only if |
| 863 |
# the user opted in in the config file |
| 864 |
display.warning( |
| 865 |
'Using world-readable permissions for temporary files Ansible ' |
| 866 |
'needs to create when becoming an unprivileged user. This may ' |
| 867 |
'be insecure. For information on securing this, see %s' |
| 868 |
'#risks-of-becoming-an-unprivileged-user' % become_link) |
| 869 |
res = self._remote_chmod(remote_paths, 'a+%s' % chmod_mode) |
| 870 |
if res['rc'] == 0: |
| 871 |
return remote_paths |
| 872 |
raise AnsibleError( |
| 873 |
'Failed to set file mode on remote files ' |
| 874 |
'(rc: {0}, err: {1})'.format( |
| 875 |
res['rc'], |
| 876 |
to_native(res['stderr']))) |
| 877 |
|
| 878 |
raise AnsibleError( |
| 879 |
'Failed to set permissions on the temporary files Ansible needs ' |
| 880 |
'to create when becoming an unprivileged user ' |
| 881 |
'(rc: %s, err: %s}). For information on working around this, see %s' |
| 882 |
'#risks-of-becoming-an-unprivileged-user' % ( |
| 883 |
res['rc'], |
| 884 |
to_native(res['stderr']), become_link)) |
| 885 |
|
| 886 |
def _remote_chmod(self, paths, mode, sudoable=False): |
| 887 |
""" |
| 888 |
Issue a remote chmod command |
| 889 |
""" |
| 890 |
cmd = self._connection._shell.chmod(paths, mode) |
| 891 |
res = self._low_level_execute_command(cmd, sudoable=sudoable) |
| 892 |
return res |
| 893 |
|
| 894 |
def _remote_chown(self, paths, user, sudoable=False): |
| 895 |
""" |
| 896 |
Issue a remote chown command |
| 897 |
""" |
| 898 |
cmd = self._connection._shell.chown(paths, user) |
| 899 |
res = self._low_level_execute_command(cmd, sudoable=sudoable) |
| 900 |
return res |
| 901 |
|
| 902 |
def _remote_chgrp(self, paths, group, sudoable=False): |
| 903 |
""" |
| 904 |
Issue a remote chgrp command |
| 905 |
""" |
| 906 |
cmd = self._connection._shell.chgrp(paths, group) |
| 907 |
res = self._low_level_execute_command(cmd, sudoable=sudoable) |
| 908 |
return res |
| 909 |
|
| 910 |
def _remote_set_user_facl(self, paths, user, mode, sudoable=False): |
| 911 |
""" |
| 912 |
Issue a remote call to setfacl |
| 913 |
""" |
| 914 |
cmd = self._connection._shell.set_user_facl(paths, user, mode) |
| 915 |
res = self._low_level_execute_command(cmd, sudoable=sudoable) |
| 916 |
return res |
| 917 |
|
| 918 |
def _execute_remote_stat(self, path, all_vars, follow, tmp=None, checksum=True): |
| 919 |
""" |
| 920 |
Get information from remote file. |
| 921 |
""" |
| 922 |
if tmp is not None: |
| 923 |
display.warning('_execute_remote_stat no longer honors the tmp parameter. Action' |
| 924 |
' plugins should set self._connection._shell.tmpdir to share' |
| 925 |
' the tmpdir') |
| 926 |
del tmp # No longer used |
| 927 |
|
| 928 |
module_args = dict( |
| 929 |
path=path, |
| 930 |
follow=follow, |
| 931 |
get_checksum=checksum, |
| 932 |
get_size=False, # ansible.windows.win_stat added this in 1.11.0 |
| 933 |
checksum_algorithm='sha1', |
| 934 |
) |
| 935 |
# Unknown opts are ignored as module_args could be specific for the |
| 936 |
# module that is being executed. |
| 937 |
mystat = self._execute_module(module_name='ansible.legacy.stat', module_args=module_args, task_vars=all_vars, |
| 938 |
wrap_async=False, ignore_unknown_opts=True) |
| 939 |
|
| 940 |
if mystat.get('failed'): |
| 941 |
msg = mystat.get('module_stderr') |
| 942 |
if not msg: |
| 943 |
msg = mystat.get('module_stdout') |
| 944 |
if not msg: |
| 945 |
msg = mystat.get('msg') |
| 946 |
raise AnsibleError('Failed to get information on remote file (%s): %s' % (path, msg)) |
| 947 |
|
| 948 |
if not mystat['stat']['exists']: |
| 949 |
# empty might be matched, 1 should never match, also backwards compatible |
| 950 |
mystat['stat']['checksum'] = '1' |
| 951 |
|
| 952 |
# happens sometimes when it is a dir and not on bsd |
| 953 |
if 'checksum' not in mystat['stat']: |
| 954 |
mystat['stat']['checksum'] = '' |
| 955 |
elif not isinstance(mystat['stat']['checksum'], str): |
| 956 |
raise AnsibleError("Invalid checksum returned by stat: expected a string type but got %s" % type(mystat['stat']['checksum'])) |
| 957 |
|
| 958 |
return mystat['stat'] |
| 959 |
|
| 960 |
def _remote_expand_user(self, path, sudoable=True, pathsep=None): |
| 961 |
""" takes a remote path and performs tilde/$HOME expansion on the remote host """ |
| 962 |
|
| 963 |
# We only expand ~/path and ~username/path |
| 964 |
if not path.startswith('~'): |
| 965 |
return path |
| 966 |
|
| 967 |
# Per Jborean, we don't have to worry about Windows as we don't have a notion of user's home |
| 968 |
# dir there. |
| 969 |
split_path = path.split(os.path.sep, 1) |
| 970 |
expand_path = split_path[0] |
| 971 |
|
| 972 |
if expand_path == '~': |
| 973 |
# Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host. |
| 974 |
# As such, we want to avoid using remote_user for paths as remote_user may not line up with the local user |
| 975 |
# This is a hack and should be solved by more intelligent handling of remote_tmp in 2.7 |
| 976 |
become_user = self.get_become_option('become_user') |
| 977 |
if getattr(self._connection, '_remote_is_local', False): |
| 978 |
pass |
| 979 |
elif sudoable and self._connection.become and become_user: |
| 980 |
expand_path = '~%s' % become_user |
| 981 |
else: |
| 982 |
# use remote user instead, if none set default to current user |
| 983 |
expand_path = '~%s' % (self._get_remote_user() or '') |
| 984 |
|
| 985 |
# use shell to construct appropriate command and execute |
| 986 |
cmd = None |
| 987 |
in_data = None |
| 988 |
if self._connection.is_pipelining_enabled(wrap_async=False): |
| 989 |
cmd_details = self._connection._shell._expand_user2(expand_path) |
| 990 |
cmd = cmd_details.command |
| 991 |
in_data = cmd_details.input_data |
| 992 |
else: |
| 993 |
cmd = self._connection._shell.expand_user(expand_path) |
| 994 |
data = self._low_level_execute_command(cmd, in_data=in_data, sudoable=False) |
| 995 |
|
| 996 |
try: |
| 997 |
initial_fragment = data['stdout'].strip().splitlines()[-1] |
| 998 |
except IndexError: |
| 999 |
initial_fragment = None |
| 1000 |
|
| 1001 |
if not initial_fragment: |
| 1002 |
# Something went wrong trying to expand the path remotely. Try using pwd, if not, return |
| 1003 |
# the original string |
| 1004 |
cmd = self._connection._shell.pwd() |
| 1005 |
pwd = self._low_level_execute_command(cmd, sudoable=False).get('stdout', '').strip() |
| 1006 |
if pwd: |
| 1007 |
expanded = pwd |
| 1008 |
else: |
| 1009 |
expanded = path |
| 1010 |
|
| 1011 |
elif len(split_path) > 1: |
| 1012 |
expanded = self._connection._shell.join_path(initial_fragment, *split_path[1:]) |
| 1013 |
else: |
| 1014 |
expanded = initial_fragment |
| 1015 |
|
| 1016 |
if '..' in os.path.dirname(expanded).split('/'): |
| 1017 |
raise AnsibleError("'%s' returned an invalid relative home directory path containing '..'" % self._get_remote_addr({})) |
| 1018 |
|
| 1019 |
return expanded |
| 1020 |
|
| 1021 |
def _strip_success_message(self, data): |
| 1022 |
""" |
| 1023 |
Removes the BECOME-SUCCESS message from the data. |
| 1024 |
""" |
| 1025 |
if data.strip().startswith('BECOME-SUCCESS-'): |
| 1026 |
data = re.sub(r'^((\r)?\n)?BECOME-SUCCESS.*(\r)?\n', '', data) |
| 1027 |
return data |
| 1028 |
|
| 1029 |
def _update_module_args(self, module_name, module_args, task_vars, ignore_unknown_opts: bool = False): |
| 1030 |
|
| 1031 |
# set check mode in the module arguments, if required |
| 1032 |
if self._task.check_mode: |
| 1033 |
if not self._supports_check_mode: |
| 1034 |
raise AnsibleError("check mode is not supported for this operation") |
| 1035 |
module_args['_ansible_check_mode'] = True |
| 1036 |
else: |
| 1037 |
module_args['_ansible_check_mode'] = False |
| 1038 |
|
| 1039 |
# set no log in the module arguments, if required |
| 1040 |
no_target_syslog = C.config.get_config_value('DEFAULT_NO_TARGET_SYSLOG', variables=task_vars) |
| 1041 |
module_args['_ansible_no_log'] = self._task.no_log or no_target_syslog |
| 1042 |
|
| 1043 |
# set debug in the module arguments, if required |
| 1044 |
module_args['_ansible_debug'] = C.DEFAULT_DEBUG |
| 1045 |
|
| 1046 |
# let module know we are in diff mode |
| 1047 |
module_args['_ansible_diff'] = self._task.diff |
| 1048 |
|
| 1049 |
# let module know our verbosity |
| 1050 |
module_args['_ansible_verbosity'] = display.verbosity |
| 1051 |
|
| 1052 |
# give the module information about the ansible version |
| 1053 |
module_args['_ansible_version'] = __version__ |
| 1054 |
|
| 1055 |
# give the module information about its name |
| 1056 |
module_args['_ansible_module_name'] = module_name |
| 1057 |
|
| 1058 |
# set the syslog facility to be used in the module |
| 1059 |
module_args['_ansible_syslog_facility'] = task_vars.get('ansible_syslog_facility', C.DEFAULT_SYSLOG_FACILITY) |
| 1060 |
|
| 1061 |
# let module know about filesystems that selinux treats specially |
| 1062 |
module_args['_ansible_selinux_special_fs'] = C.DEFAULT_SELINUX_SPECIAL_FS |
| 1063 |
|
| 1064 |
# give the module the socket for persistent connections |
| 1065 |
module_args['_ansible_socket'] = getattr(self._connection, 'socket_path') |
| 1066 |
if not module_args['_ansible_socket']: |
| 1067 |
module_args['_ansible_socket'] = task_vars.get('ansible_socket') |
| 1068 |
|
| 1069 |
# make sure all commands use the designated shell executable |
| 1070 |
module_args['_ansible_shell_executable'] = self._play_context.executable |
| 1071 |
|
| 1072 |
# make sure modules are aware if they need to keep the remote files |
| 1073 |
module_args['_ansible_keep_remote_files'] = C.DEFAULT_KEEP_REMOTE_FILES |
| 1074 |
|
| 1075 |
# make sure all commands use the designated temporary directory if created |
| 1076 |
if self._is_become_unprivileged(): # force fallback on remote_tmp as user cannot normally write to dir |
| 1077 |
module_args['_ansible_tmpdir'] = None |
| 1078 |
else: |
| 1079 |
module_args['_ansible_tmpdir'] = self._connection._shell.tmpdir |
| 1080 |
|
| 1081 |
# make sure the remote_tmp value is sent through in case modules needs to create their own |
| 1082 |
module_args['_ansible_remote_tmp'] = self.get_shell_option('remote_tmp', default='~/.ansible/tmp') |
| 1083 |
|
| 1084 |
# tells the module to ignore options that are not in its argspec. |
| 1085 |
module_args['_ansible_ignore_unknown_opts'] = ignore_unknown_opts |
| 1086 |
|
| 1087 |
# allow user to insert string to add context to remote logging |
| 1088 |
module_args['_ansible_target_log_info'] = C.config.get_config_value('TARGET_LOG_INFO', variables=task_vars) |
| 1089 |
|
| 1090 |
module_args['_ansible_tracebacks_for'] = _traceback.traceback_for() |
| 1091 |
|
| 1092 |
module_args['_ansible_inject_invocation'] = C.config.get_config_value('INJECT_INVOCATION', variables=task_vars) |
| 1093 |
|
| 1094 |
def _execute_module( |
| 1095 |
self, |
| 1096 |
module_name: str | None = None, |
| 1097 |
module_args: dict[str, object] | None = None, |
| 1098 |
tmp: str | None = None, |
| 1099 |
task_vars: dict[str, object] | None = None, |
| 1100 |
persist_files: bool = False, |
| 1101 |
delete_remote_tmp: bool | None = None, |
| 1102 |
wrap_async: bool = False, |
| 1103 |
ignore_unknown_opts: bool = False, |
| 1104 |
) -> dict[str, object]: |
| 1105 |
""" |
| 1106 |
Transfer and run a module along with its arguments. |
| 1107 |
""" |
| 1108 |
if tmp is not None: |
| 1109 |
display.warning('_execute_module no longer honors the tmp parameter. Action plugins' |
| 1110 |
' should set self._connection._shell.tmpdir to share the tmpdir') |
| 1111 |
del tmp # No longer used |
| 1112 |
if delete_remote_tmp is not None: |
| 1113 |
display.warning('_execute_module no longer honors the delete_remote_tmp parameter.' |
| 1114 |
' Action plugins should check self._connection._shell.tmpdir to' |
| 1115 |
' see if a tmpdir existed before they were called to determine' |
| 1116 |
' if they are responsible for removing it.') |
| 1117 |
del delete_remote_tmp # No longer used |
| 1118 |
|
| 1119 |
tmpdir = self._connection._shell.tmpdir |
| 1120 |
|
| 1121 |
# We set the module_style to new here so the remote_tmp is created |
| 1122 |
# before the module args are built if remote_tmp is needed (async). |
| 1123 |
# If the module_style turns out to not be new and we didn't create the |
| 1124 |
# remote tmp here, it will still be created. This must be done before |
| 1125 |
# calling self._update_module_args() so the module wrapper has the |
| 1126 |
# correct remote_tmp value set. |
| 1127 |
# FUTURE: Async shouldn't be part of a connection's capabilities but |
| 1128 |
# rather part of the module's exec/style caps. The current setup is |
| 1129 |
# hard to achieve this as we need to build the module_args before we |
| 1130 |
# can build the module so we keep this here for now. |
| 1131 |
if not self._is_pipelining_enabled("new", wrap_async) and tmpdir is None: |
| 1132 |
self._make_tmp_path() |
| 1133 |
tmpdir = self._connection._shell.tmpdir |
| 1134 |
|
| 1135 |
if task_vars is None: |
| 1136 |
task_vars = dict() |
| 1137 |
|
| 1138 |
# if a module name was not specified for this execution, use the action from the task |
| 1139 |
if module_name is None: |
| 1140 |
module_name = self._task.action |
| 1141 |
if module_args is None: |
| 1142 |
module_args = self._task.args |
| 1143 |
|
| 1144 |
self._update_module_args(module_name, module_args, task_vars, ignore_unknown_opts=ignore_unknown_opts) |
| 1145 |
|
| 1146 |
remove_async_dir = None |
| 1147 |
if wrap_async or self._task.async_val: |
| 1148 |
async_dir = self.get_shell_option('async_dir', default="~/.ansible_async") |
| 1149 |
remove_async_dir = len(self._task.environment) |
| 1150 |
self._task.environment.append({"ANSIBLE_ASYNC_DIR": async_dir}) |
| 1151 |
|
| 1152 |
# FUTURE: refactor this along with module build process to better encapsulate "smart wrapper" functionality |
| 1153 |
module_bits, module_path = self._configure_module(module_name=module_name, module_args=module_args, task_vars=task_vars) |
| 1154 |
(module_style, module_shebang, module_data) = (module_bits.module_style, module_bits.shebang, module_bits.b_module_data) |
| 1155 |
display.vvv("Using module file %s" % module_path) |
| 1156 |
if not module_shebang and module_style != 'binary': |
| 1157 |
raise AnsibleError("module (%s) is missing interpreter line" % module_name) |
| 1158 |
|
| 1159 |
# If the module payload has async builtin, e.g. pwsh exec_wrapper, then |
| 1160 |
# we can bypass the async_wrapper.py and pipelining checks done for |
| 1161 |
# async as it's treated like a normal module. |
| 1162 |
wrap_async = wrap_async and not module_bits.has_async |
| 1163 |
|
| 1164 |
self._used_interpreter = module_shebang |
| 1165 |
|
| 1166 |
# FUTURE: Instead of module_style we should add "capabilities" to the |
| 1167 |
# module_bits dataclass that indicate things like argument format. |
| 1168 |
# This will reduce the cognitive overload of trying to remember all the |
| 1169 |
# different styles and what they mean. |
| 1170 |
args_file_path = None |
| 1171 |
remote_module_path = None |
| 1172 |
remote_files = [] |
| 1173 |
if not self._is_pipelining_enabled(module_style) or wrap_async: |
| 1174 |
if tmpdir is None: |
| 1175 |
self._make_tmp_path() |
| 1176 |
tmpdir = self._connection._shell.tmpdir |
| 1177 |
|
| 1178 |
remote_files.append(tmpdir) |
| 1179 |
|
| 1180 |
if module_style != 'new': |
| 1181 |
# binary, old, and non_native_want_json module styles use an |
| 1182 |
# args file to store the module arguments. |
| 1183 |
args_file_path = self._connection._shell.join_path(tmpdir, 'args') |
| 1184 |
remote_files.append(args_file_path) |
| 1185 |
|
| 1186 |
remote_module_filename = self._connection._shell.get_remote_filename(module_path) |
| 1187 |
remote_module_path = self._connection._shell.join_path(tmpdir, 'AnsiballZ_%s' % remote_module_filename) |
| 1188 |
remote_files.append(remote_module_path) |
| 1189 |
|
| 1190 |
display.debug("transferring module to remote %s" % remote_module_path) |
| 1191 |
if module_data: |
| 1192 |
# modify_module edited the data in some way, we cannot transfer |
| 1193 |
# from the existing path. |
| 1194 |
self._transfer_data(remote_module_path, module_data) |
| 1195 |
else: |
| 1196 |
self._transfer_file(module_path, remote_module_path) |
| 1197 |
|
| 1198 |
if args_file_path: |
| 1199 |
if module_style == 'old': |
| 1200 |
# we need to dump the module args to a k=v string in a file on |
| 1201 |
# the remote system, which can be read and parsed by the module |
| 1202 |
args_data = "" |
| 1203 |
for k, v in module_args.items(): |
| 1204 |
args_data += '%s=%s ' % (k, shlex.quote(str(v))) |
| 1205 |
self._transfer_data(args_file_path, args_data) |
| 1206 |
else: |
| 1207 |
profile_encoder = get_module_encoder(module_bits.serialization_profile, Direction.CONTROLLER_TO_MODULE) |
| 1208 |
self._transfer_data(args_file_path, json.dumps(module_args, cls=profile_encoder)) |
| 1209 |
|
| 1210 |
display.debug("done transferring module to remote") |
| 1211 |
|
| 1212 |
environment_string = '' |
| 1213 |
if not module_bits.has_environment: |
| 1214 |
environment_string = self._compute_environment_string() |
| 1215 |
|
| 1216 |
# remove the ANSIBLE_ASYNC_DIR env entry if we added a temporary one for |
| 1217 |
# the async_wrapper task. |
| 1218 |
if remove_async_dir is not None: |
| 1219 |
del self._task.environment[remove_async_dir] |
| 1220 |
|
| 1221 |
module_in_data: bytes | None = None |
| 1222 |
module_cmd = '' |
| 1223 |
module_cmd_args: list[str] = [] |
| 1224 |
|
| 1225 |
# FUTURE: If we can deprecated and remove shell.build_module_command() |
| 1226 |
# we can move all this logic into the get_command_args for all module |
| 1227 |
# types rather than it being opt in per exec style. |
| 1228 |
if cmd_args := module_bits.get_command_args(remote_module_path): |
| 1229 |
module_cmd_args, module_in_data = cmd_args |
| 1230 |
|
| 1231 |
else: |
| 1232 |
if remote_module_path: |
| 1233 |
module_cmd_args = [remote_module_path] |
| 1234 |
else: |
| 1235 |
module_in_data = module_data |
| 1236 |
|
| 1237 |
# We still skip build_module_command if using async as that always |
| 1238 |
# built its own command. The async_wrapper expects the full command |
| 1239 |
# to run so we need to add the shebang and args path (if set). |
| 1240 |
if wrap_async: |
| 1241 |
if module_shebang: |
| 1242 |
module_interpreter = module_shebang.replace('#!', '').strip() |
| 1243 |
module_cmd_args.insert(0, module_interpreter) |
| 1244 |
|
| 1245 |
if args_file_path: |
| 1246 |
module_cmd_args.append(args_file_path) |
| 1247 |
|
| 1248 |
else: |
| 1249 |
module_cmd = self._connection._shell.build_module_command( |
| 1250 |
environment_string, |
| 1251 |
module_shebang, |
| 1252 |
" ".join(module_cmd_args), |
| 1253 |
arg_path=args_file_path, |
| 1254 |
).strip() |
| 1255 |
|
| 1256 |
if wrap_async: |
| 1257 |
# configure, upload, and chmod the async_wrapper module |
| 1258 |
(async_module_bits, async_module_path) = self._configure_module(module_name='ansible.legacy.async_wrapper', module_args=dict(), task_vars=task_vars) |
| 1259 |
(async_shebang, async_module_data) = (async_module_bits.shebang, async_module_bits.b_module_data) |
| 1260 |
async_module_remote_filename = self._connection._shell.get_remote_filename(async_module_path) |
| 1261 |
remote_async_module_path = self._connection._shell.join_path(tmpdir, async_module_remote_filename) |
| 1262 |
self._transfer_data(remote_async_module_path, async_module_data) |
| 1263 |
remote_files.append(remote_async_module_path) |
| 1264 |
|
| 1265 |
async_limit = str(self._task.async_val) |
| 1266 |
async_jid = f'j{secrets.randbelow(999999999999)}' |
| 1267 |
|
| 1268 |
# call the interpreter for async_wrapper directly |
| 1269 |
# this permits use of a script for an interpreter on non-Linux platforms |
| 1270 |
interpreter = async_shebang.replace('#!', '').strip() |
| 1271 |
|
| 1272 |
preserve_tmp = str(not self._should_remove_tmp_path(tmpdir)).lower() |
| 1273 |
async_cmd = [interpreter, remote_async_module_path, async_jid, async_limit, preserve_tmp, remote_module_path] |
| 1274 |
async_cmd.extend(module_cmd_args) |
| 1275 |
|
| 1276 |
module_cmd_args = async_cmd |
| 1277 |
|
| 1278 |
if not module_cmd: |
| 1279 |
module_cmd = self._connection._shell.join(module_cmd_args) |
| 1280 |
if environment_string: |
| 1281 |
module_cmd = f"{environment_string} {module_cmd}" |
| 1282 |
|
| 1283 |
# Fix permissions of the tmpdir path and tmpdir files. This should be called after all |
| 1284 |
# files have been transferred. |
| 1285 |
if remote_files: |
| 1286 |
# remove none/empty |
| 1287 |
remote_files = [x for x in remote_files if x] |
| 1288 |
self._fixup_perms2(remote_files, self._get_remote_user()) |
| 1289 |
|
| 1290 |
# actually execute |
| 1291 |
res = self._low_level_execute_command( |
| 1292 |
module_cmd, |
| 1293 |
sudoable=not module_bits.has_become, |
| 1294 |
in_data=module_in_data, |
| 1295 |
process_result=module_bits.process_result, |
| 1296 |
) |
| 1297 |
|
| 1298 |
# parse the main result |
| 1299 |
utr = self._parse_returned_data(res, module_bits.serialization_profile) |
| 1300 |
|
| 1301 |
# NOTE: INTERNAL KEYS ONLY ACCESSIBLE HERE |
| 1302 |
# get internal info before cleaning |
| 1303 |
if utr.suppress_tmpdir_delete: |
| 1304 |
self._cleanup_remote_tmp = False |
| 1305 |
|
| 1306 |
# remove internal keys |
| 1307 |
utr.remove_internal_keys() |
| 1308 |
|
| 1309 |
if wrap_async: |
| 1310 |
# async_wrapper will clean up its tmpdir on its own so we want the controller side to |
| 1311 |
# forget about it now |
| 1312 |
self._connection._shell.tmpdir = None |
| 1313 |
|
| 1314 |
# RPFIX-9: FUTURE: for backward compat (pre-RP), figure out if still makes sense |
| 1315 |
utr.changed = True |
| 1316 |
|
| 1317 |
# propagate interpreter discovery results back to the controller |
| 1318 |
if self._discovered_interpreter_key: |
| 1319 |
utr.set_fact(self._discovered_interpreter_key, self._discovered_interpreter) |
| 1320 |
|
| 1321 |
display.debug("done with _execute_module (%s, %s)" % (module_name, module_args)) |
| 1322 |
return utr.as_result_dict(for_round_trip=True) |
| 1323 |
|
| 1324 |
def _parse_returned_data(self, res: LowLevelExecuteCommandResult, profile: str) -> _task.UnifiedTaskResult: |
| 1325 |
try: |
| 1326 |
filtered_output, warnings = _filter_non_json_lines(res['stdout'], objects_only=True) |
| 1327 |
|
| 1328 |
for w in warnings: |
| 1329 |
display.warning(w) |
| 1330 |
|
| 1331 |
decoder = get_module_decoder(profile, Direction.MODULE_TO_CONTROLLER) |
| 1332 |
|
| 1333 |
data = json.loads(filtered_output, cls=decoder) |
| 1334 |
|
| 1335 |
utr = _task.UnifiedTaskResult.from_module_result_dict(data) |
| 1336 |
utr.ansible_parsed = True # this must occur after normalize_result_exception, since it checks the type of data to ensure it's a dict |
| 1337 |
except ValueError as ex: |
| 1338 |
message = "Module result deserialization failed." |
| 1339 |
help_text = "" |
| 1340 |
include_cause_message = True |
| 1341 |
|
| 1342 |
if self._used_interpreter is not None: |
| 1343 |
interpreter = self._used_interpreter.lstrip('!#') |
| 1344 |
# "not found" case is currently not tested; it was once reproducible |
| 1345 |
# see: https://github.com/ansible/ansible/pull/53534 |
| 1346 |
not_found_err_re = re.compile(rf'{re.escape(interpreter)}: (?:No such file or directory|not found|command not found)') |
| 1347 |
|
| 1348 |
if not_found_err_re.search(res['stderr']) or not_found_err_re.search(res['stdout']): |
| 1349 |
message = f"The module interpreter {interpreter!r} was not found." |
| 1350 |
help_text = 'Consider overriding the configured interpreter path for this host. ' |
| 1351 |
include_cause_message = False # cause context *might* be useful in the traceback, but the JSON deserialization failure message is not |
| 1352 |
|
| 1353 |
try: |
| 1354 |
# Because the underlying action API is built on result dicts instead of exceptions (for all but the most catastrophic failures), |
| 1355 |
# we're using a tweaked version of the module exception handler to get new ErrorDetail-backed errors from this part of the code. |
| 1356 |
# Ideally this would raise immediately on failure, but this would likely break actions that assume `ActionBase._execute_module()` |
| 1357 |
# does not raise on module failure. |
| 1358 |
|
| 1359 |
error = AnsibleError( |
| 1360 |
message=message, |
| 1361 |
help_text=help_text + "See stdout/stderr for the returned output.", |
| 1362 |
) |
| 1363 |
|
| 1364 |
error._include_cause_message = include_cause_message |
| 1365 |
|
| 1366 |
raise error from ex |
| 1367 |
except AnsibleError as ansible_ex: |
| 1368 |
utr = _task.UnifiedTaskResult.create_from_module_exception(ansible_ex) |
| 1369 |
utr.ansible_parsed = False |
| 1370 |
utr.module_stdout = res['stdout'] |
| 1371 |
utr.module_stderr = res['stderr'] |
| 1372 |
utr.rc = res['rc'] |
| 1373 |
|
| 1374 |
return utr |
| 1375 |
|
| 1376 |
# FIXME: move to connection base |
| 1377 |
def _low_level_execute_command( |
| 1378 |
self, |
| 1379 |
cmd: str, |
| 1380 |
sudoable: bool = True, |
| 1381 |
in_data: bytes | None = None, |
| 1382 |
executable: str | None = None, |
| 1383 |
encoding_errors: str = 'surrogate_then_replace', |
| 1384 |
chdir: str | None = None, |
| 1385 |
process_result: Callable[[int, bytes, bytes], tuple[int, bytes, bytes]] | None = None, |
| 1386 |
) -> LowLevelExecuteCommandResult: |
| 1387 |
""" |
| 1388 |
This is the function which executes the low level shell command, which |
| 1389 |
may be commands to create/remove directories for temporary files, or to |
| 1390 |
run the module code or python directly when pipelining. |
| 1391 |
|
| 1392 |
:kwarg encoding_errors: If the value returned by the command isn't |
| 1393 |
utf-8 then we have to figure out how to transform it to unicode. |
| 1394 |
If the value is just going to be displayed to the user (or |
| 1395 |
discarded) then the default of 'replace' is fine. If the data is |
| 1396 |
used as a key or is going to be written back out to a file |
| 1397 |
verbatim, then this won't work. May have to use some sort of |
| 1398 |
replacement strategy (python3 could use surrogateescape) |
| 1399 |
:kwarg chdir: cd into this directory before executing the command. |
| 1400 |
""" |
| 1401 |
|
| 1402 |
display.debug("_low_level_execute_command(): starting") |
| 1403 |
# if not cmd: |
| 1404 |
# # this can happen with powershell modules when there is no analog to a Windows command (like chmod) |
| 1405 |
# display.debug("_low_level_execute_command(): no command, exiting") |
| 1406 |
# return dict(stdout='', stderr='', rc=254) |
| 1407 |
|
| 1408 |
if chdir: |
| 1409 |
display.debug("_low_level_execute_command(): changing cwd to %s for this command" % chdir) |
| 1410 |
cmd = self._connection._shell.append_command('cd %s' % chdir, cmd) |
| 1411 |
|
| 1412 |
# https://github.com/ansible/ansible/issues/68054 |
| 1413 |
if executable: |
| 1414 |
self._connection._shell.executable = executable |
| 1415 |
|
| 1416 |
ruser = self._get_remote_user() |
| 1417 |
buser = self.get_become_option('become_user') |
| 1418 |
if (sudoable and self._connection.become and # if sudoable and have become |
| 1419 |
resource_from_fqcr(self._connection.transport) != 'network_cli' and # if not using network_cli |
| 1420 |
(C.BECOME_ALLOW_SAME_USER or (buser != ruser or not any((ruser, buser))))): # if we allow same user PE or users are different and either is set |
| 1421 |
display.debug("_low_level_execute_command(): using become for this command") |
| 1422 |
cmd = self._connection.become.build_become_command(cmd, self._connection._shell) |
| 1423 |
|
| 1424 |
if self._connection.allow_executable: |
| 1425 |
if executable is None: |
| 1426 |
executable = self._play_context.executable |
| 1427 |
if executable: |
| 1428 |
cmd = executable + ' -c ' + shlex.quote(cmd) |
| 1429 |
|
| 1430 |
display.debug("_low_level_execute_command(): executing: %s" % (cmd,)) |
| 1431 |
|
| 1432 |
# Change directory to basedir of task for command execution when connection is local |
| 1433 |
if self._connection.transport == 'local': |
| 1434 |
self._connection.cwd = self._loader.get_basedir() |
| 1435 |
|
| 1436 |
rc, stdout, stderr = self._connection.exec_command(cmd, in_data=in_data, sudoable=sudoable) |
| 1437 |
|
| 1438 |
if process_result: |
| 1439 |
rc, stdout, stderr = process_result(rc, stdout, stderr) |
| 1440 |
|
| 1441 |
# stdout and stderr may be either a file-like or a bytes object. |
| 1442 |
# Convert either one to a text type |
| 1443 |
if isinstance(stdout, bytes): |
| 1444 |
out = to_text(stdout, errors=encoding_errors) |
| 1445 |
elif not isinstance(stdout, str): |
| 1446 |
out = to_text(b''.join(stdout.readlines()), errors=encoding_errors) |
| 1447 |
else: |
| 1448 |
out = stdout |
| 1449 |
|
| 1450 |
if isinstance(stderr, bytes): |
| 1451 |
err = to_text(stderr, errors=encoding_errors) |
| 1452 |
elif not isinstance(stderr, str): |
| 1453 |
err = to_text(b''.join(stderr.readlines()), errors=encoding_errors) |
| 1454 |
else: |
| 1455 |
err = stderr |
| 1456 |
|
| 1457 |
if rc is None: |
| 1458 |
rc = 0 |
| 1459 |
|
| 1460 |
# be sure to remove the BECOME-SUCCESS message now |
| 1461 |
out = self._strip_success_message(out) |
| 1462 |
|
| 1463 |
# Known limitation: under ANSIBLE_DEBUG the raw output is shown before any secrets in module output have been |
| 1464 |
# registered with the secret masker (that happens when the result is parsed), so they may be shown in plaintext. |
| 1465 |
display.debug(u"_low_level_execute_command() done: rc=%d, stdout=%s, stderr=%s" % (rc, out, err)) |
| 1466 |
return dict(rc=rc, stdout=out, stdout_lines=out.splitlines(), stderr=err, stderr_lines=err.splitlines()) |
| 1467 |
|
| 1468 |
def _get_diff_data(self, destination, source, task_vars, content=None, source_file=True): |
| 1469 |
|
| 1470 |
# Note: Since we do not diff the source and destination before we transform from bytes into |
| 1471 |
# text the diff between source and destination may not be accurate. To fix this, we'd need |
| 1472 |
# to move the diffing from the callback plugins into here. |
| 1473 |
# |
| 1474 |
# Example of data which would cause trouble is src_content == b'\xff' and dest_content == |
| 1475 |
# b'\xfe'. Neither of those are valid utf-8 so both get turned into the replacement |
| 1476 |
# character: diff['before'] = u'�' ; diff['after'] = u'�' When the callback plugin later |
| 1477 |
# diffs before and after it shows an empty diff. |
| 1478 |
|
| 1479 |
diff = {} |
| 1480 |
display.debug("Going to peek to see if file has changed permissions") |
| 1481 |
peek_result = self._execute_module( |
| 1482 |
module_name='ansible.legacy.file', module_args=dict(path=destination, _diff_peek=True), |
| 1483 |
task_vars=task_vars, persist_files=True) |
| 1484 |
|
| 1485 |
if peek_result.get('failed', False): |
| 1486 |
display.warning(u"Failed to get diff between '%s' and '%s': %s" % (os.path.basename(source), destination, to_text(peek_result.get(u'msg', u'')))) |
| 1487 |
return diff |
| 1488 |
|
| 1489 |
if peek_result.get('rc', 0) == 0: |
| 1490 |
|
| 1491 |
if peek_result.get('state') in (None, 'absent'): |
| 1492 |
diff['before'] = u'' |
| 1493 |
elif peek_result.get('appears_binary'): |
| 1494 |
diff['dst_binary'] = 1 |
| 1495 |
elif peek_result.get('size') and C.MAX_FILE_SIZE_FOR_DIFF > 0 and peek_result['size'] > C.MAX_FILE_SIZE_FOR_DIFF: |
| 1496 |
diff['dst_larger'] = C.MAX_FILE_SIZE_FOR_DIFF |
| 1497 |
else: |
| 1498 |
display.debug(u"Slurping the file %s" % destination) |
| 1499 |
dest_result = self._execute_module( |
| 1500 |
module_name='ansible.legacy.slurp', module_args=dict(path=destination), |
| 1501 |
task_vars=task_vars, persist_files=True) |
| 1502 |
if 'content' in dest_result: |
| 1503 |
dest_contents = dest_result['content'] |
| 1504 |
if dest_result['encoding'] == u'base64': |
| 1505 |
dest_contents = base64.b64decode(dest_contents) |
| 1506 |
else: |
| 1507 |
raise AnsibleError("unknown encoding in content option, failed: %s" % to_native(dest_result)) |
| 1508 |
diff['before_header'] = destination |
| 1509 |
diff['before'] = to_text(dest_contents) |
| 1510 |
|
| 1511 |
if source_file: |
| 1512 |
st = os.stat(source) |
| 1513 |
if C.MAX_FILE_SIZE_FOR_DIFF > 0 and st[stat.ST_SIZE] > C.MAX_FILE_SIZE_FOR_DIFF: |
| 1514 |
diff['src_larger'] = C.MAX_FILE_SIZE_FOR_DIFF |
| 1515 |
else: |
| 1516 |
display.debug("Reading local copy of the file %s" % source) |
| 1517 |
try: |
| 1518 |
with open(source, 'rb') as src: |
| 1519 |
src_contents = src.read() |
| 1520 |
except Exception as e: |
| 1521 |
raise AnsibleError("Unexpected error while reading source (%s) for diff: %s " % (source, to_native(e))) |
| 1522 |
|
| 1523 |
if b"\x00" in src_contents: |
| 1524 |
diff['src_binary'] = 1 |
| 1525 |
else: |
| 1526 |
if content: |
| 1527 |
diff['after_header'] = destination |
| 1528 |
else: |
| 1529 |
diff['after_header'] = source |
| 1530 |
diff['after'] = to_text(src_contents) |
| 1531 |
else: |
| 1532 |
display.debug(u"source of file passed in") |
| 1533 |
diff['after_header'] = u'dynamically generated' |
| 1534 |
diff['after'] = source |
| 1535 |
|
| 1536 |
if self._task.no_log: |
| 1537 |
if 'before' in diff: |
| 1538 |
diff["before"] = u"" |
| 1539 |
if 'after' in diff: |
| 1540 |
diff["after"] = u" [[ Diff output has been hidden because 'no_log: true' was specified for this result ]]\n" |
| 1541 |
|
| 1542 |
return diff |
| 1543 |
|
| 1544 |
def _find_needle(self, dirname, needle): |
| 1545 |
""" |
| 1546 |
find a needle in haystack of paths, optionally using 'dirname' as a subdir. |
| 1547 |
This will build the ordered list of paths to search and pass them to dwim |
| 1548 |
to get back the first existing file found. |
| 1549 |
""" |
| 1550 |
|
| 1551 |
# dwim already deals with playbook basedirs |
| 1552 |
path_stack = self._task.get_search_path() |
| 1553 |
|
| 1554 |
# if missing it will return a file not found exception |
| 1555 |
return self._loader.path_dwim_relative_stack(path_stack, dirname, needle) |