def main():
    module_args = proxmox_auth_argument_spec()
    group_info_args = proxmox_group_info_argument_spec()
    module_args.update(group_info_args)

    module = AnsibleModule(argument_spec=module_args,
                           required_one_of=[('api_password', 'api_token_id')],
                           required_together=[('api_token_id',
                                               'api_token_secret')],
                           supports_check_mode=True)
    result = dict(changed=False)

    if not HAS_PROXMOXER:
        module.fail_json(msg=missing_required_lib('proxmoxer'),
                         exception=PROXMOXER_IMP_ERR)

    proxmox = ProxmoxGroupInfoAnsible(module)
    group = module.params['group']

    if group:
        groups = [proxmox.get_group(group=group)]
    else:
        groups = proxmox.get_groups()
    result['proxmox_groups'] = [group.group for group in groups]

    module.exit_json(**result)
예제 #2
0
def main():
    module_args = proxmox_auth_argument_spec()
    task_info_args = proxmox_task_info_argument_spec()
    module_args.update(task_info_args)

    module = AnsibleModule(argument_spec=module_args,
                           required_together=[('api_token_id',
                                               'api_token_secret'),
                                              ('api_user', 'api_password')],
                           required_one_of=[('api_password', 'api_token_id')],
                           supports_check_mode=True)
    result = dict(changed=False)

    if not HAS_PROXMOXER:
        module.fail_json(msg=missing_required_lib('proxmoxer'),
                         exception=PROXMOXER_IMP_ERR)
    proxmox = ProxmoxTaskInfoAnsible(module)
    upid = module.params['task']
    node = module.params['node']
    if upid:
        tasks = proxmox.get_task(upid=upid, node=node)
    else:
        tasks = proxmox.get_tasks(node=node)
    if tasks is not None:
        result['proxmox_tasks'] = [task.info for task in tasks]
        module.exit_json(**result)
    else:
        result['msg'] = 'Task: {0} does not exist on node: {1}.'.format(
            upid, node)
        module.fail_json(**result)
예제 #3
0
def main():
    module_args = proxmox_auth_argument_spec()
    domain_info_args = proxmox_domain_info_argument_spec()
    module_args.update(domain_info_args)

    module = AnsibleModule(argument_spec=module_args,
                           required_one_of=[('api_password', 'api_token_id')],
                           required_together=[('api_token_id',
                                               'api_token_secret')],
                           supports_check_mode=True)
    result = dict(changed=False)

    if not HAS_PROXMOXER:
        module.fail_json(msg=missing_required_lib('proxmoxer'),
                         exception=PROXMOXER_IMP_ERR)

    proxmox = ProxmoxDomainInfoAnsible(module)
    domain = module.params['domain']

    if domain:
        domains = [proxmox.get_domain(realm=domain)]
    else:
        domains = proxmox.get_domains()
    result['proxmox_domains'] = domains

    module.exit_json(**result)
def main():
    module_args = proxmox_auth_argument_spec()
    storage_info_args = proxmox_storage_info_argument_spec()
    module_args.update(storage_info_args)

    module = AnsibleModule(
        argument_spec=module_args,
        required_one_of=[('api_password', 'api_token_id')],
        required_together=[('api_token_id', 'api_token_secret')],
        mutually_exclusive=[('storage', 'type')],
        supports_check_mode=True
    )
    result = dict(
        changed=False
    )

    if not HAS_PROXMOXER:
        module.fail_json(msg=missing_required_lib('proxmoxer'), exception=PROXMOXER_IMP_ERR)

    proxmox = ProxmoxStorageInfoAnsible(module)
    storage = module.params['storage']
    storagetype = module.params['type']

    if storage:
        storages = [proxmox.get_storage(storage)]
    else:
        storages = proxmox.get_storages(type=storagetype)
    result['proxmox_storages'] = [storage.storage for storage in storages]

    module.exit_json(**result)
