Debian Codegraph @

ansible_collections/community/docker/plugins/modules/docker_network.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_network
11 short_description: Manage Docker networks
12 description:
13 - Create/remove Docker networks and connect containers to them.
14 - Performs largely the same function as the C(docker network) CLI subcommand.
15 extends_documentation_fragment:
16 - community.docker._docker.api_documentation
17 - community.docker._attributes
18 - community.docker._attributes.actiongroup_docker
19
20 attributes:
21 check_mode:
22 support: full
23 diff_mode:
24 support: full
25 idempotent:
26 support: partial
27 details:
28 - If O(force=true) the module is not idempotent.
29
30 options:
31 name:
32 description:
33 - Name of the network to operate on.
34 type: str
35 required: true
36 aliases:
37 - network_name
38
39 config_from:
40 description:
41 - Specifies the config only network to use the config from.
42 type: str
43 version_added: 3.10.0
44
45 config_only:
46 description:
47 - Sets that this is a config only network.
48 type: bool
49 version_added: 3.10.0
50
51 connected:
52 description:
53 - List of container names or container IDs to connect to a network.
54 - Please note that the module only makes sure that these containers are connected to the network, but does not care
55 about connection options. If you rely on specific IP addresses and so on, use the M(community.docker.docker_container)
56 module to ensure your containers are correctly connected to this network.
57 type: list
58 elements: str
59 default: []
60 aliases:
61 - containers
62
63 driver:
64 description:
65 - Specify the type of network. Docker provides bridge and overlay drivers, but 3rd party drivers can also be used.
66 type: str
67 default: bridge
68
69 driver_options:
70 description:
71 - Dictionary of network settings. Consult docker docs for valid options and values.
72 type: dict
73 default: {}
74
75 force:
76 description:
77 - With state V(present) will disconnect all containers for existing networks, delete the network and re-create the network.
78 - This option is required if you have changed the IPAM or driver options and want an existing network to be updated
79 to use the new options.
80 type: bool
81 default: false
82
83 appends:
84 description:
85 - By default the connected list is canonical, meaning containers not on the list are removed from the network.
86 - Use O(appends) to leave existing containers connected.
87 type: bool
88 default: false
89 aliases:
90 - incremental
91
92 enable_ipv4:
93 description:
94 - Enable IPv4 networking.
95 - This is enabled by default, but can be explicitly disabled.
96 - Requires Docker API 1.47 or newer.
97 type: bool
98 version_added: 4.5.0
99
100 enable_ipv6:
101 description:
102 - Enable IPv6 networking.
103 type: bool
104
105 ingress:
106 description:
107 - Enable Swarm routing-mesh.
108 type: bool
109 version_added: 4.2.0
110
111 ipam_driver:
112 description:
113 - Specify an IPAM driver.
114 type: str
115
116 ipam_driver_options:
117 description:
118 - Dictionary of IPAM driver options.
119 type: dict
120
121 ipam_config:
122 description:
123 - List of IPAM config blocks. Consult L(Docker docs,https://docs.docker.com/compose/compose-file/compose-file-v2/#ipam)
124 for valid options and values. Note that O(ipam_config[].iprange) is spelled differently here (we use the notation
125 from the Docker SDK for Python).
126 type: list
127 elements: dict
128 suboptions:
129 subnet:
130 description:
131 - IP subset in CIDR notation.
132 type: str
133 iprange:
134 description:
135 - IP address range in CIDR notation.
136 type: str
137 gateway:
138 description:
139 - IP gateway address.
140 type: str
141 aux_addresses:
142 description:
143 - Auxiliary IP addresses used by Network driver, as a mapping from hostname to IP.
144 type: dict
145
146 state:
147 description:
148 - V(absent) deletes the network. If a network has connected containers, these will be detached from the network.
149 - V(present) creates the network, if it does not already exist with the specified parameters, and connects the list
150 of containers provided by the O(connected) parameter. Containers not on the list will be disconnected. An empty list
151 will leave no containers connected to the network. Use the O(appends) option to leave existing containers connected.
152 Use the O(force) options to force re-creation of the network.
153 type: str
154 default: present
155 choices:
156 - absent
157 - present
158
159 internal:
160 description:
161 - Restrict external access to the network.
162 type: bool
163
164 labels:
165 description:
166 - Dictionary of labels.
167 type: dict
168 default: {}
169
170 scope:
171 description:
172 - Specify the network's scope.
173 type: str
174 choices:
175 - local
176 - global
177 - swarm
178
179 attachable:
180 description:
181 - If enabled, and the network is in the global scope, non-service containers on worker nodes will be able to connect
182 to the network.
183 type: bool
184
185 notes:
186 - When network options are changed, the module disconnects all containers from the network, deletes the network, and re-creates
187 the network. It does not try to reconnect containers, except the ones listed in (O(connected), and even for these, it
188 does not consider specific connection options like fixed IP addresses or MAC addresses. If you need more control over
189 how the containers are connected to the network, loop the M(community.docker.docker_container) module to loop over your
190 containers to make sure they are connected properly.
191 - The module does not support Docker Swarm. This means that it will not try to disconnect or reconnect services. If services
192 are connected to the network, deleting the network will fail. When network options are changed, the network has to be
193 deleted and recreated, so this will fail as well.
194 author:
195 - "Ben Keith (@keitwb)"
196 - "Chris Houseknecht (@chouseknecht)"
197 - "Dave Bendit (@DBendit)"
198
199 requirements:
200 - "Docker API >= 1.25"
201 """
202
203 EXAMPLES = r"""
204 ---
205 - name: Create a network
206 community.docker.docker_network:
207 name: network_one
208
209 - name: Remove all but selected list of containers
210 community.docker.docker_network:
211 name: network_one
212 connected:
213 - container_a
214 - container_b
215 - container_c
216
217 - name: Remove a single container
218 community.docker.docker_network:
219 name: network_one
220 connected: "{{ fulllist|difference(['container_a']) }}"
221
222 - name: Add a container to a network, leaving existing containers connected
223 community.docker.docker_network:
224 name: network_one
225 connected:
226 - container_a
227 appends: true
228
229 - name: Create a network with driver options
230 community.docker.docker_network:
231 name: network_two
232 driver_options:
233 com.docker.network.bridge.name: net2
234
235 - name: Create a network with custom IPAM config
236 community.docker.docker_network:
237 name: network_three
238 ipam_config:
239 - subnet: 172.23.27.0/24
240 gateway: 172.23.27.2
241 iprange: 172.23.27.0/26
242 aux_addresses:
243 host1: 172.23.27.3
244 host2: 172.23.27.4
245
246 - name: Create a network with labels
247 community.docker.docker_network:
248 name: network_four
249 labels:
250 key1: value1
251 key2: value2
252
253 - name: Create a network with IPv6 IPAM config
254 community.docker.docker_network:
255 name: network_ipv6_one
256 enable_ipv6: true
257 ipam_config:
258 - subnet: fdd1:ac8c:0557:7ce1::/64
259
260 - name: Create a network with IPv6 and custom IPv4 IPAM config
261 community.docker.docker_network:
262 name: network_ipv6_two
263 enable_ipv6: true
264 ipam_config:
265 - subnet: 172.24.27.0/24
266 - subnet: fdd1:ac8c:0557:7ce2::/64
267
268 - name: Delete a network, disconnecting all containers
269 community.docker.docker_network:
270 name: network_one
271 state: absent
272 """
273
274 RETURN = r"""
275 network:
276 description:
277 - Network inspection results for the affected network.
278 returned: success
279 type: dict
280 sample: {}
281 """
282
283 import re
284 import time
285 import traceback
286 import typing as t
287
288 from ansible.module_utils.common.text.converters import to_text
289
290 from ansible_collections.community.docker.plugins.module_utils._api.errors import (
291 DockerException,
292 )
293 from ansible_collections.community.docker.plugins.module_utils._common_api import (
294 AnsibleDockerClient,
295 RequestException,
296 )
297 from ansible_collections.community.docker.plugins.module_utils._util import (
298 DifferenceTracker,
299 DockerBaseClass,
300 clean_dict_booleans_for_docker_api,
301 normalize_ip_address,
302 normalize_ip_network,
303 sanitize_labels,
304 )
305
306
307 class TaskParameters(DockerBaseClass):
308 name: str
309
310 def __init__(self, client: AnsibleDockerClient) -> None:
311 super().__init__()
312 self.client = client
313
314 self.connected: list[str] = []
315 self.config_from: str | None = None
316 self.config_only: bool | None = None
317 self.driver: str = "bridge"
318 self.driver_options: dict[str, t.Any] = {}
319 self.ipam_driver: str | None = None
320 self.ipam_driver_options: dict[str, t.Any] | None = None
321 self.ipam_config: list[dict[str, t.Any]] | None = None
322 self.appends: bool = False
323 self.force: bool = False
324 self.internal: bool | None = None
325 self.labels: dict[str, t.Any] = {}
326 self.debug: bool = False
327 self.enable_ipv4: bool | None = None
328 self.enable_ipv6: bool | None = None
329 self.scope: t.Literal["local", "global", "swarm"] | None = None
330 self.attachable: bool | None = None
331 self.ingress: bool | None = None
332 self.state: t.Literal["present", "absent"] = "present"
333
334 for key, value in client.module.params.items():
335 setattr(self, key, value)
336
337 # config_only sets driver to 'null' (and scope to 'local') so force that here. Otherwise we get
338 # diffs of 'null' --> 'bridge' given that the driver option defaults to 'bridge'.
339 if self.config_only:
340 self.driver = "null" # type: ignore[unreachable]
341
342
343 def container_names_in_network(network: dict[str, t.Any]) -> list[str]:
344 return (
345 [c["Name"] for c in network["Containers"].values()]
346 if network["Containers"]
347 else []
348 )
349
350
351 CIDR_IPV4 = re.compile(r"^([0-9]{1,3}\.){3}[0-9]{1,3}/([0-9]|[1-2][0-9]|3[0-2])$")
352 CIDR_IPV6 = re.compile(r"^[0-9a-fA-F:]+/([0-9]|[1-9][0-9]|1[0-2][0-9])$")
353
354
355 def validate_cidr(cidr: str) -> t.Literal["ipv4", "ipv6"]:
356 """Validate CIDR. Return IP version of a CIDR string on success.
357
358 :param cidr: Valid CIDR
359 :type cidr: str
360 :return: ``ipv4`` or ``ipv6``
361 :rtype: str
362 :raises ValueError: If ``cidr`` is not a valid CIDR
363 """
364 # TODO: Use ipaddress for this instead of rolling your own...
365 if CIDR_IPV4.match(cidr):
366 return "ipv4"
367 if CIDR_IPV6.match(cidr):
368 return "ipv6"
369 raise ValueError(f'"{cidr}" is not a valid CIDR')
370
371
372 def normalize_ipam_config_key(key: str) -> str:
373 """Normalizes IPAM config keys returned by Docker API to match Ansible keys.
374
375 :param key: Docker API key
376 :type key: str
377 :return Ansible module key
378 :rtype str
379 """
380 special_cases = {"AuxiliaryAddresses": "aux_addresses"}
381 return special_cases.get(key, key.lower())
382
383
384 def dicts_are_essentially_equal(a: dict[str, t.Any], b: dict[str, t.Any]) -> bool:
385 """Make sure that a is a subset of b, where None entries of a are ignored."""
386 for k, v in a.items():
387 if v is None:
388 continue
389 if b.get(k) != v:
390 return False
391 return True
392
393
394 def normalize_ipam_values(ipam_config: dict[str, t.Any]) -> dict[str, t.Any]:
395 result = {}
396 for key, value in ipam_config.items():
397 if key in ("subnet", "iprange"):
398 value = normalize_ip_network(value)
399 elif key in ("gateway",):
400 value = normalize_ip_address(value)
401 elif key in ("aux_addresses",) and value is not None:
402 value = {k: normalize_ip_address(v) for k, v in value.items()}
403 result[key] = value
404 return result
405
406
407 class DockerNetworkManager:
408 def __init__(self, client: AnsibleDockerClient) -> None:
409 self.client = client
410 self.parameters = TaskParameters(client)
411 self.check_mode = self.client.check_mode
412 self.actions: list[str] = []
413 self.results: dict[str, t.Any] = {"changed": False, "actions": self.actions}
414 self.diff = self.client.module._diff
415 self.diff_tracker = DifferenceTracker()
416 self.diff_result: dict[str, t.Any] = {}
417
418 self.existing_network = self.get_existing_network()
419
420 if not self.parameters.connected and self.existing_network:
421 self.parameters.connected = container_names_in_network(
422 self.existing_network
423 )
424
425 if self.parameters.ipam_config:
426 try:
427 for ipam_config in self.parameters.ipam_config:
428 validate_cidr(ipam_config["subnet"])
429 except ValueError as e:
430 self.client.fail(to_text(e))
431
432 if self.parameters.driver_options:
433 self.parameters.driver_options = clean_dict_booleans_for_docker_api(
434 self.parameters.driver_options
435 )
436
437 state = self.parameters.state
438 if state == "present":
439 self.present()
440 elif state == "absent":
441 self.absent()
442
443 if self.diff or self.check_mode or self.parameters.debug:
444 if self.diff:
445 self.diff_result["before"], self.diff_result["after"] = (
446 self.diff_tracker.get_before_after()
447 )
448 self.results["diff"] = self.diff_result
449
450 def get_existing_network(self) -> dict[str, t.Any] | None:
451 return self.client.get_network(name=self.parameters.name)
452
453 def has_different_config(
454 self, net: dict[str, t.Any]
455 ) -> tuple[bool, DifferenceTracker]:
456 """
457 Evaluates an existing network and returns a tuple containing a boolean
458 indicating if the configuration is different and a list of differences.
459
460 :param net: the inspection output for an existing network
461 :return: (bool, list)
462 """
463 differences = DifferenceTracker()
464 if (
465 self.parameters.config_only is not None
466 and self.parameters.config_only != net.get("ConfigOnly", False)
467 ):
468 differences.add(
469 "config_only",
470 parameter=self.parameters.config_only,
471 active=net.get("ConfigOnly", False),
472 )
473 if (
474 self.parameters.config_from is not None
475 and self.parameters.config_from
476 != net.get("ConfigFrom", {}).get("Network", "")
477 ):
478 differences.add(
479 "config_from",
480 parameter=self.parameters.config_from,
481 active=net.get("ConfigFrom", {}).get("Network", ""),
482 )
483 if self.parameters.driver and self.parameters.driver != net["Driver"]:
484 differences.add(
485 "driver", parameter=self.parameters.driver, active=net["Driver"]
486 )
487 if self.parameters.driver_options:
488 if not net.get("Options"):
489 differences.add(
490 "driver_options",
491 parameter=self.parameters.driver_options,
492 active=net.get("Options"),
493 )
494 else:
495 for key, value in self.parameters.driver_options.items():
496 if key not in net["Options"] or value != net["Options"][key]:
497 differences.add(
498 f"driver_options.{key}",
499 parameter=value,
500 active=net["Options"].get(key),
501 )
502
503 if self.parameters.ipam_driver and (
504 not net.get("IPAM") or net["IPAM"]["Driver"] != self.parameters.ipam_driver
505 ):
506 differences.add(
507 "ipam_driver",
508 parameter=self.parameters.ipam_driver,
509 active=net.get("IPAM"),
510 )
511
512 if self.parameters.ipam_driver_options is not None:
513 ipam_driver_options = net["IPAM"].get("Options") or {}
514 if ipam_driver_options != self.parameters.ipam_driver_options:
515 differences.add(
516 "ipam_driver_options",
517 parameter=self.parameters.ipam_driver_options,
518 active=ipam_driver_options,
519 )
520
521 if self.parameters.ipam_config is not None and self.parameters.ipam_config:
522 if not net.get("IPAM") or not net["IPAM"]["Config"]:
523 differences.add(
524 "ipam_config",
525 parameter=self.parameters.ipam_config,
526 active=net.get("IPAM", {}).get("Config"),
527 )
528 else:
529 # Put network's IPAM config into the same format as module's IPAM config
530 net_ipam_configs = []
531 net_ipam_configs_normalized = []
532 for net_ipam_config in net["IPAM"]["Config"]:
533 config = {}
534 for k, v in net_ipam_config.items():
535 config[normalize_ipam_config_key(k)] = v
536 net_ipam_configs.append(config)
537 net_ipam_configs_normalized.append(normalize_ipam_values(config))
538 # Compare lists of dicts as sets of dicts
539 for idx, ipam_config in enumerate(self.parameters.ipam_config):
540 ipam_config_normalized = normalize_ipam_values(ipam_config)
541 net_config = {}
542 net_config_normalized = {}
543 for net_ipam_config, net_ipam_config_normalized in zip(
544 net_ipam_configs, net_ipam_configs_normalized
545 ):
546 if dicts_are_essentially_equal(
547 ipam_config_normalized, net_ipam_config_normalized
548 ):
549 net_config = net_ipam_config
550 net_config_normalized = net_ipam_config_normalized
551 break
552 for key, value in ipam_config.items():
553 if value is None:
554 # due to recursive argument_spec, all keys are always present
555 # (but have default value None if not specified)
556 continue
557 if ipam_config_normalized[key] != net_config_normalized.get(
558 key
559 ):
560 differences.add(
561 f"ipam_config[{idx}].{key}",
562 parameter=value,
563 active=net_config.get(key),
564 )
565
566 if (
567 self.parameters.enable_ipv4 is not None
568 and self.parameters.enable_ipv4 != net.get("EnableIPv4", False)
569 ):
570 differences.add(
571 "enable_ipv4",
572 parameter=self.parameters.enable_ipv4,
573 active=net.get("EnableIPv4", False),
574 )
575 if (
576 self.parameters.enable_ipv6 is not None
577 and self.parameters.enable_ipv6 != net.get("EnableIPv6", False)
578 ):
579 differences.add(
580 "enable_ipv6",
581 parameter=self.parameters.enable_ipv6,
582 active=net.get("EnableIPv6", False),
583 )
584
585 if (
586 self.parameters.internal is not None
587 and self.parameters.internal != net.get("Internal", False)
588 ):
589 differences.add(
590 "internal",
591 parameter=self.parameters.internal,
592 active=net.get("Internal"),
593 )
594
595 if self.parameters.scope is not None and self.parameters.scope != net.get(
596 "Scope"
597 ):
598 differences.add(
599 "scope", parameter=self.parameters.scope, active=net.get("Scope")
600 )
601
602 if (
603 self.parameters.attachable is not None
604 and self.parameters.attachable != net.get("Attachable", False)
605 ):
606 differences.add(
607 "attachable",
608 parameter=self.parameters.attachable,
609 active=net.get("Attachable"),
610 )
611 if self.parameters.ingress is not None and self.parameters.ingress != net.get(
612 "Ingress", False
613 ):
614 differences.add(
615 "ingress", parameter=self.parameters.ingress, active=net.get("Ingress")
616 )
617 if self.parameters.labels:
618 if not net.get("Labels"):
619 differences.add(
620 "labels", parameter=self.parameters.labels, active=net.get("Labels")
621 )
622 else:
623 for key, value in self.parameters.labels.items():
624 if key not in net["Labels"] or value != net["Labels"][key]:
625 differences.add(
626 f"labels.{key}",
627 parameter=value,
628 active=net["Labels"].get(key),
629 )
630
631 return not differences.empty, differences
632
633 def create_network(self) -> None:
634 if not self.existing_network:
635 data: dict[str, t.Any] = {
636 "Name": self.parameters.name,
637 "Driver": self.parameters.driver,
638 "Options": self.parameters.driver_options,
639 "IPAM": None,
640 "CheckDuplicate": None,
641 }
642
643 if self.parameters.config_only is not None:
644 data["ConfigOnly"] = self.parameters.config_only
645 if self.parameters.config_from:
646 data["ConfigFrom"] = {"Network": self.parameters.config_from}
647 if self.parameters.enable_ipv6 is not None:
648 data["EnableIPv6"] = self.parameters.enable_ipv6
649 if self.parameters.enable_ipv4 is not None:
650 data["EnableIPv4"] = self.parameters.enable_ipv4
651 if self.parameters.internal:
652 data["Internal"] = True
653 if self.parameters.scope is not None:
654 data["Scope"] = self.parameters.scope
655 if self.parameters.attachable is not None:
656 data["Attachable"] = self.parameters.attachable
657 if self.parameters.ingress is not None:
658 data["Ingress"] = self.parameters.ingress
659 if self.parameters.labels is not None:
660 data["Labels"] = self.parameters.labels
661
662 ipam_pools = []
663 if self.parameters.ipam_config:
664 for ipam_pool in self.parameters.ipam_config:
665 ipam_pools.append(
666 {
667 "Subnet": ipam_pool["subnet"],
668 "IPRange": ipam_pool["iprange"],
669 "Gateway": ipam_pool["gateway"],
670 "AuxiliaryAddresses": ipam_pool["aux_addresses"],
671 }
672 )
673
674 if (
675 self.parameters.ipam_driver
676 or self.parameters.ipam_driver_options
677 or ipam_pools
678 ):
679 # Only add IPAM if a driver was specified or if IPAM parameters were
680 # specified. Leaving this parameter out can significantly speed up
681 # creation; on my machine creation with this option needs ~15 seconds,
682 # and without just a few seconds.
683 data["IPAM"] = {
684 "Driver": self.parameters.ipam_driver,
685 "Config": ipam_pools or [],
686 "Options": self.parameters.ipam_driver_options,
687 }
688
689 if not self.check_mode:
690 resp = self.client.post_json_to_json("/networks/create", data=data)
691 self.client.report_warnings(resp, ["Warning"])
692 self.existing_network = self.client.get_network(network_id=resp["Id"])
693 self.actions.append(
694 f"Created network {self.parameters.name} with driver {self.parameters.driver}"
695 )
696 self.results["changed"] = True
697
698 def remove_network(self) -> None:
699 if self.existing_network:
700 self.disconnect_all_containers()
701 if not self.check_mode:
702 self.client.delete_call("/networks/{0}", self.parameters.name)
703 if self.existing_network.get("Scope", "local") == "swarm":
704 while self.get_existing_network():
705 time.sleep(0.1)
706 self.actions.append(f"Removed network {self.parameters.name}")
707 self.results["changed"] = True
708
709 def is_container_connected(self, container_name: str) -> bool:
710 if not self.existing_network:
711 return False
712 return container_name in container_names_in_network(self.existing_network)
713
714 def is_container_exist(self, container_name: str) -> bool:
715 try:
716 container = self.client.get_container(container_name)
717 return bool(container)
718
719 except DockerException as e:
720 self.client.fail(
721 f"An unexpected Docker error occurred: {e}",
722 exception=traceback.format_exc(),
723 )
724 except RequestException as e:
725 self.client.fail(
726 f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
727 exception=traceback.format_exc(),
728 )
729
730 def connect_containers(self) -> None:
731 for name in self.parameters.connected:
732 if not self.is_container_connected(name) and self.is_container_exist(name):
733 if not self.check_mode:
734 data = {
735 "Container": name,
736 "EndpointConfig": None,
737 }
738 self.client.post_json(
739 "/networks/{0}/connect", self.parameters.name, data=data
740 )
741 self.actions.append(f"Connected container {name}")
742 self.results["changed"] = True
743 self.diff_tracker.add(f"connected.{name}", parameter=True, active=False)
744
745 def disconnect_missing(self) -> None:
746 if not self.existing_network:
747 return
748 containers = self.existing_network["Containers"]
749 if not containers:
750 return
751 for c in containers.values():
752 name = c["Name"]
753 if name not in self.parameters.connected:
754 self.disconnect_container(name)
755
756 def disconnect_all_containers(self) -> None:
757 network = self.client.get_network(name=self.parameters.name)
758 if not network:
759 return
760 containers = network["Containers"]
761 if not containers:
762 return
763 for cont in containers.values():
764 self.disconnect_container(cont["Name"])
765
766 def disconnect_container(self, container_name: str) -> None:
767 if not self.check_mode:
768 data = {"Container": container_name, "Force": True}
769 self.client.post_json(
770 "/networks/{0}/disconnect", self.parameters.name, data=data
771 )
772 self.actions.append(f"Disconnected container {container_name}")
773 self.results["changed"] = True
774 self.diff_tracker.add(
775 f"connected.{container_name}", parameter=False, active=True
776 )
777
778 def present(self) -> None:
779 different = False
780 differences = DifferenceTracker()
781 if self.existing_network:
782 different, differences = self.has_different_config(self.existing_network)
783
784 self.diff_tracker.add(
785 "exists", parameter=True, active=self.existing_network is not None
786 )
787 if self.parameters.force or different:
788 self.remove_network()
789 self.existing_network = None
790
791 self.create_network()
792 self.connect_containers()
793 if not self.parameters.appends:
794 self.disconnect_missing()
795
796 if self.diff or self.check_mode or self.parameters.debug:
797 self.diff_result["differences"] = differences.get_legacy_docker_diffs()
798 self.diff_tracker.merge(differences)
799
800 if not self.check_mode and not self.parameters.debug:
801 self.results.pop("actions")
802
803 network_facts = self.get_existing_network()
804 self.results["network"] = network_facts
805
806 def absent(self) -> None:
807 self.diff_tracker.add(
808 "exists", parameter=False, active=self.existing_network is not None
809 )
810 self.remove_network()
811
812
813 def main() -> None:
814 argument_spec = {
815 "name": {"type": "str", "required": True, "aliases": ["network_name"]},
816 "config_from": {"type": "str"},
817 "config_only": {"type": "bool"},
818 "connected": {
819 "type": "list",
820 "default": [],
821 "elements": "str",
822 "aliases": ["containers"],
823 },
824 "state": {
825 "type": "str",
826 "default": "present",
827 "choices": ["present", "absent"],
828 },
829 "driver": {"type": "str", "default": "bridge"},
830 "driver_options": {"type": "dict", "default": {}},
831 "force": {"type": "bool", "default": False},
832 "appends": {"type": "bool", "default": False, "aliases": ["incremental"]},
833 "ipam_driver": {"type": "str"},
834 "ipam_driver_options": {"type": "dict"},
835 "ipam_config": {
836 "type": "list",
837 "elements": "dict",
838 "options": {
839 "subnet": {"type": "str"},
840 "iprange": {"type": "str"},
841 "gateway": {"type": "str"},
842 "aux_addresses": {"type": "dict"},
843 },
844 },
845 "enable_ipv4": {"type": "bool"},
846 "enable_ipv6": {"type": "bool"},
847 "internal": {"type": "bool"},
848 "labels": {"type": "dict", "default": {}},
849 "debug": {"type": "bool", "default": False},
850 "scope": {"type": "str", "choices": ["local", "global", "swarm"]},
851 "attachable": {"type": "bool"},
852 "ingress": {"type": "bool"},
853 }
854
855 option_minimal_versions = {
856 "config_from": {"docker_api_version": "1.30"},
857 "config_only": {"docker_api_version": "1.30"},
858 "scope": {"docker_api_version": "1.30"},
859 "attachable": {"docker_api_version": "1.26"},
860 "enable_ipv4": {"docker_api_version": "1.47"},
861 }
862
863 client = AnsibleDockerClient(
864 argument_spec=argument_spec,
865 supports_check_mode=True,
866 # "The docker server >= 1.10.0"
867 option_minimal_versions=option_minimal_versions,
868 )
869 sanitize_labels(client.module.params["labels"], "labels", client)
870 try:
871 cm = DockerNetworkManager(client)
872 client.module.exit_json(**cm.results)
873 except DockerException as e:
874 client.fail(
875 f"An unexpected Docker error occurred: {e}",
876 exception=traceback.format_exc(),
877 )
878 except RequestException as e:
879 client.fail(
880 f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
881 exception=traceback.format_exc(),
882 )
883
884
885 if __name__ == "__main__":
886 main()