| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2021, Felix Fontein <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: docker_container_exec |
| 11 |
|
| 12 |
short_description: Execute command in a docker container |
| 13 |
|
| 14 |
version_added: 1.5.0 |
| 15 |
|
| 16 |
description: |
| 17 |
- Executes a command in a Docker container. |
| 18 |
extends_documentation_fragment: |
| 19 |
- community.docker._docker.api_documentation |
| 20 |
- community.docker._attributes |
| 21 |
- community.docker._attributes.actiongroup_docker |
| 22 |
|
| 23 |
attributes: |
| 24 |
check_mode: |
| 25 |
support: none |
| 26 |
diff_mode: |
| 27 |
support: none |
| 28 |
idempotent: |
| 29 |
support: N/A |
| 30 |
details: |
| 31 |
- Whether the executed command is idempotent depends on the command. |
| 32 |
|
| 33 |
options: |
| 34 |
container: |
| 35 |
type: str |
| 36 |
required: true |
| 37 |
description: |
| 38 |
- The name of the container to execute the command in. |
| 39 |
argv: |
| 40 |
type: list |
| 41 |
elements: str |
| 42 |
description: |
| 43 |
- The command to execute. |
| 44 |
- Since this is a list of arguments, no quoting is needed. |
| 45 |
- Exactly one of O(argv) or O(command) must be specified. |
| 46 |
command: |
| 47 |
type: str |
| 48 |
description: |
| 49 |
- The command to execute. |
| 50 |
- Exactly one of O(argv) or O(command) must be specified. |
| 51 |
chdir: |
| 52 |
type: str |
| 53 |
description: |
| 54 |
- The directory to run the command in. |
| 55 |
detach: |
| 56 |
description: |
| 57 |
- Whether to run the command synchronously (O(detach=false), default) or asynchronously (O(detach=true)). |
| 58 |
- If set to V(true), O(stdin) cannot be provided, and the return values RV(stdout), RV(stderr), and RV(rc) are not returned. |
| 59 |
type: bool |
| 60 |
default: false |
| 61 |
version_added: 2.1.0 |
| 62 |
user: |
| 63 |
type: str |
| 64 |
description: |
| 65 |
- If specified, the user to execute this command with. |
| 66 |
stdin: |
| 67 |
type: str |
| 68 |
description: |
| 69 |
- Set the stdin of the command directly to the specified value. |
| 70 |
- Can only be used if O(detach=false). |
| 71 |
stdin_add_newline: |
| 72 |
type: bool |
| 73 |
default: true |
| 74 |
description: |
| 75 |
- If set to V(true), appends a newline to O(stdin). |
| 76 |
strip_empty_ends: |
| 77 |
type: bool |
| 78 |
default: true |
| 79 |
description: |
| 80 |
- Strip empty lines from the end of stdout/stderr in result. |
| 81 |
tty: |
| 82 |
type: bool |
| 83 |
default: false |
| 84 |
description: |
| 85 |
- Whether to allocate a TTY. |
| 86 |
env: |
| 87 |
description: |
| 88 |
- Dictionary of environment variables with their respective values to be passed to the command ran inside the container. |
| 89 |
- Values which might be parsed as numbers, booleans or other types by the YAML parser must be quoted (for example V("true")) |
| 90 |
in order to avoid data loss. |
| 91 |
- Please note that if you are passing values in with Jinja2 templates, like V("{{ value }}"), you need to add V(| string) |
| 92 |
to prevent Ansible to convert strings such as V("true") back to booleans. The correct way is to use V("{{ value | |
| 93 |
string }}"). |
| 94 |
type: dict |
| 95 |
version_added: 2.1.0 |
| 96 |
|
| 97 |
notes: |
| 98 |
- Does B(not work with TCP TLS sockets) when using O(stdin). This is caused by the inability to send C(close_notify) without |
| 99 |
closing the connection with Python's C(SSLSocket)s. See U(https://github.com/ansible-collections/community.docker/issues/605) |
| 100 |
for more information. |
| 101 |
- If you need to evaluate environment variables of the container in O(command) or O(argv), you need to pass the command |
| 102 |
through a shell, like O(command=/bin/sh -c "echo $ENV_VARIABLE"). The same needs to be done in case you want to use glob patterns |
| 103 |
or other shell features such as redirects. |
| 104 |
author: |
| 105 |
- "Felix Fontein (@felixfontein)" |
| 106 |
|
| 107 |
requirements: |
| 108 |
- "Docker API >= 1.25" |
| 109 |
""" |
| 110 |
|
| 111 |
EXAMPLES = r""" |
| 112 |
--- |
| 113 |
- name: Run a simple command (command) |
| 114 |
community.docker.docker_container_exec: |
| 115 |
container: foo |
| 116 |
command: /bin/bash -c "ls -lah" |
| 117 |
chdir: /root |
| 118 |
register: result |
| 119 |
|
| 120 |
- name: Print stdout |
| 121 |
ansible.builtin.debug: |
| 122 |
var: result.stdout |
| 123 |
|
| 124 |
- name: Run a simple command (argv) |
| 125 |
community.docker.docker_container_exec: |
| 126 |
container: foo |
| 127 |
argv: |
| 128 |
- /bin/bash |
| 129 |
- "-c" |
| 130 |
- "ls -lah > /dev/stderr" |
| 131 |
chdir: /root |
| 132 |
register: result |
| 133 |
|
| 134 |
- name: Print stderr lines |
| 135 |
ansible.builtin.debug: |
| 136 |
var: result.stderr_lines |
| 137 |
""" |
| 138 |
|
| 139 |
RETURN = r""" |
| 140 |
stdout: |
| 141 |
type: str |
| 142 |
returned: success and O(detach=false) |
| 143 |
description: |
| 144 |
- The standard output of the container command. |
| 145 |
stderr: |
| 146 |
type: str |
| 147 |
returned: success and O(detach=false) |
| 148 |
description: |
| 149 |
- The standard error output of the container command. |
| 150 |
rc: |
| 151 |
type: int |
| 152 |
returned: success and O(detach=false) |
| 153 |
sample: 0 |
| 154 |
description: |
| 155 |
- The exit code of the command. |
| 156 |
exec_id: |
| 157 |
type: str |
| 158 |
returned: success and O(detach=true) |
| 159 |
sample: 249d9e3075655baf705ed8f40488c5e9434049cf3431976f1bfdb73741c574c5 |
| 160 |
description: |
| 161 |
- The execution ID of the command. |
| 162 |
version_added: 2.1.0 |
| 163 |
""" |
| 164 |
|
| 165 |
import shlex |
| 166 |
import traceback |
| 167 |
import typing as t |
| 168 |
|
| 169 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 170 |
|
| 171 |
from ansible_collections.community.docker.plugins.module_utils._api.errors import ( |
| 172 |
APIError, |
| 173 |
DockerException, |
| 174 |
NotFound, |
| 175 |
) |
| 176 |
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import ( |
| 177 |
format_environment, |
| 178 |
) |
| 179 |
from ansible_collections.community.docker.plugins.module_utils._common_api import ( |
| 180 |
AnsibleDockerClient, |
| 181 |
RequestException, |
| 182 |
) |
| 183 |
from ansible_collections.community.docker.plugins.module_utils._socket_handler import ( |
| 184 |
DockerSocketHandlerModule, |
| 185 |
) |
| 186 |
|
| 187 |
|
| 188 |
def main() -> None: |
| 189 |
argument_spec = { |
| 190 |
"container": {"type": "str", "required": True}, |
| 191 |
"argv": {"type": "list", "elements": "str"}, |
| 192 |
"command": {"type": "str"}, |
| 193 |
"chdir": {"type": "str"}, |
| 194 |
"detach": {"type": "bool", "default": False}, |
| 195 |
"user": {"type": "str"}, |
| 196 |
"stdin": {"type": "str"}, |
| 197 |
"stdin_add_newline": {"type": "bool", "default": True}, |
| 198 |
"strip_empty_ends": {"type": "bool", "default": True}, |
| 199 |
"tty": {"type": "bool", "default": False}, |
| 200 |
"env": {"type": "dict"}, |
| 201 |
} |
| 202 |
|
| 203 |
option_minimal_versions = { |
| 204 |
"chdir": {"docker_api_version": "1.35"}, |
| 205 |
} |
| 206 |
|
| 207 |
client = AnsibleDockerClient( |
| 208 |
argument_spec=argument_spec, |
| 209 |
option_minimal_versions=option_minimal_versions, |
| 210 |
mutually_exclusive=[("argv", "command")], |
| 211 |
required_one_of=[("argv", "command")], |
| 212 |
) |
| 213 |
|
| 214 |
container: str = client.module.params["container"] |
| 215 |
argv: list[str] | None = client.module.params["argv"] |
| 216 |
command: str | None = client.module.params["command"] |
| 217 |
chdir: str | None = client.module.params["chdir"] |
| 218 |
detach: bool = client.module.params["detach"] |
| 219 |
user: str | None = client.module.params["user"] |
| 220 |
stdin: str | None = client.module.params["stdin"] |
| 221 |
strip_empty_ends: bool = client.module.params["strip_empty_ends"] |
| 222 |
tty: bool = client.module.params["tty"] |
| 223 |
env: dict[str, t.Any] | None = client.module.params["env"] |
| 224 |
|
| 225 |
if env is not None: |
| 226 |
for name, value in env.items(): |
| 227 |
if not isinstance(value, str): |
| 228 |
client.module.fail_json( |
| 229 |
msg="Non-string value found for env option. Ambiguous env options must be " |
| 230 |
"wrapped in quotes to avoid them being interpreted when directly specified " |
| 231 |
"in YAML, or explicitly converted to strings when the option is templated. " |
| 232 |
f"Key: {name}" |
| 233 |
) |
| 234 |
|
| 235 |
if command is not None: |
| 236 |
argv = shlex.split(command) |
| 237 |
assert argv is not None |
| 238 |
|
| 239 |
if detach and stdin is not None: |
| 240 |
client.module.fail_json(msg="If detach=true, stdin cannot be provided.") |
| 241 |
|
| 242 |
if stdin is not None and client.module.params["stdin_add_newline"]: |
| 243 |
stdin += "\n" |
| 244 |
|
| 245 |
try: |
| 246 |
data = { |
| 247 |
"Container": container, |
| 248 |
"User": user or "", |
| 249 |
"Privileged": False, |
| 250 |
"Tty": False, |
| 251 |
"AttachStdin": bool(stdin), |
| 252 |
"AttachStdout": True, |
| 253 |
"AttachStderr": True, |
| 254 |
"Cmd": argv, |
| 255 |
"Env": format_environment(env) if env is not None else None, |
| 256 |
} |
| 257 |
if chdir is not None: |
| 258 |
data["WorkingDir"] = chdir |
| 259 |
|
| 260 |
exec_data = client.post_json_to_json( |
| 261 |
"/containers/{0}/exec", container, data=data |
| 262 |
) |
| 263 |
exec_id: str = exec_data["Id"] |
| 264 |
|
| 265 |
data = { |
| 266 |
"Tty": tty, |
| 267 |
"Detach": detach, |
| 268 |
} |
| 269 |
if detach: |
| 270 |
client.post_json_to_text("/exec/{0}/start", exec_id, data=data) |
| 271 |
client.module.exit_json(changed=True, exec_id=exec_id) |
| 272 |
|
| 273 |
else: |
| 274 |
stdout: bytes | None |
| 275 |
stderr: bytes | None |
| 276 |
if stdin and not detach: |
| 277 |
exec_socket = client.post_json_to_stream_socket( |
| 278 |
"/exec/{0}/start", exec_id, data=data |
| 279 |
) |
| 280 |
try: |
| 281 |
with DockerSocketHandlerModule( |
| 282 |
exec_socket, client.module |
| 283 |
) as exec_socket_handler: |
| 284 |
if stdin: |
| 285 |
exec_socket_handler.write(to_bytes(stdin)) |
| 286 |
|
| 287 |
stdout, stderr = exec_socket_handler.consume() |
| 288 |
finally: |
| 289 |
exec_socket.close() |
| 290 |
elif tty: |
| 291 |
stdout, stderr = client.post_json_to_stream( |
| 292 |
"/exec/{0}/start", |
| 293 |
exec_id, |
| 294 |
data=data, |
| 295 |
stream=False, |
| 296 |
tty=True, |
| 297 |
demux=True, |
| 298 |
) |
| 299 |
else: |
| 300 |
stdout, stderr = client.post_json_to_stream( |
| 301 |
"/exec/{0}/start", |
| 302 |
exec_id, |
| 303 |
data=data, |
| 304 |
stream=False, |
| 305 |
tty=False, |
| 306 |
demux=True, |
| 307 |
) |
| 308 |
|
| 309 |
result = client.get_json("/exec/{0}/json", exec_id) |
| 310 |
|
| 311 |
stdout_t = to_text(stdout or b"") |
| 312 |
stderr_t = to_text(stderr or b"") |
| 313 |
if strip_empty_ends: |
| 314 |
stdout_t = stdout_t.rstrip("\r\n") |
| 315 |
stderr_t = stderr_t.rstrip("\r\n") |
| 316 |
|
| 317 |
client.module.exit_json( |
| 318 |
changed=True, |
| 319 |
stdout=stdout_t, |
| 320 |
stderr=stderr_t, |
| 321 |
rc=result.get("ExitCode") or 0, |
| 322 |
) |
| 323 |
except NotFound: |
| 324 |
client.fail(f'Could not find container "{container}"') |
| 325 |
except APIError as e: |
| 326 |
if e.response is not None and e.response.status_code == 409: |
| 327 |
client.fail(f'The container "{container}" has been paused ({e})') |
| 328 |
client.fail( |
| 329 |
f"An unexpected Docker error occurred: {e}", |
| 330 |
exception=traceback.format_exc(), |
| 331 |
) |
| 332 |
except DockerException as e: |
| 333 |
client.fail( |
| 334 |
f"An unexpected Docker error occurred: {e}", |
| 335 |
exception=traceback.format_exc(), |
| 336 |
) |
| 337 |
except RequestException as e: |
| 338 |
client.fail( |
| 339 |
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}", |
| 340 |
exception=traceback.format_exc(), |
| 341 |
) |
| 342 |
|
| 343 |
|
| 344 |
if __name__ == "__main__": |
| 345 |
main() |