Merge pull request #21 from xezpeleta/feature-resolveip

Get the IP address automatically (fixes #8)
This commit is contained in:
Xabi 2020-02-03 12:14:23 +01:00 committed by GitHub
commit ebcd5ac294
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 50 additions and 2 deletions

View File

@ -29,6 +29,7 @@ Resolvable VM names: the inventory script collects the VM names (and not IP addr
- Handle cases where node is unavailable (@andor44) [#7] - Handle cases where node is unavailable (@andor44) [#7]
- Fix python 2 and 3 compatibility (@gardar) [#14] - Fix python 2 and 3 compatibility (@gardar) [#14]
- Filter on qemu and lxc resources only (@adubreuiltk) [#16] - Filter on qemu and lxc resources only (@adubreuiltk) [#16]
- Get the IP address automatically (@xezpeleta) [#8]
## Instructions ## Instructions

View File

@ -33,6 +33,8 @@ except ImportError:
import simplejson as json import simplejson as json
import os import os
import sys import sys
import socket
import re
from optparse import OptionParser from optparse import OptionParser
from six import iteritems from six import iteritems
@ -191,6 +193,44 @@ class ProxmoxAPI(object):
def pool(self, poolid): def pool(self, poolid):
return ProxmoxPool(self.get('api2/json/pools/{0}'.format(poolid))) return ProxmoxPool(self.get('api2/json/pools/{0}'.format(poolid)))
def qemu_agent(self, node, vm):
try:
info = self.get('api2/json/nodes/{0}/qemu/{1}/agent/info'.format(node, vm))
if info is not None:
return True
except HTTPError as error:
return False
def qemu_ip_address(self, node, vm):
ip_address = None
networks = self.get('api2/json/nodes/{0}/qemu/{1}/agent/network-get-interfaces'.format(node, vm))['result']
if networks:
if type(network) is dict:
for network in networks:
for address in network['ip-addresses']:
ip_address = address['ip-address']
try:
# IP address validation
if socket.inet_aton(ip_address):
# Ignore localhost
if ip_address != '127.0.0.1':
return ip_address
except socket.error:
pass
return None
def openvz_ip_address(self, node, vm):
try:
config = self.get('api2/json/nodes/{0}/lxc/{1}/config'.format(node, vm))
except HTTPError:
return False
try:
ip_address = re.search('ip=(\d*\.\d*\.\d*\.\d*)', config['net0']).group(1)
return ip_address
except:
return False
def version(self): def version(self):
return ProxmoxVersion(self.get('api2/json/version')) return ProxmoxVersion(self.get('api2/json/version'))
@ -256,6 +296,13 @@ def main_list(options, config_path):
'notes': description 'notes': description
} }
if type == 'qemu':
# If Qemu Agent is enabled, try to guess the IP address
if proxmox_api.qemu_agent(node, vmid):
results['_meta']['hostvars'][vm]['ansible_host'] = proxmox_api.qemu_ip_address(node, vmid)
else:
results['_meta']['hostvars'][vm]['ansible_host'] = proxmox_api.openvz_ip_address(node, vmid)
if 'groups' in metadata: if 'groups' in metadata:
# print metadata # print metadata
for group in metadata['groups']: for group in metadata['groups']: