Debian Codegraph @

ansible_collections/community/general/plugins/inventory/lxd.py

raw
1 # Copyright (c) 2021, Frank Dornheim <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 name: lxd
9 short_description: Returns Ansible inventory from lxd host
10 description:
11 - Get inventory from the lxd.
12 - Uses a YAML configuration file that ends with 'lxd.(yml|yaml)'.
13 version_added: "3.0.0"
14 author: "Frank Dornheim (@conloos)"
15 requirements:
16 - ipaddress
17 - lxd >= 4.0
18 options:
19 plugin:
20 description: Token that ensures this is a source file for the 'lxd' plugin.
21 type: string
22 required: true
23 choices: ['community.general.lxd']
24 url:
25 description:
26 - The unix domain socket path or the https URL for the lxd server.
27 - Sockets in filesystem have to start with C(unix:).
28 - Mostly C(unix:/var/lib/lxd/unix.socket) or C(unix:/var/snap/lxd/common/lxd/unix.socket).
29 type: string
30 default: unix:/var/snap/lxd/common/lxd/unix.socket
31 client_key:
32 description:
33 - The client certificate key file path.
34 aliases: [key_file]
35 default: $HOME/.config/lxc/client.key
36 type: path
37 client_cert:
38 description:
39 - The client certificate file path.
40 aliases: [cert_file]
41 default: $HOME/.config/lxc/client.crt
42 type: path
43 server_cert:
44 description:
45 - The server certificate file path.
46 type: path
47 version_added: 8.0.0
48 server_check_hostname:
49 description:
50 - This option controls if the server's hostname is checked as part of the HTTPS connection verification. This can be
51 useful to disable, if for example, the server certificate provided (see O(server_cert) option) does not cover a name
52 matching the one used to communicate with the server. Such mismatch is common as LXD generates self-signed server
53 certificates by default.
54 type: bool
55 default: true
56 version_added: 8.0.0
57 trust_password:
58 description:
59 - The client trusted password.
60 - You need to set this password on the lxd server before running this module using the following command C(lxc config
61 set core.trust_password <some random password>) See
62 U(https://documentation.ubuntu.com/lxd/en/latest/authentication/#adding-client-certificates-using-a-trust-password).
63 - If O(trust_password) is set, this module send a request for authentication before sending any requests.
64 type: str
65 state:
66 description: Filter the instance according to the current status.
67 type: str
68 default: none
69 choices: ['STOPPED', 'STARTING', 'RUNNING', 'none']
70 project:
71 description: Filter the instance according to the given project.
72 type: str
73 default: default
74 version_added: 6.2.0
75 type_filter:
76 description:
77 - Filter the instances by type V(virtual-machine), V(container) or V(both).
78 - The first version of the inventory only supported containers.
79 type: str
80 default: container
81 choices: ['virtual-machine', 'container', 'both']
82 version_added: 4.2.0
83 prefered_instance_network_interface:
84 description:
85 - If an instance has multiple network interfaces, select which one is the preferred as pattern.
86 - Combined with the first number that can be found, for example C(eth) + C(0).
87 - The option has been renamed from O(prefered_container_network_interface) to O(prefered_instance_network_interface)
88 in community.general 3.8.0. The old name still works as an alias.
89 type: str
90 default: eth
91 aliases:
92 - prefered_container_network_interface
93 prefered_instance_network_family:
94 description:
95 - If an instance has multiple network interfaces, which one is the preferred by family.
96 - Specify V(inet) for IPv4 and V(inet6) for IPv6.
97 type: str
98 default: inet
99 choices: ['inet', 'inet6']
100 groupby:
101 description:
102 - Create groups by the following keywords C(location), C(network_range), C(os), C(pattern), C(profile), C(release),
103 C(type), C(vlanid).
104 - See example for syntax.
105 type: dict
106 """
107
108 EXAMPLES = r"""
109 ---
110 # simple lxd.yml
111 plugin: community.general.lxd
112 url: unix:/var/snap/lxd/common/lxd/unix.socket
113
114 ---
115 # simple lxd.yml including filter
116 plugin: community.general.lxd
117 url: unix:/var/snap/lxd/common/lxd/unix.socket
118 state: RUNNING
119
120 ---
121 # simple lxd.yml including virtual machines and containers
122 plugin: community.general.lxd
123 url: unix:/var/snap/lxd/common/lxd/unix.socket
124 type_filter: both
125
126 # grouping lxd.yml
127 groupby:
128 locationBerlin:
129 type: location
130 attribute: Berlin
131 netRangeIPv4:
132 type: network_range
133 attribute: 10.98.143.0/24
134 netRangeIPv6:
135 type: network_range
136 attribute: fd42:bd00:7b11:2167:216:3eff::/24
137 osUbuntu:
138 type: os
139 attribute: ubuntu
140 testpattern:
141 type: pattern
142 attribute: test
143 profileDefault:
144 type: profile
145 attribute: default
146 profileX11:
147 type: profile
148 attribute: x11
149 releaseFocal:
150 type: release
151 attribute: focal
152 releaseBionic:
153 type: release
154 attribute: bionic
155 typeVM:
156 type: type
157 attribute: virtual-machine
158 typeContainer:
159 type: type
160 attribute: container
161 vlan666:
162 type: vlanid
163 attribute: 666
164 projectInternals:
165 type: project
166 attribute: internals
167 """
168
169 import json
170 import os
171 import re
172 import time
173 from urllib.parse import urlencode
174
175 from ansible.errors import AnsibleError, AnsibleParserError
176 from ansible.module_utils.common.dict_transformations import dict_merge
177 from ansible.module_utils.common.text.converters import to_native, to_text
178 from ansible.plugins.inventory import BaseInventoryPlugin
179
180 from ansible_collections.community.general.plugins.module_utils._lxd import LXDClient, LXDClientException
181 from ansible_collections.community.general.plugins.plugin_utils._unsafe import make_unsafe
182
183 IPADDRESS_IMPORT_ERROR: ImportError | None
184 try:
185 import ipaddress
186 except ImportError as exc:
187 IPADDRESS_IMPORT_ERROR = exc
188 else:
189 IPADDRESS_IMPORT_ERROR = None
190
191
192 class InventoryModule(BaseInventoryPlugin):
193 DEBUG = 4
194 NAME = "community.general.lxd"
195 SNAP_SOCKET_URL = "unix:/var/snap/lxd/common/lxd/unix.socket"
196 SOCKET_URL = "unix:/var/lib/lxd/unix.socket"
197
198 @staticmethod
199 def load_json_data(path):
200 """Load json data
201
202 Load json data from file
203
204 Args:
205 list(path): Path elements
206 str(file_name): Filename of data
207 Kwargs:
208 None
209 Raises:
210 None
211 Returns:
212 dict(json_data): json data"""
213 try:
214 with open(path) as json_file:
215 return json.load(json_file)
216 except (OSError, json.decoder.JSONDecodeError) as err:
217 raise AnsibleParserError(f"Could not load the test data from {to_native(path)}: {err}") from err
218
219 def save_json_data(self, path, file_name=None):
220 """save data as json
221
222 Save data as json file
223
224 Args:
225 list(path): Path elements
226 str(file_name): Filename of data
227 Kwargs:
228 None
229 Raises:
230 None
231 Returns:
232 None"""
233
234 if file_name:
235 path.append(file_name)
236 else:
237 prefix = "lxd_data-"
238 time_stamp = time.strftime("%Y%m%d-%H%M%S")
239 suffix = ".atd"
240 path.append(prefix + time_stamp + suffix)
241
242 try:
243 cwd = os.path.abspath(os.path.dirname(__file__))
244 with open(os.path.abspath(os.path.join(cwd, *path)), "w") as json_file:
245 json.dump(self.data, json_file)
246 except OSError as err:
247 raise AnsibleParserError(f"Could not save data: {err}") from err
248
249 def verify_file(self, path):
250 """Check the config
251
252 Return true/false if the config-file is valid for this plugin
253
254 Args:
255 str(path): path to the config
256 Kwargs:
257 None
258 Raises:
259 None
260 Returns:
261 bool(valid): is valid"""
262 valid = False
263 if super().verify_file(path):
264 if path.endswith(("lxd.yaml", "lxd.yml")):
265 valid = True
266 else:
267 self.display.vvv('Inventory source not ending in "lxd.yaml" or "lxd.yml"')
268 return valid
269
270 @staticmethod
271 def validate_url(url):
272 """validate url
273
274 check whether the url is correctly formatted
275
276 Args:
277 url
278 Kwargs:
279 None
280 Raises:
281 AnsibleError
282 Returns:
283 bool"""
284 if not isinstance(url, str):
285 return False
286 if not url.startswith(("unix:", "https:")):
287 raise AnsibleError(f"URL is malformed: {url}")
288 return True
289
290 def _connect_to_socket(self):
291 """connect to lxd socket
292
293 Connect to lxd socket by provided url or defaults
294
295 Args:
296 None
297 Kwargs:
298 None
299 Raises:
300 AnsibleError
301 Returns:
302 None"""
303 error_storage = {}
304 url_list = [self.get_option("url"), self.SNAP_SOCKET_URL, self.SOCKET_URL]
305 urls = (url for url in url_list if self.validate_url(url))
306 for url in urls:
307 try:
308 socket_connection = LXDClient(
309 url, self.client_key, self.client_cert, self.debug, self.server_cert, self.server_check_hostname
310 )
311 return socket_connection
312 except LXDClientException as err:
313 error_storage[url] = err
314 raise AnsibleError(f"No connection to the socket: {error_storage}")
315
316 def _get_networks(self):
317 """Get Networknames
318
319 Returns all network config names
320
321 Args:
322 None
323 Kwargs:
324 None
325 Raises:
326 None
327 Returns:
328 list(names): names of all network_configs"""
329 # e.g. {'type': 'sync',
330 # 'status': 'Success',
331 # 'status_code': 200,
332 # 'operation': '',
333 # 'error_code': 0,
334 # 'error': '',
335 # 'metadata': ['/1.0/networks/lxdbr0']}
336 network_configs = self.socket.do("GET", "/1.0/networks")
337 return [m.split("/")[3] for m in network_configs["metadata"]]
338
339 def _get_instances(self):
340 """Get instancenames
341
342 Returns all instancenames
343
344 Args:
345 None
346 Kwargs:
347 None
348 Raises:
349 None
350 Returns:
351 list(names): names of all instances"""
352 # e.g. {
353 # "metadata": [
354 # "/1.0/instances/foo",
355 # "/1.0/instances/bar"
356 # ],
357 # "status": "Success",
358 # "status_code": 200,
359 # "type": "sync"
360 # }
361 url = "/1.0/instances"
362 if self.project:
363 url = f"{url}?{urlencode(dict(project=self.project))}"
364
365 instances = self.socket.do("GET", url)
366
367 if self.project:
368 return [m.split("/")[3].split("?")[0] for m in instances["metadata"]]
369
370 return [m.split("/")[3] for m in instances["metadata"]]
371
372 def _get_config(self, branch, name):
373 """Get inventory of instance
374
375 Get config of instance
376
377 Args:
378 str(branch): Name oft the API-Branch
379 str(name): Name of instance
380 Kwargs:
381 None
382 Source:
383 https://documentation.ubuntu.com/lxd/en/latest/rest-api/
384 Raises:
385 None
386 Returns:
387 dict(config): Config of the instance"""
388 config = {}
389 if isinstance(branch, (tuple, list)):
390 config[name] = {
391 branch[1]: self.socket.do(
392 "GET",
393 f"/1.0/{to_native(branch[0])}/{to_native(name)}/{to_native(branch[1])}?{urlencode(dict(project=self.project))}",
394 )
395 }
396 else:
397 config[name] = {
398 branch: self.socket.do(
399 "GET", f"/1.0/{to_native(branch)}/{to_native(name)}?{urlencode(dict(project=self.project))}"
400 )
401 }
402 return config
403
404 def get_instance_data(self, names):
405 """Create Inventory of the instance
406
407 Iterate through the different branches of the instances and collect Information.
408
409 Args:
410 list(names): List of instance names
411 Kwargs:
412 None
413 Raises:
414 None
415 Returns:
416 None"""
417 # tuple(('instances','metadata/templates')) to get section in branch
418 # e.g. /1.0/instances/<name>/metadata/templates
419 branches = ["instances", ("instances", "state")]
420 instance_config = {}
421 for branch in branches:
422 for name in names:
423 instance_config["instances"] = self._get_config(branch, name)
424 self.data = dict_merge(instance_config, self.data)
425
426 def get_network_data(self, names):
427 """Create Inventory of the instance
428
429 Iterate through the different branches of the instances and collect Information.
430
431 Args:
432 list(names): List of instance names
433 Kwargs:
434 None
435 Raises:
436 None
437 Returns:
438 None"""
439 # tuple(('instances','metadata/templates')) to get section in branch
440 # e.g. /1.0/instances/<name>/metadata/templates
441 branches = [("networks", "state")]
442 network_config = {}
443 for branch in branches:
444 for name in names:
445 try:
446 network_config["networks"] = self._get_config(branch, name)
447 except LXDClientException:
448 network_config["networks"] = {name: None}
449 self.data = dict_merge(network_config, self.data)
450
451 def extract_network_information_from_instance_config(self, instance_name):
452 """Returns the network interface configuration
453
454 Returns the network ipv4 and ipv6 config of the instance without local-link
455
456 Args:
457 str(instance_name): Name oft he instance
458 Kwargs:
459 None
460 Raises:
461 None
462 Returns:
463 dict(network_configuration): network config"""
464 instance_network_interfaces = self._get_data_entry(f"instances/{instance_name}/state/metadata/network")
465 network_configuration = None
466 if instance_network_interfaces:
467 network_configuration = {}
468 gen_interface_names = [
469 interface_name for interface_name in instance_network_interfaces if interface_name != "lo"
470 ]
471 for interface_name in gen_interface_names:
472 gen_address = [
473 address
474 for address in instance_network_interfaces[interface_name]["addresses"]
475 if address.get("scope") != "link"
476 ]
477 network_configuration[interface_name] = []
478 for address in gen_address:
479 address_set = {}
480 address_set["family"] = address.get("family")
481 address_set["address"] = address.get("address")
482 address_set["netmask"] = address.get("netmask")
483 address_set["combined"] = f"{address.get('address')}/{address.get('netmask')}"
484 network_configuration[interface_name].append(address_set)
485 return network_configuration
486
487 def get_prefered_instance_network_interface(self, instance_name):
488 """Helper to get the preferred interface of thr instance
489
490 Helper to get the preferred interface provide by neme pattern from 'prefered_instance_network_interface'.
491
492 Args:
493 str(instance_name): name of instance
494 Kwargs:
495 None
496 Raises:
497 None
498 Returns:
499 str(prefered_interface): None or interface name"""
500 instance_network_interfaces = self._get_data_entry(f"inventory/{instance_name}/network_interfaces")
501 prefered_interface = None # init
502 if instance_network_interfaces: # instance have network interfaces
503 # generator if interfaces which start with the desired pattern
504 net_generator = [
505 interface
506 for interface in instance_network_interfaces
507 if interface.startswith(self.prefered_instance_network_interface)
508 ]
509 selected_interfaces = [] # init
510 for interface in net_generator:
511 selected_interfaces.append(interface)
512 if len(selected_interfaces) > 0:
513 prefered_interface = sorted(selected_interfaces)[0]
514 return prefered_interface
515
516 def get_instance_vlans(self, instance_name):
517 """Get VLAN(s) from instance
518
519 Helper to get the VLAN_ID from the instance
520
521 Args:
522 str(instance_name): name of instance
523 Kwargs:
524 None
525 Raises:
526 None
527 Returns:
528 None"""
529 # get network device configuration and store {network: vlan_id}
530 network_vlans = {}
531 for network in self._get_data_entry("networks"):
532 if self._get_data_entry("state/metadata/vlan/vid", data=self.data["networks"].get(network)):
533 network_vlans[network] = self._get_data_entry(
534 "state/metadata/vlan/vid", data=self.data["networks"].get(network)
535 )
536
537 # get networkdevices of instance and return
538 # e.g.
539 # "eth0":{ "name":"eth0",
540 # "network":"lxdbr0",
541 # "type":"nic"},
542 vlan_ids = {}
543 devices = self._get_data_entry(f"instances/{to_native(instance_name)}/instances/metadata/expanded_devices")
544 for device in devices:
545 if "network" in devices[device]:
546 if devices[device]["network"] in network_vlans:
547 vlan_ids[devices[device].get("network")] = network_vlans[devices[device].get("network")]
548 return vlan_ids if vlan_ids else None
549
550 def _get_data_entry(self, path, data=None, delimiter="/"):
551 """Helper to get data
552
553 Helper to get data from self.data by a path like 'path/to/target'
554 Attention: Escaping of the delimiter is not (yet) provided.
555
556 Args:
557 str(path): path to nested dict
558 Kwargs:
559 dict(data): datastore
560 str(delimiter): delimiter in Path.
561 Raises:
562 None
563 Returns:
564 *(value)"""
565 try:
566 if not data:
567 data = self.data
568 if delimiter in path:
569 path = path.split(delimiter)
570
571 if isinstance(path, list) and len(path) > 1:
572 data = data[path.pop(0)]
573 path = delimiter.join(path)
574 return self._get_data_entry(path, data, delimiter) # recursion
575 return data[path]
576 except KeyError:
577 return None
578
579 def _set_data_entry(self, instance_name, key, value, path=None):
580 """Helper to save data
581
582 Helper to save the data in self.data
583 Detect if data is already in branch and use dict_merge() to prevent that branch is overwritten.
584
585 Args:
586 str(instance_name): name of instance
587 str(key): same as dict
588 *(value): same as dict
589 Kwargs:
590 str(path): path to branch-part
591 Raises:
592 AnsibleParserError
593 Returns:
594 None"""
595 if not path:
596 path = self.data["inventory"]
597 if instance_name not in path:
598 path[instance_name] = {}
599
600 try:
601 if isinstance(value, dict) and key in path[instance_name]:
602 path[instance_name] = dict_merge(value, path[instance_name][key])
603 else:
604 path[instance_name][key] = value
605 except KeyError as err:
606 raise AnsibleParserError(f"Unable to store Information: {err}") from err
607
608 def extract_information_from_instance_configs(self):
609 """Process configuration information
610
611 Preparation of the data
612
613 Args:
614 dict(configs): instance configurations
615 Kwargs:
616 None
617 Raises:
618 None
619 Returns:
620 None"""
621 # create branch "inventory"
622 if "inventory" not in self.data:
623 self.data["inventory"] = {}
624
625 for instance_name in self.data["instances"]:
626 self._set_data_entry(
627 instance_name,
628 "os",
629 self._get_data_entry(f"instances/{instance_name}/instances/metadata/config/image.os"),
630 )
631 self._set_data_entry(
632 instance_name,
633 "release",
634 self._get_data_entry(f"instances/{instance_name}/instances/metadata/config/image.release"),
635 )
636 self._set_data_entry(
637 instance_name,
638 "version",
639 self._get_data_entry(f"instances/{instance_name}/instances/metadata/config/image.version"),
640 )
641 self._set_data_entry(
642 instance_name, "profile", self._get_data_entry(f"instances/{instance_name}/instances/metadata/profiles")
643 )
644 self._set_data_entry(
645 instance_name,
646 "location",
647 self._get_data_entry(f"instances/{instance_name}/instances/metadata/location"),
648 )
649 self._set_data_entry(
650 instance_name,
651 "state",
652 self._get_data_entry(f"instances/{instance_name}/instances/metadata/config/volatile.last_state.power"),
653 )
654 self._set_data_entry(
655 instance_name, "type", self._get_data_entry(f"instances/{instance_name}/instances/metadata/type")
656 )
657 self._set_data_entry(
658 instance_name,
659 "network_interfaces",
660 self.extract_network_information_from_instance_config(instance_name),
661 )
662 self._set_data_entry(
663 instance_name, "preferred_interface", self.get_prefered_instance_network_interface(instance_name)
664 )
665 self._set_data_entry(instance_name, "vlan_ids", self.get_instance_vlans(instance_name))
666 self._set_data_entry(
667 instance_name, "project", self._get_data_entry(f"instances/{instance_name}/instances/metadata/project")
668 )
669
670 def build_inventory_network(self, instance_name):
671 """Add the network interfaces of the instance to the inventory
672
673 Logic:
674 - if the instance have no interface -> 'ansible_connection: local'
675 - get preferred_interface & prefered_instance_network_family -> 'ansible_connection: ssh' & 'ansible_host: <IP>'
676 - first Interface from: network_interfaces prefered_instance_network_family -> 'ansible_connection: ssh' & 'ansible_host: <IP>'
677
678 Args:
679 str(instance_name): name of instance
680 Kwargs:
681 None
682 Raises:
683 None
684 Returns:
685 None"""
686
687 def interface_selection(instance_name):
688 """Select instance Interface for inventory
689
690 Logic:
691 - get preferred_interface & prefered_instance_network_family -> str(IP)
692 - first Interface from: network_interfaces prefered_instance_network_family -> str(IP)
693
694 Args:
695 str(instance_name): name of instance
696 Kwargs:
697 None
698 Raises:
699 None
700 Returns:
701 dict(interface_name: ip)"""
702 prefered_interface = self._get_data_entry(f"inventory/{instance_name}/preferred_interface") # name or None
703 prefered_instance_network_family = self.prefered_instance_network_family
704
705 ip_address = ""
706 if prefered_interface:
707 interface = self._get_data_entry(f"inventory/{instance_name}/network_interfaces/{prefered_interface}")
708 for config in interface:
709 if config["family"] == prefered_instance_network_family:
710 ip_address = config["address"]
711 break
712 else:
713 interfaces = self._get_data_entry(f"inventory/{instance_name}/network_interfaces")
714 for interface in interfaces.values():
715 for config in interface:
716 if config["family"] == prefered_instance_network_family:
717 ip_address = config["address"]
718 break
719 return ip_address
720
721 if self._get_data_entry(f"inventory/{instance_name}/network_interfaces"): # instance have network interfaces
722 self.inventory.set_variable(instance_name, "ansible_connection", "ssh")
723 self.inventory.set_variable(instance_name, "ansible_host", make_unsafe(interface_selection(instance_name)))
724 else:
725 self.inventory.set_variable(instance_name, "ansible_connection", "local")
726
727 def build_inventory_hosts(self):
728 """Build host-part dynamic inventory
729
730 Build the host-part of the dynamic inventory.
731 Add Hosts and host_vars to the inventory.
732
733 Args:
734 None
735 Kwargs:
736 None
737 Raises:
738 None
739 Returns:
740 None"""
741 for instance_name in self.data["inventory"]:
742 instance_state = str(self._get_data_entry(f"inventory/{instance_name}/state") or "STOPPED").lower()
743
744 # Only consider instances that match the "state" filter, if self.state is not None
745 if self.filter:
746 if self.filter.lower() != instance_state:
747 continue
748 # add instance
749 instance_name = make_unsafe(instance_name)
750 self.inventory.add_host(instance_name)
751 # add network information
752 self.build_inventory_network(instance_name)
753 # add os
754 v = self._get_data_entry(f"inventory/{instance_name}/os")
755 if v:
756 self.inventory.set_variable(instance_name, "ansible_lxd_os", make_unsafe(v.lower()))
757 # add release
758 v = self._get_data_entry(f"inventory/{instance_name}/release")
759 if v:
760 self.inventory.set_variable(instance_name, "ansible_lxd_release", make_unsafe(v.lower()))
761 # add profile
762 self.inventory.set_variable(
763 instance_name,
764 "ansible_lxd_profile",
765 make_unsafe(self._get_data_entry(f"inventory/{instance_name}/profile")),
766 )
767 # add state
768 self.inventory.set_variable(instance_name, "ansible_lxd_state", make_unsafe(instance_state))
769 # add type
770 self.inventory.set_variable(
771 instance_name, "ansible_lxd_type", make_unsafe(self._get_data_entry(f"inventory/{instance_name}/type"))
772 )
773 # add location information
774 if (
775 self._get_data_entry(f"inventory/{instance_name}/location") != "none"
776 ): # wrong type by lxd 'none' != 'None'
777 self.inventory.set_variable(
778 instance_name,
779 "ansible_lxd_location",
780 make_unsafe(self._get_data_entry(f"inventory/{instance_name}/location")),
781 )
782 # add VLAN_ID information
783 if self._get_data_entry(f"inventory/{instance_name}/vlan_ids"):
784 self.inventory.set_variable(
785 instance_name,
786 "ansible_lxd_vlan_ids",
787 make_unsafe(self._get_data_entry(f"inventory/{instance_name}/vlan_ids")),
788 )
789 # add project
790 self.inventory.set_variable(
791 instance_name,
792 "ansible_lxd_project",
793 make_unsafe(self._get_data_entry(f"inventory/{instance_name}/project")),
794 )
795
796 def build_inventory_groups_location(self, group_name):
797 """create group by attribute: location
798
799 Args:
800 str(group_name): Group name
801 Kwargs:
802 None
803 Raises:
804 None
805 Returns:
806 None"""
807 # maybe we just want to expand one group
808 if group_name not in self.inventory.groups:
809 self.inventory.add_group(group_name)
810
811 for instance_name in self.inventory.hosts:
812 if "ansible_lxd_location" in self.inventory.get_host(instance_name).get_vars():
813 self.inventory.add_child(group_name, instance_name)
814
815 def build_inventory_groups_pattern(self, group_name):
816 """create group by name pattern
817
818 Args:
819 str(group_name): Group name
820 Kwargs:
821 None
822 Raises:
823 None
824 Returns:
825 None"""
826 # maybe we just want to expand one group
827 if group_name not in self.inventory.groups:
828 self.inventory.add_group(group_name)
829
830 regex_pattern = self.groupby[group_name].get("attribute")
831
832 for instance_name in self.inventory.hosts:
833 result = re.search(regex_pattern, instance_name)
834 if result:
835 self.inventory.add_child(group_name, instance_name)
836
837 def build_inventory_groups_network_range(self, group_name):
838 """check if IP is in network-class
839
840 Args:
841 str(group_name): Group name
842 Kwargs:
843 None
844 Raises:
845 None
846 Returns:
847 None"""
848 # maybe we just want to expand one group
849 if group_name not in self.inventory.groups:
850 self.inventory.add_group(group_name)
851
852 try:
853 network = ipaddress.ip_network(to_text(self.groupby[group_name].get("attribute")))
854 except ValueError as err:
855 raise AnsibleParserError(
856 f"Error while parsing network range {self.groupby[group_name].get('attribute')}: {err}"
857 ) from err
858
859 for instance_name in self.inventory.hosts:
860 if self.data["inventory"][instance_name].get("network_interfaces") is not None:
861 for interface in self.data["inventory"][instance_name].get("network_interfaces"):
862 for interface_family in self.data["inventory"][instance_name].get("network_interfaces")[interface]:
863 try:
864 address = ipaddress.ip_address(to_text(interface_family["address"]))
865 if address.version == network.version and address in network:
866 self.inventory.add_child(group_name, instance_name)
867 except ValueError:
868 # Ignore invalid IP addresses returned by lxd
869 pass
870
871 def build_inventory_groups_project(self, group_name):
872 """create group by attribute: project
873
874 Args:
875 str(group_name): Group name
876 Kwargs:
877 None
878 Raises:
879 None
880 Returns:
881 None"""
882 # maybe we just want to expand one group
883 if group_name not in self.inventory.groups:
884 self.inventory.add_group(group_name)
885
886 gen_instances = [
887 instance_name
888 for instance_name in self.inventory.hosts
889 if "ansible_lxd_project" in self.inventory.get_host(instance_name).get_vars()
890 ]
891 for instance_name in gen_instances:
892 if self.groupby[group_name].get("attribute").lower() == self.inventory.get_host(
893 instance_name
894 ).get_vars().get("ansible_lxd_project"):
895 self.inventory.add_child(group_name, instance_name)
896
897 def build_inventory_groups_os(self, group_name):
898 """create group by attribute: os
899
900 Args:
901 str(group_name): Group name
902 Kwargs:
903 None
904 Raises:
905 None
906 Returns:
907 None"""
908 # maybe we just want to expand one group
909 if group_name not in self.inventory.groups:
910 self.inventory.add_group(group_name)
911
912 gen_instances = [
913 instance_name
914 for instance_name in self.inventory.hosts
915 if "ansible_lxd_os" in self.inventory.get_host(instance_name).get_vars()
916 ]
917 for instance_name in gen_instances:
918 if self.groupby[group_name].get("attribute").lower() == self.inventory.get_host(
919 instance_name
920 ).get_vars().get("ansible_lxd_os"):
921 self.inventory.add_child(group_name, instance_name)
922
923 def build_inventory_groups_release(self, group_name):
924 """create group by attribute: release
925
926 Args:
927 str(group_name): Group name
928 Kwargs:
929 None
930 Raises:
931 None
932 Returns:
933 None"""
934 # maybe we just want to expand one group
935 if group_name not in self.inventory.groups:
936 self.inventory.add_group(group_name)
937
938 gen_instances = [
939 instance_name
940 for instance_name in self.inventory.hosts
941 if "ansible_lxd_release" in self.inventory.get_host(instance_name).get_vars()
942 ]
943 for instance_name in gen_instances:
944 if self.groupby[group_name].get("attribute").lower() == self.inventory.get_host(
945 instance_name
946 ).get_vars().get("ansible_lxd_release"):
947 self.inventory.add_child(group_name, instance_name)
948
949 def build_inventory_groups_profile(self, group_name):
950 """create group by attribute: profile
951
952 Args:
953 str(group_name): Group name
954 Kwargs:
955 None
956 Raises:
957 None
958 Returns:
959 None"""
960 # maybe we just want to expand one group
961 if group_name not in self.inventory.groups:
962 self.inventory.add_group(group_name)
963
964 gen_instances = [
965 instance_name
966 for instance_name in self.inventory.hosts.keys()
967 if "ansible_lxd_profile" in self.inventory.get_host(instance_name).get_vars().keys()
968 ]
969 for instance_name in gen_instances:
970 if self.groupby[group_name].get("attribute").lower() in self.inventory.get_host(
971 instance_name
972 ).get_vars().get("ansible_lxd_profile"):
973 self.inventory.add_child(group_name, instance_name)
974
975 def build_inventory_groups_vlanid(self, group_name):
976 """create group by attribute: vlanid
977
978 Args:
979 str(group_name): Group name
980 Kwargs:
981 None
982 Raises:
983 None
984 Returns:
985 None"""
986 # maybe we just want to expand one group
987 if group_name not in self.inventory.groups:
988 self.inventory.add_group(group_name)
989
990 gen_instances = [
991 instance_name
992 for instance_name in self.inventory.hosts.keys()
993 if "ansible_lxd_vlan_ids" in self.inventory.get_host(instance_name).get_vars().keys()
994 ]
995 for instance_name in gen_instances:
996 if (
997 self.groupby[group_name].get("attribute")
998 in self.inventory.get_host(instance_name).get_vars().get("ansible_lxd_vlan_ids").values()
999 ):
1000 self.inventory.add_child(group_name, instance_name)
1001
1002 def build_inventory_groups_type(self, group_name):
1003 """create group by attribute: type
1004
1005 Args:
1006 str(group_name): Group name
1007 Kwargs:
1008 None
1009 Raises:
1010 None
1011 Returns:
1012 None"""
1013 # maybe we just want to expand one group
1014 if group_name not in self.inventory.groups:
1015 self.inventory.add_group(group_name)
1016
1017 gen_instances = [
1018 instance_name
1019 for instance_name in self.inventory.hosts
1020 if "ansible_lxd_type" in self.inventory.get_host(instance_name).get_vars()
1021 ]
1022 for instance_name in gen_instances:
1023 if self.groupby[group_name].get("attribute").lower() == self.inventory.get_host(
1024 instance_name
1025 ).get_vars().get("ansible_lxd_type"):
1026 self.inventory.add_child(group_name, instance_name)
1027
1028 def build_inventory_groups(self):
1029 """Build group-part dynamic inventory
1030
1031 Build the group-part of the dynamic inventory.
1032 Add groups to the inventory.
1033
1034 Args:
1035 None
1036 Kwargs:
1037 None
1038 Raises:
1039 None
1040 Returns:
1041 None"""
1042
1043 def group_type(group_name):
1044 """create groups defined by lxd.yml or defaultvalues
1045
1046 create groups defined by lxd.yml or defaultvalues
1047 supportetd:
1048 * 'location'
1049 * 'pattern'
1050 * 'network_range'
1051 * 'os'
1052 * 'release'
1053 * 'profile'
1054 * 'vlanid'
1055 * 'type'
1056 * 'project'
1057
1058 Args:
1059 str(group_name): Group name
1060 Kwargs:
1061 None
1062 Raises:
1063 None
1064 Returns:
1065 None"""
1066
1067 # Due to the compatibility with python 2 no use of map
1068 if self.groupby[group_name].get("type") == "location":
1069 self.build_inventory_groups_location(group_name)
1070 elif self.groupby[group_name].get("type") == "pattern":
1071 self.build_inventory_groups_pattern(group_name)
1072 elif self.groupby[group_name].get("type") == "network_range":
1073 self.build_inventory_groups_network_range(group_name)
1074 elif self.groupby[group_name].get("type") == "os":
1075 self.build_inventory_groups_os(group_name)
1076 elif self.groupby[group_name].get("type") == "release":
1077 self.build_inventory_groups_release(group_name)
1078 elif self.groupby[group_name].get("type") == "profile":
1079 self.build_inventory_groups_profile(group_name)
1080 elif self.groupby[group_name].get("type") == "vlanid":
1081 self.build_inventory_groups_vlanid(group_name)
1082 elif self.groupby[group_name].get("type") == "type":
1083 self.build_inventory_groups_type(group_name)
1084 elif self.groupby[group_name].get("type") == "project":
1085 self.build_inventory_groups_project(group_name)
1086 else:
1087 raise AnsibleParserError(f"Unknown group type: {to_native(group_name)}")
1088
1089 if self.groupby:
1090 for group_name in self.groupby:
1091 if not group_name.isalnum():
1092 raise AnsibleParserError(f"Invalid character(s) in groupname: {to_native(group_name)}")
1093 group_type(make_unsafe(group_name))
1094
1095 def build_inventory(self):
1096 """Build dynamic inventory
1097
1098 Build the dynamic inventory.
1099
1100 Args:
1101 None
1102 Kwargs:
1103 None
1104 Raises:
1105 None
1106 Returns:
1107 None"""
1108
1109 self.build_inventory_hosts()
1110 self.build_inventory_groups()
1111
1112 def cleandata(self):
1113 """Clean the dynamic inventory
1114
1115 The first version of the inventory only supported container.
1116 This will change in the future.
1117 The following function cleans up the data and remove the all items with the wrong type.
1118
1119 Args:
1120 None
1121 Kwargs:
1122 None
1123 Raises:
1124 None
1125 Returns:
1126 None"""
1127 iter_keys = list(self.data["instances"].keys())
1128 for instance_name in iter_keys:
1129 if self._get_data_entry(f"instances/{instance_name}/instances/metadata/type") != self.type_filter:
1130 del self.data["instances"][instance_name]
1131
1132 def _populate(self):
1133 """Return the hosts and groups
1134
1135 Returns the processed instance configurations from the lxd import
1136
1137 Args:
1138 None
1139 Kwargs:
1140 None
1141 Raises:
1142 None
1143 Returns:
1144 None"""
1145
1146 if len(self.data) == 0: # If no data is injected by unittests open socket
1147 self.socket = self._connect_to_socket()
1148 self.get_instance_data(self._get_instances())
1149 self.get_network_data(self._get_networks())
1150
1151 # The first version of the inventory only supported containers.
1152 # This will change in the future.
1153 # The following function cleans up the data.
1154 if self.type_filter != "both":
1155 self.cleandata()
1156
1157 self.extract_information_from_instance_configs()
1158
1159 # self.display.vvv(self.save_json_data([os.path.abspath(__file__)]))
1160
1161 self.build_inventory()
1162
1163 def parse(self, inventory, loader, path, cache):
1164 """Return dynamic inventory from source
1165
1166 Returns the processed inventory from the lxd import
1167
1168 Args:
1169 str(inventory): inventory object with existing data and
1170 the methods to add hosts/groups/variables
1171 to inventory
1172 str(loader): Ansible's DataLoader
1173 str(path): path to the config
1174 bool(cache): use or avoid caches
1175 Kwargs:
1176 None
1177 Raises:
1178 AnsibleParserError
1179 Returns:
1180 None"""
1181 if IPADDRESS_IMPORT_ERROR:
1182 raise AnsibleError("another_library must be installed to use this plugin") from IPADDRESS_IMPORT_ERROR
1183
1184 super().parse(inventory, loader, path, cache=False)
1185 # Read the inventory YAML file
1186 self._read_config_data(path)
1187 try:
1188 self.client_key = self.get_option("client_key")
1189 self.client_cert = self.get_option("client_cert")
1190 self.server_cert = self.get_option("server_cert")
1191 self.server_check_hostname = self.get_option("server_check_hostname")
1192 self.project = self.get_option("project")
1193 self.debug = self.DEBUG
1194 self.data = {} # store for inventory-data
1195 self.groupby = self.get_option("groupby")
1196 self.plugin = self.get_option("plugin")
1197 self.prefered_instance_network_family = self.get_option("prefered_instance_network_family")
1198 self.prefered_instance_network_interface = self.get_option("prefered_instance_network_interface")
1199 self.type_filter = self.get_option("type_filter")
1200 if self.get_option("state").lower() == "none": # none in config is str()
1201 self.filter = None
1202 else:
1203 self.filter = self.get_option("state").lower()
1204 self.trust_password = self.get_option("trust_password")
1205 self.url = self.get_option("url")
1206 except Exception as err:
1207 raise AnsibleParserError(f"All correct options required: {err}") from err
1208 # Call our internal helper to populate the dynamic inventory
1209 self._populate()