Debian Codegraph @

ansible_collections/community/docker/plugins/modules/docker_compose_v2_run.py

raw
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_run
11
12 short_description: Run command in a new 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 new container for a service.
18 - This encapsulates C(docker compose run).
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 argv:
43 type: list
44 elements: str
45 description:
46 - The command to execute.
47 - Since this is a list of arguments, no quoting is needed.
48 - O(argv) or O(command) are mutually exclusive.
49 command:
50 type: str
51 description:
52 - The command to execute.
53 - O(argv) or O(command) are mutually exclusive.
54 build:
55 description:
56 - Build image before starting container.
57 - Note that building can insert information into RV(stdout) or RV(stderr).
58 type: bool
59 default: false
60 cap_add:
61 description:
62 - Linux capabilities to add to the container.
63 type: list
64 elements: str
65 cap_drop:
66 description:
67 - Linux capabilities to drop from the container.
68 type: list
69 elements: str
70 entrypoint:
71 description:
72 - Override the entrypoint of the container image.
73 type: str
74 interactive:
75 description:
76 - Whether to keep STDIN open even if not attached.
77 type: bool
78 default: true
79 labels:
80 description:
81 - Add or override labels to the container.
82 type: list
83 elements: str
84 name:
85 description:
86 - Assign a name to the container.
87 type: str
88 no_deps:
89 description:
90 - Do not start linked services.
91 type: bool
92 default: false
93 publish:
94 description:
95 - Publish a container's port(s) to the host.
96 type: list
97 elements: str
98 quiet_pull:
99 description:
100 - Pull without printing progress information.
101 - Note that pulling can insert information into RV(stdout) or RV(stderr).
102 type: bool
103 default: false
104 remove_orphans:
105 description:
106 - Remove containers for services not defined in the Compose file.
107 type: bool
108 default: false
109 cleanup:
110 description:
111 - Automatically remove th econtainer when it exits.
112 - Corresponds to the C(--rm) option of C(docker compose run).
113 type: bool
114 default: false
115 service_ports:
116 description:
117 - Run command with all service's ports enabled and mapped to the host.
118 type: bool
119 default: false
120 use_aliases:
121 description:
122 - Use the service's network C(useAliases) in the network(s) the container connects to.
123 type: bool
124 default: false
125 volumes:
126 description:
127 - Bind mount one or more volumes.
128 type: list
129 elements: str
130 chdir:
131 type: str
132 description:
133 - The directory to run the command in.
134 detach:
135 description:
136 - Whether to run the command synchronously (O(detach=false), default) or asynchronously (O(detach=true)).
137 - If set to V(true), O(stdin) cannot be provided, and the return values RV(stdout), RV(stderr), and RV(rc) are not returned.
138 Instead, the return value RV(container_id) is provided.
139 type: bool
140 default: false
141 user:
142 type: str
143 description:
144 - If specified, the user to execute this command with.
145 stdin:
146 type: str
147 description:
148 - Set the stdin of the command directly to the specified value.
149 - Can only be used if O(detach=false).
150 stdin_add_newline:
151 type: bool
152 default: true
153 description:
154 - If set to V(true), appends a newline to O(stdin).
155 strip_empty_ends:
156 type: bool
157 default: true
158 description:
159 - Strip empty lines from the end of stdout/stderr in result.
160 tty:
161 type: bool
162 default: true
163 description:
164 - Whether to allocate a TTY.
165 env:
166 description:
167 - Dictionary of environment variables with their respective values to be passed to the command ran inside the container.
168 - Values which might be parsed as numbers, booleans or other types by the YAML parser must be quoted (for example V("true"))
169 in order to avoid data loss.
170 - Please note that if you are passing values in with Jinja2 templates, like V("{{ value }}"), you need to add V(| string)
171 to prevent Ansible to convert strings such as V("true") back to booleans. The correct way is to use V("{{ value |
172 string }}").
173 type: dict
174
175 author:
176 - Felix Fontein (@felixfontein)
177
178 seealso:
179 - module: community.docker.docker_compose_v2
180
181 notes:
182 - If you need to evaluate environment variables of the container in O(command) or O(argv), you need to pass the command
183 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
184 or other shell features such as redirects.
185 """
186
187 EXAMPLES = r"""
188 ---
189 - name: Run a simple command (command)
190 community.docker.docker_compose_v2_run:
191 service: foo
192 command: /bin/bash -c "ls -lah"
193 chdir: /root
194 register: result
195
196 - name: Print stdout
197 ansible.builtin.debug:
198 var: result.stdout
199
200 - name: Run a simple command (argv)
201 community.docker.docker_compose_v2_run:
202 service: foo
203 argv:
204 - /bin/bash
205 - "-c"
206 - "ls -lah > /dev/stderr"
207 chdir: /root
208 register: result
209
210 - name: Print stderr lines
211 ansible.builtin.debug:
212 var: result.stderr_lines
213 """
214
215 RETURN = r"""
216 container_id:
217 type: str
218 returned: success and O(detach=true)
219 description:
220 - The ID of the created container.
221 stdout:
222 type: str
223 returned: success and O(detach=false)
224 description:
225 - The standard output of the container command.
226 stderr:
227 type: str
228 returned: success and O(detach=false)
229 description:
230 - The standard error output of the container command.
231 rc:
232 type: int
233 returned: success and O(detach=false)
234 sample: 0
235 description:
236 - The exit code of the command.
237 """
238
239 import shlex
240 import traceback
241 import typing as t
242
243 from ansible.module_utils.common.text.converters import to_text
244
245 from ansible_collections.community.docker.plugins.module_utils._common_cli import (
246 AnsibleModuleDockerClient,
247 DockerException,
248 )
249 from ansible_collections.community.docker.plugins.module_utils._compose_v2 import (
250 BaseComposeManager,
251 common_compose_argspec_ex,
252 )
253
254
255 class ExecManager(BaseComposeManager):
256 def __init__(self, client: AnsibleModuleDockerClient) -> None:
257 super().__init__(client)
258 parameters = self.client.module.params
259
260 self.service: str = parameters["service"]
261 self.build: bool = parameters["build"]
262 self.cap_add: list[str] | None = parameters["cap_add"]
263 self.cap_drop: list[str] | None = parameters["cap_drop"]
264 self.entrypoint: str | None = parameters["entrypoint"]
265 self.interactive: bool = parameters["interactive"]
266 self.labels: list[str] | None = parameters["labels"]
267 self.name: str | None = parameters["name"]
268 self.no_deps: bool = parameters["no_deps"]
269 self.publish: list[str] | None = parameters["publish"]
270 self.quiet_pull: bool = parameters["quiet_pull"]
271 self.remove_orphans: bool = parameters["remove_orphans"]
272 self.do_cleanup: bool = parameters["cleanup"]
273 self.service_ports: bool = parameters["service_ports"]
274 self.use_aliases: bool = parameters["use_aliases"]
275 self.volumes: list[str] | None = parameters["volumes"]
276 self.chdir: str | None = parameters["chdir"]
277 self.detach: bool = parameters["detach"]
278 self.user: str | None = parameters["user"]
279 self.stdin: str | None = parameters["stdin"]
280 self.strip_empty_ends: bool = parameters["strip_empty_ends"]
281 self.tty: bool = parameters["tty"]
282 self.env: dict[str, t.Any] | None = parameters["env"]
283
284 self.argv: list[str]
285 if parameters["command"] is not None:
286 self.argv = shlex.split(parameters["command"])
287 else:
288 self.argv = parameters["argv"]
289
290 if self.detach and self.stdin is not None:
291 self.fail("If detach=true, stdin cannot be provided.")
292
293 stdin_add_newline: bool = parameters["stdin_add_newline"]
294 if self.stdin is not None and stdin_add_newline:
295 self.stdin += "\n"
296
297 if self.env is not None:
298 for name, value in self.env.items():
299 if not isinstance(value, str):
300 self.fail(
301 "Non-string value found for env option. Ambiguous env options must be "
302 "wrapped in quotes to avoid them being interpreted when directly specified "
303 "in YAML, or explicitly converted to strings when the option is templated. "
304 f"Key: {name}"
305 )
306
307 def get_run_cmd(self, dry_run: bool) -> list[str]:
308 args = self.get_base_args(plain_progress=True) + ["run"]
309 if self.build:
310 args.append("--build")
311 if self.cap_add:
312 for cap in self.cap_add:
313 args.extend(["--cap-add", cap])
314 if self.cap_drop:
315 for cap in self.cap_drop:
316 args.extend(["--cap-drop", cap])
317 if self.entrypoint is not None:
318 args.extend(["--entrypoint", self.entrypoint])
319 if not self.interactive:
320 args.append("--no-interactive")
321 if self.labels:
322 for label in self.labels:
323 args.extend(["--label", label])
324 if self.name is not None:
325 args.extend(["--name", self.name])
326 if self.no_deps:
327 args.append("--no-deps")
328 if self.publish:
329 for publish in self.publish:
330 args.extend(["--publish", publish])
331 if self.quiet_pull:
332 args.append("--quiet-pull")
333 if self.remove_orphans:
334 args.append("--remove-orphans")
335 if self.do_cleanup:
336 args.append("--rm")
337 if self.service_ports:
338 args.append("--service-ports")
339 if self.use_aliases:
340 args.append("--use-aliases")
341 if self.volumes:
342 for volume in self.volumes:
343 args.extend(["--volume", volume])
344 if self.chdir is not None:
345 args.extend(["--workdir", self.chdir])
346 if self.detach:
347 args.extend(["--detach"])
348 if self.user is not None:
349 args.extend(["--user", self.user])
350 if not self.tty:
351 args.append("--no-TTY")
352 if self.env:
353 for name, value in list(self.env.items()):
354 args.append("--env")
355 args.append(f"{name}={value}")
356 args.append("--")
357 args.append(self.service)
358 if self.argv:
359 args.extend(self.argv)
360 return args
361
362 def run(self) -> dict[str, t.Any]:
363 args = self.get_run_cmd(self.check_mode)
364 kwargs: dict[str, t.Any] = {
365 "cwd": self.project_src,
366 }
367 if self.stdin is not None:
368 kwargs["data"] = self.stdin.encode("utf-8")
369 if self.detach:
370 kwargs["check_rc"] = True
371 rc, stdout_b, stderr_b = self.client.call_cli(*args, **kwargs)
372 if self.detach:
373 return {
374 "container_id": to_text(stdout_b.strip()),
375 }
376 stdout = to_text(stdout_b)
377 stderr = to_text(stderr_b)
378 if self.strip_empty_ends:
379 stdout = stdout.rstrip("\r\n")
380 stderr = stderr.rstrip("\r\n")
381 return {
382 "changed": True,
383 "rc": rc,
384 "stdout": stdout,
385 "stderr": stderr,
386 }
387
388
389 def main() -> None:
390 argument_spec = {
391 "service": {"type": "str", "required": True},
392 "argv": {"type": "list", "elements": "str"},
393 "command": {"type": "str"},
394 "build": {"type": "bool", "default": False},
395 "cap_add": {"type": "list", "elements": "str"},
396 "cap_drop": {"type": "list", "elements": "str"},
397 "entrypoint": {"type": "str"},
398 "interactive": {"type": "bool", "default": True},
399 "labels": {"type": "list", "elements": "str"},
400 "name": {"type": "str"},
401 "no_deps": {"type": "bool", "default": False},
402 "publish": {"type": "list", "elements": "str"},
403 "quiet_pull": {"type": "bool", "default": False},
404 "remove_orphans": {"type": "bool", "default": False},
405 "cleanup": {"type": "bool", "default": False},
406 "service_ports": {"type": "bool", "default": False},
407 "use_aliases": {"type": "bool", "default": False},
408 "volumes": {"type": "list", "elements": "str"},
409 "chdir": {"type": "str"},
410 "detach": {"type": "bool", "default": False},
411 "user": {"type": "str"},
412 "stdin": {"type": "str"},
413 "stdin_add_newline": {"type": "bool", "default": True},
414 "strip_empty_ends": {"type": "bool", "default": True},
415 "tty": {"type": "bool", "default": True},
416 "env": {"type": "dict"},
417 }
418 argspec_ex = common_compose_argspec_ex()
419 argument_spec.update(argspec_ex.pop("argspec"))
420
421 client = AnsibleModuleDockerClient(
422 argument_spec=argument_spec,
423 supports_check_mode=False,
424 needs_api_version=False,
425 **argspec_ex,
426 )
427
428 try:
429 manager = ExecManager(client)
430 result = manager.run()
431 manager.cleanup()
432 client.module.exit_json(**result)
433 except DockerException as e:
434 client.fail(
435 f"An unexpected Docker error occurred: {e}",
436 exception=traceback.format_exc(),
437 )
438
439
440 if __name__ == "__main__":
441 main()