Misc fixes and Pep8 fixes for proxmox_* modules (#24162)

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
pull/24144/head
Abhijeet Kasurde 8 years ago committed by Matt Martz
parent cdca648f15
commit d8f76bed97

@ -309,6 +309,9 @@ EXAMPLES = '''
import os import os
import time import time
# import module snippets
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
try: try:
from proxmoxer import ProxmoxAPI from proxmoxer import ProxmoxAPI
@ -316,34 +319,41 @@ try:
except ImportError: except ImportError:
HAS_PROXMOXER = False HAS_PROXMOXER = False
VZ_TYPE=None VZ_TYPE = None
def get_nextvmid(proxmox): def get_nextvmid(module, proxmox):
try: try:
vmid = proxmox.cluster.nextid.get() vmid = proxmox.cluster.nextid.get()
return vmid return vmid
except Exception as e: except Exception:
module.fail_json(msg="Unable to get next vmid. Failed with exception: %s") exc = get_exception()
module.fail_json(msg="Unable to get next vmid. Failed with exception: %s" % exc)
def get_vmid(proxmox, hostname): def get_vmid(proxmox, hostname):
return [ vm['vmid'] for vm in proxmox.cluster.resources.get(type='vm') if vm['name'] == hostname ] return [vm['vmid'] for vm in proxmox.cluster.resources.get(type='vm') if vm['name'] == hostname]
def get_instance(proxmox, vmid): def get_instance(proxmox, vmid):
return [ vm for vm in proxmox.cluster.resources.get(type='vm') if vm['vmid'] == int(vmid) ] return [vm for vm in proxmox.cluster.resources.get(type='vm') if vm['vmid'] == int(vmid)]
def content_check(proxmox, node, ostemplate, template_store): def content_check(proxmox, node, ostemplate, template_store):
return [ True for cnt in proxmox.nodes(node).storage(template_store).content.get() if cnt['volid'] == ostemplate ] return [True for cnt in proxmox.nodes(node).storage(template_store).content.get() if cnt['volid'] == ostemplate]
def node_check(proxmox, node): def node_check(proxmox, node):
return [ True for nd in proxmox.nodes.get() if nd['node'] == node ] return [True for nd in proxmox.nodes.get() if nd['node'] == node]
def create_instance(module, proxmox, vmid, node, disk, storage, cpus, memory, swap, timeout, **kwargs): def create_instance(module, proxmox, vmid, node, disk, storage, cpus, memory, swap, timeout, **kwargs):
proxmox_node = proxmox.nodes(node) proxmox_node = proxmox.nodes(node)
kwargs = dict((k,v) for k, v in kwargs.items() if v is not None) kwargs = dict((k, v) for k, v in kwargs.items() if v is not None)
if VZ_TYPE =='lxc': if VZ_TYPE == 'lxc':
kwargs['cpulimit']=cpus kwargs['cpulimit'] = cpus
kwargs['rootfs']=disk kwargs['rootfs'] = disk
if 'netif' in kwargs: if 'netif' in kwargs:
kwargs.update(kwargs['netif']) kwargs.update(kwargs['netif'])
del kwargs['netif'] del kwargs['netif']
@ -355,8 +365,8 @@ def create_instance(module, proxmox, vmid, node, disk, storage, cpus, memory, sw
kwargs['ssh-public-keys'] = kwargs['pubkey'] kwargs['ssh-public-keys'] = kwargs['pubkey']
del kwargs['pubkey'] del kwargs['pubkey']
else: else:
kwargs['cpus']=cpus kwargs['cpus'] = cpus
kwargs['disk']=disk kwargs['disk'] = disk
taskid = getattr(proxmox_node, VZ_TYPE).create(vmid=vmid, storage=storage, memory=memory, swap=swap, **kwargs) taskid = getattr(proxmox_node, VZ_TYPE).create(vmid=vmid, storage=storage, memory=memory, swap=swap, **kwargs)
@ -364,7 +374,7 @@ def create_instance(module, proxmox, vmid, node, disk, storage, cpus, memory, sw
if (proxmox_node.tasks(taskid).status.get()['status'] == 'stopped' and if (proxmox_node.tasks(taskid).status.get()['status'] == 'stopped' and
proxmox_node.tasks(taskid).status.get()['exitstatus'] == 'OK'): proxmox_node.tasks(taskid).status.get()['exitstatus'] == 'OK'):
return True return True
timeout = timeout - 1 timeout -= 1
if timeout == 0: if timeout == 0:
module.fail_json(msg='Reached timeout while waiting for creating VM. Last line in task before timeout: %s' % module.fail_json(msg='Reached timeout while waiting for creating VM. Last line in task before timeout: %s' %
proxmox_node.tasks(taskid).log.get()[:1]) proxmox_node.tasks(taskid).log.get()[:1])
@ -372,13 +382,14 @@ def create_instance(module, proxmox, vmid, node, disk, storage, cpus, memory, sw
time.sleep(1) time.sleep(1)
return False return False
def start_instance(module, proxmox, vm, vmid, timeout): def start_instance(module, proxmox, vm, vmid, timeout):
taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.start.post() taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.start.post()
while timeout: while timeout:
if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and
proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'): proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'):
return True return True
timeout = timeout - 1 timeout -= 1
if timeout == 0: if timeout == 0:
module.fail_json(msg='Reached timeout while waiting for starting VM. Last line in task before timeout: %s' % module.fail_json(msg='Reached timeout while waiting for starting VM. Last line in task before timeout: %s' %
proxmox.nodes(vm[0]['node']).tasks(taskid).log.get()[:1]) proxmox.nodes(vm[0]['node']).tasks(taskid).log.get()[:1])
@ -386,6 +397,7 @@ def start_instance(module, proxmox, vm, vmid, timeout):
time.sleep(1) time.sleep(1)
return False return False
def stop_instance(module, proxmox, vm, vmid, timeout, force): def stop_instance(module, proxmox, vm, vmid, timeout, force):
if force: if force:
taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.shutdown.post(forceStop=1) taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.shutdown.post(forceStop=1)
@ -395,59 +407,61 @@ def stop_instance(module, proxmox, vm, vmid, timeout, force):
if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and
proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'): proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'):
return True return True
timeout = timeout - 1 timeout -= 1
if timeout == 0: if timeout == 0:
module.fail_json(msg='Reached timeout while waiting for stopping VM. Last line in task before timeout: %s' % module.fail_json(msg='Reached timeout while waiting for stopping VM. Last line in task before timeout: %s' %
proxmox_node.tasks(taskid).log.get()[:1]) proxmox.nodes(vm[0]['node']).tasks(taskid).log.get()[:1])
time.sleep(1) time.sleep(1)
return False return False
def umount_instance(module, proxmox, vm, vmid, timeout): def umount_instance(module, proxmox, vm, vmid, timeout):
taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.umount.post() taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.umount.post()
while timeout: while timeout:
if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and
proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'): proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'):
return True return True
timeout = timeout - 1 timeout -= 1
if timeout == 0: if timeout == 0:
module.fail_json(msg='Reached timeout while waiting for unmounting VM. Last line in task before timeout: %s' % module.fail_json(msg='Reached timeout while waiting for unmounting VM. Last line in task before timeout: %s' %
proxmox_node.tasks(taskid).log.get()[:1]) proxmox.nodes(vm[0]['node']).tasks(taskid).log.get()[:1])
time.sleep(1) time.sleep(1)
return False return False
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec = dict( argument_spec=dict(
api_host = dict(required=True), api_host=dict(required=True),
api_user = dict(required=True), api_user=dict(required=True),
api_password = dict(no_log=True), api_password=dict(no_log=True),
vmid = dict(required=False), vmid=dict(required=False),
validate_certs = dict(type='bool', default='no'), validate_certs=dict(type='bool', default='no'),
node = dict(), node=dict(),
pool = dict(), pool=dict(),
password = dict(no_log=True), password=dict(no_log=True),
hostname = dict(), hostname=dict(),
ostemplate = dict(), ostemplate=dict(),
disk = dict(type='str', default='3'), disk=dict(type='str', default='3'),
cpus = dict(type='int', default=1), cpus=dict(type='int', default=1),
memory = dict(type='int', default=512), memory=dict(type='int', default=512),
swap = dict(type='int', default=0), swap=dict(type='int', default=0),
netif = dict(type='dict'), netif=dict(type='dict'),
mounts = dict(type='dict'), mounts=dict(type='dict'),
ip_address = dict(), ip_address=dict(),
onboot = dict(type='bool', default='no'), onboot=dict(type='bool', default='no'),
storage = dict(default='local'), storage=dict(default='local'),
cpuunits = dict(type='int', default=1000), cpuunits=dict(type='int', default=1000),
nameserver = dict(), nameserver=dict(),
searchdomain = dict(), searchdomain=dict(),
timeout = dict(type='int', default=30), timeout=dict(type='int', default=30),
force = dict(type='bool', default='no'), force=dict(type='bool', default='no'),
state = dict(default='present', choices=['present', 'absent', 'stopped', 'started', 'restarted']), state=dict(default='present', choices=['present', 'absent', 'stopped', 'started', 'restarted']),
pubkey = dict(type='str', default=None), pubkey=dict(type='str', default=None),
unprivileged = dict(type='bool', default='no') unprivileged=dict(type='bool', default='no')
) )
) )
if not HAS_PROXMOXER: if not HAS_PROXMOXER:
@ -488,7 +502,7 @@ def main():
# If vmid not set get the Next VM id from ProxmoxAPI # If vmid not set get the Next VM id from ProxmoxAPI
# If hostname is set get the VM id from ProxmoxAPI # If hostname is set get the VM id from ProxmoxAPI
if not vmid and state == 'present': if not vmid and state == 'present':
vmid = get_nextvmid(proxmox) vmid = get_nextvmid(module, proxmox)
elif not vmid and hostname: elif not vmid and hostname:
vmid = get_vmid(proxmox, hostname)[0] vmid = get_vmid(proxmox, hostname)[0]
elif not vmid: elif not vmid:
@ -510,24 +524,24 @@ def main():
% (module.params['ostemplate'], node, template_store)) % (module.params['ostemplate'], node, template_store))
create_instance(module, proxmox, vmid, node, disk, storage, cpus, memory, swap, timeout, create_instance(module, proxmox, vmid, node, disk, storage, cpus, memory, swap, timeout,
pool = module.params['pool'], pool=module.params['pool'],
password = module.params['password'], password=module.params['password'],
hostname = module.params['hostname'], hostname=module.params['hostname'],
ostemplate = module.params['ostemplate'], ostemplate=module.params['ostemplate'],
netif = module.params['netif'], netif=module.params['netif'],
mounts = module.params['mounts'], mounts=module.params['mounts'],
ip_address = module.params['ip_address'], ip_address=module.params['ip_address'],
onboot = int(module.params['onboot']), onboot=int(module.params['onboot']),
cpuunits = module.params['cpuunits'], cpuunits=module.params['cpuunits'],
nameserver = module.params['nameserver'], nameserver=module.params['nameserver'],
searchdomain = module.params['searchdomain'], searchdomain=module.params['searchdomain'],
force = int(module.params['force']), force=int(module.params['force']),
pubkey = module.params['pubkey'], pubkey=module.params['pubkey'],
unprivileged = int(module.params['unprivileged'])) unprivileged=int(module.params['unprivileged']))
module.exit_json(changed=True, msg="deployed VM %s from template %s" % (vmid, module.params['ostemplate'])) module.exit_json(changed=True, msg="deployed VM %s from template %s" % (vmid, module.params['ostemplate']))
except Exception as e: except Exception as e:
module.fail_json(msg="creation of %s VM %s failed with exception: %s" % ( VZ_TYPE, vmid, e )) module.fail_json(msg="creation of %s VM %s failed with exception: %s" % (VZ_TYPE, vmid, e))
elif state == 'started': elif state == 'started':
try: try:
@ -540,7 +554,7 @@ def main():
if start_instance(module, proxmox, vm, vmid, timeout): if start_instance(module, proxmox, vm, vmid, timeout):
module.exit_json(changed=True, msg="VM %s started" % vmid) module.exit_json(changed=True, msg="VM %s started" % vmid)
except Exception as e: except Exception as e:
module.fail_json(msg="starting of VM %s failed with exception: %s" % ( vmid, e )) module.fail_json(msg="starting of VM %s failed with exception: %s" % (vmid, e))
elif state == 'stopped': elif state == 'stopped':
try: try:
@ -559,10 +573,10 @@ def main():
if getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status'] == 'stopped': if getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status'] == 'stopped':
module.exit_json(changed=False, msg="VM %s is already shutdown" % vmid) module.exit_json(changed=False, msg="VM %s is already shutdown" % vmid)
if stop_instance(module, proxmox, vm, vmid, timeout, force = module.params['force']): if stop_instance(module, proxmox, vm, vmid, timeout, force=module.params['force']):
module.exit_json(changed=True, msg="VM %s is shutting down" % vmid) module.exit_json(changed=True, msg="VM %s is shutting down" % vmid)
except Exception as e: except Exception as e:
module.fail_json(msg="stopping of VM %s failed with exception: %s" % ( vmid, e )) module.fail_json(msg="stopping of VM %s failed with exception: %s" % (vmid, e))
elif state == 'restarted': elif state == 'restarted':
try: try:
@ -573,11 +587,11 @@ def main():
getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status'] == 'mounted'): getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status'] == 'mounted'):
module.exit_json(changed=False, msg="VM %s is not running" % vmid) module.exit_json(changed=False, msg="VM %s is not running" % vmid)
if (stop_instance(module, proxmox, vm, vmid, timeout, force = module.params['force']) and if (stop_instance(module, proxmox, vm, vmid, timeout, force=module.params['force']) and
start_instance(module, proxmox, vm, vmid, timeout)): start_instance(module, proxmox, vm, vmid, timeout)):
module.exit_json(changed=True, msg="VM %s is restarted" % vmid) module.exit_json(changed=True, msg="VM %s is restarted" % vmid)
except Exception as e: except Exception as e:
module.fail_json(msg="restarting of VM %s failed with exception: %s" % ( vmid, e )) module.fail_json(msg="restarting of VM %s failed with exception: %s" % (vmid, e))
elif state == 'absent': elif state == 'absent':
try: try:
@ -596,17 +610,15 @@ def main():
if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and
proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'): proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'):
module.exit_json(changed=True, msg="VM %s removed" % vmid) module.exit_json(changed=True, msg="VM %s removed" % vmid)
timeout = timeout - 1 timeout -= 1
if timeout == 0: if timeout == 0:
module.fail_json(msg='Reached timeout while waiting for removing VM. Last line in task before timeout: %s' module.fail_json(msg='Reached timeout while waiting for removing VM. Last line in task before timeout: %s'
% proxmox_node.tasks(taskid).log.get()[:1]) % proxmox.nodes(vm[0]['node']).tasks(taskid).log.get()[:1])
time.sleep(1) time.sleep(1)
except Exception as e: except Exception as e:
module.fail_json(msg="deletion of VM %s failed with exception: %s" % ( vmid, e )) module.fail_json(msg="deletion of VM %s failed with exception: %s" % (vmid, e))
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -704,8 +704,11 @@ status:
''' '''
import os import os
import re
import time import time
# import module snippets
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
try: try:
from proxmoxer import ProxmoxAPI from proxmoxer import ProxmoxAPI
@ -716,12 +719,13 @@ except ImportError:
VZ_TYPE = 'qemu' VZ_TYPE = 'qemu'
def get_nextvmid(proxmox): def get_nextvmid(module, proxmox):
try: try:
vmid = proxmox.cluster.nextid.get() vmid = proxmox.cluster.nextid.get()
return vmid return vmid
except Exception as e: except Exception:
module.fail_json(msg="Unable to get next vmid. Failed with exception: %s") exc = get_exception()
module.fail_json(msg="Unable to get next vmid. Failed with exception: %s" % exc)
def get_vmid(proxmox, name): def get_vmid(proxmox, name):
@ -801,7 +805,7 @@ def create_vm(module, proxmox, vmid, newid, node, name, memory, cpu, cores, sock
proxmox_node = proxmox.nodes(node) proxmox_node = proxmox.nodes(node)
# Sanitize kwargs. Remove not defined args and ensure True and False converted to int. # Sanitize kwargs. Remove not defined args and ensure True and False converted to int.
kwargs = dict((k,v) for k, v in kwargs.items() if v is not None) kwargs = dict((k, v) for k, v in kwargs.items() if v is not None)
kwargs.update(dict([k, int(v)] for k, v in kwargs.items() if isinstance(v, bool))) kwargs.update(dict([k, int(v)] for k, v in kwargs.items() if isinstance(v, bool)))
# The features work only on PVE 4 # The features work only on PVE 4
@ -876,9 +880,9 @@ def start_vm(module, proxmox, vm, vmid, timeout):
taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.start.post() taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.start.post()
while timeout: while timeout:
if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and
proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK' ): proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'):
return True return True
timeout = timeout - 1 timeout -= 1
if timeout == 0: if timeout == 0:
module.fail_json(msg='Reached timeout while waiting for starting VM. Last line in task before timeout: %s' module.fail_json(msg='Reached timeout while waiting for starting VM. Last line in task before timeout: %s'
% proxmox.nodes(vm[0]['node']).tasks(taskid).log.get()[:1]) % proxmox.nodes(vm[0]['node']).tasks(taskid).log.get()[:1])
@ -896,7 +900,7 @@ def stop_vm(module, proxmox, vm, vmid, timeout, force):
if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and
proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'): proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'):
return True return True
timeout = timeout - 1 timeout -= 1
if timeout == 0: if timeout == 0:
module.fail_json(msg='Reached timeout while waiting for stopping VM. Last line in task before timeout: %s' module.fail_json(msg='Reached timeout while waiting for stopping VM. Last line in task before timeout: %s'
% proxmox.nodes(vm[0]['node']).tasks(taskid).log.get()[:1]) % proxmox.nodes(vm[0]['node']).tasks(taskid).log.get()[:1])
@ -906,83 +910,83 @@ def stop_vm(module, proxmox, vm, vmid, timeout, force):
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec = dict( argument_spec=dict(
acpi = dict(type='bool', default='yes'), acpi=dict(type='bool', default='yes'),
agent = dict(type='bool'), agent=dict(type='bool'),
args = dict(type='str', default=None), args=dict(type='str', default=None),
api_host = dict(required=True), api_host=dict(required=True),
api_user = dict(required=True), api_user=dict(required=True),
api_password = dict(no_log=True), api_password=dict(no_log=True),
autostart = dict(type='bool', default='no'), autostart=dict(type='bool', default='no'),
balloon = dict(type='int',default=0), balloon=dict(type='int', default=0),
bios = dict(choices=['seabios', 'ovmf']), bios=dict(choices=['seabios', 'ovmf']),
boot = dict(type='str', default='cnd'), boot=dict(type='str', default='cnd'),
bootdisk = dict(type='str'), bootdisk=dict(type='str'),
clone = dict(type='str', default=None), clone=dict(type='str', default=None),
cores = dict(type='int', default=1), cores=dict(type='int', default=1),
cpu = dict(type='str', default='kvm64'), cpu=dict(type='str', default='kvm64'),
cpulimit = dict(type='int'), cpulimit=dict(type='int'),
cpuunits = dict(type='int', default=1000), cpuunits=dict(type='int', default=1000),
delete = dict(type='str', default=None), delete=dict(type='str', default=None),
description = dict(type='str'), description=dict(type='str'),
digest = dict(type='str'), digest=dict(type='str'),
force = dict(type='bool', default=None), force=dict(type='bool', default=None),
format = dict(type='str', default='qcow2', choices=['cloop', 'cow', 'qcow', 'qcow2', 'qed', 'raw', 'vmdk' ]), format=dict(type='str', default='qcow2', choices=['cloop', 'cow', 'qcow', 'qcow2', 'qed', 'raw', 'vmdk']),
freeze = dict(type='bool'), freeze=dict(type='bool'),
full = dict(type='bool', default='yes'), full=dict(type='bool', default='yes'),
hostpci = dict(type='dict'), hostpci=dict(type='dict'),
hotplug = dict(type='str'), hotplug=dict(type='str'),
hugepages = dict(choices=['any', '2', '1024']), hugepages=dict(choices=['any', '2', '1024']),
ide = dict(type='dict', default=None), ide=dict(type='dict', default=None),
keyboard = dict(type='str'), keyboard=dict(type='str'),
kvm = dict(type='bool', default='yes'), kvm=dict(type='bool', default='yes'),
localtime = dict(type='bool'), localtime=dict(type='bool'),
lock = dict(choices=['migrate', 'backup', 'snapshot', 'rollback']), lock=dict(choices=['migrate', 'backup', 'snapshot', 'rollback']),
machine = dict(type='str'), machine=dict(type='str'),
memory = dict(type='int', default=512), memory=dict(type='int', default=512),
migrate_downtime = dict(type='int'), migrate_downtime=dict(type='int'),
migrate_speed = dict(type='int'), migrate_speed=dict(type='int'),
name = dict(type='str'), name=dict(type='str'),
net = dict(type='dict'), net=dict(type='dict'),
newid = dict(type='int', default=None), newid=dict(type='int', default=None),
node = dict(), node=dict(),
numa = dict(type='dict'), numa=dict(type='dict'),
numa_enabled = dict(type='bool'), numa_enabled=dict(type='bool'),
onboot = dict(type='bool', default='yes'), onboot=dict(type='bool', default='yes'),
ostype = dict(default='l26', choices=['other', 'wxp', 'w2k', 'w2k3', 'w2k8', 'wvista', 'win7', 'win8', 'l24', 'l26', 'solaris']), ostype=dict(default='l26', choices=['other', 'wxp', 'w2k', 'w2k3', 'w2k8', 'wvista', 'win7', 'win8', 'l24', 'l26', 'solaris']),
parallel = dict(type='dict'), parallel=dict(type='dict'),
pool = dict(type='str'), pool=dict(type='str'),
protection = dict(type='bool'), protection=dict(type='bool'),
reboot = dict(type='bool'), reboot=dict(type='bool'),
revert = dict(type='str', default=None), revert=dict(type='str', default=None),
sata = dict(type='dict'), sata=dict(type='dict'),
scsi = dict(type='dict'), scsi=dict(type='dict'),
scsihw = dict(choices=['lsi', 'lsi53c810', 'virtio-scsi-pci', 'virtio-scsi-single', 'megasas', 'pvscsi']), scsihw=dict(choices=['lsi', 'lsi53c810', 'virtio-scsi-pci', 'virtio-scsi-single', 'megasas', 'pvscsi']),
serial = dict(type='dict'), serial=dict(type='dict'),
shares = dict(type='int'), shares=dict(type='int'),
skiplock = dict(type='bool'), skiplock=dict(type='bool'),
smbios = dict(type='str'), smbios=dict(type='str'),
snapname = dict(type='str'), snapname=dict(type='str'),
sockets = dict(type='int', default=1), sockets=dict(type='int', default=1),
startdate = dict(type='str'), startdate=dict(type='str'),
startup = dict(), startup=dict(),
state = dict(default='present', choices=['present', 'absent', 'stopped', 'started', 'restarted', 'current']), state=dict(default='present', choices=['present', 'absent', 'stopped', 'started', 'restarted', 'current']),
storage = dict(type='str'), storage=dict(type='str'),
tablet = dict(type='bool', default='no'), tablet=dict(type='bool', default='no'),
target = dict(type='str'), target=dict(type='str'),
tdf = dict(type='bool'), tdf=dict(type='bool'),
template = dict(type='bool', default='no'), template=dict(type='bool', default='no'),
timeout = dict(type='int', default=30), timeout=dict(type='int', default=30),
update = dict(type='bool', default='no'), update=dict(type='bool', default='no'),
validate_certs = dict(type='bool', default='no'), validate_certs=dict(type='bool', default='no'),
vcpus = dict(type='int', default=None), vcpus=dict(type='int', default=None),
vga = dict(default='std', choices=['std', 'cirrus', 'vmware', 'qxl', 'serial0', 'serial1', 'serial2', 'serial3', 'qxl2', 'qxl3', 'qxl4']), vga=dict(default='std', choices=['std', 'cirrus', 'vmware', 'qxl', 'serial0', 'serial1', 'serial2', 'serial3', 'qxl2', 'qxl3', 'qxl4']),
virtio = dict(type='dict', default=None), virtio=dict(type='dict', default=None),
vmid = dict(type='int', default=None), vmid=dict(type='int', default=None),
watchdog = dict(), watchdog=dict(),
), ),
mutually_exclusive = [('delete', 'revert'), ('delete','update'), ('revert','update'), ('clone', 'update'), ('clone', 'delete'), ('clone','revert')], mutually_exclusive=[('delete', 'revert'), ('delete', 'update'), ('revert', 'update'), ('clone', 'update'), ('clone', 'delete'), ('clone', 'revert')],
required_one_of=[('name','vmid',)], required_one_of=[('name', 'vmid',)],
required_if=[('state', 'present', ['node'])] required_if=[('state', 'present', ['node'])]
) )
@ -1026,9 +1030,9 @@ def main():
# If vmid not set get the Next VM id from ProxmoxAPI # If vmid not set get the Next VM id from ProxmoxAPI
# If vm name is set get the VM id from ProxmoxAPI # If vm name is set get the VM id from ProxmoxAPI
if not vmid: if not vmid:
if state == 'present' and ( not update and not clone) and (not delete and not revert): if state == 'present' and (not update and not clone) and (not delete and not revert):
try: try:
vmid = get_nextvmid(proxmox) vmid = get_nextvmid(module, proxmox)
except Exception as e: except Exception as e:
module.fail_json(msg="Can't get the next vimd for VM {} automatically. Ensure your cluster state is good".format(name)) module.fail_json(msg="Can't get the next vimd for VM {} automatically. Ensure your cluster state is good".format(name))
else: else:
@ -1052,7 +1056,7 @@ def main():
module.fail_json(msg='VM with vmid = %s does not exist in cluster' % vmid) module.fail_json(msg='VM with vmid = %s does not exist in cluster' % vmid)
if not newid: if not newid:
try: try:
newid = get_nextvmid(proxmox) newid = get_nextvmid(module, proxmox)
except Exception as e: except Exception as e:
module.fail_json(msg="Can't get the next vimd for VM {} automatically. Ensure your cluster state is good".format(name)) module.fail_json(msg="Can't get the next vimd for VM {} automatically. Ensure your cluster state is good".format(name))
else: else:
@ -1085,65 +1089,65 @@ def main():
module.fail_json(msg="node '%s' does not exist in cluster" % node) module.fail_json(msg="node '%s' does not exist in cluster" % node)
create_vm(module, proxmox, vmid, newid, node, name, memory, cpu, cores, sockets, timeout, update, create_vm(module, proxmox, vmid, newid, node, name, memory, cpu, cores, sockets, timeout, update,
acpi = module.params['acpi'], acpi=module.params['acpi'],
agent = module.params['agent'], agent=module.params['agent'],
autostart = module.params['autostart'], autostart=module.params['autostart'],
balloon = module.params['balloon'], balloon=module.params['balloon'],
bios = module.params['bios'], bios=module.params['bios'],
boot = module.params['boot'], boot=module.params['boot'],
bootdisk = module.params['bootdisk'], bootdisk=module.params['bootdisk'],
cpulimit = module.params['cpulimit'], cpulimit=module.params['cpulimit'],
cpuunits = module.params['cpuunits'], cpuunits=module.params['cpuunits'],
description = module.params['description'], description=module.params['description'],
digest = module.params['digest'], digest=module.params['digest'],
force = module.params['force'], force=module.params['force'],
freeze = module.params['freeze'], freeze=module.params['freeze'],
hostpci = module.params['hostpci'], hostpci=module.params['hostpci'],
hotplug = module.params['hotplug'], hotplug=module.params['hotplug'],
hugepages = module.params['hugepages'], hugepages=module.params['hugepages'],
ide = module.params['ide'], ide=module.params['ide'],
keyboard = module.params['keyboard'], keyboard=module.params['keyboard'],
kvm = module.params['kvm'], kvm=module.params['kvm'],
localtime = module.params['localtime'], localtime=module.params['localtime'],
lock = module.params['lock'], lock=module.params['lock'],
machine = module.params['machine'], machine=module.params['machine'],
migrate_downtime = module.params['migrate_downtime'], migrate_downtime=module.params['migrate_downtime'],
migrate_speed = module.params['migrate_speed'], migrate_speed=module.params['migrate_speed'],
net = module.params['net'], net=module.params['net'],
numa = module.params['numa'], numa=module.params['numa'],
numa_enabled = module.params['numa_enabled'], numa_enabled=module.params['numa_enabled'],
onboot = module.params['onboot'], onboot=module.params['onboot'],
ostype = module.params['ostype'], ostype=module.params['ostype'],
parallel = module.params['parallel'], parallel=module.params['parallel'],
pool = module.params['pool'], pool=module.params['pool'],
protection = module.params['protection'], protection=module.params['protection'],
reboot = module.params['reboot'], reboot=module.params['reboot'],
sata = module.params['sata'], sata=module.params['sata'],
scsi = module.params['scsi'], scsi=module.params['scsi'],
scsihw = module.params['scsihw'], scsihw=module.params['scsihw'],
serial = module.params['serial'], serial=module.params['serial'],
shares = module.params['shares'], shares=module.params['shares'],
skiplock = module.params['skiplock'], skiplock=module.params['skiplock'],
smbios1 = module.params['smbios'], smbios1=module.params['smbios'],
snapname = module.params['snapname'], snapname=module.params['snapname'],
startdate = module.params['startdate'], startdate=module.params['startdate'],
startup = module.params['startup'], startup=module.params['startup'],
tablet = module.params['tablet'], tablet=module.params['tablet'],
target = module.params['target'], target=module.params['target'],
tdf = module.params['tdf'], tdf=module.params['tdf'],
template = module.params['template'], template=module.params['template'],
vcpus = module.params['vcpus'], vcpus=module.params['vcpus'],
vga = module.params['vga'], vga=module.params['vga'],
virtio = module.params['virtio'], virtio=module.params['virtio'],
watchdog = module.params['watchdog']) watchdog=module.params['watchdog'])
if not clone: if not clone:
get_vminfo(module, proxmox, node, vmid, get_vminfo(module, proxmox, node, vmid,
ide = module.params['ide'], ide=module.params['ide'],
net = module.params['net'], net=module.params['net'],
sata = module.params['sata'], sata=module.params['sata'],
scsi = module.params['scsi'], scsi=module.params['scsi'],
virtio = module.params['virtio']) virtio=module.params['virtio'])
if update: if update:
module.exit_json(changed=True, msg="VM %s with vmid %s updated" % (name, vmid)) module.exit_json(changed=True, msg="VM %s with vmid %s updated" % (name, vmid))
elif clone is not None: elif clone is not None:
@ -1180,7 +1184,7 @@ def main():
if getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status'] == 'stopped': if getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status'] == 'stopped':
module.exit_json(changed=False, msg="VM %s is already stopped" % vmid) module.exit_json(changed=False, msg="VM %s is already stopped" % vmid)
if stop_vm(module, proxmox, vm, vmid, timeout, force = module.params['force']): if stop_vm(module, proxmox, vm, vmid, timeout, force=module.params['force']):
module.exit_json(changed=True, msg="VM %s is shutting down" % vmid) module.exit_json(changed=True, msg="VM %s is shutting down" % vmid)
except Exception as e: except Exception as e:
module.fail_json(msg="stopping of VM %s failed with exception: %s" % (vmid, e)) module.fail_json(msg="stopping of VM %s failed with exception: %s" % (vmid, e))
@ -1193,11 +1197,10 @@ def main():
if getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status'] == 'stopped': if getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE)(vmid).status.current.get()['status'] == 'stopped':
module.exit_json(changed=False, msg="VM %s is not running" % vmid) module.exit_json(changed=False, msg="VM %s is not running" % vmid)
if (stop_vm(module, proxmox, vm, vmid, timeout, force = module.params['force']) if stop_vm(module, proxmox, vm, vmid, timeout, force=module.params['force']) and start_vm(module, proxmox, vm, vmid, timeout):
and start_vm(module, proxmox, vm, vmid, timeout)):
module.exit_json(changed=True, msg="VM %s is restarted" % vmid) module.exit_json(changed=True, msg="VM %s is restarted" % vmid)
except Exception as e: except Exception as e:
module.fail_json(msg="restarting of VM %s failed with exception: %s" % ( vmid, e )) module.fail_json(msg="restarting of VM %s failed with exception: %s" % (vmid, e))
elif state == 'absent': elif state == 'absent':
try: try:
@ -1211,12 +1214,12 @@ def main():
taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE).delete(vmid) taskid = getattr(proxmox.nodes(vm[0]['node']), VZ_TYPE).delete(vmid)
while timeout: while timeout:
if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and if (proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['status'] == 'stopped' and
proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK' ): proxmox.nodes(vm[0]['node']).tasks(taskid).status.get()['exitstatus'] == 'OK'):
module.exit_json(changed=True, msg="VM %s removed" % vmid) module.exit_json(changed=True, msg="VM %s removed" % vmid)
timeout = timeout - 1 timeout -= 1
if timeout == 0: if timeout == 0:
module.fail_json(msg='Reached timeout while waiting for removing VM. Last line in task before timeout: %s' module.fail_json(msg='Reached timeout while waiting for removing VM. Last line in task before timeout: %s'
% proxmox_node.tasks(taskid).log.get()[:1]) % proxmox.nodes(vm[0]['node']).tasks(taskid).log.get()[:1])
time.sleep(1) time.sleep(1)
except Exception as e: except Exception as e:
@ -1236,7 +1239,5 @@ def main():
module.fail_json(msg="Unable to get vm {} with vmid = {} status: ".format(name, vmid) + str(e)) module.fail_json(msg="Unable to get vm {} with vmid = {} status: ".format(name, vmid) + str(e))
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -138,6 +138,8 @@ EXAMPLES = '''
import os import os
import time import time
# import module snippets
from ansible.module_utils.basic import AnsibleModule
try: try:
from proxmoxer import ProxmoxAPI from proxmoxer import ProxmoxAPI
@ -145,9 +147,11 @@ try:
except ImportError: except ImportError:
HAS_PROXMOXER = False HAS_PROXMOXER = False
def get_template(proxmox, node, storage, content_type, template): def get_template(proxmox, node, storage, content_type, template):
return [ True for tmpl in proxmox.nodes(node).storage(storage).content.get() return [True for tmpl in proxmox.nodes(node).storage(storage).content.get()
if tmpl['volid'] == '%s:%s/%s' % (storage, content_type, template) ] if tmpl['volid'] == '%s:%s/%s' % (storage, content_type, template)]
def upload_template(module, proxmox, api_host, node, storage, content_type, realpath, timeout): def upload_template(module, proxmox, api_host, node, storage, content_type, realpath, timeout):
taskid = proxmox.nodes(node).storage(storage).upload.post(content=content_type, filename=open(realpath)) taskid = proxmox.nodes(node).storage(storage).upload.post(content=content_type, filename=open(realpath))
@ -163,6 +167,7 @@ def upload_template(module, proxmox, api_host, node, storage, content_type, real
time.sleep(1) time.sleep(1)
return False return False
def delete_template(module, proxmox, node, storage, content_type, template, timeout): def delete_template(module, proxmox, node, storage, content_type, template, timeout):
volid = '%s:%s/%s' % (storage, content_type, template) volid = '%s:%s/%s' % (storage, content_type, template)
proxmox.nodes(node).storage(storage).content.delete(volid) proxmox.nodes(node).storage(storage).content.delete(volid)
@ -176,22 +181,23 @@ def delete_template(module, proxmox, node, storage, content_type, template, time
time.sleep(1) time.sleep(1)
return False return False
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec = dict( argument_spec=dict(
api_host = dict(required=True), api_host=dict(required=True),
api_user = dict(required=True), api_user=dict(required=True),
api_password = dict(no_log=True), api_password=dict(no_log=True),
validate_certs = dict(type='bool', default='no'), validate_certs=dict(type='bool', default='no'),
node = dict(), node=dict(),
src = dict(), src=dict(),
template = dict(), template=dict(),
content_type = dict(default='vztmpl', choices=['vztmpl','iso']), content_type=dict(default='vztmpl', choices=['vztmpl', 'iso']),
storage = dict(default='local'), storage=dict(default='local'),
timeout = dict(type='int', default=30), timeout=dict(type='int', default=30),
force = dict(type='bool', default='no'), force=dict(type='bool', default='no'),
state = dict(default='present', choices=['present', 'absent']), state=dict(default='present', choices=['present', 'absent']),
) )
) )
if not HAS_PROXMOXER: if not HAS_PROXMOXER:
@ -236,7 +242,7 @@ def main():
if upload_template(module, proxmox, api_host, node, storage, content_type, realpath, timeout): if upload_template(module, proxmox, api_host, node, storage, content_type, realpath, timeout):
module.exit_json(changed=True, msg='template with volid=%s:%s/%s uploaded' % (storage, content_type, template)) module.exit_json(changed=True, msg='template with volid=%s:%s/%s uploaded' % (storage, content_type, template))
except Exception as e: except Exception as e:
module.fail_json(msg="uploading of template %s failed with exception: %s" % ( template, e )) module.fail_json(msg="uploading of template %s failed with exception: %s" % (template, e))
elif state == 'absent': elif state == 'absent':
try: try:
@ -251,10 +257,8 @@ def main():
if delete_template(module, proxmox, node, storage, content_type, template, timeout): if delete_template(module, proxmox, node, storage, content_type, template, timeout):
module.exit_json(changed=True, msg='template with volid=%s:%s/%s deleted' % (storage, content_type, template)) module.exit_json(changed=True, msg='template with volid=%s:%s/%s deleted' % (storage, content_type, template))
except Exception as e: except Exception as e:
module.fail_json(msg="deleting of template %s failed with exception: %s" % ( template, e )) module.fail_json(msg="deleting of template %s failed with exception: %s" % (template, e))
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -284,9 +284,6 @@ lib/ansible/modules/cloud/lxc/lxc_container.py
lib/ansible/modules/cloud/lxd/lxd_container.py lib/ansible/modules/cloud/lxd/lxd_container.py
lib/ansible/modules/cloud/lxd/lxd_profile.py lib/ansible/modules/cloud/lxd/lxd_profile.py
lib/ansible/modules/cloud/misc/ovirt.py lib/ansible/modules/cloud/misc/ovirt.py
lib/ansible/modules/cloud/misc/proxmox.py
lib/ansible/modules/cloud/misc/proxmox_kvm.py
lib/ansible/modules/cloud/misc/proxmox_template.py
lib/ansible/modules/cloud/misc/rhevm.py lib/ansible/modules/cloud/misc/rhevm.py
lib/ansible/modules/cloud/misc/serverless.py lib/ansible/modules/cloud/misc/serverless.py
lib/ansible/modules/cloud/misc/virt.py lib/ansible/modules/cloud/misc/virt.py

Loading…
Cancel
Save