| 1 |
# Copyright (c) 2024 Vladimir Botka <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see COPYING 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: iocage |
| 9 |
short_description: C(iocage) inventory source |
| 10 |
version_added: 10.2.0 |
| 11 |
author: |
| 12 |
- Vladimir Botka (@vbotka) |
| 13 |
requirements: |
| 14 |
- iocage >= 1.8 |
| 15 |
description: |
| 16 |
- Get inventory hosts from the C(iocage) jail manager running on O(host). |
| 17 |
- By default, O(host) is V(localhost). If O(host) is not V(localhost) it is expected that the user running Ansible on the |
| 18 |
controller can connect to the O(host) account O(user) with SSH non-interactively and execute the command C(iocage list). |
| 19 |
- Uses a configuration file as an inventory source, it must end in C(.iocage.yml) or C(.iocage.yaml). |
| 20 |
extends_documentation_fragment: |
| 21 |
- ansible.builtin.constructed |
| 22 |
- ansible.builtin.inventory_cache |
| 23 |
options: |
| 24 |
plugin: |
| 25 |
description: |
| 26 |
- The name of this plugin, it should always be set to V(community.general.iocage) for this plugin to recognize it as |
| 27 |
its own. |
| 28 |
required: true |
| 29 |
choices: ['community.general.iocage'] |
| 30 |
type: str |
| 31 |
host: |
| 32 |
description: The IP/hostname of the C(iocage) host. |
| 33 |
type: str |
| 34 |
default: localhost |
| 35 |
user: |
| 36 |
description: |
| 37 |
- C(iocage) user. It is expected that the O(user) is able to connect to the O(host) with SSH and execute the command |
| 38 |
C(iocage list). This option is not required if O(host=localhost). |
| 39 |
type: str |
| 40 |
sudo: |
| 41 |
description: |
| 42 |
- Enable execution as root. |
| 43 |
- This requires passwordless sudo of the command C(iocage list*). |
| 44 |
type: bool |
| 45 |
default: false |
| 46 |
version_added: 10.3.0 |
| 47 |
sudo_preserve_env: |
| 48 |
description: |
| 49 |
- Preserve environment if O(sudo) is enabled. |
| 50 |
- This requires C(SETENV) sudoers tag. |
| 51 |
type: bool |
| 52 |
default: false |
| 53 |
version_added: 10.3.0 |
| 54 |
get_properties: |
| 55 |
description: |
| 56 |
- Get jails' properties. Creates dictionary C(iocage_properties) for each added host. |
| 57 |
type: bool |
| 58 |
default: false |
| 59 |
env: |
| 60 |
description: |
| 61 |
- O(user)'s environment on O(host). |
| 62 |
- Enable O(sudo_preserve_env) if O(sudo) is enabled. |
| 63 |
type: dict |
| 64 |
default: {} |
| 65 |
hooks_results: |
| 66 |
description: |
| 67 |
- List of paths to the files in a jail. |
| 68 |
- Content of the files is stored in the items of the list C(iocage_hooks). |
| 69 |
- If a file is not available the item keeps the dash character C(-). |
| 70 |
- The variable C(iocage_hooks) is not created if O(hooks_results) is empty. |
| 71 |
type: list |
| 72 |
elements: path |
| 73 |
version_added: 10.4.0 |
| 74 |
inventory_hostname_tag: |
| 75 |
description: |
| 76 |
- The name of the tag in the C(iocage properties notes) that contains the jails alias. |
| 77 |
- By default, the C(iocage list -l) column C(NAME) is used to name the jail. |
| 78 |
- This option requires the notes format C("t1=v1 t2=v2 ..."). |
| 79 |
- The option O(get_properties) must be enabled. |
| 80 |
type: str |
| 81 |
version_added: 11.0.0 |
| 82 |
inventory_hostname_required: |
| 83 |
description: |
| 84 |
- If enabled, the tag declared in O(inventory_hostname_tag) is required. |
| 85 |
type: bool |
| 86 |
default: false |
| 87 |
version_added: 11.0.0 |
| 88 |
notes: |
| 89 |
- You might want to test the command C(ssh user@host iocage list -l) on the controller before using this inventory plugin |
| 90 |
with O(user) specified and with O(host) other than V(localhost). |
| 91 |
- If you run this inventory plugin on V(localhost) C(ssh) is not used. In this case, test the command C(iocage list -l). |
| 92 |
- This inventory plugin creates variables C(iocage_*) for each added host. |
| 93 |
- The values of these variables are collected from the output of the command C(iocage list -l). |
| 94 |
- The names of these variables correspond to the output columns. |
| 95 |
- The column C(NAME) is used to name the added host. |
| 96 |
- The option O(hooks_results) expects the C(poolname) of a jail is mounted to C(/poolname). For example, if you activate |
| 97 |
the pool C(iocage) this plugin expects to find the O(hooks_results) items in the path C(/iocage/iocage/jails/<name>/root). |
| 98 |
If you mount the C(poolname) to a different path the easiest remedy is to create a symlink. |
| 99 |
""" |
| 100 |
|
| 101 |
EXAMPLES = r""" |
| 102 |
--- |
| 103 |
# file name must end with iocage.yaml or iocage.yml |
| 104 |
plugin: community.general.iocage |
| 105 |
host: 10.1.0.73 |
| 106 |
user: admin |
| 107 |
|
| 108 |
--- |
| 109 |
# user is not required if iocage is running on localhost (default) |
| 110 |
plugin: community.general.iocage |
| 111 |
|
| 112 |
--- |
| 113 |
# run cryptography without legacy algorithms |
| 114 |
plugin: community.general.iocage |
| 115 |
host: 10.1.0.73 |
| 116 |
user: admin |
| 117 |
env: |
| 118 |
CRYPTOGRAPHY_OPENSSL_NO_LEGACY: 1 |
| 119 |
|
| 120 |
--- |
| 121 |
# execute as root |
| 122 |
# sudoers example 'admin ALL=(ALL) NOPASSWD:SETENV: /usr/local/bin/iocage list*' |
| 123 |
plugin: community.general.iocage |
| 124 |
host: 10.1.0.73 |
| 125 |
user: admin |
| 126 |
sudo: true |
| 127 |
sudo_preserve_env: true |
| 128 |
env: |
| 129 |
CRYPTOGRAPHY_OPENSSL_NO_LEGACY: 1 |
| 130 |
|
| 131 |
--- |
| 132 |
# enable cache |
| 133 |
plugin: community.general.iocage |
| 134 |
host: 10.1.0.73 |
| 135 |
user: admin |
| 136 |
env: |
| 137 |
CRYPTOGRAPHY_OPENSSL_NO_LEGACY: 1 |
| 138 |
cache: true |
| 139 |
|
| 140 |
--- |
| 141 |
# see inventory plugin ansible.builtin.constructed |
| 142 |
plugin: community.general.iocage |
| 143 |
host: 10.1.0.73 |
| 144 |
user: admin |
| 145 |
env: |
| 146 |
CRYPTOGRAPHY_OPENSSL_NO_LEGACY: 1 |
| 147 |
cache: true |
| 148 |
strict: false |
| 149 |
compose: |
| 150 |
ansible_host: iocage_ip4 |
| 151 |
release: iocage_release | split('-') | first |
| 152 |
groups: |
| 153 |
test: inventory_hostname.startswith('test') |
| 154 |
keyed_groups: |
| 155 |
- prefix: distro |
| 156 |
key: iocage_release |
| 157 |
- prefix: state |
| 158 |
key: iocage_state |
| 159 |
|
| 160 |
--- |
| 161 |
# Read the file /var/db/dhclient-hook.address.epair0b in the jails and use it as ansible_host |
| 162 |
plugin: community.general.iocage |
| 163 |
host: 10.1.0.73 |
| 164 |
user: admin |
| 165 |
hooks_results: |
| 166 |
- /var/db/dhclient-hook.address.epair0b |
| 167 |
compose: |
| 168 |
ansible_host: iocage_hooks.0 |
| 169 |
groups: |
| 170 |
test: inventory_hostname.startswith('test') |
| 171 |
""" |
| 172 |
|
| 173 |
import os |
| 174 |
import re |
| 175 |
from subprocess import PIPE, Popen |
| 176 |
|
| 177 |
from ansible.errors import AnsibleError, AnsibleParserError |
| 178 |
from ansible.module_utils.common.text.converters import to_native, to_text |
| 179 |
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable |
| 180 |
from ansible.utils.display import Display |
| 181 |
|
| 182 |
display = Display() |
| 183 |
|
| 184 |
|
| 185 |
def _parse_ip4(ip4): |
| 186 |
"""Return dictionary iocage_ip4_dict. default = {ip4: [], msg: ''}. |
| 187 |
If item matches ifc|IP or ifc|CIDR parse ifc, ip, and mask. |
| 188 |
Otherwise, append item to msg. |
| 189 |
""" |
| 190 |
|
| 191 |
iocage_ip4_dict = {} |
| 192 |
iocage_ip4_dict["ip4"] = [] |
| 193 |
iocage_ip4_dict["msg"] = "" |
| 194 |
|
| 195 |
items = ip4.split(",") |
| 196 |
for item in items: |
| 197 |
if re.match("^\\w+\\|(?:\\d{1,3}\\.){3}\\d{1,3}.*$", item): |
| 198 |
i = re.split("\\||/", item) |
| 199 |
if len(i) == 3: |
| 200 |
iocage_ip4_dict["ip4"].append({"ifc": i[0], "ip": i[1], "mask": i[2]}) |
| 201 |
else: |
| 202 |
iocage_ip4_dict["ip4"].append({"ifc": i[0], "ip": i[1], "mask": "-"}) |
| 203 |
else: |
| 204 |
iocage_ip4_dict["msg"] += item |
| 205 |
|
| 206 |
return iocage_ip4_dict |
| 207 |
|
| 208 |
|
| 209 |
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): |
| 210 |
"""Host inventory parser for ansible using iocage as source.""" |
| 211 |
|
| 212 |
NAME = "community.general.iocage" |
| 213 |
IOCAGE = "/usr/local/bin/iocage" |
| 214 |
|
| 215 |
def __init__(self): |
| 216 |
super().__init__() |
| 217 |
|
| 218 |
def verify_file(self, path): |
| 219 |
valid = False |
| 220 |
if super().verify_file(path): |
| 221 |
if path.endswith(("iocage.yaml", "iocage.yml")): |
| 222 |
valid = True |
| 223 |
else: |
| 224 |
self.display.vvv('Skipping due to inventory source not ending in "iocage.yaml" nor "iocage.yml"') |
| 225 |
return valid |
| 226 |
|
| 227 |
def parse(self, inventory, loader, path, cache=True): |
| 228 |
super().parse(inventory, loader, path) |
| 229 |
|
| 230 |
self._read_config_data(path) |
| 231 |
cache_key = self.get_cache_key(path) |
| 232 |
|
| 233 |
user_cache_setting = self.get_option("cache") |
| 234 |
attempt_to_read_cache = user_cache_setting and cache |
| 235 |
cache_needs_update = user_cache_setting and not cache |
| 236 |
|
| 237 |
if attempt_to_read_cache: |
| 238 |
try: |
| 239 |
results = self._cache[cache_key] |
| 240 |
except KeyError: |
| 241 |
cache_needs_update = True |
| 242 |
if not attempt_to_read_cache or cache_needs_update: |
| 243 |
results = self.get_inventory(path) |
| 244 |
if cache_needs_update: |
| 245 |
self._cache[cache_key] = results |
| 246 |
|
| 247 |
self.populate(results) |
| 248 |
|
| 249 |
def get_inventory(self, path): |
| 250 |
host = self.get_option("host") |
| 251 |
sudo = self.get_option("sudo") |
| 252 |
sudo_preserve_env = self.get_option("sudo_preserve_env") |
| 253 |
env = self.get_option("env") |
| 254 |
get_properties = self.get_option("get_properties") |
| 255 |
hooks_results = self.get_option("hooks_results") |
| 256 |
inventory_hostname_tag = self.get_option("inventory_hostname_tag") |
| 257 |
inventory_hostname_required = self.get_option("inventory_hostname_required") |
| 258 |
|
| 259 |
cmd = [] |
| 260 |
my_env = os.environ.copy() |
| 261 |
if host == "localhost": |
| 262 |
my_env.update({str(k): str(v) for k, v in env.items()}) |
| 263 |
else: |
| 264 |
user = self.get_option("user") |
| 265 |
cmd.append("ssh") |
| 266 |
cmd.append(f"{user}@{host}") |
| 267 |
cmd.extend([f"{k}={v}" for k, v in env.items()]) |
| 268 |
|
| 269 |
cmd_list = cmd.copy() |
| 270 |
if sudo: |
| 271 |
cmd_list.append("sudo") |
| 272 |
if sudo_preserve_env: |
| 273 |
cmd_list.append("--preserve-env") |
| 274 |
cmd_list.append(self.IOCAGE) |
| 275 |
cmd_list.append("list") |
| 276 |
cmd_list.append("--long") |
| 277 |
try: |
| 278 |
p = Popen(cmd_list, stdout=PIPE, stderr=PIPE, env=my_env) |
| 279 |
stdout, stderr = p.communicate() |
| 280 |
if p.returncode != 0: |
| 281 |
raise AnsibleError(f"Failed to run cmd={cmd_list}, rc={p.returncode}, stderr={to_native(stderr)}") |
| 282 |
|
| 283 |
try: |
| 284 |
t_stdout = to_text(stdout, errors="surrogate_or_strict") |
| 285 |
except UnicodeError as e: |
| 286 |
raise AnsibleError(f"Invalid (non unicode) input returned: {e}") from e |
| 287 |
|
| 288 |
except Exception as e: |
| 289 |
raise AnsibleParserError(f"Failed to parse {to_native(path)}: {e}") from e |
| 290 |
|
| 291 |
results = {"_meta": {"hostvars": {}}} |
| 292 |
self.get_jails(t_stdout, results) |
| 293 |
|
| 294 |
if get_properties: |
| 295 |
for hostname in results["_meta"]["hostvars"]: |
| 296 |
cmd_get_properties = cmd.copy() |
| 297 |
cmd_get_properties.append(self.IOCAGE) |
| 298 |
cmd_get_properties.append("get") |
| 299 |
cmd_get_properties.append("--all") |
| 300 |
cmd_get_properties.append(f"{hostname}") |
| 301 |
try: |
| 302 |
p = Popen(cmd_get_properties, stdout=PIPE, stderr=PIPE, env=my_env) |
| 303 |
stdout, stderr = p.communicate() |
| 304 |
if p.returncode != 0: |
| 305 |
raise AnsibleError( |
| 306 |
f"Failed to run cmd={cmd_get_properties}, rc={p.returncode}, stderr={to_native(stderr)}" |
| 307 |
) |
| 308 |
|
| 309 |
try: |
| 310 |
t_stdout = to_text(stdout, errors="surrogate_or_strict") |
| 311 |
except UnicodeError as e: |
| 312 |
raise AnsibleError(f"Invalid (non unicode) input returned: {e}") from e |
| 313 |
|
| 314 |
except Exception as e: |
| 315 |
raise AnsibleError(f"Failed to get properties: {e}") from e |
| 316 |
|
| 317 |
self.get_properties(t_stdout, results, hostname) |
| 318 |
|
| 319 |
if hooks_results: |
| 320 |
cmd_get_pool = cmd.copy() |
| 321 |
cmd_get_pool.append(self.IOCAGE) |
| 322 |
cmd_get_pool.append("get") |
| 323 |
cmd_get_pool.append("--pool") |
| 324 |
try: |
| 325 |
p = Popen(cmd_get_pool, stdout=PIPE, stderr=PIPE, env=my_env) |
| 326 |
stdout, stderr = p.communicate() |
| 327 |
if p.returncode != 0: |
| 328 |
raise AnsibleError( |
| 329 |
f"Failed to run cmd={cmd_get_pool}, rc={p.returncode}, stderr={to_native(stderr)}" |
| 330 |
) |
| 331 |
try: |
| 332 |
iocage_pool = to_text(stdout, errors="surrogate_or_strict").strip() |
| 333 |
except UnicodeError as e: |
| 334 |
raise AnsibleError(f"Invalid (non unicode) input returned: {e}") from e |
| 335 |
except Exception as e: |
| 336 |
raise AnsibleError(f"Failed to get pool: {e}") from e |
| 337 |
|
| 338 |
for hostname in results["_meta"]["hostvars"]: |
| 339 |
iocage_hooks = [] |
| 340 |
for hook in hooks_results: |
| 341 |
path = f"/{iocage_pool}/iocage/jails/{hostname}/root{hook}" |
| 342 |
cmd_cat_hook = cmd.copy() |
| 343 |
cmd_cat_hook.append("cat") |
| 344 |
cmd_cat_hook.append(path) |
| 345 |
try: |
| 346 |
p = Popen(cmd_cat_hook, stdout=PIPE, stderr=PIPE, env=my_env) |
| 347 |
stdout, stderr = p.communicate() |
| 348 |
if p.returncode != 0: |
| 349 |
iocage_hooks.append("-") |
| 350 |
continue |
| 351 |
|
| 352 |
try: |
| 353 |
iocage_hook = to_text(stdout, errors="surrogate_or_strict").strip() |
| 354 |
except UnicodeError as e: |
| 355 |
raise AnsibleError(f"Invalid (non unicode) input returned: {e}") from e |
| 356 |
|
| 357 |
except Exception: |
| 358 |
iocage_hooks.append("-") |
| 359 |
else: |
| 360 |
iocage_hooks.append(iocage_hook) |
| 361 |
|
| 362 |
results["_meta"]["hostvars"][hostname]["iocage_hooks"] = iocage_hooks |
| 363 |
|
| 364 |
# Optionally, get the jails names from the properties notes. |
| 365 |
# Requires the notes format "t1=v1 t2=v2 ..." |
| 366 |
if inventory_hostname_tag: |
| 367 |
if not get_properties: |
| 368 |
raise AnsibleError("Jail properties are needed to use inventory_hostname_tag. Enable get_properties") |
| 369 |
update = {} |
| 370 |
for hostname, host_vars in results["_meta"]["hostvars"].items(): |
| 371 |
tags = dict(tag.split("=", 1) for tag in host_vars["iocage_properties"]["notes"].split() if "=" in tag) |
| 372 |
if inventory_hostname_tag in tags: |
| 373 |
update[hostname] = tags[inventory_hostname_tag] |
| 374 |
elif inventory_hostname_required: |
| 375 |
raise AnsibleError(f"Mandatory tag {inventory_hostname_tag!r} is missing in the properties notes.") |
| 376 |
for hostname, alias in update.items(): |
| 377 |
results["_meta"]["hostvars"][alias] = results["_meta"]["hostvars"].pop(hostname) |
| 378 |
|
| 379 |
return results |
| 380 |
|
| 381 |
def get_jails(self, t_stdout, results): |
| 382 |
lines = t_stdout.splitlines() |
| 383 |
if len(lines) < 5: |
| 384 |
return |
| 385 |
indices = [i for i, val in enumerate(lines[1]) if val == "|"] |
| 386 |
for line in lines[3::2]: |
| 387 |
jail = [line[i + 1 : j].strip() for i, j in zip(indices[:-1], indices[1:])] |
| 388 |
iocage_name = jail[1] |
| 389 |
iocage_ip4_dict = _parse_ip4(jail[6]) |
| 390 |
if iocage_ip4_dict["ip4"]: |
| 391 |
iocage_ip4 = ",".join([d["ip"] for d in iocage_ip4_dict["ip4"]]) |
| 392 |
else: |
| 393 |
iocage_ip4 = "-" |
| 394 |
results["_meta"]["hostvars"][iocage_name] = {} |
| 395 |
results["_meta"]["hostvars"][iocage_name]["iocage_jid"] = jail[0] |
| 396 |
results["_meta"]["hostvars"][iocage_name]["iocage_boot"] = jail[2] |
| 397 |
results["_meta"]["hostvars"][iocage_name]["iocage_state"] = jail[3] |
| 398 |
results["_meta"]["hostvars"][iocage_name]["iocage_type"] = jail[4] |
| 399 |
results["_meta"]["hostvars"][iocage_name]["iocage_release"] = jail[5] |
| 400 |
results["_meta"]["hostvars"][iocage_name]["iocage_ip4_dict"] = iocage_ip4_dict |
| 401 |
results["_meta"]["hostvars"][iocage_name]["iocage_ip4"] = iocage_ip4 |
| 402 |
results["_meta"]["hostvars"][iocage_name]["iocage_ip6"] = jail[7] |
| 403 |
results["_meta"]["hostvars"][iocage_name]["iocage_template"] = jail[8] |
| 404 |
results["_meta"]["hostvars"][iocage_name]["iocage_basejail"] = jail[9] |
| 405 |
|
| 406 |
def get_properties(self, t_stdout, results, hostname): |
| 407 |
properties = dict(x.split(":", 1) for x in t_stdout.splitlines()) |
| 408 |
results["_meta"]["hostvars"][hostname]["iocage_properties"] = properties |
| 409 |
|
| 410 |
def populate(self, results): |
| 411 |
strict = self.get_option("strict") |
| 412 |
|
| 413 |
for hostname, host_vars in results["_meta"]["hostvars"].items(): |
| 414 |
self.inventory.add_host(hostname, group="all") |
| 415 |
for var, value in host_vars.items(): |
| 416 |
self.inventory.set_variable(hostname, var, value) |
| 417 |
self._set_composite_vars(self.get_option("compose"), host_vars, hostname, strict=True) |
| 418 |
self._add_host_to_composed_groups(self.get_option("groups"), host_vars, hostname, strict=strict) |
| 419 |
self._add_host_to_keyed_groups(self.get_option("keyed_groups"), host_vars, hostname, strict=strict) |