Debian Codegraph @

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

raw
1 # Copyright (c) 2018, Stefan Heitmueller <[email protected]>
2 # Copyright (c) 2018 Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 name: docker_swarm
10 author:
11 - Stefan Heitmüller (@morph027) <[email protected]>
12 short_description: Ansible dynamic inventory plugin for Docker swarm nodes
13 requirements:
14 - L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 1.10.0
15 extends_documentation_fragment:
16 - ansible.builtin.constructed
17 - community.library_inventory_filtering_v1.inventory_filter
18 description:
19 - Reads inventories from the Docker swarm API.
20 - Uses a YAML configuration file that ends with V(docker_swarm.(yml|yaml\)).
21 - 'The plugin returns following groups of swarm nodes: C(all) - all hosts; C(workers) - all worker nodes; C(managers) -
22 all manager nodes; C(leader) - the swarm leader node; C(nonleaders) - all nodes except the swarm leader.'
23 notes:
24 - The configuration file must be a YAML file whose filename ends with V(docker_swarm.yml) or V(docker_swarm.yaml). Other
25 filenames will not be accepted.
26 options:
27 plugin:
28 description: The name of this plugin, it should always be set to V(community.docker.docker_swarm) for this plugin to recognize
29 it as its own.
30 type: str
31 required: true
32 choices: [docker_swarm, community.docker.docker_swarm]
33 docker_host:
34 description:
35 - Socket of a Docker swarm manager node (C(tcp), C(unix)).
36 - Use V(unix:///var/run/docker.sock) to connect through a local socket.
37 type: str
38 required: true
39 aliases: [docker_url]
40 verbose_output:
41 description: Toggle to (not) include all available nodes metadata (for example C(Platform), C(Architecture), C(OS), C(EngineVersion)).
42 type: bool
43 default: true
44 tls:
45 description: Connect using TLS without verifying the authenticity of the Docker host server.
46 type: bool
47 default: false
48 validate_certs:
49 description: Toggle if connecting using TLS with or without verifying the authenticity of the Docker host server.
50 type: bool
51 default: false
52 aliases: [tls_verify]
53 client_key:
54 description: Path to the client's TLS key file.
55 type: path
56 aliases: [tls_client_key, key_path]
57 ca_path:
58 description:
59 - Use a CA certificate when performing server verification by providing the path to a CA certificate file.
60 - This option was called O(ca_cert) and got renamed to O(ca_path) in community.docker 3.6.0. The old name has been added
61 as an alias and can still be used.
62 type: path
63 aliases: [ca_cert, tls_ca_cert, cacert_path]
64 client_cert:
65 description: Path to the client's TLS certificate file.
66 type: path
67 aliases: [tls_client_cert, cert_path]
68 tls_hostname:
69 description: When verifying the authenticity of the Docker host server, provide the expected name of the server.
70 type: str
71 api_version:
72 description:
73 - The version of the Docker API running on the Docker Host.
74 - Defaults to the latest version of the API supported by Docker SDK for Python.
75 type: str
76 aliases: [docker_api_version]
77 timeout:
78 description:
79 - The maximum amount of time in seconds to wait on a response from the API.
80 - If the value is not specified in the task, the value of environment variable E(DOCKER_TIMEOUT). will be used instead.
81 If the environment variable is not set, the default value will be used.
82 type: int
83 default: 60
84 aliases: [time_out]
85 use_ssh_client:
86 description:
87 - For SSH transports, use the C(ssh) CLI tool instead of paramiko.
88 - Requires Docker SDK for Python 4.4.0 or newer.
89 type: bool
90 default: false
91 version_added: 1.5.0
92 include_host_uri:
93 description: Toggle to return the additional attribute C(ansible_host_uri) which contains the URI of the swarm leader
94 in format of V(tcp://172.16.0.1:2376). This value may be used without additional modification as value of option O(docker_host)
95 in Docker Swarm modules when connecting through the API. The port always defaults to V(2376).
96 type: bool
97 default: false
98 include_host_uri_port:
99 description: Override the detected port number included in C(ansible_host_uri).
100 type: int
101 filters:
102 version_added: 3.5.0
103 """
104
105 EXAMPLES = """
106 ---
107 # Minimal example using local docker
108 plugin: community.docker.docker_swarm
109 docker_host: unix:///var/run/docker.sock
110
111 ---
112 # Minimal example using remote docker
113 plugin: community.docker.docker_swarm
114 docker_host: tcp://my-docker-host:2375
115
116 ---
117 # Example using remote docker with unverified TLS
118 plugin: community.docker.docker_swarm
119 docker_host: tcp://my-docker-host:2376
120 tls: true
121
122 ---
123 # Example using remote docker with verified TLS and client certificate verification
124 plugin: community.docker.docker_swarm
125 docker_host: tcp://my-docker-host:2376
126 validate_certs: true
127 ca_path: /somewhere/ca.pem
128 client_key: /somewhere/key.pem
129 client_cert: /somewhere/cert.pem
130
131 ---
132 # Example using constructed features to create groups and set ansible_host
133 plugin: community.docker.docker_swarm
134 docker_host: tcp://my-docker-host:2375
135 strict: false
136 keyed_groups:
137 # add for example x86_64 hosts to an arch_x86_64 group
138 - prefix: arch
139 key: 'Description.Platform.Architecture'
140 # add for example linux hosts to an os_linux group
141 - prefix: os
142 key: 'Description.Platform.OS'
143 # create a group per node label
144 # for exomple a node labeled w/ "production" ends up in group "label_production"
145 # hint: labels containing special characters will be converted to safe names
146 - key: 'Spec.Labels'
147 prefix: label
148 """
149
150 import typing as t
151
152 from ansible.errors import AnsibleError
153 from ansible.parsing.utils.addresses import parse_address
154 from ansible.plugins.inventory import BaseInventoryPlugin, Constructable
155 from ansible_collections.community.library_inventory_filtering_v1.plugins.plugin_utils.inventory_filter import (
156 filter_host,
157 parse_filters,
158 )
159
160 from ansible_collections.community.docker.plugins.module_utils._common import (
161 get_connect_params,
162 )
163 from ansible_collections.community.docker.plugins.module_utils._util import (
164 update_tls_hostname,
165 )
166 from ansible_collections.community.docker.plugins.plugin_utils._unsafe import (
167 make_unsafe,
168 )
169
170 if t.TYPE_CHECKING:
171 from ansible.inventory.data import InventoryData
172 from ansible.parsing.dataloader import DataLoader
173
174
175 try:
176 import docker
177
178 HAS_DOCKER = True
179 except ImportError:
180 HAS_DOCKER = False
181
182
183 class InventoryModule(BaseInventoryPlugin, Constructable):
184 """Host inventory parser for ansible using Docker swarm as source."""
185
186 NAME = "community.docker.docker_swarm"
187
188 def _fail(self, msg: str) -> t.NoReturn:
189 raise AnsibleError(msg)
190
191 def _populate(self) -> None:
192 if self.inventory is None:
193 raise AssertionError("Inventory must be there")
194
195 raw_params = {
196 "docker_host": self.get_option("docker_host"),
197 "tls": self.get_option("tls"),
198 "tls_verify": self.get_option("validate_certs"),
199 "key_path": self.get_option("client_key"),
200 "cacert_path": self.get_option("ca_path"),
201 "cert_path": self.get_option("client_cert"),
202 "tls_hostname": self.get_option("tls_hostname"),
203 "api_version": self.get_option("api_version"),
204 "timeout": self.get_option("timeout"),
205 "use_ssh_client": self.get_option("use_ssh_client"),
206 "debug": None,
207 }
208 update_tls_hostname(raw_params)
209 connect_params = get_connect_params(raw_params, fail_function=self._fail)
210 client = docker.DockerClient(**connect_params)
211 self.inventory.add_group("all")
212 self.inventory.add_group("manager")
213 self.inventory.add_group("worker")
214 self.inventory.add_group("leader")
215 self.inventory.add_group("nonleaders")
216
217 filters = parse_filters(self.get_option("filters"))
218
219 if self.get_option("include_host_uri"):
220 if self.get_option("include_host_uri_port"):
221 host_uri_port = str(self.get_option("include_host_uri_port"))
222 elif self.get_option("tls") or self.get_option("validate_certs"):
223 host_uri_port = "2376"
224 else:
225 host_uri_port = "2375"
226
227 try:
228 nodes = client.nodes.list()
229 for node in nodes:
230 node_attrs = client.nodes.get(node.id).attrs
231 unsafe_node_attrs = make_unsafe(node_attrs)
232 if not filter_host(
233 self, unsafe_node_attrs["ID"], unsafe_node_attrs, filters
234 ):
235 continue
236 self.inventory.add_host(unsafe_node_attrs["ID"])
237 self.inventory.add_host(
238 unsafe_node_attrs["ID"], group=unsafe_node_attrs["Spec"]["Role"]
239 )
240 self.inventory.set_variable(
241 unsafe_node_attrs["ID"],
242 "ansible_host",
243 unsafe_node_attrs["Status"]["Addr"],
244 )
245 if self.get_option("include_host_uri"):
246 self.inventory.set_variable(
247 unsafe_node_attrs["ID"],
248 "ansible_host_uri",
249 make_unsafe(
250 "tcp://"
251 + unsafe_node_attrs["Status"]["Addr"]
252 + ":"
253 + host_uri_port
254 ),
255 )
256 if self.get_option("verbose_output"):
257 self.inventory.set_variable(
258 unsafe_node_attrs["ID"],
259 "docker_swarm_node_attributes",
260 unsafe_node_attrs,
261 )
262 if "ManagerStatus" in unsafe_node_attrs:
263 if unsafe_node_attrs["ManagerStatus"].get("Leader"):
264 # This is workaround of bug in Docker when in some cases the Leader IP is 0.0.0.0
265 # Check moby/moby#35437 for details
266 swarm_leader_ip = (
267 parse_address(node_attrs["ManagerStatus"]["Addr"])[0]
268 or unsafe_node_attrs["Status"]["Addr"]
269 )
270 if self.get_option("include_host_uri"):
271 self.inventory.set_variable(
272 unsafe_node_attrs["ID"],
273 "ansible_host_uri",
274 make_unsafe(
275 "tcp://" + swarm_leader_ip + ":" + host_uri_port
276 ),
277 )
278 self.inventory.set_variable(
279 unsafe_node_attrs["ID"],
280 "ansible_host",
281 make_unsafe(swarm_leader_ip),
282 )
283 self.inventory.add_host(unsafe_node_attrs["ID"], group="leader")
284 else:
285 self.inventory.add_host(
286 unsafe_node_attrs["ID"], group="nonleaders"
287 )
288 else:
289 self.inventory.add_host(unsafe_node_attrs["ID"], group="nonleaders")
290 # Use constructed if applicable
291 strict = self.get_option("strict")
292 # Composed variables
293 self._set_composite_vars(
294 self.get_option("compose"),
295 unsafe_node_attrs,
296 unsafe_node_attrs["ID"],
297 strict=strict,
298 )
299 # Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group
300 self._add_host_to_composed_groups(
301 self.get_option("groups"),
302 unsafe_node_attrs,
303 unsafe_node_attrs["ID"],
304 strict=strict,
305 )
306 # Create groups based on variable values and add the corresponding hosts to it
307 self._add_host_to_keyed_groups(
308 self.get_option("keyed_groups"),
309 unsafe_node_attrs,
310 unsafe_node_attrs["ID"],
311 strict=strict,
312 )
313 except Exception as e:
314 raise AnsibleError(
315 f"Unable to fetch hosts from Docker swarm API, this was the original exception: {e}"
316 ) from e
317
318 def verify_file(self, path: str) -> bool:
319 """Return the possibly of a file being consumable by this plugin."""
320 return super().verify_file(path) and path.endswith(
321 ("docker_swarm.yaml", "docker_swarm.yml")
322 )
323
324 def parse(
325 self,
326 inventory: InventoryData,
327 loader: DataLoader,
328 path: str,
329 cache: bool = True,
330 ) -> None:
331 if not HAS_DOCKER:
332 raise AnsibleError(
333 "The Docker swarm dynamic inventory plugin requires the Docker SDK for Python: "
334 "https://github.com/docker/docker-py."
335 )
336 super().parse(inventory, loader, path, cache)
337 self._read_config_data(path)
338 self._populate()