예제 #5
0
def main():
    module_args = proxmox_auth_argument_spec()
    user_info_args = proxmox_user_info_argument_spec()
    module_args.update(user_info_args)

    module = AnsibleModule(argument_spec=module_args,
                           required_one_of=[('api_password', 'api_token_id')],
                           required_together=[('api_token_id',
                                               'api_token_secret')],
                           mutually_exclusive=[('user', 'userid'),
                                               ('domain', 'userid')],
                           supports_check_mode=True)
    result = dict(changed=False)

    if not HAS_PROXMOXER:
        module.fail_json(msg=missing_required_lib('proxmoxer'),
                         exception=PROXMOXER_IMP_ERR)

    proxmox = ProxmoxUserInfoAnsible(module)
    domain = module.params['domain']
    user = module.params['user']
    if user and domain:
        userid = user + '@' + domain
    else:
        userid = module.params['userid']

    if userid:
        users = [proxmox.get_user(userid=userid)]
    else:
        users = proxmox.get_users(domain=domain)
    result['proxmox_users'] = [user.user for user in users]

    module.exit_json(**result)
예제 #6
0
def main():
    module_args = proxmox_auth_argument_spec()
    proxmox_args = dict(
        vmid=dict(type='int', required=False),
        node=dict(),
        pool=dict(),
        password=dict(no_log=True),
        hostname=dict(),
        ostemplate=dict(),
        disk=dict(type='str'),
        cores=dict(type='int'),
        cpus=dict(type='int'),
        memory=dict(type='int'),
        swap=dict(type='int'),
        netif=dict(type='dict'),
        mounts=dict(type='dict'),
        ip_address=dict(),
        onboot=dict(type='bool'),
        features=dict(type='list', elements='str'),
        storage=dict(default='local'),
        cpuunits=dict(type='int'),
        nameserver=dict(),
        searchdomain=dict(),
        timeout=dict(type='int', default=30),
        force=dict(type='bool', default=False),
        purge=dict(type='bool', default=False),
        state=dict(
            default='present',
            choices=['present', 'absent', 'stopped', 'started', 'restarted']),
        pubkey=dict(type='str', default=None),
        unprivileged=dict(type='bool', default=False),
        description=dict(type='str'),
        hookscript=dict(type='str'),
        proxmox_default_behavior=dict(type='str',
                                      default='no_defaults',
                                      choices=['compatibility',
                                               'no_defaults']),
        clone=dict(type='int'),
        clone_type=dict(default='opportunistic',
                        choices=['full', 'linked', 'opportunistic']),
    )
    module_args.update(proxmox_args)

    module = AnsibleModule(
        argument_spec=module_args,
        required_if=[
            ('state', 'present', ['node', 'hostname']),
            (
                'state', 'present', ('clone', 'ostemplate'), True
            ),  # Require one of clone and ostemplate. Together with mutually_exclusive this ensures that we
            # either clone a container or create a new one from a template file.
        ],
        required_together=[('api_token_id', 'api_token_secret')],
        required_one_of=[('api_password', 'api_token_id')],
        mutually_exclusive=[
            ('clone', 'ostemplate')
        ],  # Creating a new container is done either by cloning an existing one, or based on a template.
    )

    proxmox = ProxmoxLxcAnsible(module)

    global VZ_TYPE
    VZ_TYPE = 'openvz' if proxmox.version() < LooseVersion('4.0') else 'lxc'

    state = module.params['state']
    vmid = module.params['vmid']
    node = module.params['node']
    disk = module.params['disk']
    cpus = module.params['cpus']
    memory = module.params['memory']
    swap = module.params['swap']
    storage = module.params['storage']
    hostname = module.params['hostname']
    if module.params['ostemplate'] is not None:
        template_store = module.params['ostemplate'].split(":")[0]
    timeout = module.params['timeout']
    clone = module.params['clone']

    if module.params['proxmox_default_behavior'] == 'compatibility':
        old_default_values = dict(
            disk="3",
            cores=1,
            cpus=1,
            memory=512,
            swap=0,
            onboot=False,
            cpuunits=1000,
        )
        for param, value in old_default_values.items():
            if module.params[param] is None:
                module.params[param] = value

    # If vmid not set get the Next VM id from ProxmoxAPI
    # If hostname is set get the VM id from ProxmoxAPI
    if not vmid and state == 'present':
        vmid = proxmox.get_nextvmid()
    elif not vmid and hostname:
        vmid = proxmox.get_vmid(hostname, choose_first_if_multiple=True)
    elif not vmid:
        module.exit_json(
            changed=False,
            msg="Vmid could not be fetched for the following action: %s" %
            state)

    # Create a new container
    if state == 'present' and clone is None:
        try:
            if proxmox.get_vm(
                    vmid, ignore_missing=True) and not module.params['force']:
                module.exit_json(changed=False,
                                 msg="VM with vmid = %s is already exists" %
                                 vmid)
            # If no vmid was passed, there cannot be another VM named 'hostname'
            if (not module.params['vmid']
                    and proxmox.get_vmid(hostname,
                                         ignore_missing=True,
                                         choose_first_if_multiple=True)
                    and not module.params['force']):
                vmid = proxmox.get_vmid(hostname,
                                        choose_first_if_multiple=True)
                module.exit_json(
                    changed=False,
                    msg=
                    "VM with hostname %s already exists and has ID number %s" %
                    (hostname, vmid))
            elif not proxmox.get_node(node):
                module.fail_json(msg="node '%s' not exists in cluster" % node)
            elif not proxmox.content_check(node, module.params['ostemplate'],
                                           template_store):
                module.fail_json(
                    msg="ostemplate '%s' not exists on node %s and storage %s"
                    % (module.params['ostemplate'], node, template_store))
        except Exception as e:
            module.fail_json(
                msg=
                "Pre-creation checks of {VZ_TYPE} VM {vmid} failed with exception: {e}"
                .format(VZ_TYPE=VZ_TYPE, vmid=vmid, e=e))

        try:
            proxmox.create_instance(
                vmid,
                node,
                disk,
                storage,
                cpus,
                memory,
                swap,
                timeout,
                clone,
                cores=module.params['cores'],
                pool=module.params['pool'],
                password=module.params['password'],
                hostname=module.params['hostname'],
                ostemplate=module.params['ostemplate'],
                netif=module.params['netif'],
                mounts=module.params['mounts'],
                ip_address=module.params['ip_address'],
                onboot=ansible_to_proxmox_bool(module.params['onboot']),
                cpuunits=module.params['cpuunits'],
                nameserver=module.params['nameserver'],
                searchdomain=module.params['searchdomain'],
                force=ansible_to_proxmox_bool(module.params['force']),
                pubkey=module.params['pubkey'],
                features=",".join(module.params['features'])
                if module.params['features'] is not None else None,
                unprivileged=ansible_to_proxmox_bool(
                    module.params['unprivileged']),
                description=module.params['description'],
                hookscript=module.params['hookscript'])

            module.exit_json(changed=True,
                             msg="Deployed VM %s from template %s" %
                             (vmid, module.params['ostemplate']))
        except Exception as e:
            module.fail_json(
                msg="Creation of %s VM %s failed with exception: %s" %
                (VZ_TYPE, vmid, e))

    # Clone a container
    elif state == 'present' and clone is not None:
        try:
            if proxmox.get_vm(
                    vmid, ignore_missing=True) and not module.params['force']:
                module.exit_json(changed=False,
                                 msg="VM with vmid = %s is already exists" %
                                 vmid)
            # If no vmid was passed, there cannot be another VM named 'hostname'
            if (not module.params['vmid']
                    and proxmox.get_vmid(hostname,
                                         ignore_missing=True,
                                         choose_first_if_multiple=True)
                    and not module.params['force']):
                vmid = proxmox.get_vmid(hostname,
                                        choose_first_if_multiple=True)
                module.exit_json(
                    changed=False,
                    msg=
                    "VM with hostname %s already exists and has ID number %s" %
                    (hostname, vmid))
            if not proxmox.get_vm(clone, ignore_missing=True):
                module.exit_json(changed=False,
                                 msg="Container to be cloned does not exist")
        except Exception as e:
            module.fail_json(
                msg=
                "Pre-clone checks of {VZ_TYPE} VM {vmid} failed with exception: {e}"
                .format(VZ_TYPE=VZ_TYPE, vmid=vmid, e=e))

        try:
            proxmox.create_instance(vmid, node, disk, storage, cpus, memory,
                                    swap, timeout, clone)

            module.exit_json(changed=True,
                             msg="Cloned VM %s from %s" % (vmid, clone))
        except Exception as e:
            module.fail_json(msg="Cloning %s VM %s failed with exception: %s" %
                             (VZ_TYPE, vmid, e))

    elif state == 'started':
        try:
            vm = proxmox.get_vm(vmid)
            if getattr(
                    proxmox.proxmox_api.nodes(vm['node']),
                    VZ_TYPE)(vmid).status.current.get()['status'] == 'running':
                module.exit_json(changed=False,
                                 msg="VM %s is already running" % vmid)

            if proxmox.start_instance(vm, vmid, timeout):
                module.exit_json(changed=True, msg="VM %s started" % vmid)
        except Exception as e:
            module.fail_json(
                msg="starting of VM %s failed with exception: %s" % (vmid, e))

    elif state == 'stopped':
        try:
            vm = proxmox.get_vm(vmid)

            if getattr(
                    proxmox.proxmox_api.nodes(vm['node']),
                    VZ_TYPE)(vmid).status.current.get()['status'] == 'mounted':
                if module.params['force']:
                    if proxmox.umount_instance(vm, vmid, timeout):
                        module.exit_json(changed=True,
                                         msg="VM %s is shutting down" % vmid)
                else:
                    module.exit_json(
                        changed=False,
                        msg=("VM %s is already shutdown, but mounted. "
                             "You can use force option to umount it.") % vmid)

            if getattr(
                    proxmox.proxmox_api.nodes(vm['node']),
                    VZ_TYPE)(vmid).status.current.get()['status'] == 'stopped':
                module.exit_json(changed=False,
                                 msg="VM %s is already shutdown" % vmid)

            if proxmox.stop_instance(vm,
                                     vmid,
                                     timeout,
                                     force=module.params['force']):
                module.exit_json(changed=True,
                                 msg="VM %s is shutting down" % vmid)
        except Exception as e:
            module.fail_json(
                msg="stopping of VM %s failed with exception: %s" % (vmid, e))

    elif state == 'restarted':
        try:
            vm = proxmox.get_vm(vmid)

            vm_status = getattr(proxmox.proxmox_api.nodes(vm['node']),
                                VZ_TYPE)(vmid).status.current.get()['status']
            if vm_status in ['stopped', 'mounted']:
                module.exit_json(changed=False,
                                 msg="VM %s is not running" % vmid)

            if (proxmox.stop_instance(
                    vm, vmid, timeout, force=module.params['force'])
                    and proxmox.start_instance(vm, vmid, timeout)):
                module.exit_json(changed=True, msg="VM %s is restarted" % vmid)
        except Exception as e:
            module.fail_json(
                msg="restarting of VM %s failed with exception: %s" %
                (vmid, e))

    elif state == 'absent':
        try:
            vm = proxmox.get_vm(vmid, ignore_missing=True)
            if not vm:
                module.exit_json(changed=False,
                                 msg="VM %s does not exist" % vmid)

            vm_status = getattr(proxmox.proxmox_api.nodes(vm['node']),
                                VZ_TYPE)(vmid).status.current.get()['status']
            if vm_status == 'running':
                module.exit_json(
                    changed=False,
                    msg="VM %s is running. Stop it before deletion." % vmid)

            if vm_status == 'mounted':
                module.exit_json(
                    changed=False,
                    msg=
                    "VM %s is mounted. Stop it with force option before deletion."
                    % vmid)

            delete_params = {}

            if module.params['purge']:
                delete_params['purge'] = 1

            taskid = getattr(proxmox.proxmox_api.nodes(vm['node']),
                             VZ_TYPE).delete(vmid, **delete_params)

            while timeout:
                task_status = proxmox.proxmox_api.nodes(
                    vm['node']).tasks(taskid).status.get()
                if (task_status['status'] == 'stopped'
                        and task_status['exitstatus'] == 'OK'):
                    module.exit_json(changed=True, msg="VM %s removed" % vmid)
                timeout -= 1
                if timeout == 0:
                    module.fail_json(
                        msg=
                        'Reached timeout while waiting for removing VM. Last line in task before timeout: %s'
                        % proxmox.proxmox_api.nodes(vm['node']).tasks(
                            taskid).log.get()[:1])

                time.sleep(1)
        except Exception as e:
            module.fail_json(
                msg="deletion of VM %s failed with exception: %s" %
                (vmid, to_native(e)))
