| 1 |
# Copyright (C) 2016 Guido Günther <[email protected]>, Daniel Lobato Garcia <[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 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = """ |
| 8 |
name: proxmox |
| 9 |
short_description: Proxmox inventory source |
| 10 |
author: |
| 11 |
- Jeffrey van Pelt (@Thulium-Drake) <[email protected]> |
| 12 |
requirements: |
| 13 |
- requests >= 1.1 |
| 14 |
description: |
| 15 |
- Get inventory hosts from a Proxmox PVE cluster. |
| 16 |
- "Uses a configuration file as an inventory source, it must end in C(.proxmox.yml) or C(.proxmox.yaml)" |
| 17 |
- Will retrieve the first network interface with an IP for Proxmox nodes. |
| 18 |
- Can retrieve LXC/QEMU configuration as facts. |
| 19 |
extends_documentation_fragment: |
| 20 |
- constructed |
| 21 |
- inventory_cache |
| 22 |
options: |
| 23 |
plugin: |
| 24 |
description: The name of this plugin, it should always be set to V(community.proxmox.proxmox) for this plugin to recognize it as its own. |
| 25 |
required: true |
| 26 |
choices: ['community.proxmox.proxmox'] |
| 27 |
type: str |
| 28 |
url: |
| 29 |
description: |
| 30 |
- URL to Proxmox cluster. |
| 31 |
- If the value is not specified in the inventory configuration, the value of environment variable E(PROXMOX_URL) will be used instead. |
| 32 |
- You can use templating to specify the value of the O(url). |
| 33 |
default: 'http://localhost:8006' |
| 34 |
type: str |
| 35 |
env: |
| 36 |
- name: PROXMOX_URL |
| 37 |
user: |
| 38 |
description: |
| 39 |
- Proxmox authentication user. |
| 40 |
- If the value is not specified in the inventory configuration, the value of environment variable E(PROXMOX_USER) will be used instead. |
| 41 |
- You can use templating to specify the value of the O(user). |
| 42 |
required: true |
| 43 |
type: str |
| 44 |
env: |
| 45 |
- name: PROXMOX_USER |
| 46 |
password: |
| 47 |
description: |
| 48 |
- Proxmox authentication password. |
| 49 |
- If the value is not specified in the inventory configuration, the value of environment variable E(PROXMOX_PASSWORD) will be used instead. |
| 50 |
- You can use templating to specify the value of the O(password). |
| 51 |
- If you do not specify a password, you must set O(token_id) and O(token_secret) instead. |
| 52 |
type: str |
| 53 |
env: |
| 54 |
- name: PROXMOX_PASSWORD |
| 55 |
token_id: |
| 56 |
description: |
| 57 |
- Proxmox authentication token ID. |
| 58 |
- If the value is not specified in the inventory configuration, the value of environment variable E(PROXMOX_TOKEN_ID) will be used instead. |
| 59 |
- To use token authentication, you must also specify O(token_secret). If you do not specify O(token_id) and O(token_secret), |
| 60 |
you must set a password instead. |
| 61 |
- Make sure to grant explicit pve permissions to the token or disable 'privilege separation' to use the users' privileges instead. |
| 62 |
type: str |
| 63 |
env: |
| 64 |
- name: PROXMOX_TOKEN_ID |
| 65 |
token_secret: |
| 66 |
description: |
| 67 |
- Proxmox authentication token secret. |
| 68 |
- If the value is not specified in the inventory configuration, the value of environment variable E(PROXMOX_TOKEN_SECRET) will be used instead. |
| 69 |
- To use token authentication, you must also specify O(token_id). If you do not specify O(token_id) and O(token_secret), |
| 70 |
you must set a password instead. |
| 71 |
type: str |
| 72 |
env: |
| 73 |
- name: PROXMOX_TOKEN_SECRET |
| 74 |
validate_certs: |
| 75 |
description: Verify SSL certificate if using HTTPS. |
| 76 |
type: boolean |
| 77 |
default: true |
| 78 |
group_prefix: |
| 79 |
description: Prefix to apply to Proxmox groups. |
| 80 |
default: proxmox_ |
| 81 |
type: str |
| 82 |
facts_prefix: |
| 83 |
description: Prefix to apply to LXC/QEMU config facts. |
| 84 |
default: proxmox_ |
| 85 |
type: str |
| 86 |
want_facts: |
| 87 |
description: |
| 88 |
- Gather LXC/QEMU configuration facts. |
| 89 |
- When O(want_facts) is set to V(true) more details about QEMU VM status are possible, besides the running and stopped states. |
| 90 |
Currently if the VM is running and it is suspended, the status will be running and the machine will be in C(running) group, |
| 91 |
but its actual state will be paused. See O(qemu_extended_statuses) for how to retrieve the real status. |
| 92 |
default: false |
| 93 |
type: bool |
| 94 |
want_post_filter_facts: |
| 95 |
description: |
| 96 |
- Whether to collect facts after host filtering (in contrast to pull all facts of all hosts before filtering as with O(want_facts) set to V(true)). |
| 97 |
- This can be useful if you want to filter hosts based on some limited available criteria but still want to have access to all facts after filtering. |
| 98 |
- When O(want_facts) is set to V(true) facts are collected before filtering and this parameter is ignored. |
| 99 |
type: bool |
| 100 |
default: false |
| 101 |
qemu_extended_statuses: |
| 102 |
description: |
| 103 |
- Requires O(want_facts) to be set to V(true) to function. This will allow you to differentiate between C(paused) and C(prelaunch) |
| 104 |
statuses of the QEMU VMs. |
| 105 |
- This introduces multiple groups [prefixed with O(group_prefix)] C(prelaunch) and C(paused). |
| 106 |
default: false |
| 107 |
type: bool |
| 108 |
want_proxmox_nodes_ansible_host: |
| 109 |
description: |
| 110 |
- Whether to set C(ansible_host) for proxmox nodes. |
| 111 |
- When set to V(true) (default), will use the first available interface. This can be different from what you expect. |
| 112 |
type: bool |
| 113 |
default: false |
| 114 |
exclude_nodes: |
| 115 |
description: Exclude proxmox nodes and the nodes-group from the inventory output. |
| 116 |
type: bool |
| 117 |
default: false |
| 118 |
filters: |
| 119 |
description: |
| 120 |
- A list of Jinja templates that allow filtering hosts. |
| 121 |
- If strict mode is enabled, any error during host filter compositing will lead to an AnsibleError being raised, otherwise the host will be ignored. |
| 122 |
- Facts collected when O(want_facts) is set to V(true) can be used in the filters. |
| 123 |
- When O(want_facts) is set to V(false) full facts are not available and filters can only used on a limited set of facts |
| 124 |
proxmox_vmid, proxmox_name, proxmox_status, proxmox_vmtype, proxmox_tags, proxmox_template. |
| 125 |
type: list |
| 126 |
elements: str |
| 127 |
default: [] |
| 128 |
""" |
| 129 |
|
| 130 |
EXAMPLES = """ |
| 131 |
--- |
| 132 |
# Minimal example which will not gather additional facts for QEMU/LXC guests |
| 133 |
# By not specifying a URL the plugin will attempt to connect to the controller host on port 8006 |
| 134 |
# my.proxmox.yml |
| 135 |
plugin: community.proxmox.proxmox |
| 136 |
user: ansible@pve |
| 137 |
password: secure |
| 138 |
# Note that this can easily give you wrong values as ansible_host. See further below for |
| 139 |
# an example where this is set to `false` and where ansible_host is set with `compose`. |
| 140 |
want_proxmox_nodes_ansible_host: true |
| 141 |
|
| 142 |
--- |
| 143 |
# Instead of login with password, proxmox supports api token authentication since release 6.2. |
| 144 |
plugin: community.proxmox.proxmox |
| 145 |
user: ci@pve |
| 146 |
token_id: gitlab-1 |
| 147 |
token_secret: fa256e9c-26ab-41ec-82da-707a2c079829 |
| 148 |
|
| 149 |
# The secret can also be a vault string or passed via the environment variable TOKEN_SECRET. |
| 150 |
token_secret: !vault | |
| 151 |
$ANSIBLE_VAULT;1.1;AES256 |
| 152 |
62353634333163633336343265623632626339313032653563653165313262343931643431656138 |
| 153 |
6134333736323265656466646539663134306166666237630a653363623262636663333762316136 |
| 154 |
34616361326263383766366663393837626437316462313332663736623066656237386531663731 |
| 155 |
3037646432383064630a663165303564623338666131353366373630656661333437393937343331 |
| 156 |
32643131386134396336623736393634373936356332623632306561356361323737313663633633 |
| 157 |
6231313333666361656537343562333337323030623732323833 |
| 158 |
|
| 159 |
--- |
| 160 |
# More complete example demonstrating the use of 'want_facts' and the constructed options |
| 161 |
# Note that using facts returned by 'want_facts' in constructed options requires 'want_facts=true' |
| 162 |
# my.proxmox.yml |
| 163 |
plugin: community.proxmox.proxmox |
| 164 |
url: http://pve.domain.com:8006 |
| 165 |
user: ansible@pve |
| 166 |
password: secure |
| 167 |
want_facts: true |
| 168 |
keyed_groups: |
| 169 |
# proxmox_tags_parsed is an example of a fact only returned when 'want_facts=true' |
| 170 |
- key: proxmox_tags_parsed |
| 171 |
separator: "" |
| 172 |
prefix: group |
| 173 |
groups: |
| 174 |
webservers: "'web' in (proxmox_tags_parsed|list)" |
| 175 |
mailservers: "'mail' in (proxmox_tags_parsed|list)" |
| 176 |
compose: |
| 177 |
ansible_port: 2222 |
| 178 |
# Note that this can easily give you wrong values as ansible_host. See further below for |
| 179 |
# an example where this is set to `false` and where ansible_host is set with `compose`. |
| 180 |
want_proxmox_nodes_ansible_host: true |
| 181 |
|
| 182 |
--- |
| 183 |
# Using the inventory to allow ansible to connect via the first IP address of the VM / Container |
| 184 |
# (Default is connection by name of QEMU/LXC guests) |
| 185 |
# Note: my_inv_var demonstrates how to add a string variable to every host used by the inventory. |
| 186 |
# my.proxmox.yml |
| 187 |
plugin: community.proxmox.proxmox |
| 188 |
url: http://192.168.1.2:8006 |
| 189 |
user: ansible@pve |
| 190 |
password: secure |
| 191 |
want_facts: true |
| 192 |
want_proxmox_nodes_ansible_host: false |
| 193 |
compose: |
| 194 |
ansible_host: proxmox_ipconfig0.ip | default(proxmox_net0.ip) | ipaddr('address') |
| 195 |
my_inv_var_1: "'my_var1_value'" |
| 196 |
my_inv_var_2: > |
| 197 |
"my_var_2_value" |
| 198 |
|
| 199 |
--- |
| 200 |
# Specify the url, user and password using templating |
| 201 |
# my.proxmox.yml |
| 202 |
plugin: community.proxmox.proxmox |
| 203 |
url: "{{ lookup('ansible.builtin.ini', 'url', section='proxmox', file='file.ini') }}" |
| 204 |
user: "{{ lookup('ansible.builtin.env','PM_USER') | default('ansible@pve') }}" |
| 205 |
password: "{{ lookup('community.proxmox.random_string', base64=True) }}" |
| 206 |
# Note that this can easily give you wrong values as ansible_host. See further up for |
| 207 |
# an example where this is set to `false` and where ansible_host is set with `compose`. |
| 208 |
want_proxmox_nodes_ansible_host: true |
| 209 |
|
| 210 |
""" |
| 211 |
|
| 212 |
import itertools |
| 213 |
import re |
| 214 |
from collections.abc import MutableMapping |
| 215 |
from sys import version as python_version |
| 216 |
from urllib.parse import urlencode |
| 217 |
|
| 218 |
from ansible.errors import AnsibleError |
| 219 |
from ansible.module_utils.ansible_release import __version__ as ansible_version |
| 220 |
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable |
| 221 |
from ansible.utils.display import Display |
| 222 |
|
| 223 |
from ansible_collections.community.proxmox.plugins.module_utils.version import LooseVersion |
| 224 |
from ansible_collections.community.proxmox.plugins.plugin_utils.unsafe import make_unsafe |
| 225 |
|
| 226 |
# 3rd party imports |
| 227 |
try: |
| 228 |
import requests |
| 229 |
|
| 230 |
if LooseVersion(requests.__version__) < LooseVersion("1.1.0"): |
| 231 |
raise ImportError |
| 232 |
HAS_REQUESTS = True |
| 233 |
except ImportError: |
| 234 |
HAS_REQUESTS = False |
| 235 |
|
| 236 |
display = Display() |
| 237 |
|
| 238 |
|
| 239 |
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): |
| 240 |
"""Host inventory parser for ansible using Proxmox as source.""" |
| 241 |
|
| 242 |
NAME = "community.proxmox.proxmox" |
| 243 |
|
| 244 |
def __init__(self): |
| 245 |
super().__init__() |
| 246 |
|
| 247 |
# from config |
| 248 |
self.proxmox_url = None |
| 249 |
|
| 250 |
self.session = None |
| 251 |
self.cache_key = None |
| 252 |
self.use_cache = None |
| 253 |
|
| 254 |
def verify_file(self, path): |
| 255 |
valid = False |
| 256 |
if super().verify_file(path): |
| 257 |
if path.endswith(("proxmox.yaml", "proxmox.yml")): |
| 258 |
valid = True |
| 259 |
else: |
| 260 |
self.display.vvv('Skipping due to inventory source not ending in "proxmox.yaml" nor "proxmox.yml"') |
| 261 |
return valid |
| 262 |
|
| 263 |
def _get_session(self): |
| 264 |
if not self.session: |
| 265 |
self.session = requests.session() |
| 266 |
self.session.headers.update( |
| 267 |
{"User-Agent": f"ansible {ansible_version} Python {python_version.split(' ', 1)[0]}"} |
| 268 |
) |
| 269 |
self.session.verify = self.get_option("validate_certs") |
| 270 |
return self.session |
| 271 |
|
| 272 |
def _get_auth(self): |
| 273 |
if self.proxmox_password: |
| 274 |
credentials = urlencode({"username": self.proxmox_user, "password": self.proxmox_password}) |
| 275 |
a = self._get_session() |
| 276 |
ret = a.post(f"{self.proxmox_url}/api2/json/access/ticket", data=credentials) |
| 277 |
json = ret.json() |
| 278 |
self.headers = { |
| 279 |
# only required for POST/PUT/DELETE methods, which we are not using currently |
| 280 |
# 'CSRFPreventionToken': json['data']['CSRFPreventionToken'], |
| 281 |
"Cookie": f"PVEAuthCookie={json['data']['ticket']}" |
| 282 |
} |
| 283 |
else: |
| 284 |
# Clean and format token components |
| 285 |
user = self.proxmox_user.strip() |
| 286 |
token_id = self.proxmox_token_id.strip() |
| 287 |
token_secret = self.proxmox_token_secret.strip() |
| 288 |
|
| 289 |
# Build token string without newlines |
| 290 |
token = f"{user}!{token_id}={token_secret}" |
| 291 |
|
| 292 |
# Set headers with clean token |
| 293 |
self.headers = {"Authorization": f"PVEAPIToken={token}"} |
| 294 |
|
| 295 |
def _get_json(self, url, ignore_errors=None): |
| 296 |
data = [] |
| 297 |
has_data = False |
| 298 |
|
| 299 |
if self.use_cache: |
| 300 |
try: |
| 301 |
data = self._cache[self.cache_key][url] |
| 302 |
has_data = True |
| 303 |
except KeyError: |
| 304 |
self.update_cache = True |
| 305 |
|
| 306 |
if not has_data: |
| 307 |
s = self._get_session() |
| 308 |
while True: |
| 309 |
ret = s.get(url, headers=self.headers) |
| 310 |
if ignore_errors and ret.status_code in ignore_errors: |
| 311 |
break |
| 312 |
ret.raise_for_status() |
| 313 |
json = ret.json() |
| 314 |
|
| 315 |
# process results |
| 316 |
# FIXME: This assumes 'return type' matches a specific query, |
| 317 |
# it will break if we expand the queries and they dont have different types |
| 318 |
if "data" not in json: |
| 319 |
# /hosts/:id does not have a 'data' key |
| 320 |
data = json |
| 321 |
break |
| 322 |
elif isinstance(json["data"], MutableMapping): |
| 323 |
# /facts are returned as dict in 'data' |
| 324 |
data = json["data"] |
| 325 |
break |
| 326 |
else: |
| 327 |
if json["data"]: |
| 328 |
# /hosts 's 'results' is a list of all hosts, returned is paginated |
| 329 |
data = data + json["data"] |
| 330 |
break |
| 331 |
|
| 332 |
self._results[url] = data |
| 333 |
return make_unsafe(data) |
| 334 |
|
| 335 |
def _get_nodes(self): |
| 336 |
return self._get_json(f"{self.proxmox_url}/api2/json/nodes") |
| 337 |
|
| 338 |
def _get_pools(self): |
| 339 |
return self._get_json(f"{self.proxmox_url}/api2/json/pools") |
| 340 |
|
| 341 |
def _get_lxc_per_node(self, node): |
| 342 |
return self._get_json(f"{self.proxmox_url}/api2/json/nodes/{node}/lxc") |
| 343 |
|
| 344 |
def _get_qemu_per_node(self, node): |
| 345 |
return self._get_json(f"{self.proxmox_url}/api2/json/nodes/{node}/qemu") |
| 346 |
|
| 347 |
def _get_members_per_pool(self, pool): |
| 348 |
ret = self._get_json(f"{self.proxmox_url}/api2/json/pools/{pool}") |
| 349 |
return ret["members"] |
| 350 |
|
| 351 |
def _get_node_ip(self, node): |
| 352 |
ret = self._get_json(f"{self.proxmox_url}/api2/json/nodes/{node}/network") |
| 353 |
|
| 354 |
# sort interface by iface name to make selection as stable as possible |
| 355 |
ret.sort(key=lambda x: x["iface"]) |
| 356 |
|
| 357 |
for iface in ret: |
| 358 |
try: |
| 359 |
# only process interfaces adhering to these rules |
| 360 |
if "active" not in iface: |
| 361 |
self.display.vvv(f"Interface {iface['iface']} on node {node} does not have an active state") |
| 362 |
continue |
| 363 |
if "address" not in iface: |
| 364 |
self.display.vvv(f"Interface {iface['iface']} on node {node} does not have an address") |
| 365 |
continue |
| 366 |
if "gateway" not in iface: |
| 367 |
self.display.vvv(f"Interface {iface['iface']} on node {node} does not have a gateway") |
| 368 |
continue |
| 369 |
self.display.vv( |
| 370 |
f"Using interface {iface['iface']} on node {node} with address {iface['address']} as node ip for ansible_host" |
| 371 |
) |
| 372 |
return iface["address"] |
| 373 |
except Exception: |
| 374 |
continue |
| 375 |
return None |
| 376 |
|
| 377 |
def _get_lxc_interfaces(self, properties, node, vmid): |
| 378 |
status_key = self._fact("status") |
| 379 |
|
| 380 |
if status_key not in properties or properties[status_key] != "running": |
| 381 |
return |
| 382 |
|
| 383 |
ret = self._get_json(f"{self.proxmox_url}/api2/json/nodes/{node}/lxc/{vmid}/interfaces", ignore_errors=[501]) |
| 384 |
if not ret: |
| 385 |
return |
| 386 |
|
| 387 |
result = [] |
| 388 |
|
| 389 |
for iface in ret: |
| 390 |
result_iface = {"name": iface["name"], "hwaddr": iface["hwaddr"]} |
| 391 |
|
| 392 |
if "inet" in iface: |
| 393 |
result_iface["inet"] = iface["inet"] |
| 394 |
|
| 395 |
if "inet6" in iface: |
| 396 |
result_iface["inet6"] = iface["inet6"] |
| 397 |
|
| 398 |
result.append(result_iface) |
| 399 |
|
| 400 |
properties[self._fact("lxc_interfaces")] = result |
| 401 |
|
| 402 |
def _get_agent_network_interfaces(self, node, vmid, vmtype): |
| 403 |
result = [] |
| 404 |
|
| 405 |
try: |
| 406 |
ifaces = self._get_json( |
| 407 |
f"{self.proxmox_url}/api2/json/nodes/{node}/{vmtype}/{vmid}/agent/network-get-interfaces" |
| 408 |
)["result"] |
| 409 |
|
| 410 |
if "error" in ifaces: |
| 411 |
if "class" in ifaces["error"]: |
| 412 |
# This happens on Windows, even though qemu agent is running, the IP address |
| 413 |
# cannot be fetched, as it is unsupported, also a command disabled can happen. |
| 414 |
errorClass = ifaces["error"]["class"] |
| 415 |
if errorClass in ["Unsupported"]: |
| 416 |
self.display.v( |
| 417 |
"Retrieving network interfaces from guest agents on windows with older qemu-guest-agents is not supported" |
| 418 |
) |
| 419 |
elif errorClass in ["CommandDisabled"]: |
| 420 |
self.display.v("Retrieving network interfaces from guest agents has been disabled") |
| 421 |
return result |
| 422 |
|
| 423 |
for iface in ifaces: |
| 424 |
result.append( |
| 425 |
{ |
| 426 |
"name": iface["name"], |
| 427 |
"mac-address": iface.get("hardware-address", ""), |
| 428 |
"ip-addresses": [f"{ip['ip-address']}/{ip['prefix']}" for ip in iface["ip-addresses"]] |
| 429 |
if "ip-addresses" in iface |
| 430 |
else [], |
| 431 |
} |
| 432 |
) |
| 433 |
except requests.HTTPError: |
| 434 |
pass |
| 435 |
|
| 436 |
return result |
| 437 |
|
| 438 |
def _get_vm_config(self, properties, node, vmid, vmtype, name): # noqa: PLR0912 |
| 439 |
ret = self._get_json(f"{self.proxmox_url}/api2/json/nodes/{node}/{vmtype}/{vmid}/config") |
| 440 |
|
| 441 |
plaintext_configs = [ |
| 442 |
"description", |
| 443 |
] |
| 444 |
|
| 445 |
for config in ret: |
| 446 |
key = self._fact(config) |
| 447 |
value = ret[config] |
| 448 |
try: |
| 449 |
# fixup disk images as they have no key |
| 450 |
if config == "rootfs" or config.startswith(("virtio", "sata", "ide", "scsi")): |
| 451 |
value = f"disk_image={value}" |
| 452 |
|
| 453 |
# Additional field containing parsed tags as list |
| 454 |
if config == "tags": |
| 455 |
stripped_value = value.strip() |
| 456 |
if stripped_value: |
| 457 |
parsed_key = f"{key}_parsed" |
| 458 |
properties[parsed_key] = [tag.strip() for tag in stripped_value.replace(",", ";").split(";")] |
| 459 |
|
| 460 |
# The first field in the agent string tells you whether the agent is enabled |
| 461 |
# the rest of the comma separated string is extra config for the agent. |
| 462 |
# In some (newer versions of proxmox) instances it can be 'enabled=1'. |
| 463 |
if config == "agent": |
| 464 |
agent_enabled = 0 |
| 465 |
try: |
| 466 |
agent_enabled = int(value.split(",")[0]) |
| 467 |
except ValueError: |
| 468 |
if value.split(",")[0] == "enabled=1": |
| 469 |
agent_enabled = 1 |
| 470 |
if agent_enabled: |
| 471 |
agent_iface_value = self._get_agent_network_interfaces(node, vmid, vmtype) |
| 472 |
if agent_iface_value: |
| 473 |
agent_iface_key = self.to_safe(f"{key}_interfaces") |
| 474 |
properties[agent_iface_key] = agent_iface_value |
| 475 |
|
| 476 |
if config == "lxc": |
| 477 |
out_val = {} |
| 478 |
for k, v in value: |
| 479 |
out_key = k[len("lxc.") :] if k.startswith("lxc.") else k |
| 480 |
out_val[out_key] = v |
| 481 |
value = out_val |
| 482 |
|
| 483 |
if ( |
| 484 |
config not in plaintext_configs |
| 485 |
and isinstance(value, (str, bytes)) |
| 486 |
and all("=" in v for v in value.split(",")) |
| 487 |
): |
| 488 |
# split off strings with commas to a dict |
| 489 |
# skip over any keys that cannot be processed |
| 490 |
try: |
| 491 |
value = dict(key.split("=", 1) for key in value.split(",")) |
| 492 |
except Exception: |
| 493 |
continue |
| 494 |
|
| 495 |
properties[key] = value |
| 496 |
except NameError: |
| 497 |
return None |
| 498 |
|
| 499 |
def _get_vm_status(self, properties, node, vmid, vmtype, name): |
| 500 |
ret = self._get_json(f"{self.proxmox_url}/api2/json/nodes/{node}/{vmtype}/{vmid}/status/current") |
| 501 |
properties[self._fact("status")] = ret["status"] |
| 502 |
if vmtype == "qemu": |
| 503 |
properties[self._fact("qmpstatus")] = ret["qmpstatus"] |
| 504 |
|
| 505 |
def _get_vm_snapshots(self, properties, node, vmid, vmtype, name): |
| 506 |
ret = self._get_json(f"{self.proxmox_url}/api2/json/nodes/{node}/{vmtype}/{vmid}/snapshot") |
| 507 |
snapshots = [snapshot["name"] for snapshot in ret if snapshot["name"] != "current"] |
| 508 |
properties[self._fact("snapshots")] = snapshots |
| 509 |
|
| 510 |
def _get_guest_facts(self, properties, node, vmid, ittype, name): |
| 511 |
self._get_vm_status(properties, node, vmid, ittype, name) |
| 512 |
self._get_vm_config(properties, node, vmid, ittype, name) |
| 513 |
self._get_vm_snapshots(properties, node, vmid, ittype, name) |
| 514 |
|
| 515 |
if ittype == "lxc": |
| 516 |
self._get_lxc_interfaces(properties, node, vmid) |
| 517 |
|
| 518 |
def to_safe(self, word): |
| 519 |
"""Converts 'bad' characters in a string to underscores so they can be used as Ansible groups |
| 520 |
#> ProxmoxInventory.to_safe("foo-bar baz") |
| 521 |
'foo_barbaz' |
| 522 |
""" |
| 523 |
regex = r"[^A-Za-z0-9\_]" |
| 524 |
return re.sub(regex, "_", word.replace(" ", "")) |
| 525 |
|
| 526 |
def _fact(self, name): |
| 527 |
"""Generate a fact's full name from the common prefix and a name.""" |
| 528 |
return self.to_safe(f"{self.facts_prefix}{name.lower()}") |
| 529 |
|
| 530 |
def _group(self, name): |
| 531 |
"""Generate a group's full name from the common prefix and a name.""" |
| 532 |
return self.to_safe(f"{self.group_prefix}{name.lower()}") |
| 533 |
|
| 534 |
def _can_add_host(self, name, properties): |
| 535 |
"""Ensure that a host satisfies all defined hosts filters. If strict mode is |
| 536 |
enabled, any error during host filter compositing will lead to an AnsibleError |
| 537 |
being raised, otherwise the filter will be ignored. |
| 538 |
""" |
| 539 |
for host_filter in self.host_filters: |
| 540 |
try: |
| 541 |
if not self._compose(host_filter, properties): |
| 542 |
return False |
| 543 |
except Exception as e: # pylint: disable=broad-except |
| 544 |
message = f"Could not evaluate host filter {host_filter} for host {name} - {e}" |
| 545 |
if self.strict: |
| 546 |
raise AnsibleError(message) from e |
| 547 |
display.warning(message) |
| 548 |
return True |
| 549 |
|
| 550 |
def _add_host(self, name, variables): |
| 551 |
self.inventory.add_host(name) |
| 552 |
for k, v in variables.items(): |
| 553 |
self.inventory.set_variable(name, k, v) |
| 554 |
variables = self.inventory.get_host(name).get_vars() |
| 555 |
self._set_composite_vars(self.get_option("compose"), variables, name, strict=self.strict) |
| 556 |
self._add_host_to_composed_groups(self.get_option("groups"), variables, name, strict=self.strict) |
| 557 |
self._add_host_to_keyed_groups(self.get_option("keyed_groups"), variables, name, strict=self.strict) |
| 558 |
|
| 559 |
def _handle_item(self, node, ittype, item): |
| 560 |
"""Handle an item from the list of LXC containers and Qemu VM. The |
| 561 |
return value will be either None if the item was skipped or the name of |
| 562 |
the item if it was added to the inventory.""" |
| 563 |
properties = dict() |
| 564 |
name, vmid, status = item["name"], item["vmid"], item["status"] |
| 565 |
is_template = bool(item.get("template", 0)) |
| 566 |
|
| 567 |
properties[self._fact("node")] = node |
| 568 |
properties[self._fact("vmid")] = vmid |
| 569 |
properties[self._fact("vmtype")] = ittype |
| 570 |
properties[self._fact("name")] = name |
| 571 |
properties[self._fact("status")] = status |
| 572 |
properties[self._fact("template")] = is_template |
| 573 |
|
| 574 |
tags = item.get("tags") |
| 575 |
if tags: |
| 576 |
properties[self._fact("tags")] = tags |
| 577 |
|
| 578 |
# get status, config and snapshots if want_facts == True |
| 579 |
want_facts = self.get_option("want_facts") |
| 580 |
if want_facts: |
| 581 |
self._get_guest_facts(properties, node, vmid, ittype, name) |
| 582 |
|
| 583 |
# ensure the host satisfies filters |
| 584 |
if not self._can_add_host(name, properties): |
| 585 |
return None |
| 586 |
|
| 587 |
# get status, config and snapshots if we want_post_filter_facts only |
| 588 |
want_post_filter_facts = self.get_option("want_post_filter_facts") |
| 589 |
if not want_facts and want_post_filter_facts: |
| 590 |
self._get_guest_facts(properties, node, vmid, ittype, name) |
| 591 |
|
| 592 |
# add the host to the inventory |
| 593 |
self._add_host(name, properties) |
| 594 |
if is_template: |
| 595 |
self.inventory.add_child(self._group("all_templates"), name) |
| 596 |
return name |
| 597 |
|
| 598 |
node_type_group = self._group(f"{node}_{ittype}") |
| 599 |
self.inventory.add_child(self._group(f"all_{ittype}"), name) |
| 600 |
self.inventory.add_child(node_type_group, name) |
| 601 |
|
| 602 |
item_status = item["status"] |
| 603 |
if item_status == "running" and want_facts and ittype == "qemu" and self.get_option("qemu_extended_statuses"): |
| 604 |
# get more details about the status of the qemu VM |
| 605 |
item_status = properties.get(self._fact("qmpstatus"), item_status) |
| 606 |
self.inventory.add_child(self._group(f"all_{item_status}"), name) |
| 607 |
|
| 608 |
return name |
| 609 |
|
| 610 |
def _populate_pool_groups(self, added_hosts): |
| 611 |
"""Generate groups from Proxmox resource pools, ignoring VMs and |
| 612 |
containers that were skipped.""" |
| 613 |
for pool in self._get_pools(): |
| 614 |
poolid = pool.get("poolid") |
| 615 |
if not poolid: |
| 616 |
continue |
| 617 |
pool_group = self._group(f"pool_{poolid}") |
| 618 |
self.inventory.add_group(pool_group) |
| 619 |
|
| 620 |
for member in self._get_members_per_pool(poolid): |
| 621 |
name = member.get("name") |
| 622 |
if name and name in added_hosts: |
| 623 |
self.inventory.add_child(pool_group, name) |
| 624 |
|
| 625 |
def _populate(self): # noqa: PLR0912 |
| 626 |
# create common groups |
| 627 |
default_groups = ["lxc", "qemu", "running", "stopped", "templates"] |
| 628 |
|
| 629 |
if self.get_option("qemu_extended_statuses"): |
| 630 |
default_groups.extend(["prelaunch", "paused"]) |
| 631 |
|
| 632 |
for group in default_groups: |
| 633 |
self.inventory.add_group(self._group(f"all_{group}")) |
| 634 |
nodes_group = self._group("nodes") |
| 635 |
if not self.exclude_nodes: |
| 636 |
self.inventory.add_group(nodes_group) |
| 637 |
|
| 638 |
want_proxmox_nodes_ansible_host = self.get_option("want_proxmox_nodes_ansible_host") |
| 639 |
|
| 640 |
# gather vm's on nodes |
| 641 |
self._get_auth() |
| 642 |
hosts = [] |
| 643 |
for node in self._get_nodes(): |
| 644 |
if not node.get("node"): |
| 645 |
continue |
| 646 |
if not self.exclude_nodes: |
| 647 |
self.inventory.add_host(node["node"]) |
| 648 |
if node["type"] == "node" and not self.exclude_nodes: |
| 649 |
self.inventory.add_child(nodes_group, node["node"]) |
| 650 |
|
| 651 |
if node["status"] == "offline": |
| 652 |
continue |
| 653 |
|
| 654 |
# get node IP address |
| 655 |
if want_proxmox_nodes_ansible_host and not self.exclude_nodes: |
| 656 |
ip = self._get_node_ip(node["node"]) |
| 657 |
self.inventory.set_variable(node["node"], "ansible_host", ip) |
| 658 |
|
| 659 |
# Setting composite variables |
| 660 |
if not self.exclude_nodes: |
| 661 |
variables = self.inventory.get_host(node["node"]).get_vars() |
| 662 |
self._set_composite_vars(self.get_option("compose"), variables, node["node"], strict=self.strict) |
| 663 |
|
| 664 |
# add LXC/Qemu groups for the node |
| 665 |
for ittype in ("lxc", "qemu"): |
| 666 |
node_type_group = self._group(f"{node['node']}_{ittype}") |
| 667 |
self.inventory.add_group(node_type_group) |
| 668 |
|
| 669 |
# get LXC containers and Qemu VMs for this node |
| 670 |
lxc_objects = zip(itertools.repeat("lxc"), self._get_lxc_per_node(node["node"])) |
| 671 |
qemu_objects = zip(itertools.repeat("qemu"), self._get_qemu_per_node(node["node"])) |
| 672 |
for ittype, item in itertools.chain(lxc_objects, qemu_objects): |
| 673 |
name = self._handle_item(node["node"], ittype, item) |
| 674 |
if name is not None: |
| 675 |
hosts.append(name) |
| 676 |
|
| 677 |
# gather vm's in pools |
| 678 |
self._populate_pool_groups(hosts) |
| 679 |
|
| 680 |
def parse(self, inventory, loader, path, cache=True): |
| 681 |
if not HAS_REQUESTS: |
| 682 |
raise AnsibleError("This module requires Python Requests 1.1.0 or higher: https://github.com/psf/requests.") |
| 683 |
|
| 684 |
super().parse(inventory, loader, path) |
| 685 |
|
| 686 |
# read config from file, this sets 'options' |
| 687 |
self._read_config_data(path) |
| 688 |
|
| 689 |
# read and template auth options |
| 690 |
for o in ("url", "user", "password", "token_id", "token_secret"): |
| 691 |
v = self.get_option(o) |
| 692 |
if self.templar.is_template(v): |
| 693 |
v = self.templar.template(v) |
| 694 |
setattr(self, f"proxmox_{o}", v) |
| 695 |
|
| 696 |
# some more cleanup and validation |
| 697 |
self.proxmox_url = self.proxmox_url.rstrip("/") |
| 698 |
|
| 699 |
if self.proxmox_password is None and (self.proxmox_token_id is None or self.proxmox_token_secret is None): |
| 700 |
raise AnsibleError("You must specify either a password or both token_id and token_secret.") |
| 701 |
|
| 702 |
if self.get_option("qemu_extended_statuses") and not self.get_option("want_facts"): |
| 703 |
raise AnsibleError("You must set want_facts to True if you want to use qemu_extended_statuses.") |
| 704 |
# read rest of options |
| 705 |
self.exclude_nodes = self.get_option("exclude_nodes") |
| 706 |
self.cache_key = self.get_cache_key(path) |
| 707 |
self.use_cache = cache and self.get_option("cache") |
| 708 |
self.update_cache = not cache and self.get_option("cache") |
| 709 |
self.host_filters = self.get_option("filters") |
| 710 |
self.group_prefix = self.get_option("group_prefix") |
| 711 |
self.facts_prefix = self.get_option("facts_prefix") |
| 712 |
self.strict = self.get_option("strict") |
| 713 |
self.want_post_filter_facts = self.get_option("want_post_filter_facts") |
| 714 |
|
| 715 |
# actually populate inventory |
| 716 |
self._results = {} |
| 717 |
self._populate() |
| 718 |
if self.update_cache: |
| 719 |
self._cache[self.cache_key] = self._results |