| 1 |
# Copyright (c) 2019-2020, Felix Fontein <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
author: |
| 9 |
- Felix Fontein (@felixfontein) |
| 10 |
name: docker_api |
| 11 |
short_description: Run tasks in docker containers |
| 12 |
version_added: 1.1.0 |
| 13 |
description: |
| 14 |
- Run commands or put/fetch files to an existing docker container. |
| 15 |
- Uses the L(requests library,https://pypi.org/project/requests/) to interact directly with the Docker daemon instead of |
| 16 |
using the Docker CLI. Use the P(community.docker.docker#connection) connection plugin if you want to use the Docker CLI. |
| 17 |
notes: |
| 18 |
- Does B(not work with TCP TLS sockets)! This is caused by the inability to send C(close_notify) without closing the connection |
| 19 |
with Python's C(SSLSocket)s. See U(https://github.com/ansible-collections/community.docker/issues/605) for more information. |
| 20 |
extends_documentation_fragment: |
| 21 |
- community.docker._docker.api_documentation |
| 22 |
- community.docker._docker.var_names |
| 23 |
options: |
| 24 |
remote_user: |
| 25 |
type: str |
| 26 |
description: |
| 27 |
- The user to execute as inside the container. |
| 28 |
vars: |
| 29 |
- name: ansible_user |
| 30 |
- name: ansible_docker_user |
| 31 |
ini: |
| 32 |
- section: defaults |
| 33 |
key: remote_user |
| 34 |
env: |
| 35 |
- name: ANSIBLE_REMOTE_USER |
| 36 |
cli: |
| 37 |
- name: user |
| 38 |
keyword: |
| 39 |
- name: remote_user |
| 40 |
remote_addr: |
| 41 |
type: str |
| 42 |
description: |
| 43 |
- The name of the container you want to access. |
| 44 |
default: inventory_hostname |
| 45 |
vars: |
| 46 |
- name: inventory_hostname |
| 47 |
- name: ansible_host |
| 48 |
- name: ansible_docker_host |
| 49 |
container_timeout: |
| 50 |
default: 10 |
| 51 |
description: |
| 52 |
- Controls how long we can wait to access reading output from the container once execution started. |
| 53 |
env: |
| 54 |
- name: ANSIBLE_TIMEOUT |
| 55 |
- name: ANSIBLE_DOCKER_TIMEOUT |
| 56 |
version_added: 2.2.0 |
| 57 |
ini: |
| 58 |
- key: timeout |
| 59 |
section: defaults |
| 60 |
- key: timeout |
| 61 |
section: docker_connection |
| 62 |
version_added: 2.2.0 |
| 63 |
vars: |
| 64 |
- name: ansible_docker_timeout |
| 65 |
version_added: 2.2.0 |
| 66 |
cli: |
| 67 |
- name: timeout |
| 68 |
type: integer |
| 69 |
extra_env: |
| 70 |
description: |
| 71 |
- Provide extra environment variables to set when running commands in the Docker container. |
| 72 |
- This option can currently only be provided as Ansible variables due to limitations of ansible-core's configuration |
| 73 |
manager. |
| 74 |
vars: |
| 75 |
- name: ansible_docker_extra_env |
| 76 |
type: dict |
| 77 |
version_added: 3.12.0 |
| 78 |
working_dir: |
| 79 |
description: |
| 80 |
- The directory inside the container to run commands in. |
| 81 |
- Requires Docker API version 1.35 or later. |
| 82 |
env: |
| 83 |
- name: ANSIBLE_DOCKER_WORKING_DIR |
| 84 |
ini: |
| 85 |
- key: working_dir |
| 86 |
section: docker_connection |
| 87 |
vars: |
| 88 |
- name: ansible_docker_working_dir |
| 89 |
type: string |
| 90 |
version_added: 3.12.0 |
| 91 |
privileged: |
| 92 |
description: |
| 93 |
- Whether commands should be run with extended privileges. |
| 94 |
- B(Note) that this allows command to potentially break out of the container. Use with care! |
| 95 |
env: |
| 96 |
- name: ANSIBLE_DOCKER_PRIVILEGED |
| 97 |
ini: |
| 98 |
- key: privileged |
| 99 |
section: docker_connection |
| 100 |
vars: |
| 101 |
- name: ansible_docker_privileged |
| 102 |
type: boolean |
| 103 |
default: false |
| 104 |
version_added: 3.12.0 |
| 105 |
""" |
| 106 |
|
| 107 |
import os |
| 108 |
import os.path |
| 109 |
import typing as t |
| 110 |
|
| 111 |
from ansible.errors import AnsibleConnectionFailure, AnsibleFileNotFound |
| 112 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 113 |
from ansible.plugins.connection import ConnectionBase |
| 114 |
from ansible.utils.display import Display |
| 115 |
|
| 116 |
from ansible_collections.community.docker.plugins.module_utils._api.errors import ( |
| 117 |
APIError, |
| 118 |
DockerException, |
| 119 |
NotFound, |
| 120 |
) |
| 121 |
from ansible_collections.community.docker.plugins.module_utils._common_api import ( |
| 122 |
RequestException, |
| 123 |
) |
| 124 |
from ansible_collections.community.docker.plugins.module_utils._copy import ( |
| 125 |
DockerFileCopyError, |
| 126 |
DockerFileNotFound, |
| 127 |
fetch_file, |
| 128 |
put_file, |
| 129 |
) |
| 130 |
from ansible_collections.community.docker.plugins.module_utils._version import ( |
| 131 |
LooseVersion, |
| 132 |
) |
| 133 |
from ansible_collections.community.docker.plugins.plugin_utils._common_api import ( |
| 134 |
AnsibleDockerClient, |
| 135 |
) |
| 136 |
from ansible_collections.community.docker.plugins.plugin_utils._socket_handler import ( |
| 137 |
DockerSocketHandler, |
| 138 |
) |
| 139 |
|
| 140 |
if t.TYPE_CHECKING: |
| 141 |
from collections.abc import Callable |
| 142 |
|
| 143 |
_T = t.TypeVar("_T") |
| 144 |
|
| 145 |
|
| 146 |
MIN_DOCKER_API = None |
| 147 |
|
| 148 |
|
| 149 |
display = Display() |
| 150 |
|
| 151 |
|
| 152 |
class Connection(ConnectionBase): |
| 153 |
"""Local docker based connections""" |
| 154 |
|
| 155 |
transport = "community.docker.docker_api" |
| 156 |
has_pipelining = True |
| 157 |
|
| 158 |
def _call_client( |
| 159 |
self, |
| 160 |
f: Callable[[AnsibleDockerClient], _T], |
| 161 |
not_found_can_be_resource: bool = False, |
| 162 |
) -> _T: |
| 163 |
if self.client is None: |
| 164 |
raise AssertionError("Client must be present") |
| 165 |
remote_addr = self.get_option("remote_addr") |
| 166 |
try: |
| 167 |
return f(self.client) |
| 168 |
except NotFound as e: |
| 169 |
if not_found_can_be_resource: |
| 170 |
raise AnsibleConnectionFailure( |
| 171 |
f'Could not find container "{remote_addr}" or resource in it ({e})' |
| 172 |
) from e |
| 173 |
raise AnsibleConnectionFailure( |
| 174 |
f'Could not find container "{remote_addr}" ({e})' |
| 175 |
) from e |
| 176 |
except APIError as e: |
| 177 |
if e.response is not None and e.response.status_code == 409: |
| 178 |
raise AnsibleConnectionFailure( |
| 179 |
f'The container "{remote_addr}" has been paused ({e})' |
| 180 |
) from e |
| 181 |
self.client.fail( |
| 182 |
f'An unexpected Docker error occurred for container "{remote_addr}": {e}' |
| 183 |
) |
| 184 |
except DockerException as e: |
| 185 |
self.client.fail( |
| 186 |
f'An unexpected Docker error occurred for container "{remote_addr}": {e}' |
| 187 |
) |
| 188 |
except RequestException as e: |
| 189 |
self.client.fail( |
| 190 |
f'An unexpected requests error occurred for container "{remote_addr}" when trying to talk to the Docker daemon: {e}' |
| 191 |
) |
| 192 |
|
| 193 |
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: |
| 194 |
super().__init__(*args, **kwargs) |
| 195 |
|
| 196 |
self.client: AnsibleDockerClient | None = None |
| 197 |
self.ids: dict[str | None, tuple[int, int]] = {} |
| 198 |
|
| 199 |
# Windows uses Powershell modules |
| 200 |
if getattr(self._shell, "_IS_WINDOWS", False): |
| 201 |
self.module_implementation_preferences = (".ps1", ".exe", "") |
| 202 |
|
| 203 |
self.actual_user: str | None = None |
| 204 |
|
| 205 |
def _connect(self) -> Connection: |
| 206 |
"""Connect to the container. Nothing to do""" |
| 207 |
super()._connect() # type: ignore[safe-super] |
| 208 |
if not self._connected: |
| 209 |
self.actual_user = self.get_option("remote_user") |
| 210 |
display.vvv( |
| 211 |
f"ESTABLISH DOCKER CONNECTION FOR USER: {self.actual_user or '?'}", |
| 212 |
host=self.get_option("remote_addr"), |
| 213 |
) |
| 214 |
if self.client is None: |
| 215 |
self.client = AnsibleDockerClient( |
| 216 |
self, min_docker_api_version=MIN_DOCKER_API |
| 217 |
) |
| 218 |
self._connected = True |
| 219 |
|
| 220 |
if self.actual_user is None and display.verbosity > 2: |
| 221 |
# Since we are not setting the actual_user, look it up so we have it for logging later |
| 222 |
# Only do this if display verbosity is high enough that we'll need the value |
| 223 |
# This saves overhead from calling into docker when we do not need to |
| 224 |
display.vvv("Trying to determine actual user") |
| 225 |
result = self._call_client( |
| 226 |
lambda client: client.get_json( |
| 227 |
"/containers/{0}/json", self.get_option("remote_addr") |
| 228 |
) |
| 229 |
) |
| 230 |
if result.get("Config"): |
| 231 |
self.actual_user = result["Config"].get("User") |
| 232 |
if self.actual_user is not None: |
| 233 |
display.vvv(f"Actual user is '{self.actual_user}'") |
| 234 |
|
| 235 |
return self |
| 236 |
|
| 237 |
def exec_command( |
| 238 |
self, cmd: str, in_data: bytes | None = None, sudoable: bool = False |
| 239 |
) -> tuple[int, bytes, bytes]: |
| 240 |
"""Run a command on the docker host""" |
| 241 |
|
| 242 |
super().exec_command(cmd, in_data=in_data, sudoable=sudoable) # type: ignore[safe-super] |
| 243 |
|
| 244 |
if self.client is None: |
| 245 |
raise AssertionError("Client must be present") |
| 246 |
|
| 247 |
command = [self._play_context.executable, "-c", cmd] |
| 248 |
|
| 249 |
do_become = self.become and self.become.expect_prompt() and sudoable |
| 250 |
|
| 251 |
stdin_part = ( |
| 252 |
f", with stdin ({len(in_data)} bytes)" if in_data is not None else "" |
| 253 |
) |
| 254 |
become_part = ", with become prompt" if do_become else "" |
| 255 |
display.vvv( |
| 256 |
f"EXEC {to_text(command)}{stdin_part}{become_part}", |
| 257 |
host=self.get_option("remote_addr"), |
| 258 |
) |
| 259 |
|
| 260 |
need_stdin = bool((in_data is not None) or do_become) |
| 261 |
|
| 262 |
data = { |
| 263 |
"Container": self.get_option("remote_addr"), |
| 264 |
"User": self.get_option("remote_user") or "", |
| 265 |
"Privileged": self.get_option("privileged"), |
| 266 |
"Tty": False, |
| 267 |
"AttachStdin": need_stdin, |
| 268 |
"AttachStdout": True, |
| 269 |
"AttachStderr": True, |
| 270 |
"Cmd": command, |
| 271 |
} |
| 272 |
|
| 273 |
if "detachKeys" in self.client._general_configs: |
| 274 |
data["detachKeys"] = self.client._general_configs["detachKeys"] |
| 275 |
|
| 276 |
if self.get_option("extra_env"): |
| 277 |
data["Env"] = [] |
| 278 |
for k, v in self.get_option("extra_env").items(): |
| 279 |
for val, what in ((k, "Key"), (v, "Value")): |
| 280 |
if not isinstance(val, str): |
| 281 |
raise AnsibleConnectionFailure( |
| 282 |
f"Non-string {what.lower()} found for extra_env option. Ambiguous env options must be " |
| 283 |
"wrapped in quotes to avoid them being interpreted when directly specified " |
| 284 |
"in YAML, or explicitly converted to strings when the option is templated. " |
| 285 |
f"{what}: {val!r}" |
| 286 |
) |
| 287 |
data["Env"].append(f"{k}={v}") |
| 288 |
|
| 289 |
if self.get_option("working_dir") is not None: |
| 290 |
data["WorkingDir"] = self.get_option("working_dir") |
| 291 |
if self.client.docker_api_version < LooseVersion("1.35"): |
| 292 |
raise AnsibleConnectionFailure( |
| 293 |
"Providing the working directory requires Docker API version 1.35 or newer." |
| 294 |
f" The Docker daemon the connection is using has API version {self.client.docker_api_version_str}." |
| 295 |
) |
| 296 |
|
| 297 |
exec_data = self._call_client( |
| 298 |
lambda client: client.post_json_to_json( |
| 299 |
"/containers/{0}/exec", self.get_option("remote_addr"), data=data |
| 300 |
) |
| 301 |
) |
| 302 |
exec_id = exec_data["Id"] |
| 303 |
|
| 304 |
data = {"Tty": False, "Detach": False} |
| 305 |
if need_stdin: |
| 306 |
exec_socket = self._call_client( |
| 307 |
lambda client: client.post_json_to_stream_socket( |
| 308 |
"/exec/{0}/start", exec_id, data=data |
| 309 |
) |
| 310 |
) |
| 311 |
try: |
| 312 |
with DockerSocketHandler( |
| 313 |
display, exec_socket, container=self.get_option("remote_addr") |
| 314 |
) as exec_socket_handler: |
| 315 |
if do_become: |
| 316 |
assert self.become is not None |
| 317 |
|
| 318 |
become_output = [b""] |
| 319 |
|
| 320 |
def append_become_output(stream_id: int, data: bytes) -> None: |
| 321 |
become_output[0] += data |
| 322 |
|
| 323 |
exec_socket_handler.set_block_done_callback( |
| 324 |
append_become_output |
| 325 |
) |
| 326 |
|
| 327 |
while not self.become.check_success( |
| 328 |
become_output[0] |
| 329 |
) and not self.become.check_password_prompt(become_output[0]): |
| 330 |
if not exec_socket_handler.select( |
| 331 |
self.get_option("container_timeout") |
| 332 |
): |
| 333 |
stdout, stderr = exec_socket_handler.consume() |
| 334 |
raise AnsibleConnectionFailure( |
| 335 |
"timeout waiting for privilege escalation password prompt:\n" |
| 336 |
+ to_text(become_output[0]) |
| 337 |
) |
| 338 |
|
| 339 |
if exec_socket_handler.is_eof(): |
| 340 |
raise AnsibleConnectionFailure( |
| 341 |
"privilege output closed while waiting for password prompt:\n" |
| 342 |
+ to_text(become_output[0]) |
| 343 |
) |
| 344 |
|
| 345 |
if not self.become.check_success(become_output[0]): |
| 346 |
become_pass = self.become.get_option( |
| 347 |
"become_pass", playcontext=self._play_context |
| 348 |
) |
| 349 |
exec_socket_handler.write( |
| 350 |
to_bytes(become_pass, errors="surrogate_or_strict") |
| 351 |
+ b"\n" |
| 352 |
) |
| 353 |
|
| 354 |
if in_data is not None: |
| 355 |
exec_socket_handler.write(in_data) |
| 356 |
|
| 357 |
stdout, stderr = exec_socket_handler.consume() |
| 358 |
finally: |
| 359 |
exec_socket.close() |
| 360 |
else: |
| 361 |
stdout, stderr = self._call_client( |
| 362 |
lambda client: client.post_json_to_stream( |
| 363 |
"/exec/{0}/start", |
| 364 |
exec_id, |
| 365 |
stream=False, |
| 366 |
demux=True, |
| 367 |
tty=False, |
| 368 |
data=data, |
| 369 |
) |
| 370 |
) |
| 371 |
|
| 372 |
result = self._call_client( |
| 373 |
lambda client: client.get_json("/exec/{0}/json", exec_id) |
| 374 |
) |
| 375 |
|
| 376 |
return result.get("ExitCode") or 0, stdout or b"", stderr or b"" |
| 377 |
|
| 378 |
def _prefix_login_path(self, remote_path: str) -> str: |
| 379 |
"""Make sure that we put files into a standard path |
| 380 |
|
| 381 |
If a path is relative, then we need to choose where to put it. |
| 382 |
ssh chooses $HOME but we are not guaranteed that a home dir will |
| 383 |
exist in any given chroot. So for now we are choosing "/" instead. |
| 384 |
This also happens to be the former default. |
| 385 |
|
| 386 |
Can revisit using $HOME instead if it is a problem |
| 387 |
""" |
| 388 |
if getattr(self._shell, "_IS_WINDOWS", False): |
| 389 |
import ntpath |
| 390 |
|
| 391 |
return ntpath.normpath(remote_path) |
| 392 |
if not remote_path.startswith(os.path.sep): |
| 393 |
remote_path = os.path.join(os.path.sep, remote_path) |
| 394 |
return os.path.normpath(remote_path) |
| 395 |
|
| 396 |
def put_file(self, in_path: str, out_path: str) -> None: |
| 397 |
"""Transfer a file from local to docker container""" |
| 398 |
super().put_file(in_path, out_path) # type: ignore[safe-super] |
| 399 |
display.vvv(f"PUT {in_path} TO {out_path}", host=self.get_option("remote_addr")) |
| 400 |
|
| 401 |
if self.client is None: |
| 402 |
raise AssertionError("Client must be present") |
| 403 |
|
| 404 |
out_path = self._prefix_login_path(out_path) |
| 405 |
|
| 406 |
if self.actual_user not in self.ids: |
| 407 |
dummy, ids, dummy2 = self.exec_command("id -u && id -g") |
| 408 |
remote_addr = self.get_option("remote_addr") |
| 409 |
try: |
| 410 |
b_user_id, b_group_id = ids.splitlines() |
| 411 |
user_id, group_id = int(b_user_id), int(b_group_id) |
| 412 |
self.ids[self.actual_user] = user_id, group_id |
| 413 |
display.vvvv( |
| 414 |
f'PUT: Determined uid={user_id} and gid={group_id} for user "{self.actual_user}"', |
| 415 |
host=remote_addr, |
| 416 |
) |
| 417 |
except Exception as e: |
| 418 |
raise AnsibleConnectionFailure( |
| 419 |
f'Error while determining user and group ID of current user in container "{remote_addr}": {e}\nGot value: {ids!r}' |
| 420 |
) from e |
| 421 |
|
| 422 |
user_id, group_id = self.ids[self.actual_user] |
| 423 |
try: |
| 424 |
self._call_client( |
| 425 |
lambda client: put_file( |
| 426 |
client, |
| 427 |
container=self.get_option("remote_addr"), |
| 428 |
in_path=in_path, |
| 429 |
out_path=out_path, |
| 430 |
user_id=user_id, |
| 431 |
group_id=group_id, |
| 432 |
user_name=self.actual_user, |
| 433 |
follow_links=True, |
| 434 |
), |
| 435 |
not_found_can_be_resource=True, |
| 436 |
) |
| 437 |
except DockerFileNotFound as exc: |
| 438 |
raise AnsibleFileNotFound(to_text(exc)) from exc |
| 439 |
except DockerFileCopyError as exc: |
| 440 |
raise AnsibleConnectionFailure(to_text(exc)) from exc |
| 441 |
|
| 442 |
def fetch_file(self, in_path: str, out_path: str) -> None: |
| 443 |
"""Fetch a file from container to local.""" |
| 444 |
super().fetch_file(in_path, out_path) # type: ignore[safe-super] |
| 445 |
display.vvv( |
| 446 |
f"FETCH {in_path} TO {out_path}", host=self.get_option("remote_addr") |
| 447 |
) |
| 448 |
|
| 449 |
if self.client is None: |
| 450 |
raise AssertionError("Client must be present") |
| 451 |
|
| 452 |
in_path = self._prefix_login_path(in_path) |
| 453 |
|
| 454 |
try: |
| 455 |
self._call_client( |
| 456 |
lambda client: fetch_file( |
| 457 |
client, |
| 458 |
container=self.get_option("remote_addr"), |
| 459 |
in_path=in_path, |
| 460 |
out_path=out_path, |
| 461 |
follow_links=True, |
| 462 |
log=lambda msg: display.vvvv( |
| 463 |
msg, host=self.get_option("remote_addr") |
| 464 |
), |
| 465 |
), |
| 466 |
not_found_can_be_resource=True, |
| 467 |
) |
| 468 |
except DockerFileNotFound as exc: |
| 469 |
raise AnsibleFileNotFound(to_text(exc)) from exc |
| 470 |
except DockerFileCopyError as exc: |
| 471 |
raise AnsibleConnectionFailure(to_text(exc)) from exc |
| 472 |
|
| 473 |
def close(self) -> None: |
| 474 |
"""Terminate the connection. Nothing to do for Docker""" |
| 475 |
super().close() # type: ignore[safe-super] |
| 476 |
self._connected = False |
| 477 |
|
| 478 |
def reset(self) -> None: |
| 479 |
self.ids.clear() |