Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2017, 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_swarm_service
11 author:
12 - "Dario Zanzico (@dariko)"
13 - "Jason Witkowski (@jwitko)"
14 - "Hannes Ljungberg (@hannseman)"
15 - "Piotr Wojciechowski (@wojciechowskipiotr)"
16 short_description: docker swarm service
17 description:
18 - Manages docker services through a swarm manager node.
19 - This modules does not support updating services in a stack.
20 extends_documentation_fragment:
21 - community.docker._docker
22 - community.docker._docker.docker_py_2_documentation
23 - community.docker._attributes
24 - community.docker._attributes.actiongroup_docker
25
26 attributes:
27 check_mode:
28 support: full
29 diff_mode:
30 support: full
31 idempotent:
32 support: full
33
34 options:
35 args:
36 description:
37 - List arguments to be passed to the container.
38 - Corresponds to the C(ARG) parameter of C(docker service create).
39 type: list
40 elements: str
41 command:
42 description:
43 - Command to execute when the container starts.
44 - A command may be either a string or a list or a list of strings.
45 - Corresponds to the C(COMMAND) parameter of C(docker service create).
46 type: raw
47 configs:
48 description:
49 - List of dictionaries describing the service configs.
50 - Corresponds to the C(--config) option of C(docker service create).
51 - Requires API version >= 1.30.
52 type: list
53 elements: dict
54 suboptions:
55 config_id:
56 description:
57 - Config's ID.
58 type: str
59 config_name:
60 description:
61 - Config's name as defined at its creation.
62 type: str
63 required: true
64 filename:
65 description:
66 - Name of the file containing the config. Defaults to the O(configs[].config_name) if not specified.
67 type: str
68 uid:
69 description:
70 - UID of the config file's owner.
71 type: str
72 gid:
73 description:
74 - GID of the config file's group.
75 type: str
76 mode:
77 description:
78 - File access mode inside the container. Must be an octal number (like V(0644) or V(0444)).
79 type: int
80 container_labels:
81 description:
82 - Dictionary of key value pairs.
83 - Corresponds to the C(--container-label) option of C(docker service create).
84 type: dict
85 sysctls:
86 description:
87 - Dictionary of key, value pairs.
88 version_added: 3.10.0
89 type: dict
90 dns:
91 description:
92 - List of custom DNS servers.
93 - Corresponds to the C(--dns) option of C(docker service create).
94 type: list
95 elements: str
96 dns_search:
97 description:
98 - List of custom DNS search domains.
99 - Corresponds to the C(--dns-search) option of C(docker service create).
100 type: list
101 elements: str
102 dns_options:
103 description:
104 - List of custom DNS options.
105 - Corresponds to the C(--dns-option) option of C(docker service create).
106 type: list
107 elements: str
108 endpoint_mode:
109 description:
110 - Service endpoint mode.
111 - Corresponds to the C(--endpoint-mode) option of C(docker service create).
112 type: str
113 choices:
114 - vip
115 - dnsrr
116 env:
117 description:
118 - List or dictionary of the service environment variables.
119 - If passed a list each items need to be in the format of C(KEY=VALUE).
120 - If passed a dictionary values which might be parsed as numbers, booleans or other types by the YAML parser must be
121 quoted (for example V("true")) in order to avoid data loss.
122 - Corresponds to the C(--env) option of C(docker service create).
123 type: raw
124 env_files:
125 description:
126 - List of paths to files, present on the target, containing environment variables C(FOO=BAR).
127 - The order of the list is significant in determining the value assigned to a variable that shows up more than once.
128 - If variable also present in O(env), then O(env) value will override.
129 type: list
130 elements: path
131 force_update:
132 description:
133 - Force update even if no changes require it.
134 - Corresponds to the C(--force) option of C(docker service update).
135 type: bool
136 default: false
137 groups:
138 description:
139 - List of additional group names and/or IDs that the container process will run as.
140 - Corresponds to the C(--group) option of C(docker service update).
141 type: list
142 elements: str
143 healthcheck:
144 description:
145 - Configure a check that is run to determine whether or not containers for this service are "healthy". See the docs
146 for the L(HEALTHCHECK Dockerfile instruction,https://docs.docker.com/engine/reference/builder/#healthcheck) for details
147 on how healthchecks work.
148 - 'O(healthcheck.interval), O(healthcheck.timeout), and O(healthcheck.start_period) are specified as durations. They
149 accept duration as a string in a format that look like: V(5h34m56s), V(1m30s), and so on. The supported units are
150 V(us), V(ms), V(s), V(m) and V(h).'
151 type: dict
152 suboptions:
153 test:
154 description:
155 - Command to run to check health.
156 - Must be either a string or a list. If it is a list, the first item must be one of V(NONE), V(CMD) or V(CMD-SHELL).
157 type: raw
158 interval:
159 description:
160 - Time between running the check.
161 type: str
162 timeout:
163 description:
164 - Maximum time to allow one check to run.
165 type: str
166 retries:
167 description:
168 - Consecutive failures needed to report unhealthy. It accept integer value.
169 type: int
170 start_period:
171 description:
172 - Start period for the container to initialize before starting health-retries countdown.
173 type: str
174 hostname:
175 description:
176 - Container hostname.
177 - Corresponds to the C(--hostname) option of C(docker service create).
178 type: str
179 hosts:
180 description:
181 - Dict of host-to-IP mappings, where each host name is a key in the dictionary. Each host name will be added to the
182 container's /etc/hosts file.
183 - Corresponds to the C(--host) option of C(docker service create).
184 type: dict
185 image:
186 description:
187 - Service image path and tag.
188 - Corresponds to the C(IMAGE) parameter of C(docker service create).
189 type: str
190 init:
191 description:
192 - Use an init inside each service container to forward signals and reap processes.
193 - Corresponds to the C(--init) option of C(docker service create).
194 - Requires API version >= 1.37.
195 type: bool
196 labels:
197 description:
198 - Dictionary of key value pairs.
199 - Corresponds to the C(--label) option of C(docker service create).
200 type: dict
201 limits:
202 description:
203 - Configures service resource limits.
204 suboptions:
205 cpus:
206 description:
207 - Service CPU limit. V(0) equals no limit.
208 - Corresponds to the C(--limit-cpu) option of C(docker service create).
209 type: float
210 memory:
211 description:
212 - Service memory limit in format C(<number>[<unit>]). Number is a positive integer. Unit can be V(B) (byte), V(K)
213 (kibibyte, 1024B), V(M) (mebibyte), V(G) (gibibyte), V(T) (tebibyte), or V(P) (pebibyte).
214 - V(0) equals no limit.
215 - Omitting the unit defaults to bytes.
216 - Corresponds to the C(--limit-memory) option of C(docker service create).
217 type: str
218 type: dict
219 logging:
220 description:
221 - Logging configuration for the service.
222 suboptions:
223 driver:
224 description:
225 - Configure the logging driver for a service.
226 - Corresponds to the C(--log-driver) option of C(docker service create).
227 type: str
228 options:
229 description:
230 - Options for service logging driver.
231 - Corresponds to the C(--log-opt) option of C(docker service create).
232 type: dict
233 type: dict
234 mode:
235 description:
236 - Service replication mode.
237 - Service will be removed and recreated when changed.
238 - Corresponds to the C(--mode) option of C(docker service create).
239 - The value V(replicated-job) was added in community.docker 4.7.0, and requires API version >= 1.41 and Docker SDK for Python >= 6.0.0.
240 type: str
241 default: replicated
242 choices:
243 - replicated
244 - global
245 - replicated-job
246 mounts:
247 description:
248 - List of dictionaries describing the service mounts.
249 - Corresponds to the C(--mount) option of C(docker service create).
250 type: list
251 elements: dict
252 suboptions:
253 source:
254 description:
255 - Mount source (for example a volume name or a host path).
256 - Must be specified if O(mounts[].type) is not V(tmpfs).
257 type: str
258 target:
259 description:
260 - Container path.
261 type: str
262 required: true
263 type:
264 description:
265 - The mount type.
266 - Note that V(npipe) is only supported by Docker for Windows. Also note that V(npipe) was added in Ansible 2.9.
267 type: str
268 default: bind
269 choices:
270 - bind
271 - volume
272 - tmpfs
273 - npipe
274 readonly:
275 description:
276 - Whether the mount should be read-only.
277 type: bool
278 labels:
279 description:
280 - Volume labels to apply.
281 type: dict
282 propagation:
283 description:
284 - The propagation mode to use.
285 - Can only be used when O(mounts[].type=bind).
286 type: str
287 choices:
288 - shared
289 - slave
290 - private
291 - rshared
292 - rslave
293 - rprivate
294 no_copy:
295 description:
296 - Disable copying of data from a container when a volume is created.
297 - Can only be used when O(mounts[].type=volume).
298 type: bool
299 driver_config:
300 description:
301 - Volume driver configuration.
302 - Can only be used when O(mounts[].type=volume).
303 suboptions:
304 name:
305 description:
306 - Name of the volume-driver plugin to use for the volume.
307 type: str
308 options:
309 description:
310 - Options as key-value pairs to pass to the driver for this volume.
311 type: dict
312 type: dict
313 tmpfs_size:
314 description:
315 - Size of the tmpfs mount in format C(<number>[<unit>]). Number is a positive integer. Unit can be V(B) (byte),
316 V(K) (kibibyte, 1024B), V(M) (mebibyte), V(G) (gibibyte), V(T) (tebibyte), or V(P) (pebibyte).
317 - Can only be used when O(mounts[].type=tmpfs).
318 type: str
319 tmpfs_mode:
320 description:
321 - File mode of the tmpfs in octal.
322 - Can only be used when O(mounts[].type=tmpfs).
323 type: int
324 name:
325 description:
326 - Service name.
327 - Corresponds to the C(--name) option of C(docker service create).
328 type: str
329 required: true
330 networks:
331 description:
332 - List of the service networks names or dictionaries.
333 - When passed dictionaries valid sub-options are C(name), which is required, and C(aliases) and C(options).
334 - Prior to API version 1.29, updating and removing networks is not supported. If changes are made the service will then
335 be removed and recreated.
336 - Corresponds to the C(--network) option of C(docker service create).
337 type: list
338 elements: raw
339 placement:
340 description:
341 - Configures service placement preferences and constraints.
342 suboptions:
343 constraints:
344 description:
345 - List of the service constraints.
346 - Corresponds to the C(--constraint) option of C(docker service create).
347 type: list
348 elements: str
349 preferences:
350 description:
351 - List of the placement preferences as key value pairs.
352 - Corresponds to the C(--placement-pref) option of C(docker service create).
353 - Requires API version >= 1.27.
354 type: list
355 elements: dict
356 replicas_max_per_node:
357 description:
358 - Maximum number of tasks per node.
359 - Corresponds to the C(--replicas_max_per_node) option of C(docker service create).
360 - Requires API version >= 1.40.
361 type: int
362 version_added: 1.3.0
363 type: dict
364 publish:
365 description:
366 - List of dictionaries describing the service published ports.
367 - Corresponds to the C(--publish) option of C(docker service create).
368 type: list
369 elements: dict
370 suboptions:
371 published_port:
372 description:
373 - The port to make externally available.
374 type: int
375 required: false
376 target_port:
377 description:
378 - The port inside the container to expose.
379 type: int
380 required: true
381 protocol:
382 description:
383 - What protocol to use.
384 type: str
385 default: tcp
386 choices:
387 - tcp
388 - udp
389 mode:
390 description:
391 - What publish mode to use.
392 - Requires API version >= 1.32.
393 type: str
394 choices:
395 - ingress
396 - host
397 read_only:
398 description:
399 - Mount the containers root filesystem as read only.
400 - Corresponds to the C(--read-only) option of C(docker service create).
401 type: bool
402 replicas:
403 description:
404 - Number of containers instantiated in the service. Valid only if O(mode=replicated) or O(mode=replicated-job).
405 - If set to V(-1), and service is not present, service replicas will be set to V(1).
406 - If set to V(-1), and service is present, service replicas will be unchanged.
407 - Corresponds to the C(--replicas) option of C(docker service create).
408 type: int
409 default: -1
410 reservations:
411 description:
412 - Configures service resource reservations.
413 suboptions:
414 cpus:
415 description:
416 - Service CPU reservation. V(0) equals no reservation.
417 - Corresponds to the C(--reserve-cpu) option of C(docker service create).
418 type: float
419 memory:
420 description:
421 - Service memory reservation in format C(<number>[<unit>]). Number is a positive integer. Unit can be V(B) (byte),
422 V(K) (kibibyte, 1024B), V(M) (mebibyte), V(G) (gibibyte), V(T) (tebibyte), or V(P) (pebibyte).
423 - V(0) equals no reservation.
424 - Omitting the unit defaults to bytes.
425 - Corresponds to the C(--reserve-memory) option of C(docker service create).
426 type: str
427 type: dict
428 resolve_image:
429 description:
430 - If the current image digest should be resolved from registry and updated if changed.
431 - Requires API version >= 1.30.
432 type: bool
433 default: false
434 restart_config:
435 description:
436 - Configures if and how to restart containers when they exit.
437 suboptions:
438 condition:
439 description:
440 - Restart condition of the service.
441 - Corresponds to the C(--restart-condition) option of C(docker service create).
442 type: str
443 choices:
444 - none
445 - on-failure
446 - any
447 delay:
448 description:
449 - Delay between restarts.
450 - 'Accepts a a string in a format that look like: V(5h34m56s), V(1m30s), and so on. The supported units are V(us), V(ms),
451 V(s), V(m) and V(h).'
452 - Corresponds to the C(--restart-delay) option of C(docker service create).
453 type: str
454 max_attempts:
455 description:
456 - Maximum number of service restarts.
457 - Corresponds to the C(--restart-condition) option of C(docker service create).
458 type: int
459 window:
460 description:
461 - Restart policy evaluation window.
462 - 'Accepts a string in a format that look like: V(5h34m56s), V(1m30s), and so on. The supported units are V(us), V(ms),
463 V(s), V(m) and V(h).'
464 - Corresponds to the C(--restart-window) option of C(docker service create).
465 type: str
466 type: dict
467 rollback_config:
468 description:
469 - Configures how the service should be rolled back in case of a failing update.
470 suboptions:
471 parallelism:
472 description:
473 - The number of containers to rollback at a time. If set to 0, all containers rollback simultaneously.
474 - Corresponds to the C(--rollback-parallelism) option of C(docker service create).
475 - Requires API version >= 1.28.
476 type: int
477 delay:
478 description:
479 - Delay between task rollbacks.
480 - 'Accepts a string in a format that look like: V(5h34m56s), V(1m30s), and so on. The supported units are V(us), V(ms),
481 V(s), V(m) and V(h).'
482 - Corresponds to the C(--rollback-delay) option of C(docker service create).
483 - Requires API version >= 1.28.
484 type: str
485 failure_action:
486 description:
487 - Action to take in case of rollback failure.
488 - Corresponds to the C(--rollback-failure-action) option of C(docker service create).
489 - Requires API version >= 1.28.
490 type: str
491 choices:
492 - continue
493 - pause
494 monitor:
495 description:
496 - Duration after each task rollback to monitor for failure.
497 - 'Accepts a string in a format that look like: V(5h34m56s), V(1m30s), and so on. The supported units are V(us), V(ms),
498 V(s), V(m) and V(h).'
499 - Corresponds to the C(--rollback-monitor) option of C(docker service create).
500 - Requires API version >= 1.28.
501 type: str
502 max_failure_ratio:
503 description:
504 - Fraction of tasks that may fail during a rollback.
505 - Corresponds to the C(--rollback-max-failure-ratio) option of C(docker service create).
506 - Requires API version >= 1.28.
507 type: float
508 order:
509 description:
510 - Specifies the order of operations during rollbacks.
511 - Corresponds to the C(--rollback-order) option of C(docker service create).
512 - Requires API version >= 1.29.
513 type: str
514 type: dict
515 secrets:
516 description:
517 - List of dictionaries describing the service secrets.
518 - Corresponds to the C(--secret) option of C(docker service create).
519 type: list
520 elements: dict
521 suboptions:
522 secret_id:
523 description:
524 - Secret's ID.
525 type: str
526 secret_name:
527 description:
528 - Secret's name as defined at its creation.
529 type: str
530 required: true
531 filename:
532 description:
533 - Name of the file containing the secret. Defaults to the O(secrets[].secret_name) if not specified.
534 - Corresponds to the C(target) key of C(docker service create --secret).
535 type: str
536 uid:
537 description:
538 - UID of the secret file's owner.
539 type: str
540 gid:
541 description:
542 - GID of the secret file's group.
543 type: str
544 mode:
545 description:
546 - File access mode inside the container. Must be an octal number (like V(0644) or V(0444)).
547 type: int
548 state:
549 description:
550 - V(absent) - A service matching the specified name will be removed and have its tasks stopped.
551 - V(present) - Asserts the existence of a service matching the name and provided configuration parameters. Unspecified
552 configuration parameters will be set to docker defaults.
553 type: str
554 default: present
555 choices:
556 - present
557 - absent
558 stop_grace_period:
559 description:
560 - Time to wait before force killing a container.
561 - 'Accepts a duration as a string in a format that look like: V(5h34m56s), V(1m30s), and so on. The supported units are V(us),
562 V(ms), V(s), V(m) and V(h).'
563 - Corresponds to the C(--stop-grace-period) option of C(docker service create).
564 type: str
565 stop_signal:
566 description:
567 - Override default signal used to stop the container.
568 - Corresponds to the C(--stop-signal) option of C(docker service create).
569 type: str
570 tty:
571 description:
572 - Allocate a pseudo-TTY.
573 - Corresponds to the C(--tty) option of C(docker service create).
574 type: bool
575 update_config:
576 description:
577 - Configures how the service should be updated. Useful for configuring rolling updates.
578 suboptions:
579 parallelism:
580 description:
581 - Rolling update parallelism.
582 - Corresponds to the C(--update-parallelism) option of C(docker service create).
583 type: int
584 delay:
585 description:
586 - Rolling update delay.
587 - 'Accepts a string in a format that look like: V(5h34m56s), V(1m30s), and so on. The supported units are V(us), V(ms),
588 V(s), V(m) and V(h).'
589 - Corresponds to the C(--update-delay) option of C(docker service create).
590 type: str
591 failure_action:
592 description:
593 - Action to take in case of container failure.
594 - Corresponds to the C(--update-failure-action) option of C(docker service create).
595 - Usage of V(rollback) requires API version >= 1.29.
596 type: str
597 choices:
598 - continue
599 - pause
600 - rollback
601 monitor:
602 description:
603 - Time to monitor updated tasks for failures.
604 - 'Accepts a string in a format that look like: V(5h34m56s), V(1m30s), and so on. The supported units are V(us), V(ms),
605 V(s), V(m) and V(h).'
606 - Corresponds to the C(--update-monitor) option of C(docker service create).
607 type: str
608 max_failure_ratio:
609 description:
610 - Fraction of tasks that may fail during an update before the failure action is invoked.
611 - Corresponds to the C(--update-max-failure-ratio) option of C(docker service create).
612 type: float
613 order:
614 description:
615 - Specifies the order of operations when rolling out an updated task.
616 - Corresponds to the C(--update-order) option of C(docker service create).
617 - Requires API version >= 1.29.
618 type: str
619 type: dict
620 user:
621 description:
622 - Sets the username or UID used for the specified command.
623 - Before Ansible 2.8, the default value for this option was V(root).
624 - The default has been removed so that the user defined in the image is used if no user is specified here.
625 - Corresponds to the C(--user) option of C(docker service create).
626 type: str
627 working_dir:
628 description:
629 - Path to the working directory.
630 - Corresponds to the C(--workdir) option of C(docker service create).
631 type: str
632 cap_add:
633 description:
634 - List of capabilities to add to the container.
635 - Requires API version >= 1.41.
636 type: list
637 elements: str
638 version_added: 2.2.0
639 cap_drop:
640 description:
641 - List of capabilities to drop from the container.
642 - Requires API version >= 1.41.
643 type: list
644 elements: str
645 version_added: 2.2.0
646
647 requirements:
648 - "L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 2.0.2"
649 - "Docker API >= 1.25"
650 notes:
651 - Images will only resolve to the latest digest when using Docker API >= 1.30 and Docker SDK for Python >= 3.2.0. When using
652 older versions use O(force_update=true) to trigger the swarm to resolve a new image.
653 """
654
655 RETURN = r"""
656 swarm_service:
657 returned: always
658 type: dict
659 description:
660 - Dictionary of variables representing the current state of the service. Matches the module parameters format.
661 - Note that facts are not part of registered vars but accessible directly.
662 - Note that before Ansible 2.7.9, the return variable was documented as C(ansible_swarm_service), while the module actually
663 returned a variable called C(ansible_docker_service). The variable was renamed to RV(swarm_service) in both code and
664 documentation for Ansible 2.7.9 and Ansible 2.8.0. In Ansible 2.7.x, the old name C(ansible_docker_service) can still
665 be used.
666 sample: '{ "args": [ "3600" ], "cap_add": null, "cap_drop": [ "ALL" ], "command": [ "sleep" ], "configs": null, "constraints":
667 [ "node.role == manager", "engine.labels.operatingsystem == ubuntu 14.04" ], "container_labels": null, "sysctls": null,
668 "dns": null, "dns_options": null, "dns_search": null, "endpoint_mode": null, "env": [ "ENVVAR1=envvar1", "ENVVAR2=envvar2"
669 ], "force_update": null, "groups": null, "healthcheck": { "interval": 90000000000, "retries": 3, "start_period": 30000000000,
670 "test": [ "CMD", "curl", "--fail", "http://nginx.host.com" ], "timeout": 10000000000 }, "healthcheck_disabled": false,
671 "hostname": null, "hosts": null, "image": "alpine:latest@sha256:b3dbf31b77fd99d9c08f780ce6f5282aba076d70a513a8be859d8d3a4d0c92b8",
672 "labels": { "com.example.department": "Finance", "com.example.description": "Accounting webapp" }, "limit_cpu": 0.5, "limit_memory":
673 52428800, "log_driver": "fluentd", "log_driver_options": { "fluentd-address": "127.0.0.1:24224", "fluentd-async-connect":
674 "true", "tag": "myservice" }, "mode": "replicated", "mounts": [ { "readonly": false, "source": "/tmp/", "target": "/remote_tmp/",
675 "type": "bind", "labels": null, "propagation": null, "no_copy": null, "driver_config": null, "tmpfs_size": null, "tmpfs_mode":
676 null } ], "networks": null, "placement_preferences": [ { "spread": "node.labels.mylabel" } ], "publish": null, "read_only":
677 null, "replicas": 1, "replicas_max_per_node": 1, "reserve_cpu": 0.25, "reserve_memory": 20971520, "restart_policy": "on-failure",
678 "restart_policy_attempts": 3, "restart_policy_delay": 5000000000, "restart_policy_window": 120000000000, "secrets": null,
679 "stop_grace_period": null, "stop_signal": null, "tty": null, "update_delay": 10000000000, "update_failure_action": null,
680 "update_max_failure_ratio": null, "update_monitor": null, "update_order": "stop-first", "update_parallelism": 2, "user":
681 null, "working_dir": null }'
682 changes:
683 returned: always
684 description:
685 - List of changed service attributes if a service has been altered, [] otherwise.
686 type: list
687 elements: str
688 sample: ['container_labels', 'replicas']
689 rebuilt:
690 returned: always
691 description:
692 - True if the service has been recreated (removed and created).
693 type: bool
694 sample: true
695 """
696
697 EXAMPLES = r"""
698 ---
699 - name: Set command and arguments
700 community.docker.docker_swarm_service:
701 name: myservice
702 image: alpine
703 command: sleep
704 args:
705 - "3600"
706
707 - name: Set a bind mount
708 community.docker.docker_swarm_service:
709 name: myservice
710 image: alpine
711 mounts:
712 - source: /tmp/
713 target: /remote_tmp/
714 type: bind
715
716 - name: Set service labels
717 community.docker.docker_swarm_service:
718 name: myservice
719 image: alpine
720 labels:
721 com.example.description: "Accounting webapp"
722 com.example.department: "Finance"
723
724 - name: Set environment variables
725 community.docker.docker_swarm_service:
726 name: myservice
727 image: alpine
728 env:
729 ENVVAR1: envvar1
730 ENVVAR2: envvar2
731 env_files:
732 - envs/common.env
733 - envs/apps/web.env
734
735 - name: Set fluentd logging
736 community.docker.docker_swarm_service:
737 name: myservice
738 image: alpine
739 logging:
740 driver: fluentd
741 options:
742 fluentd-address: "127.0.0.1:24224"
743 fluentd-async-connect: "true"
744 tag: myservice
745
746 - name: Set restart policies
747 community.docker.docker_swarm_service:
748 name: myservice
749 image: alpine
750 restart_config:
751 condition: on-failure
752 delay: 5s
753 max_attempts: 3
754 window: 120s
755
756 - name: Set update config
757 community.docker.docker_swarm_service:
758 name: myservice
759 image: alpine
760 update_config:
761 parallelism: 2
762 delay: 10s
763 order: stop-first
764
765 - name: Set rollback config
766 community.docker.docker_swarm_service:
767 name: myservice
768 image: alpine
769 update_config:
770 failure_action: rollback
771 rollback_config:
772 parallelism: 2
773 delay: 10s
774 order: stop-first
775
776 - name: Set placement preferences
777 community.docker.docker_swarm_service:
778 name: myservice
779 image: alpine:edge
780 placement:
781 preferences:
782 - spread: node.labels.mylabel
783 constraints:
784 - node.role == manager
785 - engine.labels.operatingsystem == ubuntu 14.04
786 replicas_max_per_node: 2
787
788 - name: Set configs
789 community.docker.docker_swarm_service:
790 name: myservice
791 image: alpine:edge
792 configs:
793 - config_name: myconfig_name
794 filename: "/tmp/config.txt"
795
796 - name: Set networks
797 community.docker.docker_swarm_service:
798 name: myservice
799 image: alpine:edge
800 networks:
801 - mynetwork
802
803 - name: Set networks as a dictionary
804 community.docker.docker_swarm_service:
805 name: myservice
806 image: alpine:edge
807 networks:
808 - name: "mynetwork"
809 aliases:
810 - "mynetwork_alias"
811 options:
812 foo: bar
813
814 - name: Set secrets
815 community.docker.docker_swarm_service:
816 name: myservice
817 image: alpine:edge
818 secrets:
819 - secret_name: mysecret_name
820 filename: "/run/secrets/secret.txt"
821
822 - name: Start service with healthcheck
823 community.docker.docker_swarm_service:
824 name: myservice
825 image: nginx:1.13
826 healthcheck:
827 # Check if nginx server is healthy by curl'ing the server.
828 # If this fails or timeouts, the healthcheck fails.
829 test: ["CMD", "curl", "--fail", "http://nginx.host.com"]
830 interval: 1m30s
831 timeout: 10s
832 retries: 3
833 start_period: 30s
834
835 - name: Configure service resources
836 community.docker.docker_swarm_service:
837 name: myservice
838 image: alpine:edge
839 reservations:
840 cpus: 0.25
841 memory: 20M
842 limits:
843 cpus: 0.50
844 memory: 50M
845
846 - name: Remove service
847 community.docker.docker_swarm_service:
848 name: myservice
849 state: absent
850 """
851
852 import shlex
853 import time
854 import traceback
855 import typing as t
856
857 from ansible.module_utils.basic import human_to_bytes
858 from ansible.module_utils.common.text.converters import to_text
859
860 from ansible_collections.community.docker.plugins.module_utils._common import (
861 AnsibleDockerClient,
862 RequestException,
863 )
864 from ansible_collections.community.docker.plugins.module_utils._util import (
865 DifferenceTracker,
866 DockerBaseClass,
867 clean_dict_booleans_for_docker_api,
868 convert_duration_to_nanosecond,
869 parse_healthcheck,
870 sanitize_labels,
871 )
872 from ansible_collections.community.docker.plugins.module_utils._version import (
873 LooseVersion,
874 )
875
876 try:
877 from docker import types
878 from docker.errors import (
879 APIError,
880 DockerException,
881 NotFound,
882 )
883 from docker.utils import (
884 format_environment,
885 parse_env_file,
886 parse_repository_tag,
887 )
888 except ImportError:
889 # missing Docker SDK for Python handled in ansible.module_utils.docker.common
890 pass
891
892
893 def get_docker_environment(
894 env: str | dict[str, t.Any] | list[t.Any] | None, env_files: list[str] | None
895 ) -> list[str] | None:
896 """
897 Will return a list of "KEY=VALUE" items. Supplied env variable can
898 be either a list or a dictionary.
899
900 If environment files are combined with explicit environment variables,
901 the explicit environment variables take precedence.
902 """
903 env_dict: dict[str, str] = {}
904 if env_files:
905 for env_file in env_files:
906 parsed_env_file = parse_env_file(env_file)
907 for name, value in parsed_env_file.items():
908 env_dict[name] = str(value)
909 if env is not None and isinstance(env, str):
910 env = env.split(",")
911 if env is not None and isinstance(env, dict):
912 for name, value in env.items():
913 if not isinstance(value, str):
914 raise ValueError(
915 "Non-string value found for env option. Ambiguous env options must be "
916 "wrapped in quotes to avoid them being interpreted when directly specified "
917 "in YAML, or explicitly converted to strings when the option is templated. "
918 f"Key: {name}"
919 )
920 env_dict[name] = str(value)
921 elif env is not None and isinstance(env, list):
922 for item in env:
923 try:
924 name, value = item.split("=", 1)
925 except ValueError as exc:
926 raise ValueError(
927 "Invalid environment variable found in list, needs to be in format KEY=VALUE."
928 ) from exc
929 env_dict[name] = value
930 elif env is not None:
931 raise ValueError(
932 f"Invalid type for env {env} ({type(env)}). Only list or dict allowed."
933 )
934 env_list = format_environment(env_dict)
935 if not env_list:
936 if env is not None or env_files is not None:
937 return []
938 return None
939 return sorted(env_list)
940
941
942 @t.overload
943 def get_docker_networks(
944 networks: list[str | dict[str, t.Any]], network_ids: dict[str, str]
945 ) -> list[dict[str, t.Any]]: ...
946
947
948 @t.overload
949 def get_docker_networks(
950 networks: list[str | dict[str, t.Any]] | None, network_ids: dict[str, str]
951 ) -> list[dict[str, t.Any]] | None: ...
952
953
954 def get_docker_networks(
955 networks: list[str | dict[str, t.Any]] | None, network_ids: dict[str, str]
956 ) -> list[dict[str, t.Any]] | None:
957 """
958 Validate a list of network names or a list of network dictionaries.
959 Network names will be resolved to ids by using the network_ids mapping.
960 """
961 if networks is None:
962 return None
963 parsed_networks = []
964 for network in networks:
965 parsed_network: dict[str, t.Any]
966 if isinstance(network, str):
967 parsed_network = {"name": network}
968 elif isinstance(network, dict):
969 if "name" not in network:
970 raise TypeError(
971 '"name" is required when networks are passed as dictionaries.'
972 )
973 name = network.pop("name")
974 parsed_network = {"name": name}
975 aliases = network.pop("aliases", None)
976 if aliases is not None:
977 if not isinstance(aliases, list):
978 raise TypeError(
979 '"aliases" network option is only allowed as a list'
980 )
981 if not all(isinstance(alias, str) for alias in aliases):
982 raise TypeError("Only strings are allowed as network aliases.")
983 parsed_network["aliases"] = aliases
984 options = network.pop("options", None)
985 if options is not None:
986 if not isinstance(options, dict):
987 raise TypeError("Only dict is allowed as network options.")
988 parsed_network["options"] = clean_dict_booleans_for_docker_api(options)
989 # Check if any invalid keys left
990 if network:
991 invalid_keys = ", ".join(network.keys())
992 raise TypeError(
993 f"{invalid_keys} are not valid keys for the networks option"
994 )
995
996 else:
997 raise TypeError(
998 "Only a list of strings or dictionaries are allowed to be passed as networks."
999 )
1000 network_name = parsed_network.pop("name")
1001 try:
1002 parsed_network["id"] = network_ids[network_name]
1003 except KeyError as e:
1004 raise ValueError(f"Could not find a network named: {e}.") from None
1005 parsed_networks.append(parsed_network)
1006 return parsed_networks or []
1007
1008
1009 def get_nanoseconds_from_raw_option(name: str, value: t.Any) -> int | None:
1010 if value is None:
1011 return None
1012 if isinstance(value, int):
1013 return value
1014 if isinstance(value, str):
1015 try:
1016 return int(value)
1017 except ValueError:
1018 return convert_duration_to_nanosecond(value)
1019 raise ValueError(
1020 f"Invalid type for {name} {value} ({type(value)}). Only string or int allowed."
1021 )
1022
1023
1024 def get_value(key: str, values: dict[str, t.Any], default: t.Any = None) -> t.Any:
1025 value = values.get(key)
1026 return value if value is not None else default
1027
1028
1029 def has_dict_changed(
1030 new_dict: dict[str, t.Any] | None, old_dict: dict[str, t.Any] | None
1031 ) -> bool:
1032 """
1033 Check if new_dict has differences compared to old_dict while
1034 ignoring keys in old_dict which are None in new_dict.
1035 """
1036 if new_dict is None:
1037 return False
1038 if not new_dict and old_dict:
1039 return True
1040 if not old_dict and new_dict:
1041 return True
1042 if old_dict is None:
1043 # in this case new_dict is empty, only the type checker didn't notice
1044 return False
1045 defined_options = {
1046 option: value for option, value in new_dict.items() if value is not None
1047 }
1048 for option, value in defined_options.items():
1049 old_value = old_dict.get(option)
1050 if not value and not old_value:
1051 continue
1052 if value != old_value:
1053 return True
1054 return False
1055
1056
1057 def has_list_changed(
1058 new_list: list[t.Any] | None,
1059 old_list: list[t.Any] | None,
1060 sort_lists: bool = True,
1061 sort_key: str | None = None,
1062 ) -> bool:
1063 """
1064 Check two lists have differences. Sort lists by default.
1065 """
1066
1067 def sort_list(unsorted_list: list[t.Any]) -> list[t.Any]:
1068 """
1069 Sort a given list.
1070 The list may contain dictionaries, so use the sort key to handle them.
1071 """
1072
1073 if unsorted_list and isinstance(unsorted_list[0], dict):
1074 if not sort_key:
1075 raise ValueError("A sort key was not specified when sorting list")
1076 return sorted(unsorted_list, key=lambda k: k[sort_key])
1077
1078 # Either the list is empty or does not contain dictionaries
1079 try:
1080 return sorted(unsorted_list)
1081 except TypeError:
1082 return unsorted_list
1083
1084 if new_list is None:
1085 return False
1086 old_list = old_list or []
1087 if len(new_list) != len(old_list):
1088 return True
1089
1090 if sort_lists:
1091 zip_data = zip(sort_list(new_list), sort_list(old_list))
1092 else:
1093 zip_data = zip(new_list, old_list)
1094 for new_item, old_item in zip_data:
1095 is_same_type = type( # noqa: E721, pylint: disable=unidiomatic-typecheck
1096 new_item
1097 ) == type( # noqa: E721, pylint: disable=unidiomatic-typecheck
1098 old_item
1099 )
1100 if not is_same_type:
1101 if isinstance(new_item, str) and isinstance(old_item, str):
1102 # Even though the types are different between these items,
1103 # they are both strings. Try matching on the same string type.
1104 try:
1105 new_item_type = type(new_item)
1106 old_item_casted = new_item_type(old_item)
1107 if new_item != old_item_casted:
1108 return True
1109 continue
1110 except UnicodeEncodeError:
1111 # Fallback to assuming the strings are different
1112 return True
1113 else:
1114 return True
1115 if isinstance(new_item, dict):
1116 if has_dict_changed(new_item, old_item):
1117 return True
1118 elif new_item != old_item:
1119 return True
1120
1121 return False
1122
1123
1124 def have_networks_changed(
1125 new_networks: list[dict[str, t.Any]] | None,
1126 old_networks: list[dict[str, t.Any]] | None,
1127 ) -> bool:
1128 """Special case list checking for networks to sort aliases"""
1129
1130 if new_networks is None:
1131 return False
1132 old_networks = old_networks or []
1133 if len(new_networks) != len(old_networks):
1134 return True
1135
1136 zip_data = zip(
1137 sorted(new_networks, key=lambda k: k["id"]),
1138 sorted(old_networks, key=lambda k: k["id"]),
1139 )
1140
1141 for new_item, old_item in zip_data:
1142 new_item = dict(new_item)
1143 old_item = dict(old_item)
1144 # Sort the aliases
1145 if "aliases" in new_item:
1146 new_item["aliases"] = sorted(new_item["aliases"] or [])
1147 if "aliases" in old_item:
1148 old_item["aliases"] = sorted(old_item["aliases"] or [])
1149
1150 if has_dict_changed(new_item, old_item):
1151 return True
1152
1153 return False
1154
1155
1156 class DockerService(DockerBaseClass):
1157 def __init__(
1158 self, docker_api_version: LooseVersion, docker_py_version: LooseVersion
1159 ) -> None:
1160 super().__init__()
1161 self.image: str | None = ""
1162 self.command: t.Any = None
1163 self.args: list[str] | None = None
1164 self.endpoint_mode: t.Literal["vip", "dnsrr"] | None = None
1165 self.dns: list[str] | None = None
1166 self.healthcheck: dict[str, t.Any] | None = None
1167 self.healthcheck_disabled: bool | None = None
1168 self.hostname: str | None = None
1169 self.hosts: dict[str, t.Any] | None = None
1170 self.tty: bool | None = None
1171 self.dns_search: list[str] | None = None
1172 self.dns_options: list[str] | None = None
1173 self.env: t.Any = None
1174 self.force_update: int | None = None
1175 self.groups: list[str] | None = None
1176 self.log_driver: str | None = None
1177 self.log_driver_options: dict[str, t.Any] | None = None
1178 self.labels: dict[str, t.Any] | None = None
1179 self.container_labels: dict[str, t.Any] | None = None
1180 self.sysctls: dict[str, t.Any] | None = None
1181 self.limit_cpu: float | None = None
1182 self.limit_memory: int | None = None
1183 self.reserve_cpu: float | None = None
1184 self.reserve_memory: int | None = None
1185 self.mode: t.Literal["replicated", "global", "replicated-job"] = "replicated"
1186 self.user: str | None = None
1187 self.mounts: list[dict[str, t.Any]] | None = None
1188 self.configs: list[dict[str, t.Any]] | None = None
1189 self.secrets: list[dict[str, t.Any]] | None = None
1190 self.constraints: list[str] | None = None
1191 self.replicas_max_per_node: int | None = None
1192 self.networks: list[t.Any] | None = None
1193 self.stop_grace_period: int | None = None
1194 self.stop_signal: str | None = None
1195 self.publish: list[dict[str, t.Any]] | None = None
1196 self.placement_preferences: list[dict[str, t.Any]] | None = None
1197 self.replicas: int | None = -1
1198 self.service_id = False
1199 self.service_version = False
1200 self.read_only: bool | None = None
1201 self.restart_policy: t.Literal["none", "on-failure", "any"] | None = None
1202 self.restart_policy_attempts: int | None = None
1203 self.restart_policy_delay: str | None = None
1204 self.restart_policy_window: str | None = None
1205 self.rollback_config: dict[str, t.Any] | None = None
1206 self.update_delay: str | None = None
1207 self.update_parallelism: int | None = None
1208 self.update_failure_action: (
1209 t.Literal["continue", "pause", "rollback"] | None
1210 ) = None
1211 self.update_monitor: str | None = None
1212 self.update_max_failure_ratio: float | None = None
1213 self.update_order: str | None = None
1214 self.working_dir: str | None = None
1215 self.init: bool | None = None
1216 self.cap_add: list[str] | None = None
1217 self.cap_drop: list[str] | None = None
1218
1219 self.docker_api_version = docker_api_version
1220 self.docker_py_version = docker_py_version
1221
1222 def get_facts(self) -> dict[str, t.Any]:
1223 return {
1224 "image": self.image,
1225 "mounts": self.mounts,
1226 "configs": self.configs,
1227 "networks": self.networks,
1228 "command": self.command,
1229 "args": self.args,
1230 "tty": self.tty,
1231 "dns": self.dns,
1232 "dns_search": self.dns_search,
1233 "dns_options": self.dns_options,
1234 "healthcheck": self.healthcheck,
1235 "healthcheck_disabled": self.healthcheck_disabled,
1236 "hostname": self.hostname,
1237 "hosts": self.hosts,
1238 "env": self.env,
1239 "force_update": self.force_update,
1240 "groups": self.groups,
1241 "log_driver": self.log_driver,
1242 "log_driver_options": self.log_driver_options,
1243 "publish": self.publish,
1244 "constraints": self.constraints,
1245 "replicas_max_per_node": self.replicas_max_per_node,
1246 "placement_preferences": self.placement_preferences,
1247 "labels": self.labels,
1248 "container_labels": self.container_labels,
1249 "sysctls": self.sysctls,
1250 "mode": self.mode,
1251 "replicas": self.replicas,
1252 "endpoint_mode": self.endpoint_mode,
1253 "restart_policy": self.restart_policy,
1254 "secrets": self.secrets,
1255 "stop_grace_period": self.stop_grace_period,
1256 "stop_signal": self.stop_signal,
1257 "limit_cpu": self.limit_cpu,
1258 "limit_memory": self.limit_memory,
1259 "read_only": self.read_only,
1260 "reserve_cpu": self.reserve_cpu,
1261 "reserve_memory": self.reserve_memory,
1262 "restart_policy_delay": self.restart_policy_delay,
1263 "restart_policy_attempts": self.restart_policy_attempts,
1264 "restart_policy_window": self.restart_policy_window,
1265 "rollback_config": self.rollback_config,
1266 "update_delay": self.update_delay,
1267 "update_parallelism": self.update_parallelism,
1268 "update_failure_action": self.update_failure_action,
1269 "update_monitor": self.update_monitor,
1270 "update_max_failure_ratio": self.update_max_failure_ratio,
1271 "update_order": self.update_order,
1272 "user": self.user,
1273 "working_dir": self.working_dir,
1274 "init": self.init,
1275 "cap_add": self.cap_add,
1276 "cap_drop": self.cap_drop,
1277 }
1278
1279 @property
1280 def can_update_networks(self) -> bool:
1281 # Before Docker API 1.29 adding/removing networks was not supported
1282 return self.docker_api_version >= LooseVersion(
1283 "1.29"
1284 ) and self.docker_py_version >= LooseVersion("2.7")
1285
1286 @property
1287 def can_use_task_template_networks(self) -> bool:
1288 # In Docker API 1.25 attaching networks to TaskTemplate is preferred over Spec
1289 return self.docker_py_version >= LooseVersion("2.7")
1290
1291 @staticmethod
1292 def get_restart_config_from_ansible_params(
1293 params: dict[str, t.Any],
1294 ) -> dict[str, t.Any]:
1295 restart_config = params["restart_config"] or {}
1296 condition = get_value(
1297 "condition",
1298 restart_config,
1299 )
1300 delay = get_value(
1301 "delay",
1302 restart_config,
1303 )
1304 delay = get_nanoseconds_from_raw_option("restart_policy_delay", delay)
1305 max_attempts = get_value(
1306 "max_attempts",
1307 restart_config,
1308 )
1309 window = get_value(
1310 "window",
1311 restart_config,
1312 )
1313 window = get_nanoseconds_from_raw_option("restart_policy_window", window)
1314 return {
1315 "restart_policy": condition,
1316 "restart_policy_delay": delay,
1317 "restart_policy_attempts": max_attempts,
1318 "restart_policy_window": window,
1319 }
1320
1321 @staticmethod
1322 def get_update_config_from_ansible_params(
1323 params: dict[str, t.Any],
1324 ) -> dict[str, t.Any]:
1325 update_config = params["update_config"] or {}
1326 parallelism = get_value(
1327 "parallelism",
1328 update_config,
1329 )
1330 delay = get_value(
1331 "delay",
1332 update_config,
1333 )
1334 delay = get_nanoseconds_from_raw_option("update_delay", delay)
1335 failure_action = get_value(
1336 "failure_action",
1337 update_config,
1338 )
1339 monitor = get_value(
1340 "monitor",
1341 update_config,
1342 )
1343 monitor = get_nanoseconds_from_raw_option("update_monitor", monitor)
1344 max_failure_ratio = get_value(
1345 "max_failure_ratio",
1346 update_config,
1347 )
1348 order = get_value(
1349 "order",
1350 update_config,
1351 )
1352 return {
1353 "update_parallelism": parallelism,
1354 "update_delay": delay,
1355 "update_failure_action": failure_action,
1356 "update_monitor": monitor,
1357 "update_max_failure_ratio": max_failure_ratio,
1358 "update_order": order,
1359 }
1360
1361 @staticmethod
1362 def get_rollback_config_from_ansible_params(
1363 params: dict[str, t.Any],
1364 ) -> dict[str, t.Any] | None:
1365 if params["rollback_config"] is None:
1366 return None
1367 rollback_config = params["rollback_config"] or {}
1368 delay = get_nanoseconds_from_raw_option(
1369 "rollback_config.delay", rollback_config.get("delay")
1370 )
1371 monitor = get_nanoseconds_from_raw_option(
1372 "rollback_config.monitor", rollback_config.get("monitor")
1373 )
1374 return {
1375 "parallelism": rollback_config.get("parallelism"),
1376 "delay": delay,
1377 "failure_action": rollback_config.get("failure_action"),
1378 "monitor": monitor,
1379 "max_failure_ratio": rollback_config.get("max_failure_ratio"),
1380 "order": rollback_config.get("order"),
1381 }
1382
1383 @staticmethod
1384 def get_logging_from_ansible_params(params: dict[str, t.Any]) -> dict[str, t.Any]:
1385 logging_config = params["logging"] or {}
1386 driver = get_value(
1387 "driver",
1388 logging_config,
1389 )
1390 options = get_value(
1391 "options",
1392 logging_config,
1393 )
1394 return {
1395 "log_driver": driver,
1396 "log_driver_options": options,
1397 }
1398
1399 @staticmethod
1400 def get_limits_from_ansible_params(params: dict[str, t.Any]) -> dict[str, t.Any]:
1401 limits = params["limits"] or {}
1402 cpus = get_value(
1403 "cpus",
1404 limits,
1405 )
1406 memory = get_value(
1407 "memory",
1408 limits,
1409 )
1410 if memory is not None:
1411 try:
1412 memory = human_to_bytes(memory)
1413 except ValueError as exc:
1414 raise ValueError(
1415 f"Failed to convert limit_memory to bytes: {exc}"
1416 ) from exc
1417 return {
1418 "limit_cpu": cpus,
1419 "limit_memory": memory,
1420 }
1421
1422 @staticmethod
1423 def get_reservations_from_ansible_params(
1424 params: dict[str, t.Any],
1425 ) -> dict[str, t.Any]:
1426 reservations = params["reservations"] or {}
1427 cpus = get_value(
1428 "cpus",
1429 reservations,
1430 )
1431 memory = get_value(
1432 "memory",
1433 reservations,
1434 )
1435
1436 if memory is not None:
1437 try:
1438 memory = human_to_bytes(memory)
1439 except ValueError as exc:
1440 raise ValueError(
1441 f"Failed to convert reserve_memory to bytes: {exc}"
1442 ) from exc
1443 return {
1444 "reserve_cpu": cpus,
1445 "reserve_memory": memory,
1446 }
1447
1448 @staticmethod
1449 def get_placement_from_ansible_params(params: dict[str, t.Any]) -> dict[str, t.Any]:
1450 placement = params["placement"] or {}
1451 constraints = get_value("constraints", placement)
1452
1453 preferences = placement.get("preferences")
1454 replicas_max_per_node = get_value("replicas_max_per_node", placement)
1455
1456 return {
1457 "constraints": constraints,
1458 "placement_preferences": preferences,
1459 "replicas_max_per_node": replicas_max_per_node,
1460 }
1461
1462 @classmethod
1463 def from_ansible_params(
1464 cls,
1465 ap: dict[str, t.Any],
1466 old_service: DockerService | None,
1467 image_digest: str,
1468 secret_ids: dict[str, str],
1469 config_ids: dict[str, str],
1470 network_ids: dict[str, str],
1471 client: AnsibleDockerClient,
1472 ) -> DockerService:
1473 s = DockerService(client.docker_api_version, client.docker_py_version)
1474 s.image = image_digest
1475 s.args = ap["args"]
1476 s.endpoint_mode = ap["endpoint_mode"]
1477 s.dns = ap["dns"]
1478 s.dns_search = ap["dns_search"]
1479 s.dns_options = ap["dns_options"]
1480 s.healthcheck, s.healthcheck_disabled = parse_healthcheck(ap["healthcheck"])
1481 s.hostname = ap["hostname"]
1482 s.hosts = ap["hosts"]
1483 s.tty = ap["tty"]
1484 s.labels = ap["labels"]
1485 sanitize_labels(s.labels, "labels", client)
1486 s.container_labels = ap["container_labels"]
1487 sanitize_labels(s.container_labels, "container_labels", client)
1488 s.sysctls = ap["sysctls"]
1489 s.mode = ap["mode"]
1490 s.stop_signal = ap["stop_signal"]
1491 s.user = ap["user"]
1492 s.working_dir = ap["working_dir"]
1493 s.read_only = ap["read_only"]
1494 s.init = ap["init"]
1495 s.cap_add = ap["cap_add"]
1496 s.cap_drop = ap["cap_drop"]
1497
1498 s.networks = get_docker_networks(ap["networks"], network_ids)
1499
1500 s.command = ap["command"]
1501 if isinstance(s.command, str):
1502 s.command = shlex.split(s.command)
1503 elif isinstance(s.command, list):
1504 invalid_items = [
1505 (index, item)
1506 for index, item in enumerate(s.command)
1507 if not isinstance(item, str)
1508 ]
1509 if invalid_items:
1510 errors = ", ".join(
1511 [
1512 f"{item} ({type(item)}) at index {index}"
1513 for index, item in invalid_items
1514 ]
1515 )
1516 raise ValueError(
1517 "All items in a command list need to be strings. "
1518 f"Check quoting. Invalid items: {errors}."
1519 )
1520 s.command = ap["command"]
1521 elif s.command is not None:
1522 raise ValueError(
1523 f"Invalid type for command {s.command} ({type(s.command)}). "
1524 "Only string or list allowed. Check quoting."
1525 )
1526
1527 s.env = get_docker_environment(ap["env"], ap["env_files"])
1528 s.rollback_config = cls.get_rollback_config_from_ansible_params(ap)
1529
1530 update_config = cls.get_update_config_from_ansible_params(ap)
1531 for key, value in update_config.items():
1532 setattr(s, key, value)
1533
1534 restart_config = cls.get_restart_config_from_ansible_params(ap)
1535 for key, value in restart_config.items():
1536 setattr(s, key, value)
1537
1538 logging_config = cls.get_logging_from_ansible_params(ap)
1539 for key, value in logging_config.items():
1540 setattr(s, key, value)
1541
1542 limits = cls.get_limits_from_ansible_params(ap)
1543 for key, value in limits.items():
1544 setattr(s, key, value)
1545
1546 reservations = cls.get_reservations_from_ansible_params(ap)
1547 for key, value in reservations.items():
1548 setattr(s, key, value)
1549
1550 placement = cls.get_placement_from_ansible_params(ap)
1551 for key, value in placement.items():
1552 setattr(s, key, value)
1553
1554 if ap["stop_grace_period"] is not None:
1555 s.stop_grace_period = convert_duration_to_nanosecond(
1556 ap["stop_grace_period"]
1557 )
1558
1559 if ap["force_update"]:
1560 s.force_update = int(str(time.time()).replace(".", ""))
1561
1562 if ap["groups"] is not None:
1563 # In case integers are passed as groups, we need to convert them to
1564 # strings as docker internally treats them as strings.
1565 s.groups = [str(g) for g in ap["groups"]]
1566
1567 if ap["replicas"] == -1:
1568 if old_service:
1569 s.replicas = old_service.replicas
1570 else:
1571 s.replicas = 1
1572 else:
1573 s.replicas = ap["replicas"]
1574
1575 if ap["publish"] is not None:
1576 s.publish = []
1577 for param_p in ap["publish"]:
1578 service_p = {}
1579 service_p["protocol"] = param_p["protocol"]
1580 service_p["mode"] = param_p["mode"]
1581 service_p["published_port"] = param_p["published_port"]
1582 service_p["target_port"] = param_p["target_port"]
1583 s.publish.append(service_p)
1584
1585 if ap["mounts"] is not None:
1586 s.mounts = []
1587 for param_m in ap["mounts"]:
1588 service_m = {}
1589 service_m["readonly"] = param_m["readonly"]
1590 service_m["type"] = param_m["type"]
1591 if param_m["source"] is None and param_m["type"] != "tmpfs":
1592 raise ValueError(
1593 "Source must be specified for mounts which are not of type tmpfs"
1594 )
1595 service_m["source"] = param_m["source"] or ""
1596 service_m["target"] = param_m["target"]
1597 service_m["labels"] = param_m["labels"]
1598 service_m["no_copy"] = param_m["no_copy"]
1599 service_m["propagation"] = param_m["propagation"]
1600 service_m["driver_config"] = param_m["driver_config"]
1601 service_m["tmpfs_mode"] = param_m["tmpfs_mode"]
1602 tmpfs_size = param_m["tmpfs_size"]
1603 if tmpfs_size is not None:
1604 try:
1605 tmpfs_size = human_to_bytes(tmpfs_size)
1606 except ValueError as exc:
1607 raise ValueError(
1608 f"Failed to convert tmpfs_size to bytes: {exc}"
1609 ) from exc
1610
1611 service_m["tmpfs_size"] = tmpfs_size
1612 s.mounts.append(service_m)
1613
1614 if ap["configs"] is not None:
1615 s.configs = []
1616 for param_m in ap["configs"]:
1617 service_c = {}
1618 config_name = param_m["config_name"]
1619 service_c["config_id"] = param_m["config_id"] or config_ids[config_name]
1620 service_c["config_name"] = config_name
1621 service_c["filename"] = param_m["filename"] or config_name
1622 service_c["uid"] = param_m["uid"]
1623 service_c["gid"] = param_m["gid"]
1624 service_c["mode"] = param_m["mode"]
1625 s.configs.append(service_c)
1626
1627 if ap["secrets"] is not None:
1628 s.secrets = []
1629 for param_m in ap["secrets"]:
1630 service_s = {}
1631 secret_name = param_m["secret_name"]
1632 service_s["secret_id"] = param_m["secret_id"] or secret_ids[secret_name]
1633 service_s["secret_name"] = secret_name
1634 service_s["filename"] = param_m["filename"] or secret_name
1635 service_s["uid"] = param_m["uid"]
1636 service_s["gid"] = param_m["gid"]
1637 service_s["mode"] = param_m["mode"]
1638 s.secrets.append(service_s)
1639
1640 return s
1641
1642 def compare(self, os: DockerService) -> tuple[bool, DifferenceTracker, bool, bool]:
1643 differences = DifferenceTracker()
1644 needs_rebuild = False
1645 force_update = False
1646 if self.endpoint_mode is not None and self.endpoint_mode != os.endpoint_mode:
1647 differences.add(
1648 "endpoint_mode", parameter=self.endpoint_mode, active=os.endpoint_mode
1649 )
1650 if has_list_changed(self.env, os.env):
1651 differences.add("env", parameter=self.env, active=os.env)
1652 if self.log_driver is not None and self.log_driver != os.log_driver:
1653 differences.add(
1654 "log_driver", parameter=self.log_driver, active=os.log_driver
1655 )
1656 if self.log_driver_options is not None and self.log_driver_options != (
1657 os.log_driver_options or {}
1658 ):
1659 differences.add(
1660 "log_opt",
1661 parameter=self.log_driver_options,
1662 active=os.log_driver_options,
1663 )
1664 if self.mode != os.mode:
1665 needs_rebuild = True
1666 differences.add("mode", parameter=self.mode, active=os.mode)
1667 if has_list_changed(self.mounts, os.mounts, sort_key="target"):
1668 differences.add("mounts", parameter=self.mounts, active=os.mounts)
1669 if has_list_changed(self.configs, os.configs, sort_key="config_name"):
1670 differences.add("configs", parameter=self.configs, active=os.configs)
1671 if has_list_changed(self.secrets, os.secrets, sort_key="secret_name"):
1672 differences.add("secrets", parameter=self.secrets, active=os.secrets)
1673 if have_networks_changed(self.networks, os.networks):
1674 differences.add("networks", parameter=self.networks, active=os.networks)
1675 needs_rebuild = not self.can_update_networks
1676 if self.replicas != os.replicas:
1677 differences.add("replicas", parameter=self.replicas, active=os.replicas)
1678 if has_list_changed(self.command, os.command, sort_lists=False):
1679 differences.add("command", parameter=self.command, active=os.command)
1680 if has_list_changed(self.args, os.args, sort_lists=False):
1681 differences.add("args", parameter=self.args, active=os.args)
1682 if has_list_changed(self.constraints, os.constraints):
1683 differences.add(
1684 "constraints", parameter=self.constraints, active=os.constraints
1685 )
1686 if (
1687 self.replicas_max_per_node is not None
1688 and self.replicas_max_per_node != os.replicas_max_per_node
1689 ):
1690 differences.add(
1691 "replicas_max_per_node",
1692 parameter=self.replicas_max_per_node,
1693 active=os.replicas_max_per_node,
1694 )
1695 if has_list_changed(
1696 self.placement_preferences, os.placement_preferences, sort_lists=False
1697 ):
1698 differences.add(
1699 "placement_preferences",
1700 parameter=self.placement_preferences,
1701 active=os.placement_preferences,
1702 )
1703 if has_list_changed(self.groups, os.groups):
1704 differences.add("groups", parameter=self.groups, active=os.groups)
1705 if self.labels is not None and self.labels != (os.labels or {}):
1706 differences.add("labels", parameter=self.labels, active=os.labels)
1707 if self.limit_cpu is not None and self.limit_cpu != os.limit_cpu:
1708 differences.add("limit_cpu", parameter=self.limit_cpu, active=os.limit_cpu)
1709 if self.limit_memory is not None and self.limit_memory != os.limit_memory:
1710 differences.add(
1711 "limit_memory", parameter=self.limit_memory, active=os.limit_memory
1712 )
1713 if self.reserve_cpu is not None and self.reserve_cpu != os.reserve_cpu:
1714 differences.add(
1715 "reserve_cpu", parameter=self.reserve_cpu, active=os.reserve_cpu
1716 )
1717 if self.reserve_memory is not None and self.reserve_memory != os.reserve_memory:
1718 differences.add(
1719 "reserve_memory",
1720 parameter=self.reserve_memory,
1721 active=os.reserve_memory,
1722 )
1723 if self.container_labels is not None and self.container_labels != (
1724 os.container_labels or {}
1725 ):
1726 differences.add(
1727 "container_labels",
1728 parameter=self.container_labels,
1729 active=os.container_labels,
1730 )
1731 if self.sysctls is not None and self.sysctls != (os.sysctls or {}):
1732 differences.add("sysctls", parameter=self.sysctls, active=os.sysctls)
1733 if self.stop_signal is not None and self.stop_signal != os.stop_signal:
1734 differences.add(
1735 "stop_signal", parameter=self.stop_signal, active=os.stop_signal
1736 )
1737 if (
1738 self.stop_grace_period is not None
1739 and self.stop_grace_period != os.stop_grace_period
1740 ):
1741 differences.add(
1742 "stop_grace_period",
1743 parameter=self.stop_grace_period,
1744 active=os.stop_grace_period,
1745 )
1746 if self.has_publish_changed(os.publish):
1747 differences.add("publish", parameter=self.publish, active=os.publish)
1748 if self.read_only is not None and self.read_only != os.read_only:
1749 differences.add("read_only", parameter=self.read_only, active=os.read_only)
1750 if self.restart_policy is not None and self.restart_policy != os.restart_policy:
1751 differences.add(
1752 "restart_policy",
1753 parameter=self.restart_policy,
1754 active=os.restart_policy,
1755 )
1756 if (
1757 self.restart_policy_attempts is not None
1758 and self.restart_policy_attempts != os.restart_policy_attempts
1759 ):
1760 differences.add(
1761 "restart_policy_attempts",
1762 parameter=self.restart_policy_attempts,
1763 active=os.restart_policy_attempts,
1764 )
1765 if (
1766 self.restart_policy_delay is not None
1767 and self.restart_policy_delay != os.restart_policy_delay
1768 ):
1769 differences.add(
1770 "restart_policy_delay",
1771 parameter=self.restart_policy_delay,
1772 active=os.restart_policy_delay,
1773 )
1774 if (
1775 self.restart_policy_window is not None
1776 and self.restart_policy_window != os.restart_policy_window
1777 ):
1778 differences.add(
1779 "restart_policy_window",
1780 parameter=self.restart_policy_window,
1781 active=os.restart_policy_window,
1782 )
1783 if has_dict_changed(self.rollback_config, os.rollback_config):
1784 differences.add(
1785 "rollback_config",
1786 parameter=self.rollback_config,
1787 active=os.rollback_config,
1788 )
1789 if self.update_delay is not None and self.update_delay != os.update_delay:
1790 differences.add(
1791 "update_delay", parameter=self.update_delay, active=os.update_delay
1792 )
1793 if (
1794 self.update_parallelism is not None
1795 and self.update_parallelism != os.update_parallelism
1796 ):
1797 differences.add(
1798 "update_parallelism",
1799 parameter=self.update_parallelism,
1800 active=os.update_parallelism,
1801 )
1802 if (
1803 self.update_failure_action is not None
1804 and self.update_failure_action != os.update_failure_action
1805 ):
1806 differences.add(
1807 "update_failure_action",
1808 parameter=self.update_failure_action,
1809 active=os.update_failure_action,
1810 )
1811 if self.update_monitor is not None and self.update_monitor != os.update_monitor:
1812 differences.add(
1813 "update_monitor",
1814 parameter=self.update_monitor,
1815 active=os.update_monitor,
1816 )
1817 if (
1818 self.update_max_failure_ratio is not None
1819 and self.update_max_failure_ratio != os.update_max_failure_ratio
1820 ):
1821 differences.add(
1822 "update_max_failure_ratio",
1823 parameter=self.update_max_failure_ratio,
1824 active=os.update_max_failure_ratio,
1825 )
1826 if self.update_order is not None and self.update_order != os.update_order:
1827 differences.add(
1828 "update_order", parameter=self.update_order, active=os.update_order
1829 )
1830 has_image_changed, change = self.has_image_changed(os.image or "")
1831 if has_image_changed:
1832 differences.add("image", parameter=self.image, active=change)
1833 if self.user and self.user != os.user:
1834 differences.add("user", parameter=self.user, active=os.user)
1835 if has_list_changed(self.dns, os.dns, sort_lists=False):
1836 differences.add("dns", parameter=self.dns, active=os.dns)
1837 if has_list_changed(self.dns_search, os.dns_search, sort_lists=False):
1838 differences.add(
1839 "dns_search", parameter=self.dns_search, active=os.dns_search
1840 )
1841 if has_list_changed(self.dns_options, os.dns_options):
1842 differences.add(
1843 "dns_options", parameter=self.dns_options, active=os.dns_options
1844 )
1845 if self.has_healthcheck_changed(os):
1846 differences.add(
1847 "healthcheck", parameter=self.healthcheck, active=os.healthcheck
1848 )
1849 if self.hostname is not None and self.hostname != os.hostname:
1850 differences.add("hostname", parameter=self.hostname, active=os.hostname)
1851 if self.hosts is not None and self.hosts != (os.hosts or {}):
1852 differences.add("hosts", parameter=self.hosts, active=os.hosts)
1853 if self.tty is not None and self.tty != os.tty:
1854 differences.add("tty", parameter=self.tty, active=os.tty)
1855 if self.working_dir is not None and self.working_dir != os.working_dir:
1856 differences.add(
1857 "working_dir", parameter=self.working_dir, active=os.working_dir
1858 )
1859 if self.force_update:
1860 force_update = True
1861 if self.init is not None and self.init != os.init:
1862 differences.add("init", parameter=self.init, active=os.init)
1863 if has_list_changed(self.cap_add, os.cap_add):
1864 differences.add("cap_add", parameter=self.cap_add, active=os.cap_add)
1865 if has_list_changed(self.cap_drop, os.cap_drop):
1866 differences.add("cap_drop", parameter=self.cap_drop, active=os.cap_drop)
1867 return (
1868 not differences.empty or force_update,
1869 differences,
1870 needs_rebuild,
1871 force_update,
1872 )
1873
1874 def has_healthcheck_changed(self, old_publish: DockerService) -> bool:
1875 if self.healthcheck_disabled is False and self.healthcheck is None:
1876 return False
1877 if self.healthcheck_disabled:
1878 if old_publish.healthcheck is None:
1879 return False
1880 if old_publish.healthcheck.get("test") == ["NONE"]:
1881 return False
1882 return self.healthcheck != old_publish.healthcheck
1883
1884 def has_publish_changed(self, old_publish: list[dict[str, t.Any]] | None) -> bool:
1885 if self.publish is None:
1886 return False
1887 old_publish = old_publish or []
1888 if len(self.publish) != len(old_publish):
1889 return True
1890
1891 def publish_sorter(item: dict[str, t.Any]) -> tuple[int, int, str]:
1892 return (
1893 item.get("published_port") or 0,
1894 item.get("target_port") or 0,
1895 item.get("protocol") or "",
1896 )
1897
1898 publish = sorted(self.publish, key=publish_sorter)
1899 old_publish = sorted(old_publish, key=publish_sorter)
1900 for publish_item, old_publish_item in zip(publish, old_publish):
1901 ignored_keys = set()
1902 if not publish_item.get("mode"):
1903 ignored_keys.add("mode")
1904 # Create copies of publish_item dicts where keys specified in ignored_keys are left out
1905 filtered_old_publish_item = {
1906 k: v for k, v in old_publish_item.items() if k not in ignored_keys
1907 }
1908 filtered_publish_item = {
1909 k: v for k, v in publish_item.items() if k not in ignored_keys
1910 }
1911 if filtered_publish_item != filtered_old_publish_item:
1912 return True
1913 return False
1914
1915 def has_image_changed(self, old_image: str) -> tuple[bool, str]:
1916 assert self.image is not None
1917 if "@" not in self.image:
1918 old_image = old_image.split("@")[0]
1919 return self.image != old_image, old_image
1920
1921 def build_container_spec(self) -> types.ContainerSpec:
1922 mounts = None
1923 if self.mounts is not None:
1924 mounts = []
1925 for mount_config in self.mounts:
1926 mount_options = {
1927 "target": "target",
1928 "source": "source",
1929 "type": "type",
1930 "readonly": "read_only",
1931 "propagation": "propagation",
1932 "labels": "labels",
1933 "no_copy": "no_copy",
1934 "driver_config": "driver_config",
1935 "tmpfs_size": "tmpfs_size",
1936 "tmpfs_mode": "tmpfs_mode",
1937 }
1938 mount_args = {}
1939 for option, mount_arg in mount_options.items():
1940 value = mount_config.get(option)
1941 if value is not None:
1942 mount_args[mount_arg] = value
1943
1944 mounts.append(types.Mount(**mount_args))
1945
1946 configs = None
1947 if self.configs is not None:
1948 configs = []
1949 for config_config in self.configs:
1950 config_args = {
1951 "config_id": config_config["config_id"],
1952 "config_name": config_config["config_name"],
1953 }
1954 filename = config_config.get("filename")
1955 if filename:
1956 config_args["filename"] = filename
1957 uid = config_config.get("uid")
1958 if uid:
1959 config_args["uid"] = uid
1960 gid = config_config.get("gid")
1961 if gid:
1962 config_args["gid"] = gid
1963 mode = config_config.get("mode")
1964 if mode:
1965 config_args["mode"] = mode
1966
1967 configs.append(types.ConfigReference(**config_args))
1968
1969 secrets = None
1970 if self.secrets is not None:
1971 secrets = []
1972 for secret_config in self.secrets:
1973 secret_args = {
1974 "secret_id": secret_config["secret_id"],
1975 "secret_name": secret_config["secret_name"],
1976 }
1977 filename = secret_config.get("filename")
1978 if filename:
1979 secret_args["filename"] = filename
1980 uid = secret_config.get("uid")
1981 if uid:
1982 secret_args["uid"] = uid
1983 gid = secret_config.get("gid")
1984 if gid:
1985 secret_args["gid"] = gid
1986 mode = secret_config.get("mode")
1987 if mode:
1988 secret_args["mode"] = mode
1989
1990 secrets.append(types.SecretReference(**secret_args))
1991
1992 dns_config_args: dict[str, t.Any] = {}
1993 if self.dns is not None:
1994 dns_config_args["nameservers"] = self.dns
1995 if self.dns_search is not None:
1996 dns_config_args["search"] = self.dns_search
1997 if self.dns_options is not None:
1998 dns_config_args["options"] = self.dns_options
1999 dns_config = types.DNSConfig(**dns_config_args) if dns_config_args else None
2000
2001 container_spec_args: dict[str, t.Any] = {}
2002 if self.command is not None:
2003 container_spec_args["command"] = self.command
2004 if self.args is not None:
2005 container_spec_args["args"] = self.args
2006 if self.env is not None:
2007 container_spec_args["env"] = self.env
2008 if self.user is not None:
2009 container_spec_args["user"] = self.user
2010 if self.container_labels is not None:
2011 container_spec_args["labels"] = self.container_labels
2012 if self.sysctls is not None:
2013 container_spec_args["sysctls"] = self.sysctls
2014 if self.healthcheck is not None:
2015 container_spec_args["healthcheck"] = types.Healthcheck(**self.healthcheck)
2016 elif self.healthcheck_disabled:
2017 container_spec_args["healthcheck"] = types.Healthcheck(test=["NONE"])
2018 if self.hostname is not None:
2019 container_spec_args["hostname"] = self.hostname
2020 if self.hosts is not None:
2021 container_spec_args["hosts"] = self.hosts
2022 if self.read_only is not None:
2023 container_spec_args["read_only"] = self.read_only
2024 if self.stop_grace_period is not None:
2025 container_spec_args["stop_grace_period"] = self.stop_grace_period
2026 if self.stop_signal is not None:
2027 container_spec_args["stop_signal"] = self.stop_signal
2028 if self.tty is not None:
2029 container_spec_args["tty"] = self.tty
2030 if self.groups is not None:
2031 container_spec_args["groups"] = self.groups
2032 if self.working_dir is not None:
2033 container_spec_args["workdir"] = self.working_dir
2034 if secrets is not None:
2035 container_spec_args["secrets"] = secrets
2036 if mounts is not None:
2037 container_spec_args["mounts"] = mounts
2038 if dns_config is not None:
2039 container_spec_args["dns_config"] = dns_config
2040 if configs is not None:
2041 container_spec_args["configs"] = configs
2042 if self.init is not None:
2043 container_spec_args["init"] = self.init
2044 if self.cap_add is not None:
2045 container_spec_args["cap_add"] = self.cap_add
2046 if self.cap_drop is not None:
2047 container_spec_args["cap_drop"] = self.cap_drop
2048
2049 return types.ContainerSpec(self.image, **container_spec_args)
2050
2051 def build_placement(self) -> types.Placement | None:
2052 placement_args: dict[str, t.Any] = {}
2053 if self.constraints is not None:
2054 placement_args["constraints"] = self.constraints
2055 if self.replicas_max_per_node is not None:
2056 placement_args["maxreplicas"] = self.replicas_max_per_node
2057 if self.placement_preferences is not None:
2058 placement_args["preferences"] = [
2059 {key.title(): {"SpreadDescriptor": value}}
2060 for preference in self.placement_preferences
2061 for key, value in preference.items()
2062 ]
2063 return types.Placement(**placement_args) if placement_args else None
2064
2065 def build_update_config(self) -> types.UpdateConfig | None:
2066 update_config_args: dict[str, t.Any] = {}
2067 if self.update_parallelism is not None:
2068 update_config_args["parallelism"] = self.update_parallelism
2069 if self.update_delay is not None:
2070 update_config_args["delay"] = self.update_delay
2071 if self.update_failure_action is not None:
2072 update_config_args["failure_action"] = self.update_failure_action
2073 if self.update_monitor is not None:
2074 update_config_args["monitor"] = self.update_monitor
2075 if self.update_max_failure_ratio is not None:
2076 update_config_args["max_failure_ratio"] = self.update_max_failure_ratio
2077 if self.update_order is not None:
2078 update_config_args["order"] = self.update_order
2079 return types.UpdateConfig(**update_config_args) if update_config_args else None
2080
2081 def build_log_driver(self) -> types.DriverConfig | None:
2082 log_driver_args: dict[str, t.Any] = {}
2083 if self.log_driver is not None:
2084 log_driver_args["name"] = self.log_driver
2085 if self.log_driver_options is not None:
2086 log_driver_args["options"] = self.log_driver_options
2087 return types.DriverConfig(**log_driver_args) if log_driver_args else None
2088
2089 def build_restart_policy(self) -> types.RestartPolicy | None:
2090 restart_policy_args: dict[str, t.Any] = {}
2091 if self.restart_policy is not None:
2092 restart_policy_args["condition"] = self.restart_policy
2093 if self.restart_policy_delay is not None:
2094 restart_policy_args["delay"] = self.restart_policy_delay
2095 if self.restart_policy_attempts is not None:
2096 restart_policy_args["max_attempts"] = self.restart_policy_attempts
2097 if self.restart_policy_window is not None:
2098 restart_policy_args["window"] = self.restart_policy_window
2099 return (
2100 types.RestartPolicy(**restart_policy_args) if restart_policy_args else None
2101 )
2102
2103 def build_rollback_config(self) -> types.RollbackConfig | None:
2104 if self.rollback_config is None:
2105 return None
2106 rollback_config_options = [
2107 "parallelism",
2108 "delay",
2109 "failure_action",
2110 "monitor",
2111 "max_failure_ratio",
2112 "order",
2113 ]
2114 rollback_config_args = {}
2115 for option in rollback_config_options:
2116 value = self.rollback_config.get(option)
2117 if value is not None:
2118 rollback_config_args[option] = value
2119 return (
2120 types.RollbackConfig(**rollback_config_args)
2121 if rollback_config_args
2122 else None
2123 )
2124
2125 def build_resources(self) -> types.Resources | None:
2126 resources_args: dict[str, t.Any] = {}
2127 if self.limit_cpu is not None:
2128 resources_args["cpu_limit"] = int(self.limit_cpu * 1000000000.0)
2129 if self.limit_memory is not None:
2130 resources_args["mem_limit"] = self.limit_memory
2131 if self.reserve_cpu is not None:
2132 resources_args["cpu_reservation"] = int(self.reserve_cpu * 1000000000.0)
2133 if self.reserve_memory is not None:
2134 resources_args["mem_reservation"] = self.reserve_memory
2135 return types.Resources(**resources_args) if resources_args else None
2136
2137 def build_task_template(
2138 self,
2139 container_spec: types.ContainerSpec,
2140 placement: types.Placement | None = None,
2141 ) -> types.TaskTemplate:
2142 log_driver = self.build_log_driver()
2143 restart_policy = self.build_restart_policy()
2144 resources = self.build_resources()
2145
2146 task_template_args: dict[str, t.Any] = {}
2147 if placement is not None:
2148 task_template_args["placement"] = placement
2149 if log_driver is not None:
2150 task_template_args["log_driver"] = log_driver
2151 if restart_policy is not None:
2152 task_template_args["restart_policy"] = restart_policy
2153 if resources is not None:
2154 task_template_args["resources"] = resources
2155 if self.force_update:
2156 task_template_args["force_update"] = self.force_update
2157 if self.can_use_task_template_networks:
2158 networks = self.build_networks()
2159 if networks:
2160 task_template_args["networks"] = networks
2161 return types.TaskTemplate(container_spec=container_spec, **task_template_args)
2162
2163 def build_service_mode(self) -> types.ServiceMode:
2164 if self.mode == "global":
2165 self.replicas = None
2166 return types.ServiceMode(self.mode, replicas=self.replicas)
2167
2168 def build_networks(self) -> list[dict[str, t.Any]] | None:
2169 networks = None
2170 if self.networks is not None:
2171 networks = []
2172 for network in self.networks:
2173 docker_network = {"Target": network["id"]}
2174 if "aliases" in network:
2175 docker_network["Aliases"] = network["aliases"]
2176 if "options" in network:
2177 docker_network["DriverOpts"] = network["options"]
2178 networks.append(docker_network)
2179 return networks
2180
2181 def build_endpoint_spec(self) -> types.EndpointSpec | None:
2182 endpoint_spec_args: dict[str, t.Any] = {}
2183 if self.publish is not None:
2184 ports = []
2185 for port in self.publish:
2186 port_spec = {
2187 "Protocol": port["protocol"],
2188 "TargetPort": port["target_port"],
2189 }
2190 if port.get("published_port"):
2191 port_spec["PublishedPort"] = port["published_port"]
2192 if port.get("mode"):
2193 port_spec["PublishMode"] = port["mode"]
2194 ports.append(port_spec)
2195 endpoint_spec_args["ports"] = ports
2196 if self.endpoint_mode is not None:
2197 endpoint_spec_args["mode"] = self.endpoint_mode
2198 return types.EndpointSpec(**endpoint_spec_args) if endpoint_spec_args else None
2199
2200 def build_docker_service(self) -> dict[str, t.Any]:
2201 container_spec = self.build_container_spec()
2202 placement = self.build_placement()
2203 task_template = self.build_task_template(container_spec, placement)
2204
2205 update_config = self.build_update_config()
2206 rollback_config = self.build_rollback_config()
2207 service_mode = self.build_service_mode()
2208 endpoint_spec = self.build_endpoint_spec()
2209
2210 service: dict[str, t.Any] = {
2211 "task_template": task_template,
2212 "mode": service_mode,
2213 }
2214 if update_config:
2215 service["update_config"] = update_config
2216 if rollback_config:
2217 service["rollback_config"] = rollback_config
2218 if endpoint_spec:
2219 service["endpoint_spec"] = endpoint_spec
2220 if self.labels:
2221 service["labels"] = self.labels
2222 if not self.can_use_task_template_networks:
2223 networks = self.build_networks()
2224 if networks:
2225 service["networks"] = networks
2226 return service
2227
2228
2229 class DockerServiceManager:
2230 def __init__(self, client: AnsibleDockerClient):
2231 self.client = client
2232 self.retries = 2
2233 self.diff_tracker: DifferenceTracker | None = None
2234
2235 def get_service(self, name: str) -> DockerService | None:
2236 try:
2237 raw_data = self.client.inspect_service(name)
2238 except NotFound:
2239 return None
2240 ds = DockerService(
2241 self.client.docker_api_version, self.client.docker_py_version
2242 )
2243
2244 task_template_data = raw_data["Spec"]["TaskTemplate"]
2245 ds.image = task_template_data["ContainerSpec"]["Image"]
2246 ds.user = task_template_data["ContainerSpec"].get("User")
2247 ds.env = task_template_data["ContainerSpec"].get("Env")
2248 ds.command = task_template_data["ContainerSpec"].get("Command")
2249 ds.args = task_template_data["ContainerSpec"].get("Args")
2250 ds.groups = task_template_data["ContainerSpec"].get("Groups")
2251 ds.stop_grace_period = task_template_data["ContainerSpec"].get(
2252 "StopGracePeriod"
2253 )
2254 ds.stop_signal = task_template_data["ContainerSpec"].get("StopSignal")
2255 ds.working_dir = task_template_data["ContainerSpec"].get("Dir")
2256 ds.read_only = task_template_data["ContainerSpec"].get("ReadOnly")
2257 ds.cap_add = task_template_data["ContainerSpec"].get("CapabilityAdd")
2258 ds.cap_drop = task_template_data["ContainerSpec"].get("CapabilityDrop")
2259 ds.sysctls = task_template_data["ContainerSpec"].get("Sysctls")
2260
2261 healthcheck_data = task_template_data["ContainerSpec"].get("Healthcheck")
2262 if healthcheck_data:
2263 options = {
2264 "Test": "test",
2265 "Interval": "interval",
2266 "Timeout": "timeout",
2267 "StartPeriod": "start_period",
2268 "Retries": "retries",
2269 }
2270 healthcheck = {
2271 options[key]: value
2272 for key, value in healthcheck_data.items()
2273 if value is not None and key in options
2274 }
2275 ds.healthcheck = healthcheck
2276
2277 update_config_data = raw_data["Spec"].get("UpdateConfig")
2278 if update_config_data:
2279 ds.update_delay = update_config_data.get("Delay")
2280 ds.update_parallelism = update_config_data.get("Parallelism")
2281 ds.update_failure_action = update_config_data.get("FailureAction")
2282 ds.update_monitor = update_config_data.get("Monitor")
2283 ds.update_max_failure_ratio = update_config_data.get("MaxFailureRatio")
2284 ds.update_order = update_config_data.get("Order")
2285
2286 rollback_config_data = raw_data["Spec"].get("RollbackConfig")
2287 if rollback_config_data:
2288 ds.rollback_config = {
2289 "parallelism": rollback_config_data.get("Parallelism"),
2290 "delay": rollback_config_data.get("Delay"),
2291 "failure_action": rollback_config_data.get("FailureAction"),
2292 "monitor": rollback_config_data.get("Monitor"),
2293 "max_failure_ratio": rollback_config_data.get("MaxFailureRatio"),
2294 "order": rollback_config_data.get("Order"),
2295 }
2296
2297 dns_config = task_template_data["ContainerSpec"].get("DNSConfig")
2298 if dns_config:
2299 ds.dns = dns_config.get("Nameservers")
2300 ds.dns_search = dns_config.get("Search")
2301 ds.dns_options = dns_config.get("Options")
2302
2303 ds.hostname = task_template_data["ContainerSpec"].get("Hostname")
2304
2305 hosts = task_template_data["ContainerSpec"].get("Hosts")
2306 if hosts:
2307 hosts = [
2308 (
2309 list(reversed(host.split(":", 1)))
2310 if ":" in host
2311 else host.split(" ", 1)
2312 )
2313 for host in hosts
2314 ]
2315 ds.hosts = {hostname: ip for ip, hostname in hosts}
2316 ds.tty = task_template_data["ContainerSpec"].get("TTY")
2317
2318 placement = task_template_data.get("Placement")
2319 if placement:
2320 ds.constraints = placement.get("Constraints")
2321 ds.replicas_max_per_node = placement.get("MaxReplicas")
2322 placement_preferences = []
2323 for preference in placement.get("Preferences", []):
2324 placement_preferences.append(
2325 {
2326 key.lower(): value["SpreadDescriptor"]
2327 for key, value in preference.items()
2328 }
2329 )
2330 ds.placement_preferences = placement_preferences or None
2331
2332 restart_policy_data = task_template_data.get("RestartPolicy")
2333 if restart_policy_data:
2334 ds.restart_policy = restart_policy_data.get("Condition")
2335 ds.restart_policy_delay = restart_policy_data.get("Delay")
2336 ds.restart_policy_attempts = restart_policy_data.get("MaxAttempts")
2337 ds.restart_policy_window = restart_policy_data.get("Window")
2338
2339 raw_data_endpoint_spec = raw_data["Spec"].get("EndpointSpec")
2340 if raw_data_endpoint_spec:
2341 ds.endpoint_mode = raw_data_endpoint_spec.get("Mode")
2342 raw_data_ports = raw_data_endpoint_spec.get("Ports")
2343 if raw_data_ports:
2344 ds.publish = []
2345 for port in raw_data_ports:
2346 ds.publish.append(
2347 {
2348 "protocol": port["Protocol"],
2349 "mode": port.get("PublishMode", None),
2350 "published_port": port.get("PublishedPort", None),
2351 "target_port": int(port["TargetPort"]),
2352 }
2353 )
2354
2355 raw_data_limits = task_template_data.get("Resources", {}).get("Limits")
2356 if raw_data_limits:
2357 raw_cpu_limits = raw_data_limits.get("NanoCPUs")
2358 if raw_cpu_limits:
2359 ds.limit_cpu = float(raw_cpu_limits) / 1000000000
2360
2361 raw_memory_limits = raw_data_limits.get("MemoryBytes")
2362 if raw_memory_limits:
2363 ds.limit_memory = int(raw_memory_limits)
2364
2365 raw_data_reservations = task_template_data.get("Resources", {}).get(
2366 "Reservations"
2367 )
2368 if raw_data_reservations:
2369 raw_cpu_reservations = raw_data_reservations.get("NanoCPUs")
2370 if raw_cpu_reservations:
2371 ds.reserve_cpu = float(raw_cpu_reservations) / 1000000000
2372
2373 raw_memory_reservations = raw_data_reservations.get("MemoryBytes")
2374 if raw_memory_reservations:
2375 ds.reserve_memory = int(raw_memory_reservations)
2376
2377 ds.labels = raw_data["Spec"].get("Labels")
2378 ds.log_driver = task_template_data.get("LogDriver", {}).get("Name")
2379 ds.log_driver_options = task_template_data.get("LogDriver", {}).get("Options")
2380 ds.container_labels = task_template_data["ContainerSpec"].get("Labels")
2381
2382 mode = raw_data["Spec"]["Mode"]
2383 if "Replicated" in mode:
2384 ds.mode = to_text("replicated", encoding="utf-8") # type: ignore
2385 ds.replicas = mode["Replicated"]["Replicas"]
2386 elif "Global" in mode:
2387 ds.mode = "global"
2388 elif "ReplicatedJob" in mode:
2389 ds.mode = to_text("replicated-job", encoding="utf-8") # type: ignore
2390 ds.replicas = mode["ReplicatedJob"]["TotalCompletions"]
2391 else:
2392 raise ValueError(f"Unknown service mode: {mode}")
2393
2394 raw_data_mounts = task_template_data["ContainerSpec"].get("Mounts")
2395 if raw_data_mounts:
2396 ds.mounts = []
2397 for mount_data in raw_data_mounts:
2398 bind_options = mount_data.get("BindOptions", {})
2399 volume_options = mount_data.get("VolumeOptions", {})
2400 tmpfs_options = mount_data.get("TmpfsOptions", {})
2401 driver_config = volume_options.get("DriverConfig", {})
2402 driver_config = {
2403 key.lower(): value for key, value in driver_config.items()
2404 } or None
2405 ds.mounts.append(
2406 {
2407 "source": mount_data.get("Source", ""),
2408 "type": mount_data["Type"],
2409 "target": mount_data["Target"],
2410 "readonly": mount_data.get("ReadOnly"),
2411 "propagation": bind_options.get("Propagation"),
2412 "no_copy": volume_options.get("NoCopy"),
2413 "labels": volume_options.get("Labels"),
2414 "driver_config": driver_config,
2415 "tmpfs_mode": tmpfs_options.get("Mode"),
2416 "tmpfs_size": tmpfs_options.get("SizeBytes"),
2417 }
2418 )
2419
2420 raw_data_configs = task_template_data["ContainerSpec"].get("Configs")
2421 if raw_data_configs:
2422 ds.configs = []
2423 for config_data in raw_data_configs:
2424 ds.configs.append(
2425 {
2426 "config_id": config_data["ConfigID"],
2427 "config_name": config_data["ConfigName"],
2428 "filename": config_data["File"].get("Name"),
2429 "uid": config_data["File"].get("UID"),
2430 "gid": config_data["File"].get("GID"),
2431 "mode": config_data["File"].get("Mode"),
2432 }
2433 )
2434
2435 raw_data_secrets = task_template_data["ContainerSpec"].get("Secrets")
2436 if raw_data_secrets:
2437 ds.secrets = []
2438 for secret_data in raw_data_secrets:
2439 ds.secrets.append(
2440 {
2441 "secret_id": secret_data["SecretID"],
2442 "secret_name": secret_data["SecretName"],
2443 "filename": secret_data["File"].get("Name"),
2444 "uid": secret_data["File"].get("UID"),
2445 "gid": secret_data["File"].get("GID"),
2446 "mode": secret_data["File"].get("Mode"),
2447 }
2448 )
2449
2450 raw_networks_data = task_template_data.get(
2451 "Networks", raw_data["Spec"].get("Networks")
2452 )
2453 if raw_networks_data:
2454 ds.networks = []
2455 for network_data in raw_networks_data:
2456 network = {"id": network_data["Target"]}
2457 if "Aliases" in network_data:
2458 network["aliases"] = network_data["Aliases"]
2459 if "DriverOpts" in network_data:
2460 network["options"] = network_data["DriverOpts"]
2461 ds.networks.append(network)
2462 ds.service_version = raw_data["Version"]["Index"]
2463 ds.service_id = raw_data["ID"]
2464
2465 ds.init = task_template_data["ContainerSpec"].get("Init", False)
2466 return ds
2467
2468 def update_service(
2469 self, name: str, old_service: DockerService, new_service: DockerService
2470 ) -> None:
2471 service_data = new_service.build_docker_service()
2472 result = self.client.update_service(
2473 old_service.service_id,
2474 old_service.service_version,
2475 name=name,
2476 **service_data,
2477 )
2478 # Prior to Docker SDK 4.0.0 no warnings were returned and will thus be ignored.
2479 # (see https://github.com/docker/docker-py/pull/2272)
2480 self.client.report_warnings(result, ["Warning"])
2481
2482 def create_service(self, name: str, service: DockerService) -> None:
2483 service_data = service.build_docker_service()
2484 result = self.client.create_service(name=name, **service_data)
2485 self.client.report_warnings(result, ["Warning"])
2486
2487 def remove_service(self, name: str) -> None:
2488 self.client.remove_service(name)
2489
2490 def get_image_digest(self, name: str, resolve: bool = False) -> str:
2491 if not name or not resolve:
2492 return name
2493 repo, tag = parse_repository_tag(name)
2494 if not tag:
2495 tag = "latest"
2496 name = repo + ":" + tag
2497 distribution_data = self.client.inspect_distribution(name)
2498 digest = distribution_data["Descriptor"]["digest"]
2499 return f"{name}@{digest}"
2500
2501 def get_networks_names_ids(self) -> dict[str, str]:
2502 return {network["Name"]: network["Id"] for network in self.client.networks()}
2503
2504 def get_missing_secret_ids(self) -> dict[str, str]:
2505 """
2506 Resolve missing secret ids by looking them up by name
2507 """
2508 secret_names = [
2509 secret["secret_name"]
2510 for secret in self.client.module.params.get("secrets") or []
2511 if secret["secret_id"] is None
2512 ]
2513 if not secret_names:
2514 return {}
2515 secrets = self.client.secrets(filters={"name": secret_names})
2516 secrets = {
2517 secret["Spec"]["Name"]: secret["ID"]
2518 for secret in secrets
2519 if secret["Spec"]["Name"] in secret_names
2520 }
2521 for secret_name in secret_names:
2522 if secret_name not in secrets:
2523 self.client.fail(f'Could not find a secret named "{secret_name}"')
2524 return secrets
2525
2526 def get_missing_config_ids(self) -> dict[str, str]:
2527 """
2528 Resolve missing config ids by looking them up by name
2529 """
2530 config_names = [
2531 config["config_name"]
2532 for config in self.client.module.params.get("configs") or []
2533 if config["config_id"] is None
2534 ]
2535 if not config_names:
2536 return {}
2537 configs = self.client.configs(filters={"name": config_names})
2538 configs = {
2539 config["Spec"]["Name"]: config["ID"]
2540 for config in configs
2541 if config["Spec"]["Name"] in config_names
2542 }
2543 for config_name in config_names:
2544 if config_name not in configs:
2545 self.client.fail(f'Could not find a config named "{config_name}"')
2546 return configs
2547
2548 def run(self) -> tuple[str, bool, bool, list[str], dict[str, t.Any]]:
2549 self.diff_tracker = DifferenceTracker()
2550 module = self.client.module
2551
2552 image = module.params["image"]
2553 try:
2554 image_digest = self.get_image_digest(
2555 name=image, resolve=module.params["resolve_image"]
2556 )
2557 except DockerException as e:
2558 self.client.fail(f"Error looking for an image named {image}: {e}")
2559
2560 try:
2561 current_service = self.get_service(module.params["name"])
2562 except Exception as e: # pylint: disable=broad-exception-caught
2563 self.client.fail(
2564 f"Error looking for service named {module.params['name']}: {e}"
2565 )
2566 try:
2567 secret_ids = self.get_missing_secret_ids()
2568 config_ids = self.get_missing_config_ids()
2569 network_ids = self.get_networks_names_ids()
2570 new_service = DockerService.from_ansible_params(
2571 module.params,
2572 current_service,
2573 image_digest,
2574 secret_ids,
2575 config_ids,
2576 network_ids,
2577 self.client,
2578 )
2579 except Exception as e: # pylint: disable=broad-exception-caught
2580 return self.client.fail(f"Error parsing module parameters: {e}")
2581
2582 changed = False
2583 msg = "noop"
2584 rebuilt = False
2585 differences = DifferenceTracker()
2586 facts = {}
2587
2588 if current_service:
2589 if module.params["state"] == "absent":
2590 if not module.check_mode:
2591 self.remove_service(module.params["name"])
2592 msg = "Service removed"
2593 changed = True
2594 else:
2595 changed, differences, need_rebuild, force_update = new_service.compare(
2596 current_service
2597 )
2598 if changed:
2599 self.diff_tracker.merge(differences)
2600 if need_rebuild:
2601 if not module.check_mode:
2602 self.remove_service(module.params["name"])
2603 self.create_service(module.params["name"], new_service)
2604 msg = "Service rebuilt"
2605 rebuilt = True
2606 else:
2607 if not module.check_mode:
2608 self.update_service(
2609 module.params["name"], current_service, new_service
2610 )
2611 msg = "Service updated"
2612 rebuilt = False
2613 else:
2614 if force_update:
2615 if not module.check_mode:
2616 self.update_service(
2617 module.params["name"], current_service, new_service
2618 )
2619 msg = "Service forcefully updated"
2620 rebuilt = False
2621 changed = True
2622 else:
2623 msg = "Service unchanged"
2624 facts = new_service.get_facts()
2625 else:
2626 if module.params["state"] == "absent":
2627 msg = "Service absent"
2628 else:
2629 if not module.check_mode:
2630 self.create_service(module.params["name"], new_service)
2631 msg = "Service created"
2632 changed = True
2633 facts = new_service.get_facts()
2634
2635 return msg, changed, rebuilt, differences.get_legacy_docker_diffs(), facts
2636
2637 def run_safe(self) -> tuple[str, bool, bool, list[str], dict[str, t.Any]]:
2638 while True:
2639 try:
2640 return self.run()
2641 except APIError as e:
2642 # Sometimes Version.Index will have changed between an inspect and
2643 # update. If this is encountered we'll retry the update.
2644 if self.retries > 0 and "update out of sequence" in str(e.explanation):
2645 self.retries -= 1
2646 time.sleep(1)
2647 else:
2648 raise
2649
2650
2651 def _detect_publish_mode_usage(client: AnsibleDockerClient) -> bool:
2652 return any(
2653 publish_def.get("mode") for publish_def in client.module.params["publish"] or []
2654 )
2655
2656
2657 def _detect_healthcheck_start_period(client: AnsibleDockerClient) -> bool:
2658 if client.module.params["healthcheck"]:
2659 return client.module.params["healthcheck"]["start_period"] is not None
2660 return False
2661
2662
2663 def _detect_mount_tmpfs_usage(client: AnsibleDockerClient) -> bool:
2664 for mount in client.module.params["mounts"] or []:
2665 if mount.get("type") == "tmpfs":
2666 return True
2667 if mount.get("tmpfs_size") is not None:
2668 return True
2669 if mount.get("tmpfs_mode") is not None:
2670 return True
2671 return False
2672
2673
2674 def _detect_update_config_failure_action_rollback(client: AnsibleDockerClient) -> bool:
2675 rollback_config_failure_action = (client.module.params["update_config"] or {}).get(
2676 "failure_action"
2677 )
2678 return rollback_config_failure_action == "rollback"
2679
2680
2681 def main() -> None:
2682 argument_spec = {
2683 "name": {"type": "str", "required": True},
2684 "image": {"type": "str"},
2685 "state": {
2686 "type": "str",
2687 "default": "present",
2688 "choices": ["present", "absent"],
2689 },
2690 "mounts": {
2691 "type": "list",
2692 "elements": "dict",
2693 "options": {
2694 "source": {"type": "str"},
2695 "target": {"type": "str", "required": True},
2696 "type": {
2697 "type": "str",
2698 "default": "bind",
2699 "choices": ["bind", "volume", "tmpfs", "npipe"],
2700 },
2701 "readonly": {"type": "bool"},
2702 "labels": {"type": "dict"},
2703 "propagation": {
2704 "type": "str",
2705 "choices": [
2706 "shared",
2707 "slave",
2708 "private",
2709 "rshared",
2710 "rslave",
2711 "rprivate",
2712 ],
2713 },
2714 "no_copy": {"type": "bool"},
2715 "driver_config": {
2716 "type": "dict",
2717 "options": {"name": {"type": "str"}, "options": {"type": "dict"}},
2718 },
2719 "tmpfs_size": {"type": "str"},
2720 "tmpfs_mode": {"type": "int"},
2721 },
2722 },
2723 "configs": {
2724 "type": "list",
2725 "elements": "dict",
2726 "options": {
2727 "config_id": {"type": "str"},
2728 "config_name": {"type": "str", "required": True},
2729 "filename": {"type": "str"},
2730 "uid": {"type": "str"},
2731 "gid": {"type": "str"},
2732 "mode": {"type": "int"},
2733 },
2734 },
2735 "secrets": {
2736 "type": "list",
2737 "elements": "dict",
2738 "no_log": False,
2739 "options": {
2740 "secret_id": {"type": "str", "no_log": False},
2741 "secret_name": {"type": "str", "required": True, "no_log": False},
2742 "filename": {"type": "str"},
2743 "uid": {"type": "str"},
2744 "gid": {"type": "str"},
2745 "mode": {"type": "int"},
2746 },
2747 },
2748 "networks": {"type": "list", "elements": "raw"},
2749 "command": {"type": "raw"},
2750 "args": {"type": "list", "elements": "str"},
2751 "env": {"type": "raw"},
2752 "env_files": {"type": "list", "elements": "path"},
2753 "force_update": {"type": "bool", "default": False},
2754 "groups": {"type": "list", "elements": "str"},
2755 "logging": {
2756 "type": "dict",
2757 "options": {
2758 "driver": {"type": "str"},
2759 "options": {"type": "dict"},
2760 },
2761 },
2762 "publish": {
2763 "type": "list",
2764 "elements": "dict",
2765 "options": {
2766 "published_port": {"type": "int", "required": False},
2767 "target_port": {"type": "int", "required": True},
2768 "protocol": {
2769 "type": "str",
2770 "default": "tcp",
2771 "choices": ["tcp", "udp"],
2772 },
2773 "mode": {"type": "str", "choices": ["ingress", "host"]},
2774 },
2775 },
2776 "placement": {
2777 "type": "dict",
2778 "options": {
2779 "constraints": {"type": "list", "elements": "str"},
2780 "preferences": {"type": "list", "elements": "dict"},
2781 "replicas_max_per_node": {"type": "int"},
2782 },
2783 },
2784 "tty": {"type": "bool"},
2785 "dns": {"type": "list", "elements": "str"},
2786 "dns_search": {"type": "list", "elements": "str"},
2787 "dns_options": {"type": "list", "elements": "str"},
2788 "healthcheck": {
2789 "type": "dict",
2790 "options": {
2791 "test": {"type": "raw"},
2792 "interval": {"type": "str"},
2793 "timeout": {"type": "str"},
2794 "start_period": {"type": "str"},
2795 "retries": {"type": "int"},
2796 },
2797 },
2798 "hostname": {"type": "str"},
2799 "hosts": {"type": "dict"},
2800 "labels": {"type": "dict"},
2801 "container_labels": {"type": "dict"},
2802 "sysctls": {"type": "dict"},
2803 "mode": {
2804 "type": "str",
2805 "default": "replicated",
2806 "choices": ["replicated", "global", "replicated-job"],
2807 },
2808 "replicas": {"type": "int", "default": -1},
2809 "endpoint_mode": {"type": "str", "choices": ["vip", "dnsrr"]},
2810 "stop_grace_period": {"type": "str"},
2811 "stop_signal": {"type": "str"},
2812 "limits": {
2813 "type": "dict",
2814 "options": {
2815 "cpus": {"type": "float"},
2816 "memory": {"type": "str"},
2817 },
2818 },
2819 "read_only": {"type": "bool"},
2820 "reservations": {
2821 "type": "dict",
2822 "options": {
2823 "cpus": {"type": "float"},
2824 "memory": {"type": "str"},
2825 },
2826 },
2827 "resolve_image": {"type": "bool", "default": False},
2828 "restart_config": {
2829 "type": "dict",
2830 "options": {
2831 "condition": {"type": "str", "choices": ["none", "on-failure", "any"]},
2832 "delay": {"type": "str"},
2833 "max_attempts": {"type": "int"},
2834 "window": {"type": "str"},
2835 },
2836 },
2837 "rollback_config": {
2838 "type": "dict",
2839 "options": {
2840 "parallelism": {"type": "int"},
2841 "delay": {"type": "str"},
2842 "failure_action": {"type": "str", "choices": ["continue", "pause"]},
2843 "monitor": {"type": "str"},
2844 "max_failure_ratio": {"type": "float"},
2845 "order": {"type": "str"},
2846 },
2847 },
2848 "update_config": {
2849 "type": "dict",
2850 "options": {
2851 "parallelism": {"type": "int"},
2852 "delay": {"type": "str"},
2853 "failure_action": {
2854 "type": "str",
2855 "choices": ["continue", "pause", "rollback"],
2856 },
2857 "monitor": {"type": "str"},
2858 "max_failure_ratio": {"type": "float"},
2859 "order": {"type": "str"},
2860 },
2861 },
2862 "user": {"type": "str"},
2863 "working_dir": {"type": "str"},
2864 "init": {"type": "bool"},
2865 "cap_add": {"type": "list", "elements": "str"},
2866 "cap_drop": {"type": "list", "elements": "str"},
2867 }
2868
2869 option_minimal_versions = {
2870 "dns": {"docker_py_version": "2.6.0"},
2871 "dns_options": {"docker_py_version": "2.6.0"},
2872 "dns_search": {"docker_py_version": "2.6.0"},
2873 "endpoint_mode": {"docker_py_version": "3.0.0"},
2874 "force_update": {"docker_py_version": "2.1.0"},
2875 "healthcheck": {"docker_py_version": "2.6.0"},
2876 "hostname": {"docker_py_version": "2.2.0"},
2877 "hosts": {"docker_py_version": "2.6.0"},
2878 "groups": {"docker_py_version": "2.6.0"},
2879 "tty": {"docker_py_version": "2.4.0"},
2880 "secrets": {"docker_py_version": "2.4.0"},
2881 "configs": {"docker_py_version": "2.6.0", "docker_api_version": "1.30"},
2882 "stop_signal": {"docker_py_version": "2.6.0", "docker_api_version": "1.28"},
2883 "publish": {"docker_py_version": "3.0.0"},
2884 "read_only": {"docker_py_version": "2.6.0", "docker_api_version": "1.28"},
2885 "resolve_image": {"docker_api_version": "1.30", "docker_py_version": "3.2.0"},
2886 "rollback_config": {"docker_py_version": "3.5.0", "docker_api_version": "1.28"},
2887 "init": {"docker_py_version": "4.0.0", "docker_api_version": "1.37"},
2888 "cap_add": {"docker_py_version": "5.0.3", "docker_api_version": "1.41"},
2889 "cap_drop": {"docker_py_version": "5.0.3", "docker_api_version": "1.41"},
2890 "sysctls": {"docker_py_version": "6.0.0", "docker_api_version": "1.40"},
2891 # specials
2892 "publish_mode": {
2893 "docker_py_version": "3.0.0",
2894 "detect_usage": _detect_publish_mode_usage,
2895 "usage_msg": "set publish.mode",
2896 },
2897 "healthcheck_start_period": {
2898 "docker_py_version": "2.6.0",
2899 "docker_api_version": "1.29",
2900 "detect_usage": _detect_healthcheck_start_period,
2901 "usage_msg": "set healthcheck.start_period",
2902 },
2903 "update_config_max_failure_ratio": {
2904 "docker_py_version": "2.1.0",
2905 "detect_usage": lambda c: (c.module.params["update_config"] or {}).get(
2906 "max_failure_ratio"
2907 )
2908 is not None,
2909 "usage_msg": "set update_config.max_failure_ratio",
2910 },
2911 "update_config_failure_action": {
2912 "docker_py_version": "3.5.0",
2913 "docker_api_version": "1.28",
2914 "detect_usage": _detect_update_config_failure_action_rollback,
2915 "usage_msg": "set update_config.failure_action.rollback",
2916 },
2917 "update_config_monitor": {
2918 "docker_py_version": "2.1.0",
2919 "detect_usage": lambda c: (c.module.params["update_config"] or {}).get(
2920 "monitor"
2921 )
2922 is not None,
2923 "usage_msg": "set update_config.monitor",
2924 },
2925 "update_config_order": {
2926 "docker_py_version": "2.7.0",
2927 "docker_api_version": "1.29",
2928 "detect_usage": lambda c: (c.module.params["update_config"] or {}).get(
2929 "order"
2930 )
2931 is not None,
2932 "usage_msg": "set update_config.order",
2933 },
2934 "placement_config_preferences": {
2935 "docker_py_version": "2.4.0",
2936 "docker_api_version": "1.27",
2937 "detect_usage": lambda c: (c.module.params["placement"] or {}).get(
2938 "preferences"
2939 )
2940 is not None,
2941 "usage_msg": "set placement.preferences",
2942 },
2943 "placement_config_constraints": {
2944 "docker_py_version": "2.4.0",
2945 "detect_usage": lambda c: (c.module.params["placement"] or {}).get(
2946 "constraints"
2947 )
2948 is not None,
2949 "usage_msg": "set placement.constraints",
2950 },
2951 "placement_config_replicas_max_per_node": {
2952 "docker_py_version": "4.4.3",
2953 "docker_api_version": "1.40",
2954 "detect_usage": lambda c: (c.module.params["placement"] or {}).get(
2955 "replicas_max_per_node"
2956 )
2957 is not None,
2958 "usage_msg": "set placement.replicas_max_per_node",
2959 },
2960 "mounts_tmpfs": {
2961 "docker_py_version": "2.6.0",
2962 "detect_usage": _detect_mount_tmpfs_usage,
2963 "usage_msg": "set mounts.tmpfs",
2964 },
2965 "rollback_config_order": {
2966 "docker_api_version": "1.29",
2967 "detect_usage": lambda c: (c.module.params["rollback_config"] or {}).get(
2968 "order"
2969 )
2970 is not None,
2971 "usage_msg": "set rollback_config.order",
2972 },
2973 "mode_replicated_job": {
2974 "docker_py_version": "6.0.0",
2975 "docker_api_version": "1.41",
2976 "detect_usage": lambda c: c.module.params.get("mode") == "replicated-job",
2977 "usage_msg": "set mode",
2978 },
2979 }
2980 required_if = [("state", "present", ["image"])]
2981
2982 client = AnsibleDockerClient(
2983 argument_spec=argument_spec,
2984 required_if=required_if,
2985 supports_check_mode=True,
2986 min_docker_version="2.0.2",
2987 option_minimal_versions=option_minimal_versions,
2988 )
2989
2990 try:
2991 dsm = DockerServiceManager(client)
2992 msg, changed, rebuilt, changes, facts = dsm.run_safe()
2993
2994 results = {
2995 "msg": msg,
2996 "changed": changed,
2997 "rebuilt": rebuilt,
2998 "changes": changes,
2999 "swarm_service": facts,
3000 }
3001 if client.module._diff:
3002 assert dsm.diff_tracker is not None
3003 before, after = dsm.diff_tracker.get_before_after()
3004 results["diff"] = {"before": before, "after": after}
3005
3006 client.module.exit_json(**results)
3007 except DockerException as e:
3008 client.fail(
3009 f"An unexpected Docker error occurred: {e}",
3010 exception=traceback.format_exc(),
3011 )
3012 except RequestException as e:
3013 client.fail(
3014 f"An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}",
3015 exception=traceback.format_exc(),
3016 )
3017
3018
3019 if __name__ == "__main__":
3020 main()