예제 #7
0
def main():
    module_args = proxmox_auth_argument_spec()
    nic_args = dict(
        bridge=dict(type='str'),
        firewall=dict(type='bool', default=False),
        interface=dict(type='str', required=True),
        link_down=dict(type='bool', default=False),
        mac=dict(type='str'),
        model=dict(choices=[
            'e1000', 'e1000-82540em', 'e1000-82544gc', 'e1000-82545em',
            'i82551', 'i82557b', 'i82559er', 'ne2k_isa', 'ne2k_pci', 'pcnet',
            'rtl8139', 'virtio', 'vmxnet3'
        ],
                   default='virtio'),
        mtu=dict(type='int'),
        name=dict(type='str'),
        queues=dict(type='int'),
        rate=dict(type='float'),
        state=dict(default='present', choices=['present', 'absent']),
        tag=dict(type='int'),
        trunks=dict(type='list', elements='int'),
        vmid=dict(type='int'),
    )
    module_args.update(nic_args)

    module = AnsibleModule(
        argument_spec=module_args,
        required_together=[('api_token_id', 'api_token_secret')],
        required_one_of=[('name', 'vmid'), ('api_password', 'api_token_id')],
        supports_check_mode=True,
    )

    proxmox = ProxmoxNicAnsible(module)

    interface = module.params['interface']
    model = module.params['model']
    name = module.params['name']
    state = module.params['state']
    vmid = module.params['vmid']

    # If vmid is not defined then retrieve its value from the vm name,
    if not vmid:
        vmid = proxmox.get_vmid(name)

    # Ensure VM id exists
    proxmox.get_vm(vmid)

    if state == 'present':
        try:
            if proxmox.update_nic(vmid,
                                  interface,
                                  model,
                                  bridge=module.params['bridge'],
                                  firewall=module.params['firewall'],
                                  link_down=module.params['link_down'],
                                  mac=module.params['mac'],
                                  mtu=module.params['mtu'],
                                  queues=module.params['queues'],
                                  rate=module.params['rate'],
                                  tag=module.params['tag'],
                                  trunks=module.params['trunks']):
                module.exit_json(
                    changed=True,
                    vmid=vmid,
                    msg="Nic {0} updated on VM with vmid {1}".format(
                        interface, vmid))
            else:
                module.exit_json(
                    vmid=vmid,
                    msg="Nic {0} unchanged on VM with vmid {1}".format(
                        interface, vmid))
        except Exception as e:
            module.fail_json(
                vmid=vmid,
                msg='Unable to change nic {0} on VM with vmid {1}: '.format(
                    interface, vmid) + str(e))

    elif state == 'absent':
        try:
            if proxmox.delete_nic(vmid, interface):
                module.exit_json(
                    changed=True,
                    vmid=vmid,
                    msg="Nic {0} deleted on VM with vmid {1}".format(
                        interface, vmid))
            else:
                module.exit_json(
                    vmid=vmid,
                    msg="Nic {0} does not exist on VM with vmid {1}".format(
                        interface, vmid))
        except Exception as e:
            module.fail_json(
                vmid=vmid,
                msg='Unable to delete nic {0} on VM with vmid {1}: '.format(
                    interface, vmid) + str(e))
