| 1 |
# Copyright (c) 2025 Ian Williams (@aph3rson) |
| 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 |
--- |
| 9 |
name: proxmox_qemu_api |
| 10 |
short_description: Connect to QEMU VMs via the Proxmox guest agent API |
| 11 |
description: |
| 12 |
- Execute commands and transfer files through the Proxmox VE QEMU Guest Agent API. |
| 13 |
- Does not require SSH or network connectivity to the VM. |
| 14 |
- Requires the QEMU Guest Agent (C(qemu-guest-agent)) to be installed and running inside the target VM. |
| 15 |
- Talks directly to the Proxmox REST API using C(proxmoxer), avoiding the overhead and limitations |
| 16 |
of shelling out to C(qm guest exec) over SSH. |
| 17 |
- Linux guests only. Windows guest support is not implemented. |
| 18 |
author: |
| 19 |
- Ian Williams (@aph3rson) |
| 20 |
version_added: "2.0.0" |
| 21 |
requirements: |
| 22 |
- proxmoxer >= 2.3.0 |
| 23 |
- requests |
| 24 |
options: |
| 25 |
api_host: |
| 26 |
description: Proxmox VE API hostname or IP address. |
| 27 |
required: true |
| 28 |
type: str |
| 29 |
vars: |
| 30 |
- name: proxmox_api_host |
| 31 |
env: |
| 32 |
- name: PROXMOX_HOST |
| 33 |
api_port: |
| 34 |
description: Proxmox VE API port. |
| 35 |
default: 8006 |
| 36 |
type: int |
| 37 |
vars: |
| 38 |
- name: proxmox_api_port |
| 39 |
env: |
| 40 |
- name: PROXMOX_PORT |
| 41 |
api_user: |
| 42 |
description: |
| 43 |
- Proxmox VE API user (for example V(root@pam)). |
| 44 |
- Used with O(api_password) to obtain an authentication ticket. |
| 45 |
- Mutually exclusive with O(api_token_id). |
| 46 |
type: str |
| 47 |
vars: |
| 48 |
- name: proxmox_api_user |
| 49 |
env: |
| 50 |
- name: PROXMOX_USER |
| 51 |
api_password: |
| 52 |
description: |
| 53 |
- Password for O(api_user). |
| 54 |
- Required when O(api_user) is set. |
| 55 |
type: str |
| 56 |
vars: |
| 57 |
- name: proxmox_api_password |
| 58 |
env: |
| 59 |
- name: PROXMOX_PASSWORD |
| 60 |
api_token_id: |
| 61 |
description: |
| 62 |
- API token ID (for example V(user@pam!token_name)). |
| 63 |
- Used with O(api_token_secret). |
| 64 |
- Mutually exclusive with O(api_user). |
| 65 |
type: str |
| 66 |
vars: |
| 67 |
- name: proxmox_api_token_id |
| 68 |
env: |
| 69 |
- name: PROXMOX_TOKEN_ID |
| 70 |
api_token_secret: |
| 71 |
description: |
| 72 |
- API token secret UUID. |
| 73 |
- Required when O(api_token_id) is set. |
| 74 |
type: str |
| 75 |
vars: |
| 76 |
- name: proxmox_api_token_secret |
| 77 |
env: |
| 78 |
- name: PROXMOX_TOKEN_SECRET |
| 79 |
node: |
| 80 |
description: Proxmox node name where the VM resides. |
| 81 |
required: true |
| 82 |
type: str |
| 83 |
vars: |
| 84 |
- name: proxmox_node |
| 85 |
env: |
| 86 |
- name: PROXMOX_NODE |
| 87 |
vmid: |
| 88 |
description: Target QEMU VM ID. |
| 89 |
required: true |
| 90 |
type: int |
| 91 |
vars: |
| 92 |
- name: proxmox_vmid |
| 93 |
env: |
| 94 |
- name: PROXMOX_VMID |
| 95 |
validate_certs: |
| 96 |
description: Validate PVE API TLS certificates. |
| 97 |
default: true |
| 98 |
type: bool |
| 99 |
vars: |
| 100 |
- name: proxmox_validate_certs |
| 101 |
env: |
| 102 |
- name: PROXMOX_VERIFY_SSL |
| 103 |
remote_tmp: |
| 104 |
description: |
| 105 |
- Temporary directory on the guest for staging chunked file transfers. |
| 106 |
- Must be writable by the guest agent process (typically root). |
| 107 |
- Only used when transferring files larger than 45000 bytes. |
| 108 |
default: /tmp |
| 109 |
type: str |
| 110 |
vars: |
| 111 |
- name: proxmox_remote_tmp |
| 112 |
executable: |
| 113 |
description: Shell executable for command execution on the guest. |
| 114 |
default: /bin/sh |
| 115 |
type: str |
| 116 |
vars: |
| 117 |
- name: ansible_executable |
| 118 |
connect_timeout: |
| 119 |
description: |
| 120 |
- Maximum number of seconds to wait for the guest agent to become responsive. |
| 121 |
- The plugin polls the agent every 5 seconds during connection. |
| 122 |
default: 60 |
| 123 |
type: int |
| 124 |
vars: |
| 125 |
- name: proxmox_connect_timeout |
| 126 |
notes: |
| 127 |
- The API user or token requires guest agent privileges on the target VM. |
| 128 |
On PVE 8, this is C(VM.Monitor). On PVE 9+, C(VM.Monitor) was replaced with |
| 129 |
fine-grained privileges -- C(VM.GuestAgent.Unrestricted) covers command execution, |
| 130 |
C(VM.GuestAgent.FileRead) and C(VM.GuestAgent.FileWrite) cover file transfers. |
| 131 |
Alternatively, C(VM.GuestAgent.Unrestricted) alone grants access to all guest agent operations. |
| 132 |
- This plugin requires the QEMU Guest Agent to be installed and running inside the VM. |
| 133 |
If the agent is not responsive, the connection will fail after O(connect_timeout) seconds. |
| 134 |
- File transfers use the PVE guest agent file-read/file-write API, which has a per-call |
| 135 |
size limit of approximately 45000 bytes. Files larger than this are automatically |
| 136 |
split into chunks using C(split) on the guest and reassembled on the controller or guest. |
| 137 |
- "Guest requirements: C(qemu-guest-agent) must be running. File transfers additionally |
| 138 |
require C(cat), C(split), C(ls), and C(rm) (coreutils)." |
| 139 |
- Works with the C(community.proxmox.proxmox) inventory plugin. Set |
| 140 |
C(ansible_connection=community.proxmox.proxmox_qemu_api) on discovered hosts. |
| 141 |
""" |
| 142 |
|
| 143 |
EXAMPLES = r""" |
| 144 |
- name: Static inventory example |
| 145 |
# inventory.yml |
| 146 |
# all: |
| 147 |
# hosts: |
| 148 |
# my-vm: |
| 149 |
# ansible_connection: community.proxmox.proxmox_qemu_api |
| 150 |
# proxmox_vmid: 100 |
| 151 |
# ansible_host: my-vm.example.com |
| 152 |
# vars: |
| 153 |
# proxmox_api_host: pve-1.example.com |
| 154 |
# proxmox_api_port: 8006 |
| 155 |
# proxmox_api_token_id: automation@pve!ansible |
| 156 |
# proxmox_api_token_secret: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
| 157 |
# proxmox_node: pve-1 |
| 158 |
hosts: my-vm |
| 159 |
gather_facts: true |
| 160 |
tasks: |
| 161 |
- name: Install a package |
| 162 |
ansible.builtin.apt: |
| 163 |
name: curl |
| 164 |
state: present |
| 165 |
|
| 166 |
- name: Copy a configuration file |
| 167 |
ansible.builtin.copy: |
| 168 |
src: app.conf |
| 169 |
dest: /etc/app/app.conf |
| 170 |
|
| 171 |
- name: Run a command |
| 172 |
ansible.builtin.command: |
| 173 |
cmd: systemctl restart app |
| 174 |
""" |
| 175 |
|
| 176 |
import base64 |
| 177 |
import logging |
| 178 |
import time |
| 179 |
|
| 180 |
from ansible.errors import AnsibleConnectionFailure, AnsibleError |
| 181 |
from ansible.plugins.connection import ConnectionBase |
| 182 |
from ansible.utils.display import Display |
| 183 |
|
| 184 |
from ansible_collections.community.proxmox.plugins.module_utils.proxmox import HAS_PROXMOXER |
| 185 |
|
| 186 |
if HAS_PROXMOXER: |
| 187 |
from proxmoxer import ProxmoxAPI |
| 188 |
|
| 189 |
display = Display() |
| 190 |
|
| 191 |
|
| 192 |
class _DisplayHandler(logging.Handler): |
| 193 |
"""Route Python logging to Ansible Display.""" |
| 194 |
|
| 195 |
_level_map = { |
| 196 |
logging.DEBUG: display.vvvv, |
| 197 |
logging.INFO: display.vvv, |
| 198 |
logging.WARNING: display.warning, |
| 199 |
} |
| 200 |
|
| 201 |
def emit(self, record): |
| 202 |
fn = self._level_map.get(record.levelno, display.warning) |
| 203 |
fn(self.format(record)) |
| 204 |
|
| 205 |
|
| 206 |
# Wire urllib3/requests logging through Display instead of stderr. |
| 207 |
_handler = _DisplayHandler() |
| 208 |
_handler.setFormatter(logging.Formatter("%(name)s: %(message)s")) |
| 209 |
for _name in ("urllib3", "requests", "py.warnings"): |
| 210 |
_logger = logging.getLogger(_name) |
| 211 |
_logger.handlers.clear() |
| 212 |
_logger.addHandler(_handler) |
| 213 |
_logger.propagate = False |
| 214 |
|
| 215 |
# PVE file-write content limit is 61440 bytes. |
| 216 |
# base64 expands 3:4, so 45000 raw bytes -> 60000 base64 chars, safely under limit. |
| 217 |
# TODO: Increase once Proxmox raises the QEMU guest agent file-write size limit. |
| 218 |
# https://forum.proxmox.com/threads/maximum-file-upload-size-for-qemu-agent-file-write.166200/ |
| 219 |
FILE_WRITE_CHUNK = 45000 |
| 220 |
FILE_WRITE_RETRIES = 5 |
| 221 |
|
| 222 |
|
| 223 |
class Connection(ConnectionBase): |
| 224 |
"""Connection plugin that uses the Proxmox QEMU Guest Agent API.""" |
| 225 |
|
| 226 |
transport = "community.proxmox.proxmox_qemu_api" |
| 227 |
has_pipelining = False |
| 228 |
has_tty = False |
| 229 |
|
| 230 |
def __init__(self, *args, **kwargs): |
| 231 |
super().__init__(*args, **kwargs) |
| 232 |
self._connected = False |
| 233 |
self._proxmox = None |
| 234 |
logging.captureWarnings(True) |
| 235 |
|
| 236 |
def _get_proxmox(self): |
| 237 |
if self._proxmox is not None: |
| 238 |
return self._proxmox |
| 239 |
|
| 240 |
if not HAS_PROXMOXER: |
| 241 |
msg = "This connection plugin requires the 'proxmoxer' library" |
| 242 |
raise AnsibleError(msg) from None |
| 243 |
|
| 244 |
host = self.get_option("api_host") |
| 245 |
port = self.get_option("api_port") |
| 246 |
verify_ssl = self.get_option("validate_certs") |
| 247 |
token_id = self.get_option("api_token_id") |
| 248 |
token_secret = self.get_option("api_token_secret") |
| 249 |
user = self.get_option("api_user") |
| 250 |
password = self.get_option("api_password") |
| 251 |
|
| 252 |
if token_id and token_secret: |
| 253 |
self._proxmox = ProxmoxAPI( |
| 254 |
host, |
| 255 |
port=port, |
| 256 |
user=token_id.split("!")[0], |
| 257 |
token_name=token_id.split("!")[-1], |
| 258 |
token_value=token_secret, |
| 259 |
verify_ssl=verify_ssl, |
| 260 |
) |
| 261 |
elif user and password: |
| 262 |
self._proxmox = ProxmoxAPI( |
| 263 |
host, |
| 264 |
port=port, |
| 265 |
user=user, |
| 266 |
password=password, |
| 267 |
verify_ssl=verify_ssl, |
| 268 |
) |
| 269 |
else: |
| 270 |
raise AnsibleConnectionFailure( |
| 271 |
"No authentication configured. Provide api_token_id + api_token_secret, or api_user + api_password." |
| 272 |
) |
| 273 |
|
| 274 |
return self._proxmox |
| 275 |
|
| 276 |
def _agent(self): |
| 277 |
proxmox = self._get_proxmox() |
| 278 |
node = self.get_option("node") |
| 279 |
vmid = self.get_option("vmid") |
| 280 |
return proxmox.nodes(node).qemu(vmid).agent |
| 281 |
|
| 282 |
def _connect(self): |
| 283 |
if self._connected: |
| 284 |
return self |
| 285 |
super()._connect() |
| 286 |
|
| 287 |
timeout = self.get_option("connect_timeout") |
| 288 |
interval = 5 |
| 289 |
attempts = max(timeout // interval, 1) |
| 290 |
|
| 291 |
for attempt in range(attempts): |
| 292 |
try: |
| 293 |
self._agent().ping.post() |
| 294 |
self._connected = True |
| 295 |
display.vvv(f"QEMU guest agent responsive on VM {self.get_option('vmid')}") |
| 296 |
return self |
| 297 |
except Exception: |
| 298 |
if attempt < attempts - 1: |
| 299 |
display.vvv( |
| 300 |
f"Guest agent not ready on VM {self.get_option('vmid')}, " |
| 301 |
f"retrying in {interval}s ({attempt + 1}/{attempts})" |
| 302 |
) |
| 303 |
time.sleep(interval) |
| 304 |
else: |
| 305 |
raise AnsibleConnectionFailure( |
| 306 |
f"QEMU guest agent is not responding on VM {self.get_option('vmid')} " |
| 307 |
f"after {timeout}s. Is qemu-guest-agent installed and running?" |
| 308 |
) from None |
| 309 |
|
| 310 |
def exec_command(self, cmd, in_data=None, sudoable=True): |
| 311 |
super().exec_command(cmd, in_data=in_data, sudoable=sudoable) |
| 312 |
self._connect() |
| 313 |
|
| 314 |
shell = self.get_option("executable") |
| 315 |
display.vvv(f"EXEC via guest agent: {cmd}") |
| 316 |
|
| 317 |
try: |
| 318 |
data = self._agent().exec.post(command=[shell, "-c", cmd]) |
| 319 |
except Exception as exc: |
| 320 |
raise AnsibleConnectionFailure(f"Failed to execute command on VM {self.get_option('vmid')}: {exc}") from exc |
| 321 |
|
| 322 |
pid = data["pid"] |
| 323 |
status = self._poll_exec_status(pid) |
| 324 |
|
| 325 |
rc = status.get("exitcode", -1) |
| 326 |
stdout = status.get("out-data", "") |
| 327 |
stderr = status.get("err-data", "") |
| 328 |
return rc, stdout, stderr |
| 329 |
|
| 330 |
def _poll_exec_status(self, pid): |
| 331 |
while True: |
| 332 |
time.sleep(0.5) |
| 333 |
status = self._agent()("exec-status").get(pid=pid) |
| 334 |
if status.get("exited"): |
| 335 |
return status |
| 336 |
|
| 337 |
def _file_write(self, guest_path, data_bytes): |
| 338 |
encoded = base64.b64encode(data_bytes).decode("ascii") |
| 339 |
for attempt in range(FILE_WRITE_RETRIES + 1): |
| 340 |
try: |
| 341 |
self._agent()("file-write").post(file=guest_path, content=encoded, encode=0) |
| 342 |
return |
| 343 |
except Exception: |
| 344 |
if attempt < FILE_WRITE_RETRIES: |
| 345 |
time.sleep(5) |
| 346 |
else: |
| 347 |
raise AnsibleConnectionFailure( |
| 348 |
f"Failed to write file {guest_path} on VM {self.get_option('vmid')} " |
| 349 |
f"after {FILE_WRITE_RETRIES + 1} attempts" |
| 350 |
) from None |
| 351 |
|
| 352 |
def put_file(self, in_path, out_path): |
| 353 |
super().put_file(in_path, out_path) |
| 354 |
self._connect() |
| 355 |
display.vvv(f"PUT {in_path} -> {out_path} via guest agent") |
| 356 |
|
| 357 |
with open(in_path, "rb") as f: |
| 358 |
raw = f.read() |
| 359 |
|
| 360 |
if len(raw) <= FILE_WRITE_CHUNK: |
| 361 |
self._file_write(out_path, raw) |
| 362 |
return |
| 363 |
|
| 364 |
self._put_file_chunked(raw, out_path) |
| 365 |
|
| 366 |
def _put_file_chunked(self, raw, out_path): |
| 367 |
remote_tmp = self.get_option("remote_tmp") |
| 368 |
parts = [] |
| 369 |
for i in range(0, len(raw), FILE_WRITE_CHUNK): |
| 370 |
part_path = f"{remote_tmp}/.ansible_part_{i}" |
| 371 |
parts.append(part_path) |
| 372 |
self._file_write(part_path, raw[i : i + FILE_WRITE_CHUNK]) |
| 373 |
|
| 374 |
cat_cmd = "cat " + " ".join(parts) + f" > {out_path} && rm -f " + " ".join(parts) |
| 375 |
rc, dummy_stdout, err = self.exec_command(cat_cmd) |
| 376 |
if rc != 0: |
| 377 |
raise AnsibleConnectionFailure(f"Failed to assemble chunked file on VM {self.get_option('vmid')}: {err}") |
| 378 |
|
| 379 |
def _file_read(self, guest_path): |
| 380 |
"""Read a file from the guest via file-read API. |
| 381 |
|
| 382 |
PVE encodes raw file bytes as JSON unicode escapes (\\u00XX), |
| 383 |
which json.loads turns into a Python str with code points 0x00-0xFF. |
| 384 |
latin-1 is the exact inverse: U+00NN -> byte 0xNN, preserving binary content. |
| 385 |
""" |
| 386 |
result = self._agent()("file-read").get(file=guest_path) |
| 387 |
content = result.get("content", "") |
| 388 |
return content.encode("latin-1") |
| 389 |
|
| 390 |
def fetch_file(self, in_path, out_path): |
| 391 |
super().fetch_file(in_path, out_path) |
| 392 |
self._connect() |
| 393 |
display.vvv(f"FETCH {in_path} -> {out_path} via guest agent") |
| 394 |
|
| 395 |
remote_tmp = self.get_option("remote_tmp") |
| 396 |
prefix = f"{remote_tmp}/.ansible_fetch_" |
| 397 |
|
| 398 |
# Split file into chunks on guest, read each chunk, append locally |
| 399 |
split_cmd = f"split -b {FILE_WRITE_CHUNK} -- {in_path} {prefix}" |
| 400 |
rc, dummy_stdout, err = self.exec_command(split_cmd) |
| 401 |
if rc != 0: |
| 402 |
raise AnsibleConnectionFailure(f"Failed to split file {in_path} on VM {self.get_option('vmid')}: {err}") |
| 403 |
|
| 404 |
# List the chunk files in order |
| 405 |
rc, stdout, err = self.exec_command(f"ls -1 {prefix}* 2>/dev/null") |
| 406 |
if rc != 0: |
| 407 |
raise AnsibleConnectionFailure( |
| 408 |
f"Failed to list chunks for {in_path} on VM {self.get_option('vmid')}: {err}" |
| 409 |
) |
| 410 |
|
| 411 |
parts = stdout.strip().split("\n") if stdout.strip() else [] |
| 412 |
|
| 413 |
try: |
| 414 |
with open(out_path, "wb") as f: |
| 415 |
for part in parts: |
| 416 |
chunk = self._file_read(part.strip()) |
| 417 |
f.write(chunk) |
| 418 |
finally: |
| 419 |
if parts: |
| 420 |
self.exec_command(f"rm -f {prefix}*") |
| 421 |
|
| 422 |
def close(self): |
| 423 |
self._proxmox = None |
| 424 |
self._connected = False |
| 425 |
super().close() |
| 426 |
|
| 427 |
def reset(self): |
| 428 |
self.close() |
| 429 |
self._connect() |