| 1 |
# Copyright (C) 2020 Orion Poplawski <[email protected]> |
| 2 |
# Copyright (c) 2020 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 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
author: Orion Poplawski (@opoplawski) |
| 9 |
name: cobbler |
| 10 |
short_description: Cobbler inventory source |
| 11 |
version_added: 1.0.0 |
| 12 |
description: |
| 13 |
- Get inventory hosts from the cobbler service. |
| 14 |
- 'Uses a configuration file as an inventory source, it must end in C(.cobbler.yml) or C(.cobbler.yaml) and have a C(plugin: |
| 15 |
cobbler) entry.' |
| 16 |
- Adds the primary IP addresses to C(cobbler_ipv4_address) and C(cobbler_ipv6_address) host variables if defined in Cobbler. |
| 17 |
The primary IP address is defined as the management interface if defined, or the interface who's DNS name matches the |
| 18 |
hostname of the system, or else the first interface found. |
| 19 |
extends_documentation_fragment: |
| 20 |
- ansible.builtin.inventory_cache |
| 21 |
options: |
| 22 |
plugin: |
| 23 |
description: The name of this plugin, it should always be set to V(community.general.cobbler) for this plugin to recognize |
| 24 |
it as its own. |
| 25 |
type: string |
| 26 |
required: true |
| 27 |
choices: ['cobbler', 'community.general.cobbler'] |
| 28 |
url: |
| 29 |
description: URL to cobbler. |
| 30 |
type: string |
| 31 |
default: 'http://cobbler/cobbler_api' |
| 32 |
env: |
| 33 |
- name: COBBLER_SERVER |
| 34 |
user: |
| 35 |
description: Cobbler authentication user. |
| 36 |
type: string |
| 37 |
required: false |
| 38 |
env: |
| 39 |
- name: COBBLER_USER |
| 40 |
password: |
| 41 |
description: Cobbler authentication password. |
| 42 |
type: string |
| 43 |
required: false |
| 44 |
env: |
| 45 |
- name: COBBLER_PASSWORD |
| 46 |
cache_fallback: |
| 47 |
description: Fallback to cached results if connection to cobbler fails. |
| 48 |
type: boolean |
| 49 |
default: false |
| 50 |
connection_timeout: |
| 51 |
description: Timeout to connect to cobbler server. |
| 52 |
type: int |
| 53 |
required: false |
| 54 |
version_added: 10.7.0 |
| 55 |
exclude_mgmt_classes: |
| 56 |
description: Management classes to exclude from inventory. |
| 57 |
type: list |
| 58 |
default: [] |
| 59 |
elements: str |
| 60 |
version_added: 7.4.0 |
| 61 |
exclude_profiles: |
| 62 |
description: |
| 63 |
- Profiles to exclude from inventory. |
| 64 |
- Ignored if O(include_profiles) is specified. |
| 65 |
type: list |
| 66 |
default: [] |
| 67 |
elements: str |
| 68 |
include_mgmt_classes: |
| 69 |
description: Management classes to include from inventory. |
| 70 |
type: list |
| 71 |
default: [] |
| 72 |
elements: str |
| 73 |
version_added: 7.4.0 |
| 74 |
include_profiles: |
| 75 |
description: |
| 76 |
- Profiles to include from inventory. |
| 77 |
- If specified, all other profiles are excluded. |
| 78 |
- O(exclude_profiles) is ignored if O(include_profiles) is specified. |
| 79 |
type: list |
| 80 |
default: [] |
| 81 |
elements: str |
| 82 |
version_added: 4.4.0 |
| 83 |
inventory_hostname: |
| 84 |
description: |
| 85 |
- What to use for the ansible inventory hostname. |
| 86 |
- By default the networking hostname is used if defined, otherwise the DNS name of the management or first non-static |
| 87 |
interface. |
| 88 |
- If set to V(system), the cobbler system name is used. |
| 89 |
type: str |
| 90 |
choices: ['hostname', 'system'] |
| 91 |
default: hostname |
| 92 |
version_added: 7.1.0 |
| 93 |
group_by: |
| 94 |
description: Keys to group hosts by. |
| 95 |
type: list |
| 96 |
elements: string |
| 97 |
default: ['mgmt_classes', 'owners', 'status'] |
| 98 |
group: |
| 99 |
description: Group to place all hosts into. |
| 100 |
default: cobbler |
| 101 |
group_prefix: |
| 102 |
description: Prefix to apply to cobbler groups. |
| 103 |
default: cobbler_ |
| 104 |
want_facts: |
| 105 |
description: Toggle, if V(true) the plugin retrieves all host facts from the server. |
| 106 |
type: boolean |
| 107 |
default: true |
| 108 |
want_ip_addresses: |
| 109 |
description: |
| 110 |
- Toggle, if V(true) the plugin adds a C(cobbler_ipv4_addresses) and C(cobbler_ipv6_addresses) dictionary to the |
| 111 |
defined O(group) mapping interface DNS names to IP addresses. |
| 112 |
type: boolean |
| 113 |
default: true |
| 114 |
version_added: 7.1.0 |
| 115 |
facts_level: |
| 116 |
description: |
| 117 |
- Set to V(normal) to gather only system-level variables. |
| 118 |
- Set to V(as_rendered) to gather all variables as rolled up by Cobbler. |
| 119 |
type: string |
| 120 |
choices: ['normal', 'as_rendered'] |
| 121 |
default: normal |
| 122 |
version_added: 10.7.0 |
| 123 |
""" |
| 124 |
|
| 125 |
EXAMPLES = r""" |
| 126 |
# my.cobbler.yml |
| 127 |
plugin: community.general.cobbler |
| 128 |
url: http://cobbler/cobbler_api |
| 129 |
user: ansible-tester |
| 130 |
password: secure |
| 131 |
""" |
| 132 |
|
| 133 |
import socket |
| 134 |
|
| 135 |
from ansible.errors import AnsibleError |
| 136 |
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, to_safe_group_name |
| 137 |
|
| 138 |
from ansible_collections.community.general.plugins.plugin_utils._unsafe import make_unsafe |
| 139 |
|
| 140 |
# xmlrpc |
| 141 |
try: |
| 142 |
import xmlrpc.client as xmlrpc_client |
| 143 |
|
| 144 |
HAS_XMLRPC_CLIENT = True |
| 145 |
except ImportError: |
| 146 |
HAS_XMLRPC_CLIENT = False |
| 147 |
|
| 148 |
|
| 149 |
class TimeoutTransport(xmlrpc_client.SafeTransport): |
| 150 |
def __init__(self, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): |
| 151 |
super().__init__() |
| 152 |
self._timeout = timeout |
| 153 |
self.context = None |
| 154 |
|
| 155 |
def make_connection(self, host): |
| 156 |
conn = xmlrpc_client.SafeTransport.make_connection(self, host) |
| 157 |
conn.timeout = self._timeout |
| 158 |
return conn |
| 159 |
|
| 160 |
|
| 161 |
class InventoryModule(BaseInventoryPlugin, Cacheable): |
| 162 |
"""Host inventory parser for ansible using cobbler as source.""" |
| 163 |
|
| 164 |
NAME = "community.general.cobbler" |
| 165 |
|
| 166 |
def __init__(self): |
| 167 |
super().__init__() |
| 168 |
self.cache_key = None |
| 169 |
|
| 170 |
if not HAS_XMLRPC_CLIENT: |
| 171 |
raise AnsibleError("Could not import xmlrpc client library") |
| 172 |
|
| 173 |
def verify_file(self, path): |
| 174 |
valid = False |
| 175 |
if super().verify_file(path): |
| 176 |
if path.endswith(("cobbler.yaml", "cobbler.yml")): |
| 177 |
valid = True |
| 178 |
else: |
| 179 |
self.display.vvv('Skipping due to inventory source not ending in "cobbler.yaml" nor "cobbler.yml"') |
| 180 |
return valid |
| 181 |
|
| 182 |
def _init_cache(self): |
| 183 |
if self.cache_key not in self._cache: |
| 184 |
self._cache[self.cache_key] = {} |
| 185 |
|
| 186 |
def _reload_cache(self): |
| 187 |
if self.get_option("cache_fallback"): |
| 188 |
self.display.vvv("Cannot connect to server, loading cache\n") |
| 189 |
self._options["cache_timeout"] = 0 |
| 190 |
self.load_cache_plugin() |
| 191 |
self._cache.get(self.cache_key, {}) |
| 192 |
|
| 193 |
def _get_profiles(self): |
| 194 |
if not self.use_cache or "profiles" not in self._cache.get(self.cache_key, {}): |
| 195 |
try: |
| 196 |
if self.token is not None: |
| 197 |
data = self.cobbler.get_profiles(self.token) |
| 198 |
else: |
| 199 |
data = self.cobbler.get_profiles() |
| 200 |
except (socket.gaierror, OSError, xmlrpc_client.ProtocolError): |
| 201 |
self._reload_cache() |
| 202 |
else: |
| 203 |
self._init_cache() |
| 204 |
self._cache[self.cache_key]["profiles"] = data |
| 205 |
|
| 206 |
return self._cache[self.cache_key]["profiles"] |
| 207 |
|
| 208 |
def _get_systems(self): |
| 209 |
if not self.use_cache or "systems" not in self._cache.get(self.cache_key, {}): |
| 210 |
try: |
| 211 |
if self.token is not None: |
| 212 |
data = self.cobbler.get_systems(self.token) |
| 213 |
else: |
| 214 |
data = self.cobbler.get_systems() |
| 215 |
|
| 216 |
# If more facts are requested, gather them all from Cobbler |
| 217 |
if self.facts_level == "as_rendered": |
| 218 |
for i, host in enumerate(data): |
| 219 |
self.display.vvvv(f"Gathering all facts for {host['name']}\n") |
| 220 |
if self.token is not None: |
| 221 |
data[i] = self.cobbler.get_system_as_rendered(host["name"], self.token) |
| 222 |
else: |
| 223 |
data[i] = self.cobbler.get_system_as_rendered(host["name"]) |
| 224 |
except (socket.gaierror, OSError, xmlrpc_client.ProtocolError): |
| 225 |
self._reload_cache() |
| 226 |
else: |
| 227 |
self._init_cache() |
| 228 |
self._cache[self.cache_key]["systems"] = data |
| 229 |
|
| 230 |
return self._cache[self.cache_key]["systems"] |
| 231 |
|
| 232 |
def _add_safe_group_name(self, group, child=None): |
| 233 |
group_name = self.inventory.add_group( |
| 234 |
to_safe_group_name(f"{self.get_option('group_prefix')}{group.lower().replace(' ', '')}") |
| 235 |
) |
| 236 |
if child is not None: |
| 237 |
self.inventory.add_child(group_name, child) |
| 238 |
return group_name |
| 239 |
|
| 240 |
def _exclude_profile(self, profile): |
| 241 |
if self.include_profiles: |
| 242 |
return profile not in self.include_profiles |
| 243 |
else: |
| 244 |
return profile in self.exclude_profiles |
| 245 |
|
| 246 |
def parse(self, inventory, loader, path, cache=True): |
| 247 |
super().parse(inventory, loader, path) |
| 248 |
|
| 249 |
# read config from file, this sets 'options' |
| 250 |
self._read_config_data(path) |
| 251 |
|
| 252 |
# get connection host |
| 253 |
self.cobbler_url = self.get_option("url") |
| 254 |
self.display.vvvv(f"Connecting to {self.cobbler_url}\n") |
| 255 |
|
| 256 |
if "connection_timeout" in self._options: |
| 257 |
self.cobbler = xmlrpc_client.Server( |
| 258 |
self.cobbler_url, |
| 259 |
allow_none=True, |
| 260 |
transport=TimeoutTransport(timeout=self.get_option("connection_timeout")), |
| 261 |
) |
| 262 |
else: |
| 263 |
self.cobbler = xmlrpc_client.Server(self.cobbler_url, allow_none=True) |
| 264 |
self.token = None |
| 265 |
if self.get_option("user") is not None: |
| 266 |
self.token = self.cobbler.login(str(self.get_option("user")), str(self.get_option("password"))) |
| 267 |
|
| 268 |
self.cache_key = self.get_cache_key(path) |
| 269 |
self.use_cache = cache and self.get_option("cache") |
| 270 |
|
| 271 |
self.exclude_mgmt_classes = self.get_option("exclude_mgmt_classes") |
| 272 |
self.include_mgmt_classes = self.get_option("include_mgmt_classes") |
| 273 |
self.exclude_profiles = self.get_option("exclude_profiles") |
| 274 |
self.include_profiles = self.get_option("include_profiles") |
| 275 |
self.group_by = self.get_option("group_by") |
| 276 |
self.inventory_hostname = self.get_option("inventory_hostname") |
| 277 |
self.facts_level = self.get_option("facts_level") |
| 278 |
|
| 279 |
for profile in self._get_profiles(): |
| 280 |
if profile["parent"]: |
| 281 |
self.display.vvvv(f"Processing profile {profile['name']} with parent {profile['parent']}\n") |
| 282 |
if not self._exclude_profile(profile["parent"]): |
| 283 |
parent_group_name = self._add_safe_group_name(profile["parent"]) |
| 284 |
self.display.vvvv(f"Added profile parent group {parent_group_name}\n") |
| 285 |
if not self._exclude_profile(profile["name"]): |
| 286 |
group_name = self._add_safe_group_name(profile["name"]) |
| 287 |
self.display.vvvv(f"Added profile group {group_name}\n") |
| 288 |
self.inventory.add_child(parent_group_name, group_name) |
| 289 |
else: |
| 290 |
self.display.vvvv(f"Processing profile {profile['name']} without parent\n") |
| 291 |
# Create a hierarchy of profile names |
| 292 |
profile_elements = profile["name"].split("-") |
| 293 |
i = 0 |
| 294 |
while i < len(profile_elements) - 1: |
| 295 |
profile_group = "-".join(profile_elements[0 : i + 1]) |
| 296 |
profile_group_child = "-".join(profile_elements[0 : i + 2]) |
| 297 |
if self._exclude_profile(profile_group): |
| 298 |
self.display.vvvv(f"Excluding profile {profile_group}\n") |
| 299 |
break |
| 300 |
group_name = self._add_safe_group_name(profile_group) |
| 301 |
self.display.vvvv(f"Added profile group {group_name}\n") |
| 302 |
child_group_name = self._add_safe_group_name(profile_group_child) |
| 303 |
self.display.vvvv(f"Added profile child group {child_group_name} to {group_name}\n") |
| 304 |
self.inventory.add_child(group_name, child_group_name) |
| 305 |
i = i + 1 |
| 306 |
|
| 307 |
# Add default group for this inventory if specified |
| 308 |
self.group = to_safe_group_name(self.get_option("group")) |
| 309 |
if self.group is not None and self.group != "": |
| 310 |
self.inventory.add_group(self.group) |
| 311 |
self.display.vvvv(f"Added site group {self.group}\n") |
| 312 |
|
| 313 |
ip_addresses = {} |
| 314 |
ipv6_addresses = {} |
| 315 |
for host in self._get_systems(): |
| 316 |
# Get the FQDN for the host and add it to the right groups |
| 317 |
if self.inventory_hostname == "system": |
| 318 |
hostname = make_unsafe(host["name"]) # None |
| 319 |
else: |
| 320 |
hostname = make_unsafe(host["hostname"]) # None |
| 321 |
interfaces = host["interfaces"] |
| 322 |
|
| 323 |
if set(host["mgmt_classes"]) & set(self.include_mgmt_classes): |
| 324 |
self.display.vvvv(f"Including host {host['name']} in mgmt_classes {host['mgmt_classes']}\n") |
| 325 |
else: |
| 326 |
if self._exclude_profile(host["profile"]): |
| 327 |
self.display.vvvv(f"Excluding host {host['name']} in profile {host['profile']}\n") |
| 328 |
continue |
| 329 |
|
| 330 |
if set(host["mgmt_classes"]) & set(self.exclude_mgmt_classes): |
| 331 |
self.display.vvvv(f"Excluding host {host['name']} in mgmt_classes {host['mgmt_classes']}\n") |
| 332 |
continue |
| 333 |
|
| 334 |
# hostname is often empty for non-static IP hosts |
| 335 |
if hostname == "": |
| 336 |
for iname, ivalue in interfaces.items(): |
| 337 |
if ivalue["management"] or not ivalue["static"]: |
| 338 |
this_dns_name = ivalue.get("dns_name", None) |
| 339 |
if this_dns_name is not None and this_dns_name != "": |
| 340 |
hostname = make_unsafe(this_dns_name) |
| 341 |
self.display.vvvv(f"Set hostname to {hostname} from {iname}\n") |
| 342 |
|
| 343 |
if hostname == "": |
| 344 |
self.display.vvvv(f"Cannot determine hostname for host {host['name']}, skipping\n") |
| 345 |
continue |
| 346 |
|
| 347 |
self.inventory.add_host(hostname) |
| 348 |
self.display.vvvv(f"Added host {host['name']} hostname {hostname}\n") |
| 349 |
|
| 350 |
# Add host to profile group |
| 351 |
if host["profile"] != "": |
| 352 |
group_name = self._add_safe_group_name(host["profile"], child=hostname) |
| 353 |
self.display.vvvv(f"Added host {hostname} to profile group {group_name}\n") |
| 354 |
else: |
| 355 |
self.display.warning(f"Host {hostname} has an empty profile\n") |
| 356 |
|
| 357 |
# Add host to groups specified by group_by fields |
| 358 |
for group_by in self.group_by: |
| 359 |
if host[group_by] == "<<inherit>>" or host[group_by] == "": |
| 360 |
groups = [] |
| 361 |
else: |
| 362 |
groups = [host[group_by]] if isinstance(host[group_by], str) else host[group_by] |
| 363 |
for group in groups: |
| 364 |
group_name = self._add_safe_group_name(group, child=hostname) |
| 365 |
self.display.vvvv(f"Added host {hostname} to group_by {group_by} group {group_name}\n") |
| 366 |
|
| 367 |
# Add to group for this inventory |
| 368 |
if self.group is not None: |
| 369 |
self.inventory.add_child(self.group, hostname) |
| 370 |
|
| 371 |
# Add host variables |
| 372 |
ip_address = None |
| 373 |
ip_address_first = None |
| 374 |
ipv6_address = None |
| 375 |
ipv6_address_first = None |
| 376 |
for ivalue in interfaces.values(): |
| 377 |
# Set to first interface or management interface if defined or hostname matches dns_name |
| 378 |
if ivalue["ip_address"] != "": |
| 379 |
if ip_address_first is None: |
| 380 |
ip_address_first = ivalue["ip_address"] |
| 381 |
if ivalue["management"]: |
| 382 |
ip_address = ivalue["ip_address"] |
| 383 |
elif ivalue["dns_name"] == hostname and ip_address is None: |
| 384 |
ip_address = ivalue["ip_address"] |
| 385 |
if ivalue["ipv6_address"] != "": |
| 386 |
if ipv6_address_first is None: |
| 387 |
ipv6_address_first = ivalue["ipv6_address"] |
| 388 |
if ivalue["management"]: |
| 389 |
ipv6_address = ivalue["ipv6_address"] |
| 390 |
elif ivalue["dns_name"] == hostname and ipv6_address is None: |
| 391 |
ipv6_address = ivalue["ipv6_address"] |
| 392 |
|
| 393 |
# Collect all interface name mappings for adding to group vars |
| 394 |
if self.get_option("want_ip_addresses"): |
| 395 |
if ivalue["dns_name"] != "": |
| 396 |
if ivalue["ip_address"] != "": |
| 397 |
ip_addresses[ivalue["dns_name"]] = ivalue["ip_address"] |
| 398 |
if ivalue["ipv6_address"] != "": |
| 399 |
ip_addresses[ivalue["dns_name"]] = ivalue["ipv6_address"] |
| 400 |
|
| 401 |
# Add ip_address to host if defined, use first if no management or matched dns_name |
| 402 |
if ip_address is None and ip_address_first is not None: |
| 403 |
ip_address = ip_address_first |
| 404 |
if ip_address is not None: |
| 405 |
self.inventory.set_variable(hostname, "cobbler_ipv4_address", make_unsafe(ip_address)) |
| 406 |
if ipv6_address is None and ipv6_address_first is not None: |
| 407 |
ipv6_address = ipv6_address_first |
| 408 |
if ipv6_address is not None: |
| 409 |
self.inventory.set_variable(hostname, "cobbler_ipv6_address", make_unsafe(ipv6_address)) |
| 410 |
|
| 411 |
if self.get_option("want_facts"): |
| 412 |
try: |
| 413 |
self.inventory.set_variable(hostname, "cobbler", make_unsafe(host)) |
| 414 |
except ValueError as e: |
| 415 |
self.display.warning(f"Could not set host info for {hostname}: {e}") |
| 416 |
|
| 417 |
if self.get_option("want_ip_addresses"): |
| 418 |
self.inventory.set_variable(self.group, "cobbler_ipv4_addresses", make_unsafe(ip_addresses)) |
| 419 |
self.inventory.set_variable(self.group, "cobbler_ipv6_addresses", make_unsafe(ipv6_addresses)) |