Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2018 Dario Zanzico ([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_stack
11 author: "Dario Zanzico (@dariko)"
12 short_description: docker stack module
13 description:
14 - Manage docker stacks using the C(docker stack) command on the target node (see examples).
15 extends_documentation_fragment:
16 - community.docker._docker.cli_documentation
17 - community.docker._attributes
18 - community.docker._attributes.actiongroup_docker
19 attributes:
20 check_mode:
21 support: none
22 diff_mode:
23 support: none
24 action_group:
25 version_added: 3.6.0
26 idempotent:
27 support: full
28 options:
29 name:
30 description:
31 - Stack name.
32 type: str
33 required: true
34 state:
35 description:
36 - Service state.
37 type: str
38 default: "present"
39 choices:
40 - present
41 - absent
42 compose:
43 description:
44 - List of compose definitions. Any element may be a string referring to the path of the compose file on the target host
45 or the YAML contents of a compose file nested as dictionary.
46 type: list
47 elements: raw
48 default: []
49 prune:
50 description:
51 - If true will add the C(--prune) option to the C(docker stack deploy) command. This will have docker remove the services
52 not present in the current stack definition.
53 type: bool
54 default: false
55 detach:
56 description:
57 - If V(false), the C(--detach=false) option is added to the C(docker stack deploy) command, allowing Docker to wait
58 for tasks to converge before exiting.
59 - If V(true) (default), Docker exits immediately instead of waiting for tasks to converge.
60 type: bool
61 default: true
62 version_added: 4.1.0
63 with_registry_auth:
64 description:
65 - If true will add the C(--with-registry-auth) option to the C(docker stack deploy) command. This will have docker send
66 registry authentication details to Swarm agents.
67 type: bool
68 default: false
69 resolve_image:
70 description:
71 - If set will add the C(--resolve-image) option to the C(docker stack deploy) command. This will have docker query the
72 registry to resolve image digest and supported platforms. If not set, docker use "always" by default.
73 type: str
74 choices: ["always", "changed", "never"]
75 absent_retries:
76 description:
77 - If larger than V(0) and O(state=absent) the module will retry up to O(absent_retries) times to delete the stack until
78 all the resources have been effectively deleted. If the last try still reports the stack as not completely removed
79 the module will fail.
80 type: int
81 default: 0
82 absent_retries_interval:
83 description:
84 - Interval in seconds between consecutive O(absent_retries).
85 type: int
86 default: 1
87 docker_cli:
88 version_added: 3.6.0
89 docker_host:
90 version_added: 3.6.0
91 tls_hostname:
92 version_added: 3.6.0
93 api_version:
94 version_added: 3.6.0
95 ca_path:
96 version_added: 3.6.0
97 client_cert:
98 version_added: 3.6.0
99 client_key:
100 version_added: 3.6.0
101 tls:
102 version_added: 3.6.0
103 validate_certs:
104 version_added: 3.6.0
105 cli_context:
106 version_added: 3.6.0
107
108 requirements:
109 - Docker CLI tool C(docker)
110 - jsondiff
111 - pyyaml
112 """
113
114 RETURN = r"""
115 stack_spec_diff:
116 description: |-
117 Dictionary containing the differences between the 'Spec' field
118 of the stack services before and after applying the new stack
119 definition.
120 sample: >
121 "stack_spec_diff":
122 {'test_stack_test_service': {'TaskTemplate': {'ContainerSpec': {delete: ['Env']}}}}
123 returned: on change
124 type: dict
125 """
126
127 EXAMPLES = r"""
128 ---
129 - name: Deploy stack from a compose file
130 community.docker.docker_stack:
131 state: present
132 name: mystack
133 compose:
134 - /opt/docker-compose.yml
135
136 - name: Deploy stack from base compose file and override the web service
137 community.docker.docker_stack:
138 state: present
139 name: mystack
140 compose:
141 - /opt/docker-compose.yml
142 - version: '3'
143 services:
144 web:
145 image: nginx:latest
146 environment:
147 ENVVAR: envvar
148
149 - name: Remove stack
150 community.docker.docker_stack:
151 name: mystack
152 state: absent
153 """
154
155
156 import json
157 import os
158 import tempfile
159 import traceback
160 import typing as t
161 from time import sleep
162
163 from ansible.module_utils.common.text.converters import to_text
164
165 from ansible_collections.community.docker.plugins.module_utils._common_cli import (
166 AnsibleModuleDockerClient,
167 DockerException,
168 )
169
170 try:
171 from jsondiff import diff as json_diff
172
173 HAS_JSONDIFF = True
174 except ImportError:
175 HAS_JSONDIFF = False
176
177 try:
178 from yaml import dump as yaml_dump
179
180 HAS_YAML = True
181 except ImportError:
182 HAS_YAML = False
183
184
185 def docker_stack_services(
186 client: AnsibleModuleDockerClient, stack_name: str
187 ) -> list[str]:
188 dummy_rc, out, err = client.call_cli(
189 "stack", "services", stack_name, "--format", "{{.Name}}"
190 )
191 if to_text(err) == f"Nothing found in stack: {stack_name}\n":
192 return []
193 return to_text(out).strip().split("\n")
194
195
196 def docker_service_inspect(
197 client: AnsibleModuleDockerClient, service_name: str
198 ) -> dict[str, t.Any] | None:
199 rc, out, dummy_err = client.call_cli("service", "inspect", service_name)
200 if rc != 0:
201 return None
202 ret = json.loads(out)[0]["Spec"]
203 return ret
204
205
206 def docker_stack_deploy(
207 client: AnsibleModuleDockerClient, stack_name: str, compose_files: list[str]
208 ) -> tuple[int, str, str]:
209 command = ["stack", "deploy"]
210 if client.module.params["prune"]:
211 command += ["--prune"]
212 if not client.module.params["detach"]:
213 command += ["--detach=false"]
214 if client.module.params["with_registry_auth"]:
215 command += ["--with-registry-auth"]
216 if client.module.params["resolve_image"]:
217 command += ["--resolve-image", client.module.params["resolve_image"]]
218 for compose_file in compose_files:
219 command += ["--compose-file", compose_file]
220 command += [stack_name]
221 rc, out, err = client.call_cli(*command)
222 return rc, to_text(out), to_text(err)
223
224
225 def docker_stack_inspect(
226 client: AnsibleModuleDockerClient, stack_name: str
227 ) -> dict[str, dict[str, t.Any] | None]:
228 ret: dict[str, dict[str, t.Any] | None] = {}
229 for service_name in docker_stack_services(client, stack_name):
230 ret[service_name] = docker_service_inspect(client, service_name)
231 return ret
232
233
234 def docker_stack_rm(
235 client: AnsibleModuleDockerClient,
236 stack_name: str,
237 retries: int,
238 interval: int | float,
239 ) -> tuple[int, str, str]:
240 command = ["stack", "rm", stack_name]
241 if not client.module.params["detach"]:
242 command += ["--detach=false"]
243 rc, out, err = client.call_cli(*command)
244
245 while to_text(err) != f"Nothing found in stack: {stack_name}\n" and retries > 0:
246 sleep(interval)
247 retries = retries - 1
248 rc, out, err = client.call_cli(*command)
249 return rc, to_text(out), to_text(err)
250
251
252 def main() -> None:
253 client = AnsibleModuleDockerClient(
254 argument_spec={
255 "name": {"type": "str", "required": True},
256 "compose": {"type": "list", "elements": "raw", "default": []},
257 "prune": {"type": "bool", "default": False},
258 "detach": {"type": "bool", "default": True},
259 "with_registry_auth": {"type": "bool", "default": False},
260 "resolve_image": {"type": "str", "choices": ["always", "changed", "never"]},
261 "state": {
262 "type": "str",
263 "default": "present",
264 "choices": ["present", "absent"],
265 },
266 "absent_retries": {"type": "int", "default": 0},
267 "absent_retries_interval": {"type": "int", "default": 1},
268 },
269 supports_check_mode=False,
270 )
271
272 if not HAS_JSONDIFF:
273 client.fail("jsondiff is not installed, try 'pip install jsondiff'")
274
275 if not HAS_YAML:
276 client.fail("yaml is not installed, try 'pip install pyyaml'")
277
278 try:
279 state = client.module.params["state"]
280 compose = client.module.params["compose"]
281 name = client.module.params["name"]
282 absent_retries = client.module.params["absent_retries"]
283 absent_retries_interval = client.module.params["absent_retries_interval"]
284
285 if state == "present":
286 if not compose:
287 client.fail(
288 "compose parameter must be a list containing at least one element"
289 )
290
291 compose_files = []
292 for compose_def in compose:
293 if isinstance(compose_def, dict):
294 compose_file_fd, compose_file = tempfile.mkstemp()
295 client.module.add_cleanup_file(compose_file)
296 with os.fdopen(compose_file_fd, "w") as stack_file:
297 compose_files.append(compose_file)
298 stack_file.write(yaml_dump(compose_def))
299 elif isinstance(compose_def, str):
300 compose_files.append(compose_def)
301 else:
302 client.fail(
303 f"compose element '{compose_def}' must be a string or a dictionary"
304 )
305
306 before_stack_services = docker_stack_inspect(client, name)
307
308 rc, out, err = docker_stack_deploy(client, name, compose_files)
309
310 after_stack_services = docker_stack_inspect(client, name)
311
312 if rc != 0:
313 client.fail(
314 "docker stack up deploy command failed",
315 rc=rc,
316 stdout=out,
317 stderr=err,
318 )
319
320 before_after_differences = json_diff(
321 before_stack_services, after_stack_services
322 )
323 for k in before_after_differences:
324 if isinstance(before_after_differences[k], dict):
325 before_after_differences[k].pop("UpdatedAt", None)
326 before_after_differences[k].pop("Version", None)
327 if not list(before_after_differences[k].keys()):
328 before_after_differences.pop(k)
329
330 if not before_after_differences:
331 client.module.exit_json(
332 changed=False,
333 rc=rc,
334 stdout=out,
335 stderr=err,
336 )
337 else:
338 client.module.exit_json(
339 changed=True,
340 rc=rc,
341 stdout=out,
342 stderr=err,
343 stack_spec_diff=json_diff(
344 before_stack_services,
345 after_stack_services,
346 dump=True,
347 ),
348 )
349
350 else:
351 if docker_stack_services(client, name):
352 rc, out, err = docker_stack_rm(
353 client, name, absent_retries, absent_retries_interval
354 )
355 if rc != 0:
356 client.module.fail_json(
357 msg="'docker stack down' command failed",
358 rc=rc,
359 stdout=out,
360 stderr=err,
361 )
362 else:
363 client.module.exit_json(
364 changed=True,
365 msg=out,
366 rc=rc,
367 stdout=out,
368 stderr=err,
369 )
370 client.module.exit_json(changed=False)
371 except DockerException as e:
372 client.fail(
373 f"An unexpected Docker error occurred: {e}",
374 exception=traceback.format_exc(),
375 )
376
377
378 if __name__ == "__main__":
379 main()