| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2023, 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_compose_v2_exec |
| 11 |
|
| 12 |
short_description: Run command in a container of a Compose service |
| 13 |
|
| 14 |
version_added: 3.13.0 |
| 15 |
|
| 16 |
description: |
| 17 |
- Uses Docker Compose to run a command in a service's container. |
| 18 |
- This can be used to run one-off commands in an existing service's container, and encapsulates C(docker compose exec). |
| 19 |
extends_documentation_fragment: |
| 20 |
- community.docker._compose_v2 |
| 21 |
- community.docker._compose_v2.minimum_version |
| 22 |
- community.docker._docker.cli_documentation |
| 23 |
- community.docker._attributes |
| 24 |
- community.docker._attributes.actiongroup_docker |
| 25 |
|
| 26 |
attributes: |
| 27 |
check_mode: |
| 28 |
support: none |
| 29 |
diff_mode: |
| 30 |
support: none |
| 31 |
idempotent: |
| 32 |
support: N/A |
| 33 |
details: |
| 34 |
- Whether the executed command is idempotent depends on the command. |
| 35 |
|
| 36 |
options: |
| 37 |
service: |
| 38 |
description: |
| 39 |
- The service to run the command in. |
| 40 |
type: str |
| 41 |
required: true |
| 42 |
index: |
| 43 |
description: |
| 44 |
- The index of the container to run the command in if the service has multiple replicas. |
| 45 |
type: int |
| 46 |
argv: |
| 47 |
type: list |
| 48 |
elements: str |
| 49 |
description: |
| 50 |
- The command to execute. |
| 51 |
- Since this is a list of arguments, no quoting is needed. |
| 52 |
- Exactly one of O(argv) or O(command) must be specified. |
| 53 |
command: |
| 54 |
type: str |
| 55 |
description: |
| 56 |
- The command to execute. |
| 57 |
- Exactly one of O(argv) or O(command) must be specified. |
| 58 |
chdir: |
| 59 |
type: str |
| 60 |
description: |
| 61 |
- The directory to run the command in. |
| 62 |
detach: |
| 63 |
description: |
| 64 |
- Whether to run the command synchronously (O(detach=false), default) or asynchronously (O(detach=true)). |
| 65 |
- If set to V(true), O(stdin) cannot be provided, and the return values RV(stdout), RV(stderr), and RV(rc) are not returned. |
| 66 |
type: bool |
| 67 |
default: false |
| 68 |
user: |
| 69 |
type: str |
| 70 |
description: |
| 71 |
- If specified, the user to execute this command with. |
| 72 |
stdin: |
| 73 |
type: str |
| 74 |
description: |
| 75 |
- Set the stdin of the command directly to the specified value. |
| 76 |
- Can only be used if O(detach=false). |
| 77 |
stdin_add_newline: |
| 78 |
type: bool |
| 79 |
default: true |
| 80 |
description: |
| 81 |
- If set to V(true), appends a newline to O(stdin). |
| 82 |
strip_empty_ends: |
| 83 |
type: bool |
| 84 |
default: true |
| 85 |
description: |
| 86 |
- Strip empty lines from the end of stdout/stderr in result. |
| 87 |
privileged: |
| 88 |
type: bool |
| 89 |
default: false |
| 90 |
description: |
| 91 |
- Whether to give extended privileges to the process. |
| 92 |
tty: |
| 93 |
type: bool |
| 94 |
default: true |
| 95 |
description: |
| 96 |
- Whether to allocate a TTY. |
| 97 |
env: |
| 98 |
description: |
| 99 |
- Dictionary of environment variables with their respective values to be passed to the command ran inside the container. |
| 100 |
- Values which might be parsed as numbers, booleans or other types by the YAML parser must be quoted (for example V("true")) |
| 101 |
in order to avoid data loss. |
| 102 |
- Please note that if you are passing values in with Jinja2 templates, like V("{{ value }}"), you need to add V(| string) |
| 103 |
to prevent Ansible to convert strings such as V("true") back to booleans. The correct way is to use V("{{ value | |
| 104 |
string }}"). |
| 105 |
type: dict |
| 106 |
|
| 107 |
author: |
| 108 |
- Felix Fontein (@felixfontein) |
| 109 |
|
| 110 |
seealso: |
| 111 |
- module: community.docker.docker_compose_v2 |
| 112 |
|
| 113 |
notes: |
| 114 |
- If you need to evaluate environment variables of the container in O(command) or O(argv), you need to pass the command |
| 115 |
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 |
| 116 |
or other shell features such as redirects. |
| 117 |
""" |
| 118 |
|
| 119 |
EXAMPLES = r""" |
| 120 |
--- |
| 121 |
- name: Run a simple command (command) |
| 122 |
community.docker.docker_compose_v2_exec: |
| 123 |
service: foo |
| 124 |
command: /bin/bash -c "ls -lah" |
| 125 |
chdir: /root |
| 126 |
register: result |
| 127 |
|
| 128 |
- name: Print stdout |
| 129 |
ansible.builtin.debug: |
| 130 |
var: result.stdout |
| 131 |
|
| 132 |
- name: Run a simple command (argv) |
| 133 |
community.docker.docker_compose_v2_exec: |
| 134 |
service: foo |
| 135 |
argv: |
| 136 |
- /bin/bash |
| 137 |
- "-c" |
| 138 |
- "ls -lah > /dev/stderr" |
| 139 |
chdir: /root |
| 140 |
register: result |
| 141 |
|
| 142 |
- name: Print stderr lines |
| 143 |
ansible.builtin.debug: |
| 144 |
var: result.stderr_lines |
| 145 |
""" |
| 146 |
|
| 147 |
RETURN = r""" |
| 148 |
stdout: |
| 149 |
type: str |
| 150 |
returned: success and O(detach=false) |
| 151 |
description: |
| 152 |
- The standard output of the container command. |
| 153 |
stderr: |
| 154 |
type: str |
| 155 |
returned: success and O(detach=false) |
| 156 |
description: |
| 157 |
- The standard error output of the container command. |
| 158 |
rc: |
| 159 |
type: int |
| 160 |
returned: success and O(detach=false) |
| 161 |
sample: 0 |
| 162 |
description: |
| 163 |
- The exit code of the command. |
| 164 |
""" |
| 165 |
|
| 166 |
import shlex |
| 167 |
import traceback |
| 168 |
import typing as t |
| 169 |
|
| 170 |
from ansible.module_utils.common.text.converters import to_text |
| 171 |
|
| 172 |
from ansible_collections.community.docker.plugins.module_utils._common_cli import ( |
| 173 |
AnsibleModuleDockerClient, |
| 174 |
DockerException, |
| 175 |
) |
| 176 |
from ansible_collections.community.docker.plugins.module_utils._compose_v2 import ( |
| 177 |
BaseComposeManager, |
| 178 |
common_compose_argspec_ex, |
| 179 |
) |
| 180 |
|
| 181 |
|
| 182 |
class ExecManager(BaseComposeManager): |
| 183 |
def __init__(self, client: AnsibleModuleDockerClient) -> None: |
| 184 |
super().__init__(client) |
| 185 |
parameters = self.client.module.params |
| 186 |
|
| 187 |
self.service: str = parameters["service"] |
| 188 |
self.index: int | None = parameters["index"] |
| 189 |
self.chdir: str | None = parameters["chdir"] |
| 190 |
self.detach: bool = parameters["detach"] |
| 191 |
self.user: str | None = parameters["user"] |
| 192 |
self.stdin: str | None = parameters["stdin"] |
| 193 |
self.strip_empty_ends: bool = parameters["strip_empty_ends"] |
| 194 |
self.privileged: bool = parameters["privileged"] |
| 195 |
self.tty: bool = parameters["tty"] |
| 196 |
self.env: dict[str, t.Any] = parameters["env"] |
| 197 |
|
| 198 |
self.argv: list[str] |
| 199 |
if parameters["command"] is not None: |
| 200 |
self.argv = shlex.split(parameters["command"]) |
| 201 |
else: |
| 202 |
self.argv = parameters["argv"] |
| 203 |
|
| 204 |
if self.detach and self.stdin is not None: |
| 205 |
self.fail("If detach=true, stdin cannot be provided.") |
| 206 |
|
| 207 |
stdin_add_newline: bool = parameters["stdin_add_newline"] |
| 208 |
if self.stdin is not None and stdin_add_newline: |
| 209 |
self.stdin += "\n" |
| 210 |
|
| 211 |
if self.env is not None: |
| 212 |
for name, value in self.env.items(): |
| 213 |
if not isinstance(value, str): |
| 214 |
self.fail( |
| 215 |
"Non-string value found for env option. Ambiguous env options must be " |
| 216 |
"wrapped in quotes to avoid them being interpreted when directly specified " |
| 217 |
"in YAML, or explicitly converted to strings when the option is templated. " |
| 218 |
f"Key: {name}" |
| 219 |
) |
| 220 |
|
| 221 |
def get_exec_cmd(self, dry_run: bool) -> list[str]: |
| 222 |
args = self.get_base_args(plain_progress=True) + ["exec"] |
| 223 |
if self.index is not None: |
| 224 |
args.extend(["--index", str(self.index)]) |
| 225 |
if self.chdir is not None: |
| 226 |
args.extend(["--workdir", self.chdir]) |
| 227 |
if self.detach: |
| 228 |
args.extend(["--detach"]) |
| 229 |
if self.user is not None: |
| 230 |
args.extend(["--user", self.user]) |
| 231 |
if self.privileged: |
| 232 |
args.append("--privileged") |
| 233 |
if not self.tty: |
| 234 |
args.append("--no-TTY") |
| 235 |
if self.env: |
| 236 |
for name, value in list(self.env.items()): |
| 237 |
args.append("--env") |
| 238 |
args.append(f"{name}={value}") |
| 239 |
args.append("--") |
| 240 |
args.append(self.service) |
| 241 |
args.extend(self.argv) |
| 242 |
return args |
| 243 |
|
| 244 |
def run(self) -> dict[str, t.Any]: |
| 245 |
args = self.get_exec_cmd(self.check_mode) |
| 246 |
kwargs: dict[str, t.Any] = { |
| 247 |
"cwd": self.project_src, |
| 248 |
} |
| 249 |
if self.stdin is not None: |
| 250 |
kwargs["data"] = self.stdin.encode("utf-8") |
| 251 |
if self.detach: |
| 252 |
kwargs["check_rc"] = True |
| 253 |
rc, stdout_b, stderr_b = self.client.call_cli(*args, **kwargs) |
| 254 |
if self.detach: |
| 255 |
return {} |
| 256 |
stdout = to_text(stdout_b) |
| 257 |
stderr = to_text(stderr_b) |
| 258 |
if self.strip_empty_ends: |
| 259 |
stdout = stdout.rstrip("\r\n") |
| 260 |
stderr = stderr.rstrip("\r\n") |
| 261 |
return { |
| 262 |
"changed": True, |
| 263 |
"rc": rc, |
| 264 |
"stdout": stdout, |
| 265 |
"stderr": stderr, |
| 266 |
} |
| 267 |
|
| 268 |
|
| 269 |
def main() -> None: |
| 270 |
argument_spec = { |
| 271 |
"service": {"type": "str", "required": True}, |
| 272 |
"index": {"type": "int"}, |
| 273 |
"argv": {"type": "list", "elements": "str"}, |
| 274 |
"command": {"type": "str"}, |
| 275 |
"chdir": {"type": "str"}, |
| 276 |
"detach": {"type": "bool", "default": False}, |
| 277 |
"user": {"type": "str"}, |
| 278 |
"stdin": {"type": "str"}, |
| 279 |
"stdin_add_newline": {"type": "bool", "default": True}, |
| 280 |
"strip_empty_ends": {"type": "bool", "default": True}, |
| 281 |
"privileged": {"type": "bool", "default": False}, |
| 282 |
"tty": {"type": "bool", "default": True}, |
| 283 |
"env": {"type": "dict"}, |
| 284 |
} |
| 285 |
argspec_ex = common_compose_argspec_ex() |
| 286 |
argument_spec.update(argspec_ex.pop("argspec")) |
| 287 |
|
| 288 |
client = AnsibleModuleDockerClient( |
| 289 |
argument_spec=argument_spec, |
| 290 |
supports_check_mode=False, |
| 291 |
needs_api_version=False, |
| 292 |
**argspec_ex, |
| 293 |
) |
| 294 |
|
| 295 |
try: |
| 296 |
manager = ExecManager(client) |
| 297 |
result = manager.run() |
| 298 |
manager.cleanup() |
| 299 |
client.module.exit_json(**result) |
| 300 |
except DockerException as e: |
| 301 |
client.fail( |
| 302 |
f"An unexpected Docker error occurred: {e}", |
| 303 |
exception=traceback.format_exc(), |
| 304 |
) |
| 305 |
|
| 306 |
|
| 307 |
if __name__ == "__main__": |
| 308 |
main() |