| 1 |
# Copyright (c) 2017 Ansible Project |
| 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 |
author: Unknown (!UNKNOWN) |
| 9 |
name: virtualbox |
| 10 |
short_description: Virtualbox inventory source |
| 11 |
description: |
| 12 |
- Get inventory hosts from the local virtualbox installation. |
| 13 |
- Uses a YAML configuration file that ends with virtualbox.(yml|yaml) or vbox.(yml|yaml). |
| 14 |
- The inventory_hostname is always the 'Name' of the virtualbox instance. |
| 15 |
- Groups can be assigned to the VMs using C(VBoxManage). Multiple groups can be assigned by using V(/) as a delimeter. |
| 16 |
- A separate parameter, O(enable_advanced_group_parsing) is exposed to change grouping behaviour. See the parameter documentation |
| 17 |
for details. |
| 18 |
extends_documentation_fragment: |
| 19 |
- ansible.builtin.constructed |
| 20 |
- ansible.builtin.inventory_cache |
| 21 |
options: |
| 22 |
plugin: |
| 23 |
description: Token that ensures this is a source file for the P(community.general.virtualbox#inventory) plugin. |
| 24 |
type: string |
| 25 |
required: true |
| 26 |
choices: ['virtualbox', 'community.general.virtualbox'] |
| 27 |
running_only: |
| 28 |
description: Toggles showing all VMs instead of only those currently running. |
| 29 |
type: boolean |
| 30 |
default: false |
| 31 |
settings_password_file: |
| 32 |
description: Provide a file containing the settings password (equivalent to C(--settingspwfile)). |
| 33 |
type: string |
| 34 |
network_info_path: |
| 35 |
description: Property path to query for network information (C(ansible_host)). |
| 36 |
type: string |
| 37 |
default: "/VirtualBox/GuestInfo/Net/0/V4/IP" |
| 38 |
query: |
| 39 |
description: Create vars from virtualbox properties. |
| 40 |
type: dictionary |
| 41 |
default: {} |
| 42 |
enable_advanced_group_parsing: |
| 43 |
description: |
| 44 |
- The default group parsing rule (when this setting is set to V(false)) is to split the VirtualBox VM's group based |
| 45 |
on the V(/) character and assign the resulting list elements as an Ansible Group. |
| 46 |
- Setting O(enable_advanced_group_parsing=true) changes this behaviour to match VirtualBox's interpretation of groups |
| 47 |
according to U(https://www.virtualbox.org/manual/UserManual.html#gui-vmgroups). Groups are now split using the V(,) |
| 48 |
character, and the V(/) character indicates nested groups. |
| 49 |
- When enabled, a VM that's been configured using V(VBoxManage modifyvm "vm01" --groups "/TestGroup/TestGroup2,/TestGroup3") |
| 50 |
results in the group C(TestGroup2) being a child group of C(TestGroup); and the VM being a part of C(TestGroup2) |
| 51 |
and C(TestGroup3). |
| 52 |
default: false |
| 53 |
type: bool |
| 54 |
version_added: 9.2.0 |
| 55 |
""" |
| 56 |
|
| 57 |
EXAMPLES = r""" |
| 58 |
--- |
| 59 |
# file must be named vbox.yaml or vbox.yml |
| 60 |
plugin: community.general.virtualbox |
| 61 |
settings_password_file: /etc/virtualbox/secrets |
| 62 |
query: |
| 63 |
logged_in_users: /VirtualBox/GuestInfo/OS/LoggedInUsersList |
| 64 |
compose: |
| 65 |
ansible_connection: ('indows' in vbox_Guest_OS)|ternary('winrm', 'ssh') |
| 66 |
|
| 67 |
--- |
| 68 |
# add hosts (all match with minishift vm) to the group container if any of the vms are in ansible_inventory' |
| 69 |
plugin: community.general.virtualbox |
| 70 |
groups: |
| 71 |
container: "'minis' in (inventory_hostname)" |
| 72 |
""" |
| 73 |
|
| 74 |
import os |
| 75 |
from collections.abc import MutableMapping |
| 76 |
from subprocess import PIPE, Popen |
| 77 |
|
| 78 |
from ansible.errors import AnsibleParserError |
| 79 |
from ansible.module_utils.common.process import get_bin_path |
| 80 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 81 |
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable |
| 82 |
|
| 83 |
from ansible_collections.community.general.plugins.plugin_utils._unsafe import make_unsafe |
| 84 |
|
| 85 |
|
| 86 |
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): |
| 87 |
"""Host inventory parser for ansible using local virtualbox.""" |
| 88 |
|
| 89 |
NAME = "community.general.virtualbox" |
| 90 |
VBOX = "VBoxManage" |
| 91 |
|
| 92 |
def __init__(self): |
| 93 |
self._vbox_path = None |
| 94 |
super().__init__() |
| 95 |
|
| 96 |
def _query_vbox_data(self, host, property_path): |
| 97 |
ret = None |
| 98 |
try: |
| 99 |
cmd = [ |
| 100 |
self._vbox_path, |
| 101 |
b"guestproperty", |
| 102 |
b"get", |
| 103 |
to_bytes(host, errors="surrogate_or_strict"), |
| 104 |
to_bytes(property_path, errors="surrogate_or_strict"), |
| 105 |
] |
| 106 |
x = Popen(cmd, stdout=PIPE) |
| 107 |
ipinfo = to_text(x.stdout.read(), errors="surrogate_or_strict") |
| 108 |
if "Value" in ipinfo: |
| 109 |
a, ip = ipinfo.split(":", 1) |
| 110 |
ret = ip.strip() |
| 111 |
except Exception: |
| 112 |
pass |
| 113 |
return ret |
| 114 |
|
| 115 |
def _set_variables(self, hostvars): |
| 116 |
# set vars in inventory from hostvars |
| 117 |
for host in hostvars: |
| 118 |
query = self.get_option("query") |
| 119 |
# create vars from vbox properties |
| 120 |
if query and isinstance(query, MutableMapping): |
| 121 |
for varname in query: |
| 122 |
hostvars[host][varname] = self._query_vbox_data(host, query[varname]) |
| 123 |
|
| 124 |
strict = self.get_option("strict") |
| 125 |
|
| 126 |
# create composite vars |
| 127 |
self._set_composite_vars(self.get_option("compose"), hostvars[host], host, strict=strict) |
| 128 |
|
| 129 |
# actually update inventory |
| 130 |
for key in hostvars[host]: |
| 131 |
self.inventory.set_variable(host, key, hostvars[host][key]) |
| 132 |
|
| 133 |
# constructed groups based on conditionals |
| 134 |
self._add_host_to_composed_groups(self.get_option("groups"), hostvars[host], host, strict=strict) |
| 135 |
|
| 136 |
# constructed keyed_groups |
| 137 |
self._add_host_to_keyed_groups(self.get_option("keyed_groups"), hostvars[host], host, strict=strict) |
| 138 |
|
| 139 |
def _populate_from_cache(self, source_data): |
| 140 |
source_data = make_unsafe(source_data) |
| 141 |
hostvars = source_data.pop("_meta", {}).get("hostvars", {}) |
| 142 |
for group in source_data: |
| 143 |
if group == "all": |
| 144 |
continue |
| 145 |
else: |
| 146 |
group = self.inventory.add_group(group) |
| 147 |
hosts = source_data[group].get("hosts", []) |
| 148 |
for host in hosts: |
| 149 |
self._populate_host_vars([host], hostvars.get(host, {}), group) |
| 150 |
self.inventory.add_child("all", group) |
| 151 |
if not source_data: |
| 152 |
for host in hostvars: |
| 153 |
self.inventory.add_host(host) |
| 154 |
self._populate_host_vars([host], hostvars.get(host, {})) |
| 155 |
|
| 156 |
def _populate_from_source(self, source_data, using_current_cache=False): |
| 157 |
if using_current_cache: |
| 158 |
self._populate_from_cache(source_data) |
| 159 |
return source_data |
| 160 |
|
| 161 |
cacheable_results = {"_meta": {"hostvars": {}}} |
| 162 |
|
| 163 |
hostvars = {} |
| 164 |
prevkey = pref_k = "" |
| 165 |
current_host = None |
| 166 |
|
| 167 |
# needed to possibly set ansible_host |
| 168 |
netinfo = self.get_option("network_info_path") |
| 169 |
|
| 170 |
for line in source_data: |
| 171 |
line = to_text(line) |
| 172 |
if ":" not in line: |
| 173 |
continue |
| 174 |
try: |
| 175 |
k, v = line.split(":", 1) |
| 176 |
except Exception: |
| 177 |
# skip non splitable |
| 178 |
continue |
| 179 |
|
| 180 |
if k.strip() == "": |
| 181 |
# skip empty |
| 182 |
continue |
| 183 |
|
| 184 |
v = v.strip() |
| 185 |
# found host |
| 186 |
if k.startswith("Name") and "," not in v: # some setting strings appear in Name |
| 187 |
current_host = make_unsafe(v) |
| 188 |
if current_host not in hostvars: |
| 189 |
hostvars[current_host] = {} |
| 190 |
self.inventory.add_host(current_host) |
| 191 |
|
| 192 |
# try to get network info |
| 193 |
netdata = self._query_vbox_data(current_host, netinfo) |
| 194 |
if netdata: |
| 195 |
self.inventory.set_variable(current_host, "ansible_host", make_unsafe(netdata)) |
| 196 |
|
| 197 |
# found groups |
| 198 |
elif k == "Groups": |
| 199 |
if self.get_option("enable_advanced_group_parsing"): |
| 200 |
self._handle_vboxmanage_group_string(v, current_host, cacheable_results) |
| 201 |
else: |
| 202 |
self._handle_group_string(v, current_host, cacheable_results) |
| 203 |
continue |
| 204 |
|
| 205 |
else: |
| 206 |
# found vars, accumulate in hostvars for clean inventory set |
| 207 |
pref_k = make_unsafe(f"vbox_{k.strip().replace(' ', '_')}") |
| 208 |
leading_spaces = len(k) - len(k.lstrip(" ")) |
| 209 |
if 0 < leading_spaces <= 2: |
| 210 |
if prevkey not in hostvars[current_host] or not isinstance(hostvars[current_host][prevkey], dict): |
| 211 |
hostvars[current_host][prevkey] = {} |
| 212 |
hostvars[current_host][prevkey][pref_k] = make_unsafe(v) |
| 213 |
elif leading_spaces > 2: |
| 214 |
continue |
| 215 |
else: |
| 216 |
if v != "": |
| 217 |
hostvars[current_host][pref_k] = make_unsafe(v) |
| 218 |
if self._ungrouped_host(current_host, cacheable_results): |
| 219 |
if "ungrouped" not in cacheable_results: |
| 220 |
cacheable_results["ungrouped"] = {"hosts": []} |
| 221 |
cacheable_results["ungrouped"]["hosts"].append(current_host) |
| 222 |
|
| 223 |
prevkey = pref_k |
| 224 |
|
| 225 |
self._set_variables(hostvars) |
| 226 |
for host in hostvars: |
| 227 |
h = self.inventory.get_host(host) |
| 228 |
cacheable_results["_meta"]["hostvars"][h.name] = h.vars |
| 229 |
|
| 230 |
return cacheable_results |
| 231 |
|
| 232 |
def _ungrouped_host(self, host, inventory): |
| 233 |
def find_host(host, inventory): |
| 234 |
for k, v in inventory.items(): |
| 235 |
if k == "_meta": |
| 236 |
continue |
| 237 |
if isinstance(v, dict): |
| 238 |
yield self._ungrouped_host(host, v) |
| 239 |
elif isinstance(v, list): |
| 240 |
yield host not in v |
| 241 |
yield True |
| 242 |
|
| 243 |
return all(find_host(host, inventory)) |
| 244 |
|
| 245 |
def _handle_group_string(self, vboxmanage_group, current_host, cacheable_results): |
| 246 |
"""Handles parsing the VM's Group assignment from VBoxManage according to this inventory's initial implementation.""" |
| 247 |
# The original implementation of this inventory plugin treated `/` as |
| 248 |
# a delimeter to split and use as Ansible Groups. |
| 249 |
for group in vboxmanage_group.split("/"): |
| 250 |
if group: |
| 251 |
group = make_unsafe(group) |
| 252 |
group = self.inventory.add_group(group) |
| 253 |
self.inventory.add_child(group, current_host) |
| 254 |
if group not in cacheable_results: |
| 255 |
cacheable_results[group] = {"hosts": []} |
| 256 |
cacheable_results[group]["hosts"].append(current_host) |
| 257 |
|
| 258 |
def _handle_vboxmanage_group_string(self, vboxmanage_group, current_host, cacheable_results): |
| 259 |
"""Handles parsing the VM's Group assignment from VBoxManage according to VirtualBox documentation.""" |
| 260 |
# Per the VirtualBox documentation, a VM can be part of many groups, |
| 261 |
# and it is possible to have nested groups. |
| 262 |
# Many groups are separated by commas ",", and nested groups use |
| 263 |
# slash "/". |
| 264 |
# https://www.virtualbox.org/manual/UserManual.html#gui-vmgroups |
| 265 |
# Multi groups: VBoxManage modifyvm "vm01" --groups "/TestGroup,/TestGroup2" |
| 266 |
# Nested groups: VBoxManage modifyvm "vm01" --groups "/TestGroup/TestGroup2" |
| 267 |
|
| 268 |
for group in vboxmanage_group.split(","): |
| 269 |
if not group: |
| 270 |
# We could get an empty element due how to split works, and |
| 271 |
# possible assignments from VirtualBox. e.g. ,/Group1 |
| 272 |
continue |
| 273 |
|
| 274 |
if group == "/": |
| 275 |
# This is the "root" group. We get here if the VM was not |
| 276 |
# assigned to a particular group. Consider the host to be |
| 277 |
# unassigned to a group. |
| 278 |
continue |
| 279 |
|
| 280 |
parent_group = None |
| 281 |
for subgroup in group.split("/"): |
| 282 |
if not subgroup: |
| 283 |
# Similarly to above, we could get an empty element. |
| 284 |
# e.g //Group1 |
| 285 |
continue |
| 286 |
|
| 287 |
if subgroup == "/": |
| 288 |
# "root" group. |
| 289 |
# Consider the host to be unassigned |
| 290 |
continue |
| 291 |
|
| 292 |
subgroup = make_unsafe(subgroup) |
| 293 |
subgroup = self.inventory.add_group(subgroup) |
| 294 |
if parent_group is not None: |
| 295 |
self.inventory.add_child(parent_group, subgroup) |
| 296 |
self.inventory.add_child(subgroup, current_host) |
| 297 |
if subgroup not in cacheable_results: |
| 298 |
cacheable_results[subgroup] = {"hosts": []} |
| 299 |
cacheable_results[subgroup]["hosts"].append(current_host) |
| 300 |
|
| 301 |
parent_group = subgroup |
| 302 |
|
| 303 |
def verify_file(self, path): |
| 304 |
valid = False |
| 305 |
if super().verify_file(path): |
| 306 |
if path.endswith(("virtualbox.yaml", "virtualbox.yml", "vbox.yaml", "vbox.yml")): |
| 307 |
valid = True |
| 308 |
return valid |
| 309 |
|
| 310 |
def parse(self, inventory, loader, path, cache=True): |
| 311 |
try: |
| 312 |
self._vbox_path = get_bin_path(self.VBOX) |
| 313 |
except ValueError as e: |
| 314 |
raise AnsibleParserError(e) from e |
| 315 |
|
| 316 |
super().parse(inventory, loader, path) |
| 317 |
|
| 318 |
cache_key = self.get_cache_key(path) |
| 319 |
|
| 320 |
config_data = self._read_config_data(path) |
| 321 |
|
| 322 |
# set _options from config data |
| 323 |
self._consume_options(config_data) |
| 324 |
|
| 325 |
source_data = None |
| 326 |
if cache: |
| 327 |
cache = self.get_option("cache") |
| 328 |
|
| 329 |
update_cache = False |
| 330 |
if cache: |
| 331 |
try: |
| 332 |
source_data = self._cache[cache_key] |
| 333 |
except KeyError: |
| 334 |
update_cache = True |
| 335 |
|
| 336 |
if not source_data: |
| 337 |
b_pwfile = to_bytes( |
| 338 |
self.get_option("settings_password_file"), errors="surrogate_or_strict", nonstring="passthru" |
| 339 |
) |
| 340 |
running = self.get_option("running_only") |
| 341 |
|
| 342 |
# start getting data |
| 343 |
cmd = [self._vbox_path, b"list", b"-l"] |
| 344 |
if running: |
| 345 |
cmd.append(b"runningvms") |
| 346 |
else: |
| 347 |
cmd.append(b"vms") |
| 348 |
|
| 349 |
if b_pwfile and os.path.exists(b_pwfile): |
| 350 |
cmd.append(b"--settingspwfile") |
| 351 |
cmd.append(b_pwfile) |
| 352 |
|
| 353 |
try: |
| 354 |
p = Popen(cmd, stdout=PIPE) |
| 355 |
except Exception as e: |
| 356 |
raise AnsibleParserError(str(e)) from e |
| 357 |
|
| 358 |
source_data = p.stdout.read().splitlines() |
| 359 |
|
| 360 |
using_current_cache = cache and not update_cache |
| 361 |
cacheable_results = self._populate_from_source(source_data, using_current_cache) |
| 362 |
|
| 363 |
if update_cache: |
| 364 |
self._cache[cache_key] = cacheable_results |