def main():
    argument_spec = ovirt_full_argument_spec(
        id=dict(default=None),
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(required=True),
        template=dict(default=None),
        cluster=dict(default=None),
        description=dict(default=None),
        vm=dict(default=None, type='dict'),
        comment=dict(default=None),
        vm_per_user=dict(default=None, type='int'),
        prestarted=dict(default=None, type='int'),
        vm_count=dict(default=None, type='int'),
        type=dict(default=None, choices=['automatic', 'manual']),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)
    check_params(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        vm_pools_service = connection.system_service().vm_pools_service()
        vm_pools_module = VmPoolsModule(
            connection=connection,
            module=module,
            service=vm_pools_service,
        )

        state = module.params['state']
        if state == 'present':
            ret = vm_pools_module.create()

            # Wait for all VM pool VMs to be created:
            if module.params['wait']:
                vms_service = connection.system_service().vms_service()
                for vm in vms_service.list(search='pool=%s' % module.params['name']):
                    wait(
                        service=vms_service.service(vm.id),
                        condition=lambda vm: vm.status in [otypes.VmStatus.DOWN, otypes.VmStatus.UP],
                        timeout=module.params['timeout'],
                    )

        elif state == 'absent':
            ret = vm_pools_module.remove()

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, required=True),
        description=dict(default=None),
        local=dict(type='bool'),
        id=dict(default=None),
        compatibility_version=dict(default=None),
        quota_mode=dict(choices=['disabled', 'audit', 'enabled']),
        comment=dict(default=None),
        mac_pool=dict(default=None),
        force=dict(default=None, type='bool'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)
    check_params(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        data_centers_service = connection.system_service(
        ).data_centers_service()
        data_centers_module = DatacentersModule(
            connection=connection,
            module=module,
            service=data_centers_service,
        )

        state = module.params['state']
        if state == 'present':
            ret = data_centers_module.create()
        elif state == 'absent':
            ret = data_centers_module.remove(force=module.params['force'])

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Example #3
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(required=True),
        authz_name=dict(required=True, aliases=['domain']),
        namespace=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)
    check_params(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        users_service = connection.system_service().users_service()
        users_module = UsersModule(
            connection=connection,
            module=module,
            service=users_service,
        )

        state = module.params['state']
        if state == 'present':
            ret = users_module.create(search_params={
                'usrname': username(module),
            })
        elif state == 'absent':
            ret = users_module.remove(search_params={
                'usrname': username(module),
            })

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Example #4
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None),
        description=dict(default=None),
        type=dict(
            default=None,
            required=True,
            choices=[
                OS_IMAGE,
                NETWORK,
                OS_VOLUME,
                FOREMAN,
            ],
            aliases=['provider'],
        ),
        url=dict(default=None),
        username=dict(default=None),
        password=dict(default=None, no_log=True),
        tenant_name=dict(default=None, aliases=['tenant']),
        authentication_url=dict(default=None, aliases=['auth_url']),
        data_center=dict(default=None),
        read_only=dict(default=None, type='bool'),
        network_type=dict(
            default='external',
            choices=['external', 'neutron'],
        ),
        authentication_keys=dict(
            default=[],
            aliases=['auth_keys'],
            type='list',
            no_log=True,
        ),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)
    check_params(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        provider_type_param = module.params.get('type')
        provider_type, external_providers_service = _external_provider_service(
            provider_type=provider_type_param,
            system_service=connection.system_service(),
        )
        external_providers_module = ExternalProviderModule(
            connection=connection,
            module=module,
            service=external_providers_service,
        )
        external_providers_module.provider_type(provider_type)

        state = module.params.pop('state')
        if state == 'absent':
            ret = external_providers_module.remove()
        elif state == 'present':
            ret = external_providers_module.create()
            openstack_volume_provider_id = ret.get('id')
            if (provider_type_param == OS_VOLUME
                    and openstack_volume_provider_id):
                external_providers_module.update_volume_provider_auth_keys(
                    ret,
                    external_providers_service,
                    module.params.get('authentication_keys'),
                )

        module.exit_json(**ret)

    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(choices=[
            'present', 'absent', 'attached', 'detached', 'exported', 'imported'
        ],
                   default='present'),
        id=dict(default=None),
        name=dict(default=None, aliases=['alias']),
        description=dict(default=None),
        vm_name=dict(default=None),
        vm_id=dict(default=None),
        size=dict(default=None),
        interface=dict(default=None, ),
        storage_domain=dict(default=None),
        storage_domains=dict(default=None, type='list'),
        profile=dict(default=None),
        quota_id=dict(default=None),
        format=dict(default='cow', choices=['raw', 'cow']),
        content_type=dict(default='data',
                          choices=[
                              'data', 'iso', 'hosted_engine',
                              'hosted_engine_sanlock',
                              'hosted_engine_metadata',
                              'hosted_engine_configuration'
                          ]),
        sparse=dict(default=None, type='bool'),
        bootable=dict(default=None, type='bool'),
        shareable=dict(default=None, type='bool'),
        logical_unit=dict(default=None, type='dict'),
        download_image_path=dict(default=None),
        upload_image_path=dict(default=None, aliases=['image_path']),
        force=dict(default=False, type='bool'),
        sparsify=dict(default=None, type='bool'),
        openstack_volume_type=dict(default=None),
        image_provider=dict(default=None),
        host=dict(default=None),
        wipe_after_delete=dict(type='bool', default=None),
        activate=dict(default=None, type='bool'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    lun = module.params.get('logical_unit')
    host = module.params['host']
    # Fail when host is specified with the LUN id. Lun id is needed to identify
    # an existing disk if already available inthe environment.
    if (host and lun is None) or (host and lun.get("id") is None):
        module.fail_json(msg="Can not use parameter host ({0!s}) without "
                         "specifying the logical_unit id".format(host))

    check_sdk(module)
    check_params(module)

    try:
        disk = None
        state = module.params['state']
        auth = module.params.get('auth')
        connection = create_connection(auth)
        disks_service = connection.system_service().disks_service()
        disks_module = DisksModule(
            connection=connection,
            module=module,
            service=disks_service,
        )

        force_create = False
        vm_service = get_vm_service(connection, module)
        if lun:
            disk = _search_by_lun(disks_service, lun.get('id'))
        else:
            disk = disks_module.search_entity(
                search_params=searchable_attributes(module))
            if vm_service and disk:
                # If the VM don't exist in VMs disks, but still it's found it means it was found
                # for template with same name as VM, so we should force create the VM disk.
                force_create = disk.id not in [
                    a.disk.id
                    for a in vm_service.disk_attachments_service().list()
                    if a.disk
                ]

        ret = None
        # First take care of creating the VM, if needed:
        if state in ('present', 'detached', 'attached'):
            # Always activate disk when its being created
            if vm_service is not None and disk is None:
                module.params['activate'] = True
            ret = disks_module.create(
                entity=disk if not force_create else None,
                result_state=otypes.DiskStatus.OK if lun is None else None,
                fail_condition=lambda d: d.status == otypes.DiskStatus.ILLEGAL
                if lun is None else False,
                force_create=force_create,
            )
            is_new_disk = ret['changed']
            ret['changed'] = ret[
                'changed'] or disks_module.update_storage_domains(ret['id'])
            # We need to pass ID to the module, so in case we want detach/attach disk
            # we have this ID specified to attach/detach method:
            module.params['id'] = ret['id']

            # Upload disk image in case it's new disk or force parameter is passed:
            if module.params['upload_image_path'] and (is_new_disk or
                                                       module.params['force']):
                uploaded = upload_disk_image(connection, module)
                ret['changed'] = ret['changed'] or uploaded
            # Download disk image in case it's file don't exist or force parameter is passed:
            if (module.params['download_image_path'] and
                (not os.path.isfile(module.params['download_image_path'])
                 or module.params['force'])):
                downloaded = download_disk_image(connection, module)
                ret['changed'] = ret['changed'] or downloaded

            # Disk sparsify, only if disk is of image type:
            if not module.check_mode:
                disk = disks_service.disk_service(module.params['id']).get()
                if disk.storage_type == otypes.DiskStorageType.IMAGE:
                    ret = disks_module.action(
                        action='sparsify',
                        action_condition=lambda d: module.params['sparsify'],
                        wait_condition=lambda d: d.status == otypes.DiskStatus.
                        OK,
                    )

        # Export disk as image to glance domain
        elif state == 'exported':
            disk = disks_module.search_entity()
            if disk is None:
                module.fail_json(
                    msg="Can not export given disk '%s', it doesn't exist" %
                    module.params.get('name') or module.params.get('id'))
            if disk.storage_type == otypes.DiskStorageType.IMAGE:
                ret = disks_module.action(
                    action='export',
                    action_condition=lambda d: module.params['image_provider'],
                    wait_condition=lambda d: d.status == otypes.DiskStatus.OK,
                    storage_domain=otypes.StorageDomain(
                        name=module.params['image_provider']),
                )
        elif state == 'imported':
            glance_service = connection.system_service(
            ).openstack_image_providers_service()
            image_provider = search_by_name(glance_service,
                                            module.params['image_provider'])
            images_service = glance_service.service(
                image_provider.id).images_service()
            entity_id = get_id_by_name(images_service, module.params['name'])
            images_service.service(entity_id).import_(
                storage_domain=otypes.StorageDomain(
                    name=module.params['storage_domain'])
                if module.params['storage_domain'] else None,
                disk=otypes.Disk(name=module.params['name']),
                import_as_template=False,
            )
            # Wait for disk to appear in system:
            disk = disks_module.wait_for_import(
                condition=lambda t: t.status == otypes.DiskStatus.OK)
            ret = disks_module.create(result_state=otypes.DiskStatus.OK)
        elif state == 'absent':
            ret = disks_module.remove()

        # If VM was passed attach/detach disks to/from the VM:
        if vm_service:
            disk_attachments_service = vm_service.disk_attachments_service()
            disk_attachments_module = DiskAttachmentsModule(
                connection=connection,
                module=module,
                service=disk_attachments_service,
                changed=ret['changed'] if ret else False,
            )

            if state == 'present' or state == 'attached':
                ret = disk_attachments_module.create()
                if lun is None:
                    wait(
                        service=disk_attachments_service.service(ret['id']),
                        condition=lambda d: follow_link(connection, d.disk).
                        status == otypes.DiskStatus.OK,
                        wait=module.params['wait'],
                        timeout=module.params['timeout'],
                    )
            elif state == 'detached':
                ret = disk_attachments_module.remove()

        # When the host parameter is specified and the disk is not being
        # removed, refresh the information about the LUN.
        if state != 'absent' and host:
            hosts_service = connection.system_service().hosts_service()
            host_id = get_id_by_name(hosts_service, host)
            disks_service.disk_service(disk.id).refresh_lun(
                otypes.Host(id=host_id))

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Example #6
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present']),
        name=dict(type='str'),
        id=dict(type='str'),
        memory=dict(type='str'),
        memory_guaranteed=dict(type='str'),
        memory_max=dict(type='str'),
        cpu_sockets=dict(type='int'),
        cpu_cores=dict(type='int'),
        cpu_threads=dict(type='int'),
        operating_system=dict(type='str'),
        boot_devices=dict(type='list', choices=['cdrom', 'hd', 'network']),
        serial_console=dict(type='bool'),
        usb_support=dict(type='bool'),
        high_availability=dict(type='bool'),
        high_availability_priority=dict(type='int'),
        watchdog=dict(type='dict'),
        host=dict(type='str'),
        graphical_console=dict(type='dict'),
        description=dict(type='str'),
        cpu_mode=dict(type='str'),
        rng_device=dict(type='str'),
        rng_bytes=dict(type='int', default=None),
        rng_period=dict(type='int', default=None),
        placement_policy=dict(type='str'),
        cpu_pinning=dict(type='list'),
        soundcard_enabled=dict(type='bool', default=None),
        virtio_scsi=dict(type='bool', default=None),
        smartcard_enabled=dict(type='bool', default=None),
        io_threads=dict(type='int', default=None),
        nics=dict(type='list', default=[]),
        ballooning_enabled=dict(type='bool', default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[['id', 'name']],
    )

    check_sdk(module)
    check_params(module)

    try:
        state = module.params['state']
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        its_service = connection.system_service().instance_types_service()
        its_module = InstanceTypeModule(
            connection=connection,
            module=module,
            service=its_service,
        )
        it = its_module.search_entity()

        if state == 'present':
            ret = its_module.create(entity=it)
            its_module.post_present(ret['id'])
            ret['changed'] = its_module.changed
        elif state == 'absent':
            ret = its_module.remove()
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)