예제 #8
0
def main():
    module_args = proxmox_auth_argument_spec()
    snap_args = dict(
        vmid=dict(required=False),
        hostname=dict(),
        timeout=dict(type='int', default=30),
        state=dict(default='present', choices=['present', 'absent']),
        description=dict(type='str'),
        snapname=dict(type='str', default='ansible_snap'),
        force=dict(type='bool', default='no'),
        vmstate=dict(type='bool', default='no'),
    )
    module_args.update(snap_args)

    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

    proxmox = ProxmoxSnapAnsible(module)

    state = module.params['state']
    vmid = module.params['vmid']
    hostname = module.params['hostname']
    description = module.params['description']
    snapname = module.params['snapname']
    timeout = module.params['timeout']
    force = module.params['force']
    vmstate = module.params['vmstate']

    # If hostname is set get the VM id from ProxmoxAPI
    if not vmid and hostname:
        vmid = proxmox.get_vmid(hostname, choose_first_if_multiple=True)
    elif not vmid:
        module.exit_json(
            changed=False,
            msg="Vmid could not be fetched for the following action: %s" %
            state)

    vm = proxmox.get_vm(vmid)

    if state == 'present':
        try:
            for i in proxmox.snapshot(vm, vmid).get():
                if i['name'] == snapname:
                    module.exit_json(changed=False,
                                     msg="Snapshot %s is already present" %
                                     snapname)

            if proxmox.snapshot_create(vm, vmid, timeout, snapname,
                                       description, vmstate):
                if module.check_mode:
                    module.exit_json(changed=False,
                                     msg="Snapshot %s would be created" %
                                     snapname)
                else:
                    module.exit_json(changed=True,
                                     msg="Snapshot %s created" % snapname)

        except Exception as e:
            module.fail_json(
                msg="Creating snapshot %s of VM %s failed with exception: %s" %
                (snapname, vmid, to_native(e)))

    elif state == 'absent':
        try:
            snap_exist = False

            for i in proxmox.snapshot(vm, vmid).get():
                if i['name'] == snapname:
                    snap_exist = True
                    continue

            if not snap_exist:
                module.exit_json(changed=False,
                                 msg="Snapshot %s does not exist" % snapname)
            else:
                if proxmox.snapshot_remove(vm, vmid, timeout, snapname, force):
                    if module.check_mode:
                        module.exit_json(changed=False,
                                         msg="Snapshot %s would be removed" %
                                         snapname)
                    else:
                        module.exit_json(changed=True,
                                         msg="Snapshot %s removed" % snapname)

        except Exception as e:
            module.fail_json(
                msg="Removing snapshot %s of VM %s failed with exception: %s" %
                (snapname, vmid, to_native(e)))
