Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2023, Felix Fontein <[email protected]>
4 # Copyright (c) 2023, Léo El Amri (@lel-amri)
5 # Copyright 2016 Red Hat | Ansible
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: docker_compose_v2
13
14 short_description: Manage multi-container Docker applications with Docker Compose CLI plugin
15
16 version_added: 3.6.0
17
18 description:
19 - Uses Docker Compose to start or shutdown services.
20 extends_documentation_fragment:
21 - community.docker._compose_v2
22 - community.docker._compose_v2.minimum_version
23 - community.docker._docker.cli_documentation
24 - community.docker._attributes
25 - community.docker._attributes.actiongroup_docker
26
27 attributes:
28 check_mode:
29 support: full
30 details:
31 - In check mode, pulling the image does not result in a changed result.
32 diff_mode:
33 support: none
34 idempotent:
35 support: partial
36 details:
37 - If O(state=restarted) or O(recreate=always) the module is not idempotent.
38
39 options:
40 state:
41 description:
42 - Desired state of the project.
43 - V(present) is equivalent to running C(docker compose up).
44 - V(stopped) is equivalent to running C(docker compose stop).
45 - V(absent) is equivalent to running C(docker compose down).
46 - V(restarted) is equivalent to running C(docker compose restart).
47 type: str
48 default: present
49 choices:
50 - absent
51 - stopped
52 - restarted
53 - present
54 pull:
55 description:
56 - Whether to pull images before running. This is used when C(docker compose up) is run.
57 - V(always) ensures that the images are always pulled, even when already present on the Docker daemon.
58 - V(missing) only pulls them when they are not present on the Docker daemon.
59 - V(never) never pulls images. If they are not present, the module will fail when trying to create the containers that
60 need them.
61 - V(policy) use the Compose file's C(pull_policy) defined for the service to figure out what to do.
62 type: str
63 choices:
64 - always
65 - missing
66 - never
67 - policy
68 default: policy
69 build:
70 description:
71 - Whether to build images before starting containers. This is used when C(docker compose up) is run.
72 - V(always) always builds before starting containers. This is equivalent to the C(--build) option of C(docker compose
73 up).
74 - V(never) never builds before starting containers. This is equivalent to the C(--no-build) option of C(docker compose
75 up).
76 - V(policy) uses the policy as defined in the Compose file.
77 type: str
78 choices:
79 - always
80 - never
81 - policy
82 default: policy
83 dependencies:
84 description:
85 - When O(state) is V(present) or V(restarted), specify whether or not to include linked services.
86 type: bool
87 default: true
88 ignore_build_events:
89 description:
90 - Ignores image building events for change detection.
91 - If O(state=present) and O(ignore_build_events=true) and O(build=always), a rebuild that does not trigger a container
92 restart no longer results in RV(ignore:changed=true).
93 - Note that Docker Compose 2.31.0 is the first Compose 2.x version to emit build events. For older versions, the behavior
94 is always as if O(ignore_build_events=true).
95 type: bool
96 default: true
97 version_added: 4.2.0
98 recreate:
99 description:
100 - By default containers will be recreated when their configuration differs from the service definition.
101 - Setting to V(never) ignores configuration differences and leaves existing containers unchanged.
102 - Setting to V(always) forces recreation of all existing containers.
103 type: str
104 default: auto
105 choices:
106 - always
107 - never
108 - auto
109 renew_anon_volumes:
110 description:
111 - Whether to recreate instead of reuse anonymous volumes from previous containers.
112 - V(true) is equivalent to the C(--renew-anon-volumes) option of C(docker compose up).
113 type: bool
114 default: false
115 version_added: 4.0.0
116 remove_images:
117 description:
118 - Use with O(state=absent) to remove all images or only local images.
119 type: str
120 choices:
121 - all
122 - local
123 remove_volumes:
124 description:
125 - Use with O(state=absent) to remove data volumes.
126 type: bool
127 default: false
128 remove_orphans:
129 description:
130 - Remove containers for services not defined in the Compose file.
131 type: bool
132 default: false
133 timeout:
134 description:
135 - Timeout in seconds for container shutdown when attached or when containers are already running.
136 type: int
137 services:
138 description:
139 - Specifies a subset of services to be targeted.
140 type: list
141 elements: str
142 scale:
143 description:
144 - Define how to scale services when running C(docker compose up).
145 - Provide a dictionary of key/value pairs where the key is the name of the service and the value is an integer count
146 for the number of containers.
147 type: dict
148 version_added: 3.7.0
149 wait:
150 description:
151 - When running C(docker compose up), pass C(--wait) to wait for services to be running/healthy.
152 - A timeout can be set with the O(wait_timeout) option.
153 type: bool
154 default: false
155 version_added: 3.8.0
156 wait_timeout:
157 description:
158 - When O(wait=true), wait at most this amount of seconds.
159 type: int
160 version_added: 3.8.0
161 assume_yes:
162 description:
163 - When O(assume_yes=true), pass C(-y)/C(--yes) to assume "yes" as answer to all prompts and run non-interactively.
164 - Right now a prompt is asked whenever a non-matching volume should be re-created. O(assume_yes=false)
165 results in the question being answered by "no", which will simply re-use the existing volume.
166 - This option is only available on Docker Compose 2.32.0 or newer.
167 type: bool
168 default: false
169 version_added: 4.5.0
170
171 author:
172 - Felix Fontein (@felixfontein)
173
174 seealso:
175 - module: community.docker.docker_compose_v2_pull
176 """
177
178 EXAMPLES = r"""
179 ---
180 # Examples use the django example at https://docs.docker.com/compose/django. Follow it to create the
181 # flask directory
182
183 - name: Run using a project directory
184 hosts: localhost
185 gather_facts: false
186 tasks:
187 - name: Tear down existing services
188 community.docker.docker_compose_v2:
189 project_src: flask
190 state: absent
191
192 - name: Create and start services
193 community.docker.docker_compose_v2:
194 project_src: flask
195 register: output
196
197 - name: Show results
198 ansible.builtin.debug:
199 var: output
200
201 - name: Run `docker compose up` again
202 community.docker.docker_compose_v2:
203 project_src: flask
204 register: output
205
206 - name: Show results
207 ansible.builtin.debug:
208 var: output
209
210 - ansible.builtin.assert:
211 that: not output.changed
212
213 - name: Stop all services
214 community.docker.docker_compose_v2:
215 project_src: flask
216 state: stopped
217 register: output
218
219 - name: Show results
220 ansible.builtin.debug:
221 var: output
222
223 - name: Verify that web and db services are not running
224 ansible.builtin.assert:
225 that:
226 - web_container.State != 'running'
227 - db_container.State != 'running'
228 vars:
229 web_container: >-
230 {{ output.containers | selectattr("Service", "equalto", "web") | first }}
231 db_container: >-
232 {{ output.containers | selectattr("Service", "equalto", "db") | first }}
233
234 - name: Restart services
235 community.docker.docker_compose_v2:
236 project_src: flask
237 state: restarted
238 register: output
239
240 - name: Show results
241 ansible.builtin.debug:
242 var: output
243
244 - name: Verify that web and db services are running
245 ansible.builtin.assert:
246 that:
247 - web_container.State == 'running'
248 - db_container.State == 'running'
249 vars:
250 web_container: >-
251 {{ output.containers | selectattr("Service", "equalto", "web") | first }}
252 db_container: >-
253 {{ output.containers | selectattr("Service", "equalto", "db") | first }}
254 """
255
256 RETURN = r"""
257 containers:
258 description:
259 - A list of containers associated to the service.
260 returned: success
261 type: list
262 elements: dict
263 contains:
264 Command:
265 description:
266 - The container's command.
267 type: raw
268 CreatedAt:
269 description:
270 - The timestamp when the container was created.
271 type: str
272 sample: "2024-01-02 12:20:41 +0100 CET"
273 ExitCode:
274 description:
275 - The container's exit code.
276 type: int
277 Health:
278 description:
279 - The container's health check.
280 type: raw
281 ID:
282 description:
283 - The container's ID.
284 type: str
285 sample: "44a7d607219a60b7db0a4817fb3205dce46e91df2cb4b78a6100b6e27b0d3135"
286 Image:
287 description:
288 - The container's image.
289 type: str
290 Labels:
291 description:
292 - Labels for this container.
293 type: dict
294 LocalVolumes:
295 description:
296 - The local volumes count.
297 type: str
298 Mounts:
299 description:
300 - Mounts.
301 type: str
302 Name:
303 description:
304 - The container's primary name.
305 type: str
306 Names:
307 description:
308 - List of names of the container.
309 type: list
310 elements: str
311 Networks:
312 description:
313 - List of networks attached to this container.
314 type: list
315 elements: str
316 Ports:
317 description:
318 - List of port assignments as a string.
319 type: str
320 Publishers:
321 description:
322 - List of port assigments.
323 type: list
324 elements: dict
325 contains:
326 URL:
327 description:
328 - Interface the port is bound to.
329 type: str
330 TargetPort:
331 description:
332 - The container's port the published port maps to.
333 type: int
334 PublishedPort:
335 description:
336 - The port that is published.
337 type: int
338 Protocol:
339 description:
340 - The protocol.
341 type: str
342 choices:
343 - tcp
344 - udp
345 RunningFor:
346 description:
347 - Amount of time the container runs.
348 type: str
349 Service:
350 description:
351 - The name of the service.
352 type: str
353 Size:
354 description:
355 - The container's size.
356 type: str
357 sample: "0B"
358 State:
359 description:
360 - The container's state.
361 type: str
362 sample: running
363 Status:
364 description:
365 - The container's status.
366 type: str
367 sample: Up About a minute
368 images:
369 description:
370 - A list of images associated to the service.
371 returned: success
372 type: list
373 elements: dict
374 contains:
375 ID:
376 description:
377 - The image's ID.
378 type: str
379 sample: sha256:c8bccc0af9571ec0d006a43acb5a8d08c4ce42b6cc7194dd6eb167976f501ef1
380 ContainerName:
381 description:
382 - Name of the conainer this image is used by.
383 type: str
384 Repository:
385 description:
386 - The repository where this image belongs to.
387 type: str
388 Tag:
389 description:
390 - The tag of the image.
391 type: str
392 Size:
393 description:
394 - The image's size in bytes.
395 type: int
396 actions:
397 description:
398 - A list of actions that have been applied.
399 returned: success
400 type: list
401 elements: dict
402 contains:
403 what:
404 description:
405 - What kind of resource was changed.
406 type: str
407 sample: container
408 choices:
409 - container
410 - image
411 - network
412 - service
413 - unknown
414 - volume
415 id:
416 description:
417 - The ID of the resource that was changed.
418 type: str
419 sample: container
420 status:
421 description:
422 - The status change that happened.
423 type: str
424 sample: Creating
425 choices:
426 - Starting
427 - Exiting
428 - Restarting
429 - Creating
430 - Stopping
431 - Killing
432 - Removing
433 - Recreating
434 - Pulling
435 - Building
436 """
437
438 import traceback
439 import typing as t
440
441 from ansible.module_utils.common.validation import check_type_int
442
443 from ansible_collections.community.docker.plugins.module_utils._common_cli import (
444 AnsibleModuleDockerClient,
445 DockerException,
446 )
447 from ansible_collections.community.docker.plugins.module_utils._compose_v2 import (
448 BaseComposeManager,
449 common_compose_argspec_ex,
450 is_failed,
451 )
452 from ansible_collections.community.docker.plugins.module_utils._version import (
453 LooseVersion,
454 )
455
456
457 class ServicesManager(BaseComposeManager):
458 def __init__(self, client: AnsibleModuleDockerClient) -> None:
459 super().__init__(client)
460 parameters = self.client.module.params
461
462 self.state: t.Literal["absent", "present", "stopped", "restarted"] = parameters[
463 "state"
464 ]
465 self.dependencies: bool = parameters["dependencies"]
466 self.pull: t.Literal["always", "missing", "never", "policy"] = parameters[
467 "pull"
468 ]
469 self.build: t.Literal["always", "never", "policy"] = parameters["build"]
470 self.ignore_build_events: bool = parameters["ignore_build_events"]
471 self.recreate: t.Literal["always", "never", "auto"] = parameters["recreate"]
472 self.remove_images: t.Literal["all", "local"] | None = parameters[
473 "remove_images"
474 ]
475 self.remove_volumes: bool = parameters["remove_volumes"]
476 self.remove_orphans: bool = parameters["remove_orphans"]
477 self.renew_anon_volumes: bool = parameters["renew_anon_volumes"]
478 self.timeout: int | None = parameters["timeout"]
479 self.services: list[str] = parameters["services"] or []
480 self.scale: dict[str, t.Any] = parameters["scale"] or {}
481 self.wait: bool = parameters["wait"]
482 self.wait_timeout: int | None = parameters["wait_timeout"]
483 self.yes: bool = parameters["assume_yes"]
484 if self.compose_version < LooseVersion("2.32.0") and self.yes:
485 self.fail(
486 f"assume_yes=true needs Docker Compose 2.32.0 or newer, not version {self.compose_version}"
487 )
488
489 for key, value in self.scale.items():
490 if not isinstance(key, str):
491 self.fail(f"The key {key!r} for `scale` is not a string")
492 try:
493 value = check_type_int(value)
494 except TypeError:
495 self.fail(f"The value {value!r} for `scale[{key!r}]` is not an integer")
496 if value < 0:
497 self.fail(f"The value {value!r} for `scale[{key!r}]` is negative")
498 self.scale[key] = value
499
500 def run(self) -> dict[str, t.Any]:
501 if self.state == "present":
502 result = self.cmd_up()
503 elif self.state == "stopped":
504 result = self.cmd_stop()
505 elif self.state == "restarted":
506 result = self.cmd_restart()
507 elif self.state == "absent":
508 result = self.cmd_down()
509 else:
510 raise AssertionError("Unexpected state")
511
512 result["containers"] = self.list_containers()
513 result["images"] = self.list_images()
514 self.cleanup_result(result)
515 return result
516
517 def get_up_cmd(self, dry_run: bool, no_start: bool = False) -> list[str]:
518 args = self.get_base_args() + ["up", "--detach", "--no-color", "--quiet-pull"]
519 if self.pull != "policy":
520 args.extend(["--pull", self.pull])
521 if self.remove_orphans:
522 args.append("--remove-orphans")
523 if self.recreate == "always":
524 args.append("--force-recreate")
525 if self.recreate == "never":
526 args.append("--no-recreate")
527 if self.renew_anon_volumes:
528 args.append("--renew-anon-volumes")
529 if not self.dependencies:
530 args.append("--no-deps")
531 if self.timeout is not None:
532 args.extend(["--timeout", f"{self.timeout}"])
533 if self.build == "always":
534 args.append("--build")
535 elif self.build == "never":
536 args.append("--no-build")
537 for key, value in sorted(self.scale.items()):
538 args.extend(["--scale", f"{key}={value}"])
539 if self.wait:
540 args.append("--wait")
541 if self.wait_timeout is not None:
542 args.extend(["--wait-timeout", str(self.wait_timeout)])
543 if no_start:
544 args.append("--no-start")
545 if dry_run:
546 args.append("--dry-run")
547 if self.yes:
548 # Note that for Docker Compose 2.32.x and 2.33.x, the long form is '--y' and not '--yes'.
549 # This was fixed in Docker Compose 2.34.0 (https://github.com/docker/compose/releases/tag/v2.34.0).
550 args.append(
551 "-y" if self.compose_version < LooseVersion("2.34.0") else "--yes"
552 )
553 args.append("--")
554 for service in self.services:
555 args.append(service)
556 return args
557
558 def cmd_up(self) -> dict[str, t.Any]:
559 result: dict[str, t.Any] = {}
560 args = self.get_up_cmd(self.check_mode)
561 rc, stdout, stderr = self.client.call_cli(*args, cwd=self.project_src)
562 events = self.parse_events(stderr, dry_run=self.check_mode, nonzero_rc=rc != 0)
563 self.emit_warnings(events)
564 self.update_result(
565 result,
566 events,
567 stdout,
568 stderr,
569 ignore_service_pull_events=True,
570 ignore_build_events=self.ignore_build_events,
571 )
572 self.update_failed(result, events, args, stdout, stderr, rc)
573 return result
574
575 def get_stop_cmd(self, dry_run: bool) -> list[str]:
576 args = self.get_base_args() + ["stop"]
577 if self.timeout is not None:
578 args.extend(["--timeout", f"{self.timeout}"])
579 if dry_run:
580 args.append("--dry-run")
581 args.append("--")
582 for service in self.services:
583 args.append(service)
584 return args
585
586 def _are_containers_stopped(self) -> bool:
587 return all(
588 container["State"] in ("created", "exited", "stopped", "killed")
589 for container in self.list_containers_raw()
590 )
591
592 def cmd_stop(self) -> dict[str, t.Any]:
593 # Since 'docker compose stop' **always** claims it is stopping containers, even if they are already
594 # stopped, we have to do this a bit more complicated.
595
596 result: dict[str, t.Any] = {}
597 # Make sure all containers are created
598 args_1 = self.get_up_cmd(self.check_mode, no_start=True)
599 rc_1, stdout_1, stderr_1 = self.client.call_cli(*args_1, cwd=self.project_src)
600 events_1 = self.parse_events(
601 stderr_1, dry_run=self.check_mode, nonzero_rc=rc_1 != 0
602 )
603 self.emit_warnings(events_1)
604 self.update_result(
605 result,
606 events_1,
607 stdout_1,
608 stderr_1,
609 ignore_service_pull_events=True,
610 ignore_build_events=self.ignore_build_events,
611 )
612 is_failed_1 = is_failed(events_1, rc_1)
613 if not is_failed_1 and not self._are_containers_stopped():
614 # Make sure all containers are stopped
615 args_2 = self.get_stop_cmd(self.check_mode)
616 rc_2, stdout_2, stderr_2 = self.client.call_cli(
617 *args_2, cwd=self.project_src
618 )
619 events_2 = self.parse_events(
620 stderr_2, dry_run=self.check_mode, nonzero_rc=rc_2 != 0
621 )
622 self.emit_warnings(events_2)
623 self.update_result(result, events_2, stdout_2, stderr_2)
624 else:
625 args_2 = []
626 rc_2, stdout_2, stderr_2 = 0, b"", b""
627 events_2 = []
628 # Compose result
629 self.update_failed(
630 result,
631 events_1 + events_2,
632 args_1 if is_failed_1 else args_2,
633 stdout_1 if is_failed_1 else stdout_2,
634 stderr_1 if is_failed_1 else stderr_2,
635 rc_1 if is_failed_1 else rc_2,
636 )
637 return result
638
639 def get_restart_cmd(self, dry_run: bool) -> list[str]:
640 args = self.get_base_args() + ["restart"]
641 if not self.dependencies:
642 args.append("--no-deps")
643 if self.timeout is not None:
644 args.extend(["--timeout", f"{self.timeout}"])
645 if dry_run:
646 args.append("--dry-run")
647 args.append("--")
648 for service in self.services:
649 args.append(service)
650 return args
651
652 def cmd_restart(self) -> dict[str, t.Any]:
653 result: dict[str, t.Any] = {}
654 args = self.get_restart_cmd(self.check_mode)
655 rc, stdout, stderr = self.client.call_cli(*args, cwd=self.project_src)
656 events = self.parse_events(stderr, dry_run=self.check_mode, nonzero_rc=rc != 0)
657 self.emit_warnings(events)
658 self.update_result(result, events, stdout, stderr)
659 self.update_failed(result, events, args, stdout, stderr, rc)
660 return result
661
662 def get_down_cmd(self, dry_run: bool) -> list[str]:
663 args = self.get_base_args() + ["down"]
664 if self.remove_orphans:
665 args.append("--remove-orphans")
666 if self.remove_images:
667 args.extend(["--rmi", self.remove_images])
668 if self.remove_volumes:
669 args.append("--volumes")
670 if self.timeout is not None:
671 args.extend(["--timeout", f"{self.timeout}"])
672 if dry_run:
673 args.append("--dry-run")
674 args.append("--")
675 for service in self.services:
676 args.append(service)
677 return args
678
679 def cmd_down(self) -> dict[str, t.Any]:
680 result: dict[str, t.Any] = {}
681 args = self.get_down_cmd(self.check_mode)
682 rc, stdout, stderr = self.client.call_cli(*args, cwd=self.project_src)
683 events = self.parse_events(stderr, dry_run=self.check_mode, nonzero_rc=rc != 0)
684 self.emit_warnings(events)
685 self.update_result(result, events, stdout, stderr)
686 self.update_failed(result, events, args, stdout, stderr, rc)
687 return result
688
689
690 def main() -> None:
691 argument_spec = {
692 "state": {
693 "type": "str",
694 "default": "present",
695 "choices": ["absent", "present", "stopped", "restarted"],
696 },
697 "dependencies": {"type": "bool", "default": True},
698 "pull": {
699 "type": "str",
700 "choices": ["always", "missing", "never", "policy"],
701 "default": "policy",
702 },
703 "build": {
704 "type": "str",
705 "choices": ["always", "never", "policy"],
706 "default": "policy",
707 },
708 "recreate": {
709 "type": "str",
710 "default": "auto",
711 "choices": ["always", "never", "auto"],
712 },
713 "renew_anon_volumes": {"type": "bool", "default": False},
714 "remove_images": {"type": "str", "choices": ["all", "local"]},
715 "remove_volumes": {"type": "bool", "default": False},
716 "remove_orphans": {"type": "bool", "default": False},
717 "timeout": {"type": "int"},
718 "services": {"type": "list", "elements": "str"},
719 "scale": {"type": "dict"},
720 "wait": {"type": "bool", "default": False},
721 "wait_timeout": {"type": "int"},
722 "ignore_build_events": {"type": "bool", "default": True},
723 "assume_yes": {"type": "bool", "default": False},
724 }
725 argspec_ex = common_compose_argspec_ex()
726 argument_spec.update(argspec_ex.pop("argspec"))
727
728 client = AnsibleModuleDockerClient(
729 argument_spec=argument_spec,
730 supports_check_mode=True,
731 needs_api_version=False,
732 **argspec_ex,
733 )
734
735 try:
736 manager = ServicesManager(client)
737 result = manager.run()
738 manager.cleanup()
739 client.module.exit_json(**result)
740 except DockerException as e:
741 client.fail(
742 f"An unexpected Docker error occurred: {e}",
743 exception=traceback.format_exc(),
744 )
745
746
747 if __name__ == "__main__":
748 main()