Debian Codegraph @

ansible_collections/community/docker/plugins/modules/docker_compose_v2_pull.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_pull
11
12 short_description: Pull a Docker compose project
13
14 version_added: 3.6.0
15
16 description:
17 - Uses Docker Compose to pull images for a project.
18 extends_documentation_fragment:
19 - community.docker._compose_v2
20 - community.docker._compose_v2.minimum_version
21 - community.docker._docker.cli_documentation
22 - community.docker._attributes
23 - community.docker._attributes.actiongroup_docker
24
25 attributes:
26 check_mode:
27 support: full
28 details:
29 - If O(policy=always), the module will always indicate a change. Docker Compose does not give any information whether
30 pulling would update the image or not.
31 diff_mode:
32 support: none
33 idempotent:
34 support: full
35
36 options:
37 policy:
38 description:
39 - Whether to pull images before running. This is used when C(docker compose up) is ran.
40 - V(always) ensures that the images are always pulled, even when already present on the Docker daemon.
41 - V(missing) only pulls them when they are not present on the Docker daemon. This is only supported since Docker Compose
42 2.22.0.
43 type: str
44 choices:
45 - always
46 - missing
47 default: always
48 ignore_buildable:
49 description:
50 - If set to V(true), will not pull images that can be built.
51 type: bool
52 default: false
53 version_added: 3.12.0
54 ignore_pull_failures:
55 description:
56 - If set to V(true), will pull what it can and ignores images with pull failures.
57 type: bool
58 default: false
59 version_added: 5.1.0
60 include_deps:
61 description:
62 - If set to V(true), also pull services that are declared as dependencies.
63 - This only makes sense if O(services) is used.
64 type: bool
65 default: false
66 version_added: 3.12.0
67 services:
68 description:
69 - Specifies a subset of services to be targeted.
70 type: list
71 elements: str
72 version_added: 3.12.0
73
74 author:
75 - Felix Fontein (@felixfontein)
76
77 seealso:
78 - module: community.docker.docker_compose_v2
79 """
80
81 EXAMPLES = r"""
82 ---
83 - name: Pull images for flask project
84 community.docker.docker_compose_v2_pull:
85 project_src: /path/to/flask
86 """
87
88 RETURN = r"""
89 actions:
90 description:
91 - A list of actions that have been applied.
92 returned: success
93 type: list
94 elements: dict
95 contains:
96 what:
97 description:
98 - What kind of resource was changed.
99 type: str
100 sample: container
101 choices:
102 - image
103 - unknown
104 id:
105 description:
106 - The ID of the resource that was changed.
107 type: str
108 sample: container
109 status:
110 description:
111 - The status change that happened.
112 type: str
113 sample: Pulling
114 choices:
115 - Pulling
116 """
117
118 import traceback
119 import typing as t
120
121 from ansible_collections.community.docker.plugins.module_utils._common_cli import (
122 AnsibleModuleDockerClient,
123 DockerException,
124 )
125 from ansible_collections.community.docker.plugins.module_utils._compose_v2 import (
126 BaseComposeManager,
127 common_compose_argspec_ex,
128 )
129 from ansible_collections.community.docker.plugins.module_utils._version import (
130 LooseVersion,
131 )
132
133
134 class PullManager(BaseComposeManager):
135 def __init__(self, client: AnsibleModuleDockerClient) -> None:
136 super().__init__(client)
137 parameters = self.client.module.params
138
139 self.policy: t.Literal["always", "missing"] = parameters["policy"]
140 self.ignore_buildable: bool = parameters["ignore_buildable"]
141 self.ignore_pull_failures: bool = parameters["ignore_pull_failures"]
142 self.include_deps: bool = parameters["include_deps"]
143 self.services: list[str] = parameters["services"] or []
144
145 if self.policy != "always" and self.compose_version < LooseVersion("2.22.0"):
146 # https://github.com/docker/compose/pull/10981 - 2.22.0
147 self.fail(
148 f"A pull policy other than always is only supported since Docker Compose 2.22.0. {self.client.get_cli()} has version {self.compose_version}"
149 )
150 if self.ignore_buildable and self.compose_version < LooseVersion("2.15.0"):
151 # https://github.com/docker/compose/pull/10134 - 2.15.0
152 self.fail(
153 f"--ignore-buildable is only supported since Docker Compose 2.15.0. {self.client.get_cli()} has version {self.compose_version}"
154 )
155
156 def get_pull_cmd(self, dry_run: bool) -> list[str]:
157 args = self.get_base_args() + ["pull"]
158 if self.policy != "always":
159 args.extend(["--policy", self.policy])
160 if self.ignore_buildable:
161 args.append("--ignore-buildable")
162 if self.ignore_pull_failures:
163 args.append("--ignore-pull-failures")
164 if self.include_deps:
165 args.append("--include-deps")
166 if dry_run:
167 args.append("--dry-run")
168 args.append("--")
169 for service in self.services:
170 args.append(service)
171 return args
172
173 def run(self) -> dict[str, t.Any]:
174 result: dict[str, t.Any] = {}
175 args = self.get_pull_cmd(self.check_mode)
176 rc, stdout, stderr = self.client.call_cli(*args, cwd=self.project_src)
177 events = self.parse_events(stderr, dry_run=self.check_mode, nonzero_rc=rc != 0)
178 self.emit_warnings(events)
179 self.update_result(
180 result,
181 events,
182 stdout,
183 stderr,
184 ignore_service_pull_events=self.policy != "missing" and not self.check_mode,
185 )
186 self.update_failed(result, events, args, stdout, stderr, rc)
187 self.cleanup_result(result)
188 return result
189
190
191 def main() -> None:
192 argument_spec = {
193 "policy": {
194 "type": "str",
195 "choices": ["always", "missing"],
196 "default": "always",
197 },
198 "ignore_buildable": {"type": "bool", "default": False},
199 "ignore_pull_failures": {"type": "bool", "default": False},
200 "include_deps": {"type": "bool", "default": False},
201 "services": {"type": "list", "elements": "str"},
202 }
203 argspec_ex = common_compose_argspec_ex()
204 argument_spec.update(argspec_ex.pop("argspec"))
205
206 client = AnsibleModuleDockerClient(
207 argument_spec=argument_spec,
208 supports_check_mode=True,
209 needs_api_version=False,
210 **argspec_ex,
211 )
212
213 try:
214 manager = PullManager(client)
215 result = manager.run()
216 manager.cleanup()
217 client.module.exit_json(**result)
218 except DockerException as e:
219 client.fail(
220 f"An unexpected docker error occurred: {e}",
221 exception=traceback.format_exc(),
222 )
223
224
225 if __name__ == "__main__":
226 main()