예제 #9
0
def main():
    module_args = proxmox_auth_argument_spec()
    nic_args = dict(
        bridge=dict(type='str'),
        firewall=dict(type='bool', default=False),
        interface=dict(type='str', required=True),
        link_down=dict(type='bool', default=False),
        mac=dict(type='str'),
        model=dict(choices=['e1000', 'e1000-82540em', 'e1000-82544gc', 'e1000-82545em',
                            'i82551', 'i82557b', 'i82559er', 'ne2k_isa', 'ne2k_pci', 'pcnet',
                            'rtl8139', 'virtio', 'vmxnet3'], default='virtio'),
        mtu=dict(type='int'),
        name=dict(type='str'),
        queues=dict(type='int'),
        rate=dict(type='float'),
        state=dict(default='present', choices=['present', 'absent']),
        tag=dict(type='int'),
        trunks=dict(type='list', elements='int'),
        vmid=dict(type='int'),
    )
    module_args.update(nic_args)

    module = AnsibleModule(
        argument_spec=module_args,
        required_together=[('api_token_id', 'api_token_secret')],
        required_one_of=[('name', 'vmid'), ('api_password', 'api_token_id')],
        supports_check_mode=True,
    )

    if not HAS_PROXMOXER:
        module.fail_json(msg='proxmoxer required for this module')

    api_host = module.params['api_host']
    api_password = module.params['api_password']
    api_token_id = module.params['api_token_id']
    api_token_secret = module.params['api_token_secret']
    api_user = module.params['api_user']
    interface = module.params['interface']
    model = module.params['model']
    name = module.params['name']
    state = module.params['state']
    validate_certs = module.params['validate_certs']
    vmid = module.params['vmid']

    auth_args = {'user': api_user}
    if not (api_token_id and api_token_secret):
        auth_args['password'] = api_password
    else:
        auth_args['token_name'] = api_token_id
        auth_args['token_value'] = api_token_secret

    try:
        proxmox = ProxmoxAPI(api_host, verify_ssl=validate_certs, **auth_args)
    except Exception as e:
        module.fail_json(msg='authorization on proxmox cluster failed with exception: %s' % e)

    # If vmid is not defined then retrieve its value from the vm name,
    if not vmid:
        vmid = get_vmid(module, proxmox, name)

    # Ensure VM id exists
    if not get_vm(proxmox, vmid):
        module.fail_json(vmid=vmid, msg='VM with vmid = %s does not exist in cluster' % vmid)

    if state == 'present':
        try:
            if update_nic(module, proxmox, vmid, interface, model,
                          bridge=module.params['bridge'],
                          firewall=module.params['firewall'],
                          link_down=module.params['link_down'],
                          mac=module.params['mac'],
                          mtu=module.params['mtu'],
                          queues=module.params['queues'],
                          rate=module.params['rate'],
                          tag=module.params['tag'],
                          trunks=module.params['trunks']):
                module.exit_json(changed=True, vmid=vmid, msg="Nic {0} updated on VM with vmid {1}".format(interface, vmid))
            else:
                module.exit_json(vmid=vmid, msg="Nic {0} unchanged on VM with vmid {1}".format(interface, vmid))
        except Exception as e:
            module.fail_json(vmid=vmid, msg='Unable to change nic {0} on VM with vmid {1}: '.format(interface, vmid) + str(e))

    elif state == 'absent':
        try:
            if delete_nic(module, proxmox, vmid, interface):
                module.exit_json(changed=True, vmid=vmid, msg="Nic {0} deleted on VM with vmid {1}".format(interface, vmid))
            else:
                module.exit_json(vmid=vmid, msg="Nic {0} does not exist on VM with vmid {1}".format(interface, vmid))
        except Exception as e:
            module.fail_json(vmid=vmid, msg='Unable to delete nic {0} on VM with vmid {1}: '.format(interface, vmid) + str(e))
