Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright 2016 Red Hat | Ansible
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
11 short_description: Manage Swarm cluster
12 description:
13 - Create a new Swarm cluster.
14 - Add/Remove nodes or managers to an existing cluster.
15 extends_documentation_fragment:
16 - community.docker._docker
17 - community.docker._docker.docker_py_2_documentation
18 - community.docker._attributes
19 - community.docker._attributes.actiongroup_docker
20
21 attributes:
22 check_mode:
23 support: full
24 diff_mode:
25 support: full
26 idempotent:
27 support: full
28
29 options:
30 advertise_addr:
31 description:
32 - Externally reachable address advertised to other nodes.
33 - This can either be an address/port combination in the form V(192.168.1.1:4567), or an interface followed by a port
34 number, like V(eth0:4567).
35 - If the port number is omitted, the port number from the listen address is used.
36 - If O(advertise_addr) is not specified, it will be automatically detected when possible.
37 - Only used when swarm is initialised or joined. Because of this it is not considered for idempotency checking.
38 type: str
39 default_addr_pool:
40 description:
41 - Default address pool in CIDR format.
42 - Only used when swarm is initialised. Because of this it is not considered for idempotency checking.
43 - Requires API version >= 1.39.
44 type: list
45 elements: str
46 subnet_size:
47 description:
48 - Default address pool subnet mask length.
49 - Only used when swarm is initialised. Because of this it is not considered for idempotency checking.
50 - Requires API version >= 1.39.
51 type: int
52 listen_addr:
53 description:
54 - Listen address used for inter-manager communication.
55 - This can either be an address/port combination in the form V(192.168.1.1:4567), or an interface followed by a port
56 number, like V(eth0:4567).
57 - If the port number is omitted, the default swarm listening port is used.
58 - Only used when swarm is initialised or joined. Because of this it is not considered for idempotency checking.
59 type: str
60 default: 0.0.0.0:2377
61 force:
62 description:
63 - Use with state V(present) to force creating a new Swarm, even if already part of one.
64 - Use with state V(absent) to Leave the swarm even if this node is a manager.
65 type: bool
66 default: false
67 state:
68 description:
69 - Set to V(present), to create/update a new cluster.
70 - Set to V(join), to join an existing cluster.
71 - Set to V(absent), to leave an existing cluster.
72 - Set to V(remove), to remove an absent node from the cluster. Note that removing requires Docker SDK for Python >=
73 2.4.0.
74 - M(community.docker.docker_node) can be used to demote a manager before removal.
75 type: str
76 default: present
77 choices:
78 - present
79 - join
80 - absent
81 - remove
82 node_id:
83 description:
84 - Swarm id of the node to remove.
85 - Used with O(state=remove).
86 type: str
87 join_token:
88 description:
89 - Swarm token used to join a swarm cluster.
90 - Used with O(state=join).
91 - If this value is specified, the corresponding value in the return values will be censored by Ansible. This is a side-effect
92 of this value not being logged.
93 type: str
94 remote_addrs:
95 description:
96 - Remote address of one or more manager nodes of an existing Swarm to connect to.
97 - Used with O(state=join).
98 type: list
99 elements: str
100 task_history_retention_limit:
101 description:
102 - Maximum number of tasks history stored.
103 - Docker default value is V(5).
104 type: int
105 snapshot_interval:
106 description:
107 - Number of logs entries between snapshot.
108 - Docker default value is V(10000).
109 type: int
110 keep_old_snapshots:
111 description:
112 - Number of snapshots to keep beyond the current snapshot.
113 - Docker default value is V(0).
114 type: int
115 log_entries_for_slow_followers:
116 description:
117 - Number of log entries to keep around to sync up slow followers after a snapshot is created.
118 type: int
119 heartbeat_tick:
120 description:
121 - Amount of ticks (in seconds) between each heartbeat.
122 - Docker default value is V(1) seconds.
123 type: int
124 election_tick:
125 description:
126 - Amount of ticks (in seconds) needed without a leader to trigger a new election.
127 - Docker default value is V(10) seconds.
128 type: int
129 dispatcher_heartbeat_period:
130 description:
131 - The delay (in nanoseconds) for an agent to send a heartbeat to the dispatcher.
132 - Docker default value is 5 seconds, which corresponds to a value of V(5000000000).
133 type: int
134 node_cert_expiry:
135 description:
136 - Automatic expiry for nodes certificates, given in nanoseconds.
137 - Docker default value is 90 days, which corresponds to a value of V(7776000000000000).
138 type: int
139 name:
140 description:
141 - The name of the swarm.
142 type: str
143 labels:
144 description:
145 - User-defined key/value metadata.
146 - Label operations in this module apply to the docker swarm cluster. Use M(community.docker.docker_node) module to add/modify/remove
147 swarm node labels.
148 - Requires API version >= 1.32.
149 type: dict
150 signing_ca_cert:
151 description:
152 - The desired signing CA certificate for all swarm node TLS leaf certificates, in PEM format.
153 - This must not be a path to a certificate, but the contents of the certificate.
154 - Requires API version >= 1.30.
155 type: str
156 signing_ca_key:
157 description:
158 - The desired signing CA key for all swarm node TLS leaf certificates, in PEM format.
159 - This must not be a path to a key, but the contents of the key.
160 - Requires API version >= 1.30.
161 type: str
162 ca_force_rotate:
163 description:
164 - An integer whose purpose is to force swarm to generate a new signing CA certificate and key, if none have been specified.
165 - Docker default value is V(0).
166 - Requires API version >= 1.30.
167 type: int
168 autolock_managers:
169 description:
170 - If set, generate a key and use it to lock data stored on the managers.
171 - Docker default value is V(false).
172 - M(community.docker.docker_swarm_info) can be used to retrieve the unlock key.
173 type: bool
174 rotate_worker_token:
175 description: Rotate the worker join token.
176 type: bool
177 default: false
178 rotate_manager_token:
179 description: Rotate the manager join token.
180 type: bool
181 default: false
182 data_path_addr:
183 description:
184 - Address or interface to use for data path traffic.
185 - This can either be an address in the form V(192.168.1.1), or an interface, like V(eth0).
186 - Only used when swarm is initialised or joined. Because of this it is not considered for idempotency checking.
187 - Requires API version >= 1.30.
188 type: str
189 version_added: 2.5.0
190 data_path_port:
191 description:
192 - Port to use for data path traffic.
193 - This needs to be a port number like V(9789).
194 - Only used when swarm is initialised. Because of this it is not considered for idempotency checking.
195 - Requires API version >= 1.40.
196 type: int
197 version_added: 3.1.0
198
199 requirements:
200 - "L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 2.0.0"
201 - Docker API >= 1.25
202 author:
203 - Thierry Bouvet (@tbouvet)
204 - Piotr Wojciechowski (@WojciechowskiPiotr)
205 """
206
207 EXAMPLES = r"""
208 ---
209 - name: Init a new swarm with default parameters
210 community.docker.docker_swarm:
211 state: present
212
213 - name: Update swarm configuration
214 community.docker.docker_swarm:
215 state: present
216 election_tick: 5
217
218 - name: Add nodes
219 community.docker.docker_swarm:
220 state: join
221 advertise_addr: 192.168.1.2
222 join_token: SWMTKN-1--xxxxx
223 remote_addrs: ['192.168.1.1:2377']
224
225 - name: Leave swarm for a node
226 community.docker.docker_swarm:
227 state: absent
228
229 - name: Remove a swarm manager
230 community.docker.docker_swarm:
231 state: absent
232 force: true
233
234 - name: Remove node from swarm
235 community.docker.docker_swarm:
236 state: remove
237 node_id: mynode
238
239 - name: Init a new swarm with different data path interface
240 community.docker.docker_swarm:
241 state: present
242 advertise_addr: eth0
243 data_path_addr: ens10
244
245 - name: Init a new swarm with a different data path port
246 community.docker.docker_swarm:
247 state: present
248 data_path_port: 9789
249 """
250
251 RETURN = r"""
252 swarm_facts:
253 description: Information about swarm.
254 returned: success
255 type: dict
256 contains:
257 JoinTokens:
258 description: Tokens to connect to the Swarm.
259 returned: success
260 type: dict
261 contains:
262 Worker:
263 description:
264 - Token to join the cluster as a new *worker* node.
265 - B(Note:) if this value has been specified as O(join_token), the value here will not be the token, but C(VALUE_SPECIFIED_IN_NO_LOG_PARAMETER).
266 If you pass O(join_token), make sure your playbook/role does not depend on this return value!
267 returned: success
268 type: str
269 example: SWMTKN-1--xxxxx
270 Manager:
271 description:
272 - Token to join the cluster as a new *manager* node.
273 - B(Note:) if this value has been specified as O(join_token), the value here will not be the token, but C(VALUE_SPECIFIED_IN_NO_LOG_PARAMETER).
274 If you pass O(join_token), make sure your playbook/role does not depend on this return value!
275 returned: success
276 type: str
277 example: SWMTKN-1--xxxxx
278 UnlockKey:
279 description: The swarm unlock-key if O(autolock_managers=true).
280 returned: on success if O(autolock_managers=true) and swarm is initialised, or if O(autolock_managers) has changed.
281 type: str
282 example: SWMKEY-1-xxx
283
284 actions:
285 description: Provides the actions done on the swarm.
286 returned: when action failed.
287 type: list
288 elements: str
289 example: ['This cluster is already a swarm cluster']
290 """
291
292 import json
293 import traceback
294 import typing as t
295
296 try:
297 from docker.errors import APIError, DockerException
298 except ImportError:
299 # missing Docker SDK for Python handled in ansible.module_utils.docker.common
300 pass
301
302 from ansible_collections.community.docker.plugins.module_utils._common import (
303 RequestException,
304 )
305 from ansible_collections.community.docker.plugins.module_utils._swarm import (
306 AnsibleDockerSwarmClient,
307 )
308 from ansible_collections.community.docker.plugins.module_utils._util import (
309 DifferenceTracker,
310 DockerBaseClass,
311 sanitize_labels,
312 )
313
314
315 class TaskParameters(DockerBaseClass):
316 def __init__(self) -> None:
317 super().__init__()
318
319 self.advertise_addr: str | None = None
320 self.listen_addr: str | None = None
321 self.remote_addrs: list[str] | None = None
322 self.join_token: str | None = None
323 self.data_path_addr: str | None = None
324 self.data_path_port: int | None = None
325 self.spec = None
326
327 # Spec
328 self.snapshot_interval: int | None = None
329 self.task_history_retention_limit: int | None = None
330 self.keep_old_snapshots: int | None = None
331 self.log_entries_for_slow_followers: int | None = None
332 self.heartbeat_tick: int | None = None
333 self.election_tick: int | None = None
334 self.dispatcher_heartbeat_period: int | None = None
335 self.node_cert_expiry: int | None = None
336 self.name: str | None = None
337 self.labels: dict[str, t.Any] | None = None
338 self.log_driver = None
339 self.signing_ca_cert: str | None = None
340 self.signing_ca_key: str | None = None
341 self.ca_force_rotate: int | None = None
342 self.autolock_managers: bool | None = None
343 self.rotate_worker_token: bool | None = None
344 self.rotate_manager_token: bool | None = None
345 self.default_addr_pool: list[str] | None = None
346 self.subnet_size: int | None = None
347
348 @staticmethod
349 def from_ansible_params(client: AnsibleDockerSwarmClient) -> TaskParameters:
350 result = TaskParameters()
351 for key, value in client.module.params.items():
352 if key in result.__dict__:
353 setattr(result, key, value)
354
355 result.update_parameters(client)
356 return result
357
358 def update_from_swarm_info(self, swarm_info: dict[str, t.Any]) -> None:
359 spec = swarm_info["Spec"]
360
361 ca_config = spec.get("CAConfig") or {}
362 if self.node_cert_expiry is None:
363 self.node_cert_expiry = ca_config.get("NodeCertExpiry")
364 if self.ca_force_rotate is None:
365 self.ca_force_rotate = ca_config.get("ForceRotate")
366
367 dispatcher = spec.get("Dispatcher") or {}
368 if self.dispatcher_heartbeat_period is None:
369 self.dispatcher_heartbeat_period = dispatcher.get("HeartbeatPeriod")
370
371 raft = spec.get("Raft") or {}
372 if self.snapshot_interval is None:
373 self.snapshot_interval = raft.get("SnapshotInterval")
374 if self.keep_old_snapshots is None:
375 self.keep_old_snapshots = raft.get("KeepOldSnapshots")
376 if self.heartbeat_tick is None:
377 self.heartbeat_tick = raft.get("HeartbeatTick")
378 if self.log_entries_for_slow_followers is None:
379 self.log_entries_for_slow_followers = raft.get("LogEntriesForSlowFollowers")
380 if self.election_tick is None:
381 self.election_tick = raft.get("ElectionTick")
382
383 orchestration = spec.get("Orchestration") or {}
384 if self.task_history_retention_limit is None:
385 self.task_history_retention_limit = orchestration.get(
386 "TaskHistoryRetentionLimit"
387 )
388
389 encryption_config = spec.get("EncryptionConfig") or {}
390 if self.autolock_managers is None:
391 self.autolock_managers = encryption_config.get("AutoLockManagers")
392
393 if self.name is None:
394 self.name = spec["Name"]
395
396 if self.labels is None:
397 self.labels = spec.get("Labels") or {}
398
399 if "LogDriver" in spec["TaskDefaults"]:
400 self.log_driver = spec["TaskDefaults"]["LogDriver"]
401
402 def update_parameters(self, client: AnsibleDockerSwarmClient) -> None:
403 assign = {
404 "snapshot_interval": "snapshot_interval",
405 "task_history_retention_limit": "task_history_retention_limit",
406 "keep_old_snapshots": "keep_old_snapshots",
407 "log_entries_for_slow_followers": "log_entries_for_slow_followers",
408 "heartbeat_tick": "heartbeat_tick",
409 "election_tick": "election_tick",
410 "dispatcher_heartbeat_period": "dispatcher_heartbeat_period",
411 "node_cert_expiry": "node_cert_expiry",
412 "name": "name",
413 "labels": "labels",
414 "signing_ca_cert": "signing_ca_cert",
415 "signing_ca_key": "signing_ca_key",
416 "ca_force_rotate": "ca_force_rotate",
417 "autolock_managers": "autolock_managers",
418 "log_driver": "log_driver",
419 }
420 params = {}
421 for dest, source in assign.items():
422 if not client.option_minimal_versions[source]["supported"]:
423 continue
424 value = getattr(self, source)
425 if value is not None:
426 params[dest] = value
427 self.spec = client.create_swarm_spec(**params)
428
429 def compare_to_active(
430 self,
431 other: TaskParameters,
432 client: AnsibleDockerSwarmClient,
433 differences: DifferenceTracker,
434 ) -> DifferenceTracker:
435 for k in self.__dict__:
436 if k in (
437 "advertise_addr",
438 "listen_addr",
439 "remote_addrs",
440 "join_token",
441 "rotate_worker_token",
442 "rotate_manager_token",
443 "spec",
444 "default_addr_pool",
445 "subnet_size",
446 "data_path_addr",
447 "data_path_port",
448 ):
449 continue
450 if not client.option_minimal_versions[k]["supported"]:
451 continue
452 value = getattr(self, k)
453 if value is None:
454 continue
455 other_value = getattr(other, k)
456 if value != other_value:
457 differences.add(k, parameter=value, active=other_value)
458 if self.rotate_worker_token:
459 differences.add("rotate_worker_token", parameter=True, active=False)
460 if self.rotate_manager_token:
461 differences.add("rotate_manager_token", parameter=True, active=False)
462 return differences
463
464
465 class SwarmManager(DockerBaseClass):
466 def __init__(
467 self, client: AnsibleDockerSwarmClient, results: dict[str, t.Any]
468 ) -> None:
469 super().__init__()
470
471 self.client = client
472 self.results = results
473 self.check_mode = self.client.check_mode
474 self.swarm_info: dict[str, t.Any] = {}
475
476 self.state: t.Literal["present", "join", "absent", "remove"] = (
477 client.module.params["state"]
478 )
479 self.force: bool = client.module.params["force"]
480 self.node_id: str | None = client.module.params["node_id"]
481
482 self.differences = DifferenceTracker()
483 self.parameters = TaskParameters.from_ansible_params(client)
484
485 self.created = False
486
487 def __call__(self) -> None:
488 choice_map = {
489 "present": self.init_swarm,
490 "join": self.join,
491 "absent": self.leave,
492 "remove": self.remove,
493 }
494
495 choice_map[self.state]()
496
497 if self.client.module._diff or self.parameters.debug:
498 diff = {}
499 diff["before"], diff["after"] = self.differences.get_before_after()
500 self.results["diff"] = diff
501
502 def inspect_swarm(self) -> None:
503 try:
504 data = self.client.inspect_swarm()
505 json_str = json.dumps(data, ensure_ascii=False)
506 self.swarm_info = json.loads(json_str)
507
508 self.results["changed"] = False
509 self.results["swarm_facts"] = self.swarm_info
510
511 unlock_key = self.get_unlock_key()
512 self.swarm_info.update(unlock_key)
513 except APIError:
514 pass
515
516 def get_unlock_key(self) -> dict[str, t.Any]:
517 default = {"UnlockKey": None}
518 if not self.has_swarm_lock_changed():
519 return default
520 try:
521 return self.client.get_unlock_key() or default
522 except APIError:
523 return default
524
525 def has_swarm_lock_changed(self) -> bool:
526 return bool(self.parameters.autolock_managers) and (
527 self.created or self.differences.has_difference_for("autolock_managers")
528 )
529
530 def init_swarm(self) -> None:
531 if not self.force and self.client.check_if_swarm_manager():
532 self.__update_swarm()
533 return
534
535 if not self.check_mode:
536 init_arguments: dict[str, t.Any] = {
537 "advertise_addr": self.parameters.advertise_addr,
538 "listen_addr": self.parameters.listen_addr,
539 "force_new_cluster": self.force,
540 "swarm_spec": self.parameters.spec,
541 }
542 if self.parameters.default_addr_pool is not None:
543 init_arguments["default_addr_pool"] = self.parameters.default_addr_pool
544 if self.parameters.subnet_size is not None:
545 init_arguments["subnet_size"] = self.parameters.subnet_size
546 if self.parameters.data_path_addr is not None:
547 init_arguments["data_path_addr"] = self.parameters.data_path_addr
548 if self.parameters.data_path_port is not None:
549 init_arguments["data_path_port"] = self.parameters.data_path_port
550 try:
551 self.client.init_swarm(**init_arguments)
552 except APIError as exc:
553 self.client.fail(f"Can not create a new Swarm Cluster: {exc}")
554
555 if not self.client.check_if_swarm_manager() and not self.check_mode:
556 self.client.fail("Swarm not created or other error!")
557
558 self.created = True
559 self.inspect_swarm()
560 self.results["actions"].append(
561 f"New Swarm cluster created: {self.swarm_info.get('ID')}"
562 )
563 self.differences.add("state", parameter="present", active="absent")
564 self.results["changed"] = True
565 self.results["swarm_facts"] = {
566 "JoinTokens": self.swarm_info.get("JoinTokens"),
567 "UnlockKey": self.swarm_info.get("UnlockKey"),
568 }
569
570 def __update_swarm(self) -> None:
571 try:
572 self.inspect_swarm()
573 version = self.swarm_info["Version"]["Index"]
574 self.parameters.update_from_swarm_info(self.swarm_info)
575 old_parameters = TaskParameters()
576 old_parameters.update_from_swarm_info(self.swarm_info)
577 self.parameters.compare_to_active(
578 old_parameters, self.client, self.differences
579 )
580 if self.differences.empty:
581 self.results["actions"].append("No modification")
582 self.results["changed"] = False
583 return
584 update_parameters = TaskParameters.from_ansible_params(self.client)
585 update_parameters.update_parameters(self.client)
586 if not self.check_mode:
587 self.client.update_swarm(
588 version=version,
589 swarm_spec=update_parameters.spec,
590 rotate_worker_token=self.parameters.rotate_worker_token,
591 rotate_manager_token=self.parameters.rotate_manager_token,
592 )
593 except APIError as exc:
594 self.client.fail(f"Can not update a Swarm Cluster: {exc}")
595
596 self.inspect_swarm()
597 self.results["actions"].append("Swarm cluster updated")
598 self.results["changed"] = True
599
600 def join(self) -> None:
601 if self.client.check_if_swarm_node():
602 self.results["actions"].append("This node is already part of a swarm.")
603 return
604 if not self.check_mode:
605 join_arguments = {
606 "remote_addrs": self.parameters.remote_addrs,
607 "join_token": self.parameters.join_token,
608 "listen_addr": self.parameters.listen_addr,
609 "advertise_addr": self.parameters.advertise_addr,
610 }
611 if self.parameters.data_path_addr is not None:
612 join_arguments["data_path_addr"] = self.parameters.data_path_addr
613 try:
614 self.client.join_swarm(**join_arguments)
615 except APIError as exc:
616 self.client.fail(f"Can not join the Swarm Cluster: {exc}")
617 self.results["actions"].append("New node is added to swarm cluster")
618 self.differences.add("joined", parameter=True, active=False)
619 self.results["changed"] = True
620
621 def leave(self) -> None:
622 if not self.client.check_if_swarm_node():
623 self.results["actions"].append("This node is not part of a swarm.")
624 return
625 if not self.check_mode:
626 try:
627 self.client.leave_swarm(force=self.force)
628 except APIError as exc:
629 self.client.fail(f"This node can not leave the Swarm Cluster: {exc}")
630 self.results["actions"].append("Node has left the swarm cluster")
631 self.differences.add("joined", parameter="absent", active="present")
632 self.results["changed"] = True
633
634 def remove(self) -> None:
635 if not self.client.check_if_swarm_manager():
636 self.client.fail("This node is not a manager.")
637
638 try:
639 status_down = self.client.check_if_swarm_node_is_down(
640 node_id=self.node_id, repeat_check=5
641 )
642 except APIError:
643 return
644
645 if not status_down:
646 self.client.fail(
647 "Can not remove the node. The status node is ready and not down."
648 )
649
650 if not self.check_mode:
651 try:
652 self.client.remove_node(node_id=self.node_id, force=self.force)
653 except APIError as exc:
654 self.client.fail(
655 f"Can not remove the node from the Swarm Cluster: {exc}"
656 )
657 self.results["actions"].append("Node is removed from swarm cluster.")
658 self.differences.add("joined", parameter=False, active=True)
659 self.results["changed"] = True
660
661
662 def _detect_remove_operation(client: AnsibleDockerSwarmClient) -> bool:
663 return client.module.params["state"] == "remove"
664
665
666 def main() -> None:
667 # TODO: missing option log_driver?
668 argument_spec = {
669 "advertise_addr": {"type": "str"},
670 "data_path_addr": {"type": "str"},
671 "data_path_port": {"type": "int"},
672 "state": {
673 "type": "str",
674 "default": "present",
675 "choices": ["present", "join", "absent", "remove"],
676 },
677 "force": {"type": "bool", "default": False},
678 "listen_addr": {"type": "str", "default": "0.0.0.0:2377"},
679 "remote_addrs": {"type": "list", "elements": "str"},
680 "join_token": {"type": "str", "no_log": True},
681 "snapshot_interval": {"type": "int"},
682 "task_history_retention_limit": {"type": "int"},
683 "keep_old_snapshots": {"type": "int"},
684 "log_entries_for_slow_followers": {"type": "int"},
685 "heartbeat_tick": {"type": "int"},
686 "election_tick": {"type": "int"},
687 "dispatcher_heartbeat_period": {"type": "int"},
688 "node_cert_expiry": {"type": "int"},
689 "name": {"type": "str"},
690 "labels": {"type": "dict"},
691 "signing_ca_cert": {"type": "str"},
692 "signing_ca_key": {"type": "str", "no_log": True},
693 "ca_force_rotate": {"type": "int"},
694 "autolock_managers": {"type": "bool"},
695 "node_id": {"type": "str"},
696 "rotate_worker_token": {"type": "bool", "default": False},
697 "rotate_manager_token": {"type": "bool", "default": False},
698 "default_addr_pool": {"type": "list", "elements": "str"},
699 "subnet_size": {"type": "int"},
700 }
701
702 required_if = [
703 ("state", "join", ["remote_addrs", "join_token"]),
704 ("state", "remove", ["node_id"]),
705 ]
706
707 option_minimal_versions = {
708 "labels": {"docker_py_version": "2.6.0", "docker_api_version": "1.32"},
709 "signing_ca_cert": {"docker_py_version": "2.6.0", "docker_api_version": "1.30"},
710 "signing_ca_key": {"docker_py_version": "2.6.0", "docker_api_version": "1.30"},
711 "ca_force_rotate": {"docker_py_version": "2.6.0", "docker_api_version": "1.30"},
712 "autolock_managers": {"docker_py_version": "2.6.0"},
713 "log_driver": {"docker_py_version": "2.6.0"},
714 "remove_operation": {
715 "docker_py_version": "2.4.0",
716 "detect_usage": _detect_remove_operation,
717 "usage_msg": "remove swarm nodes",
718 },
719 "default_addr_pool": {
720 "docker_py_version": "4.0.0",
721 "docker_api_version": "1.39",
722 },
723 "subnet_size": {"docker_py_version": "4.0.0", "docker_api_version": "1.39"},
724 "data_path_addr": {"docker_py_version": "4.0.0", "docker_api_version": "1.30"},
725 "data_path_port": {"docker_py_version": "6.0.0", "docker_api_version": "1.40"},
726 }
727
728 client = AnsibleDockerSwarmClient(
729 argument_spec=argument_spec,
730 supports_check_mode=True,
731 required_if=required_if,
732 min_docker_version="2.0.0",
733 option_minimal_versions=option_minimal_versions,
734 )
735 sanitize_labels(client.module.params["labels"], "labels", client)
736
737 try:
738 results = {"changed": False, "result": "", "actions": []}
739
740 SwarmManager(client, results)()
741 client.module.exit_json(**results)
742 except DockerException as e:
743 client.fail(
744 f"An unexpected Docker error occurred: {e}",
745 exception=traceback.format_exc(),
746 )
747 except RequestException as e:
748 client.fail(
749 f"An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}",
750 exception=traceback.format_exc(),
751 )
752
753
754 if __name__ == "__main__":
755 main()