52 lines
1.8 KiB
Python
52 lines
1.8 KiB
Python
#!/usr/bin/env python3
|
|
# encoding: utf-8
|
|
|
|
from typing import List
|
|
from proxmoxer import ProxmoxAPI
|
|
import time
|
|
|
|
class PveWrapper:
|
|
|
|
def __init__(self, hostname: str, username: str, token_name: str, token_value: str, nodename: str, verify_ssl=False) -> None:
|
|
"""Wrapper for Proxmox API query."""
|
|
|
|
self.conn = ProxmoxAPI(
|
|
hostname,
|
|
user=username,
|
|
token_name=token_name,
|
|
token_value=token_value,
|
|
verify_ssl=verify_ssl)
|
|
|
|
self.instance = self.conn.nodes(nodename)
|
|
|
|
def ipv4_addresses(self, vmid: str) -> List[str]:
|
|
"""Returns the list of ipv4_addresses of the VM."""
|
|
|
|
while True:
|
|
try:
|
|
netints = self.instance.qemu(int(vmid)).agent.get("network-get-interfaces")
|
|
except:
|
|
time.sleep(5)
|
|
continue
|
|
else:
|
|
# When QEMU agent is running, all the needed informations are
|
|
# retrieved. No need to check each possible outcome.
|
|
|
|
# All non-lo interfaces
|
|
filtered = [ x for x in netints['result'] if x['name'] != 'lo' ]
|
|
|
|
retval = []
|
|
for interface in filtered:
|
|
ipv4_addresses = [ x['ip-address'] for x in interface['ip-addresses'] if x['ip-address-type'] == 'ipv4' ]
|
|
# We assume a new machine has just been spawned, so it has just 1 ipv4 address per interface (if any).
|
|
ipv4_address = ''
|
|
if len(ipv4_addresses) >= 1:
|
|
ipv4_address = ipv4_addresses[0]
|
|
|
|
retval.append({
|
|
"name": interface['name'],
|
|
"address": ipv4_address
|
|
})
|
|
|
|
return retval
|