예제 #10
0
def main():
    module_args = proxmox_auth_argument_spec()
    template_args = dict(
        node=dict(),
        src=dict(type='path'),
        template=dict(),
        content_type=dict(default='vztmpl', choices=['vztmpl', 'iso']),
        storage=dict(default='local'),
        timeout=dict(type='int', default=30),
        force=dict(type='bool', default=False),
        state=dict(default='present', choices=['present', 'absent']),
    )
    module_args.update(template_args)

    module = AnsibleModule(
        argument_spec=module_args,
        required_together=[('api_token_id', 'api_token_secret')],
        required_one_of=[('api_password', 'api_token_id')],
        required_if=[('state', 'absent', ['template'])]
    )

    proxmox = ProxmoxTemplateAnsible(module)

    state = module.params['state']
    node = module.params['node']
    storage = module.params['storage']
    timeout = module.params['timeout']

    if state == 'present':
        try:
            content_type = module.params['content_type']
            src = module.params['src']

            # download appliance template
            if content_type == 'vztmpl' and not src:
                template = module.params['template']

                if not template:
                    module.fail_json(msg='template param for downloading appliance template is mandatory')

                if proxmox.get_template(node, storage, content_type, template) and not module.params['force']:
                    module.exit_json(changed=False, msg='template with volid=%s:%s/%s already exists' % (storage, content_type, template))

                if proxmox.download_template(node, storage, template, timeout):
                    module.exit_json(changed=True, msg='template with volid=%s:%s/%s downloaded' % (storage, content_type, template))

            template = os.path.basename(src)
            if proxmox.get_template(node, storage, content_type, template) and not module.params['force']:
                module.exit_json(changed=False, msg='template with volid=%s:%s/%s is already exists' % (storage, content_type, template))
            elif not src:
                module.fail_json(msg='src param to uploading template file is mandatory')
            elif not (os.path.exists(src) and os.path.isfile(src)):
                module.fail_json(msg='template file on path %s not exists' % src)

            if proxmox.upload_template(node, storage, content_type, src, timeout):
                module.exit_json(changed=True, msg='template with volid=%s:%s/%s uploaded' % (storage, content_type, template))
        except Exception as e:
            module.fail_json(msg="uploading/downloading of template %s failed with exception: %s" % (template, e))

    elif state == 'absent':
        try:
            content_type = module.params['content_type']
            template = module.params['template']

            if not proxmox.get_template(node, storage, content_type, template):
                module.exit_json(changed=False, msg='template with volid=%s:%s/%s is already deleted' % (storage, content_type, template))

            if proxmox.delete_template(node, storage, content_type, template, timeout):
                module.exit_json(changed=True, msg='template with volid=%s:%s/%s deleted' % (storage, content_type, template))
        except Exception as e:
            module.fail_json(msg="deleting of template %s failed with exception: %s" % (template, e))