def _find_attached_datacenter_name(self, sd_name):
        """
        Finds the name of the datacenter that a given
        storage domain is attached to.

        Args:
            sd_name (str): Storage Domain name

        Returns:
            str: Data Center name

        Raises:
            Exception: In case storage domain in not attached to
                an active Datacenter
        """
        dcs_service = self._connection.system_service().data_centers_service()
        dc = search_by_attributes(dcs_service, storage=sd_name)
        if dc is None:
            raise Exception(
                "Can't bring storage to state `%s`, because it seems that"
                "it is not attached to any datacenter"
                % self.param('state')
            )
        else:
            if dc.status == dcstatus.UP:
                return dc.name
            else:
                raise Exception(
                    "Can't bring storage to state `%s`, because Datacenter "
                    "%s is not UP"
                )
Beispiel #2
0
    def _find_attached_datacenter_name(self, sd_name):
        """
        Finds the name of the datacenter that a given
        storage domain is attached to.

        Args:
            sd_name (str): Storage Domain name

        Returns:
            str: Data Center name

        Raises:
            Exception: In case storage domain in not attached to
                an active Datacenter
        """
        dcs_service = self._connection.system_service().data_centers_service()
        dc = search_by_attributes(dcs_service, storage=sd_name)
        if dc is None:
            raise Exception(
                "Can't bring storage to state `%s`, because it seems that"
                "it is not attached to any datacenter" % self.param('state'))
        else:
            if dc.status == dcstatus.UP:
                return dc.name
            else:
                raise Exception(
                    "Can't bring storage to state `%s`, because Datacenter "
                    "%s is not UP")
Beispiel #3
0
 def _user(self):
     user = search_by_attributes(
         self._connection.system_service().users_service(),
         usrname="{name}@{authz_name}".format(
             name=self._module.params['user_name'],
             authz_name=self._module.params['authz_name'],
         ),
     )
     if user is None:
         raise Exception("User '%s' was not found." % self._module.params['user_name'])
     return user
Beispiel #4
0
 def _user(self):
     user = search_by_attributes(
         self._connection.system_service().users_service(),
         usrname="{name}@{authz_name}".format(
             name=self._module.params['user_name'],
             authz_name=self._module.params['authz_name'],
         ),
     )
     if user is None:
         raise Exception("User '%s' was not found." % self._module.params['user_name'])
     return user
 def _attached_sd_service(self, storage_domain):
     dc_name = self._module.params['data_center']
     # Find the DC, where the storage we want to remove reside:
     if not dc_name and self._module.params['state'] == 'absent':
         dcs_service = self._connection.system_service().data_centers_service()
         dc = search_by_attributes(dcs_service, storage=storage_domain.name, status='up')
         if dc is None:
             raise Exception("Can't remove storage, because no active datacenter found for it's removal")
         dc_name = dc.name
     attached_sds_service = self._attached_sds_service(dc_name)
     attached_sd_service = attached_sds_service.storage_domain_service(storage_domain.id)
     return attached_sd_service
Beispiel #6
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'exported', 'imported', 'registered'
            ],
            default='present',
        ),
        name=dict(default=None, required=True),
        vm=dict(default=None),
        description=dict(default=None),
        cluster=dict(default=None),
        cpu_profile=dict(default=None),
        disks=dict(default=[], type='list'),
        clone_permissions=dict(type='bool'),
        export_domain=dict(default=None),
        storage_domain=dict(default=None),
        exclusive=dict(type='bool'),
        image_provider=dict(default=None),
        image_disk=dict(default=None, aliases=['glance_image_disk_name']),
        template_image_disk_name=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        templates_service = connection.system_service().templates_service()
        templates_module = TemplatesModule(
            connection=connection,
            module=module,
            service=templates_service,
        )

        state = module.params['state']
        if state == 'present':
            ret = templates_module.create(
                result_state=otypes.TemplateStatus.OK,
                clone_permissions=module.params['clone_permissions'],
            )
        elif state == 'absent':
            ret = templates_module.remove()
        elif state == 'exported':
            template = templates_module.search_entity()
            export_service = templates_module._get_export_domain_service()
            export_template = search_by_attributes(
                export_service.templates_service(), id=template.id)

            ret = templates_module.action(
                entity=template,
                action='export',
                action_condition=lambda t: export_template is None,
                wait_condition=lambda t: t is not None,
                post_action=templates_module.post_export_action,
                storage_domain=otypes.StorageDomain(
                    id=export_service.get().id),
                exclusive=module.params['exclusive'],
            )
        elif state == 'imported':
            template = templates_module.search_entity()
            if template:
                ret = templates_module.create(
                    result_state=otypes.TemplateStatus.OK, )
            else:
                kwargs = {}
                if module.params['image_provider']:
                    kwargs.update(
                        disk=otypes.Disk(
                            name=module.params['template_image_disk_name']
                            or module.params['image_disk']),
                        template=otypes.Template(name=module.params['name'], ),
                        import_as_template=True,
                    )

                if module.params['image_disk']:
                    # We need to refresh storage domain to get list of images:
                    templates_module._get_export_domain_service(
                    ).images_service().list()

                    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()
                else:
                    images_service = templates_module._get_export_domain_service(
                    ).templates_service()
                template_name = module.params['image_disk'] or module.params[
                    'name']
                entity = search_by_name(images_service, template_name)
                if entity is None:
                    raise Exception("Image/template '%s' was not found." %
                                    template_name)

                images_service.service(entity.id).import_(
                    storage_domain=otypes.StorageDomain(
                        name=module.params['storage_domain'])
                    if module.params['storage_domain'] else None,
                    cluster=otypes.Cluster(name=module.params['cluster'])
                    if module.params['cluster'] else None,
                    **kwargs)
                template = wait_for_import(module, templates_service)
                ret = {
                    'changed': True,
                    'id': template.id,
                    'template': get_dict_of_struct(template),
                }
        elif state == 'registered':
            storage_domains_service = connection.system_service(
            ).storage_domains_service()
            # Find the storage domain with unregistered template:
            sd_id = get_id_by_name(storage_domains_service,
                                   module.params['storage_domain'])
            storage_domain_service = storage_domains_service.storage_domain_service(
                sd_id)
            templates_service = storage_domain_service.templates_service()

            # Find the unregistered Template we want to register:
            templates = templates_service.list(unregistered=True)
            template = next(
                (t for t in templates if t.name == module.params['name']),
                None)
            changed = False
            if template is None:
                # Test if template is registered:
                template = templates_module.search_entity()
                if template is None:
                    raise ValueError("Template with name '%s' wasn't found." %
                                     module.params['name'])
            else:
                changed = True
                template_service = templates_service.template_service(
                    template.id)
                # Register the template into the system:
                template_service.register(
                    cluster=otypes.Cluster(name=module.params['cluster'])
                    if module.params['cluster'] else None,
                    template=otypes.Template(name=module.params['name'], ),
                )
                if module.params['wait']:
                    template = wait_for_import(module, templates_service)

            ret = {
                'changed': changed,
                'id': template.id,
                'template': get_dict_of_struct(template)
            }
        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)
Beispiel #7
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'maintenance', 'unattached', 'imported',
                'update_ovf_store'
            ],
            default='present',
        ),
        id=dict(default=None),
        name=dict(default=None),
        description=dict(default=None),
        comment=dict(default=None),
        data_center=dict(default=None),
        domain_function=dict(choices=['data', 'iso', 'export'],
                             default='data',
                             aliases=['type']),
        host=dict(default=None),
        localfs=dict(default=None, type='dict'),
        nfs=dict(default=None, type='dict'),
        iscsi=dict(default=None, type='dict'),
        posixfs=dict(default=None, type='dict'),
        glusterfs=dict(default=None, type='dict'),
        fcp=dict(default=None, type='dict'),
        wipe_after_delete=dict(type='bool', default=None),
        backup=dict(type='bool', default=None),
        critical_space_action_blocker=dict(type='int', default=None),
        warning_low_space=dict(type='int', default=None),
        destroy=dict(type='bool', default=None),
        format=dict(type='bool', default=None),
        discard_after_delete=dict(type='bool', default=None))
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    if module._name == 'ovirt_storage_domains':
        module.deprecate(
            "The 'ovirt_storage_domains' module is being renamed 'ovirt_storage_domain'",
            version=2.8)

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        storage_domains_service = connection.system_service(
        ).storage_domains_service()
        storage_domains_module = StorageDomainModule(
            connection=connection,
            module=module,
            service=storage_domains_service,
        )

        state = module.params['state']
        control_state(storage_domains_module)
        if state == 'absent':
            # Pick random available host when host parameter is missing
            host_param = module.params['host']
            if not host_param:
                host = search_by_attributes(
                    connection.system_service().hosts_service(), status='up')
                if host is None:
                    raise Exception(
                        "Not possible to remove storage domain '%s' "
                        "because no host found with status `up`." %
                        module.params['name'])
                host_param = host.name
            ret = storage_domains_module.remove(
                destroy=module.params['destroy'],
                format=module.params['format'],
                host=host_param,
            )
        elif state == 'present' or state == 'imported':
            sd_id = storage_domains_module.create()['id']
            storage_domains_module.post_create_check(sd_id)
            ret = storage_domains_module.action(
                action='activate',
                action_condition=lambda s: s.status == sdstate.MAINTENANCE,
                wait_condition=lambda s: s.status == sdstate.ACTIVE,
                fail_condition=failed_state,
                search_params={'id': sd_id} if state == 'imported' else None)
        elif state == 'maintenance':
            sd_id = storage_domains_module.create()['id']
            storage_domains_module.post_create_check(sd_id)
            ret = storage_domains_module.action(
                action='deactivate',
                action_condition=lambda s: s.status == sdstate.ACTIVE,
                wait_condition=lambda s: s.status == sdstate.MAINTENANCE,
                fail_condition=failed_state,
            )
        elif state == 'unattached':
            ret = storage_domains_module.create()
            storage_domains_module.pre_remove(
                storage_domain=storage_domains_service.service(
                    ret['id']).get())
            ret['changed'] = storage_domains_module.changed
        elif state == 'update_ovf_store':
            ret = storage_domains_module.action(action='update_ovf_store')
        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)
Beispiel #8
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'exported', 'imported', 'registered'
            ],
            default='present',
        ),
        id=dict(default=None),
        name=dict(default=None),
        vm=dict(default=None),
        timezone=dict(type='str'),
        description=dict(default=None),
        sso=dict(type='bool'),
        ballooning_enabled=dict(type='bool', default=None),
        cluster=dict(default=None),
        usb_support=dict(type='bool'),
        allow_partial_import=dict(default=None, type='bool'),
        cpu_profile=dict(default=None),
        clone_permissions=dict(type='bool'),
        export_domain=dict(default=None),
        storage_domain=dict(default=None),
        exclusive=dict(type='bool'),
        clone_name=dict(default=None),
        image_provider=dict(default=None),
        soundcard_enabled=dict(type='bool', default=None),
        smartcard_enabled=dict(type='bool', default=None),
        image_disk=dict(default=None, aliases=['glance_image_disk_name']),
        io_threads=dict(type='int', default=None),
        template_image_disk_name=dict(default=None),
        version=dict(default=None, type='dict'),
        seal=dict(type='bool'),
        vnic_profile_mappings=dict(default=[], type='list'),
        cluster_mappings=dict(default=[], type='list'),
        role_mappings=dict(default=[], type='list'),
        domain_mappings=dict(default=[], type='list'),
        operating_system=dict(type='str'),
        memory=dict(type='str'),
        memory_guaranteed=dict(type='str'),
        memory_max=dict(type='str'),
        nics=dict(type='list', default=[]),
        cloud_init=dict(type='dict'),
        cloud_init_nics=dict(type='list', default=[]),
        sysprep=dict(type='dict'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[['id', 'name']],
    )

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        templates_service = connection.system_service().templates_service()
        templates_module = TemplatesModule(
            connection=connection,
            module=module,
            service=templates_service,
        )

        entity = None
        if module.params['version'] is not None and module.params[
                'version'].get('number') is not None:
            entity = find_subversion_template(module, templates_service)

        state = module.params['state']
        if state == 'present':
            force_create = False
            if entity is None and module.params['version'] is not None:
                force_create = True

            ret = templates_module.create(
                entity=entity,
                # When user want to create new template subversion, we must make sure
                # template is force created as it already exists, but new version should be created.
                force_create=force_create,
                result_state=otypes.TemplateStatus.OK,
                search_params=searchable_attributes(module),
                clone_permissions=module.params['clone_permissions'],
                seal=module.params['seal'],
            )
        elif state == 'absent':
            ret = templates_module.remove(entity=entity)
        elif state == 'exported':
            template = templates_module.search_entity()
            if entity is not None:
                template = entity
            export_service = templates_module._get_export_domain_service()
            export_template = search_by_attributes(
                export_service.templates_service(), id=template.id)

            ret = templates_module.action(
                entity=template,
                action='export',
                action_condition=lambda t: export_template is None or module.
                params['exclusive'],
                wait_condition=lambda t: t is not None,
                post_action=templates_module.post_export_action,
                storage_domain=otypes.StorageDomain(
                    id=export_service.get().id),
                exclusive=module.params['exclusive'],
            )
        elif state == 'imported':
            template = templates_module.search_entity()
            if entity is not None:
                template = entity
            if template and module.params['clone_name'] is None:
                ret = templates_module.create(
                    result_state=otypes.TemplateStatus.OK, )
            else:
                kwargs = {}
                if module.params['image_provider']:
                    kwargs.update(
                        disk=otypes.Disk(
                            name=module.params['template_image_disk_name']
                            or module.params['image_disk']),
                        template=otypes.Template(
                            name=module.params['name']
                            if module.params['clone_name'] is None else
                            module.params['clone_name'], ),
                        clone=True
                        if module.params['clone_name'] is not None else False,
                        import_as_template=True,
                    )

                if module.params['image_disk']:
                    # We need to refresh storage domain to get list of images:
                    templates_module._get_export_domain_service(
                    ).images_service().list()

                    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()
                else:
                    images_service = templates_module._get_export_domain_service(
                    ).templates_service()
                template_name = module.params['image_disk'] or module.params[
                    'name']
                entity = search_by_name(images_service, template_name)
                if entity is None:
                    raise Exception("Image/template '%s' was not found." %
                                    template_name)

                images_service.service(entity.id).import_(
                    storage_domain=otypes.StorageDomain(
                        name=module.params['storage_domain'])
                    if module.params['storage_domain'] else None,
                    cluster=otypes.Cluster(name=module.params['cluster'])
                    if module.params['cluster'] else None,
                    **kwargs)
                # Wait for template to appear in system:
                template = templates_module.wait_for_import(
                    condition=lambda t: t.status == otypes.TemplateStatus.OK)
                ret = templates_module.create(
                    result_state=otypes.TemplateStatus.OK)
                ret = {
                    'changed': True,
                    'id': template.id,
                    'template': get_dict_of_struct(template),
                }
        elif state == 'registered':
            storage_domains_service = connection.system_service(
            ).storage_domains_service()
            # Find the storage domain with unregistered template:
            sd_id = get_id_by_name(storage_domains_service,
                                   module.params['storage_domain'])
            storage_domain_service = storage_domains_service.storage_domain_service(
                sd_id)
            templates_service = storage_domain_service.templates_service()

            # Find the unregistered Template we want to register:
            templates = templates_service.list(unregistered=True)
            template = next(
                (t for t in templates if (t.id == module.params['id']
                                          or t.name == module.params['name'])),
                None)
            changed = False
            if template is None:
                template = templates_module.search_entity()
                if template is None:
                    raise ValueError(
                        "Template '%s(%s)' wasn't found." %
                        (module.params['name'], module.params['id']))
            else:
                # Register the template into the system:
                changed = True
                template_service = templates_service.template_service(
                    template.id)
                template_service.register(
                    allow_partial_import=module.params['allow_partial_import'],
                    cluster=otypes.Cluster(name=module.params['cluster'])
                    if module.params['cluster'] else None,
                    vnic_profile_mappings=_get_vnic_profile_mappings(module)
                    if module.params['vnic_profile_mappings'] else None,
                    registration_configuration=otypes.
                    RegistrationConfiguration(
                        cluster_mappings=_get_cluster_mappings(module),
                        role_mappings=_get_role_mappings(module),
                        domain_mappings=_get_domain_mappings(module),
                    ) if (module.params['cluster_mappings']
                          or module.params['role_mappings']
                          or module.params['domain_mappings']) else None)

                if module.params['wait']:
                    template = templates_module.wait_for_import()
                else:
                    # Fetch template to initialize return.
                    template = template_service.get()
                ret = templates_module.create(
                    result_state=otypes.TemplateStatus.OK)
            ret = {
                'changed': changed,
                'id': template.id,
                'template': get_dict_of_struct(template)
            }
        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)
Beispiel #9
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'exported', 'imported'],
            default='present',
        ),
        name=dict(default=None, required=True),
        vm=dict(default=None),
        description=dict(default=None),
        cluster=dict(default=None),
        cpu_profile=dict(default=None),
        disks=dict(default=[], type='list'),
        clone_permissions=dict(type='bool'),
        export_domain=dict(default=None),
        storage_domain=dict(default=None),
        exclusive=dict(type='bool'),
        image_provider=dict(default=None),
        image_disk=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        templates_service = connection.system_service().templates_service()
        templates_module = TemplatesModule(
            connection=connection,
            module=module,
            service=templates_service,
        )

        state = module.params['state']
        if state == 'present':
            ret = templates_module.create(
                result_state=otypes.TemplateStatus.OK,
                clone_permissions=module.params['clone_permissions'],
            )
        elif state == 'absent':
            ret = templates_module.remove()
        elif state == 'exported':
            template = templates_module.search_entity()
            export_service = templates_module._get_export_domain_service()
            export_template = search_by_attributes(export_service.templates_service(), id=template.id)

            ret = templates_module.action(
                entity=template,
                action='export',
                action_condition=lambda t: export_template is None,
                wait_condition=lambda t: t is not None,
                post_action=templates_module.post_export_action,
                storage_domain=otypes.StorageDomain(id=export_service.get().id),
                exclusive=module.params['exclusive'],
            )
        elif state == 'imported':
            template = templates_module.search_entity()
            if template:
                ret = templates_module.create(
                    result_state=otypes.TemplateStatus.OK,
                )
            else:
                kwargs = {}
                if module.params['image_provider']:
                    kwargs.update(
                        disk=otypes.Disk(
                            name=module.params['image_disk']
                        ),
                        template=otypes.Template(
                            name=module.params['name'],
                        ),
                        import_as_template=True,
                    )

                if module.params['image_disk']:
                    # We need to refresh storage domain to get list of images:
                    templates_module._get_export_domain_service().images_service().list()

                    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()
                else:
                    images_service = templates_module._get_export_domain_service().templates_service()
                template_name = module.params['image_disk'] or module.params['name']
                entity = search_by_name(images_service, template_name)
                if entity is None:
                    raise Exception("Image/template '%s' was not found." % template_name)

                images_service.service(entity.id).import_(
                    storage_domain=otypes.StorageDomain(
                        name=module.params['storage_domain']
                    ) if module.params['storage_domain'] else None,
                    cluster=otypes.Cluster(
                        name=module.params['cluster']
                    ) if module.params['cluster'] else None,
                    **kwargs
                )
                template = wait_for_import(module, templates_service)
                ret = {
                    'changed': True,
                    'id': template.id,
                    'template': get_dict_of_struct(template),
                }

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Beispiel #10
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'exported', 'imported', 'registered'],
            default='present',
        ),
        id=dict(default=None),
        name=dict(default=None),
        vm=dict(default=None),
        description=dict(default=None),
        cluster=dict(default=None),
        allow_partial_import=dict(default=None, type='bool'),
        cpu_profile=dict(default=None),
        disks=dict(default=[], type='list'),
        clone_permissions=dict(type='bool'),
        export_domain=dict(default=None),
        storage_domain=dict(default=None),
        exclusive=dict(type='bool'),
        image_provider=dict(default=None),
        image_disk=dict(default=None, aliases=['glance_image_disk_name']),
        template_image_disk_name=dict(default=None),
        seal=dict(type='bool'),
        vnic_profile_mappings=dict(default=[], type='list'),
        cluster_mappings=dict(default=[], type='list'),
        role_mappings=dict(default=[], type='list'),
        domain_mappings=dict(default=[], type='list'),
        operating_system=dict(type='str'),
        memory=dict(type='str'),
        memory_guaranteed=dict(type='str'),
        memory_max=dict(type='str'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[['id', 'name']],
    )
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        templates_service = connection.system_service().templates_service()
        templates_module = TemplatesModule(
            connection=connection,
            module=module,
            service=templates_service,
        )

        state = module.params['state']
        if state == 'present':
            ret = templates_module.create(
                result_state=otypes.TemplateStatus.OK,
                clone_permissions=module.params['clone_permissions'],
                seal=module.params['seal'],
            )
        elif state == 'absent':
            ret = templates_module.remove()
        elif state == 'exported':
            template = templates_module.search_entity()
            export_service = templates_module._get_export_domain_service()
            export_template = search_by_attributes(export_service.templates_service(), id=template.id)

            ret = templates_module.action(
                entity=template,
                action='export',
                action_condition=lambda t: export_template is None or module.params['exclusive'],
                wait_condition=lambda t: t is not None,
                post_action=templates_module.post_export_action,
                storage_domain=otypes.StorageDomain(id=export_service.get().id),
                exclusive=module.params['exclusive'],
            )
        elif state == 'imported':
            template = templates_module.search_entity()
            if template:
                ret = templates_module.create(
                    result_state=otypes.TemplateStatus.OK,
                )
            else:
                kwargs = {}
                if module.params['image_provider']:
                    kwargs.update(
                        disk=otypes.Disk(
                            name=module.params['template_image_disk_name'] or module.params['image_disk']
                        ),
                        template=otypes.Template(
                            name=module.params['name'],
                        ),
                        import_as_template=True,
                    )

                if module.params['image_disk']:
                    # We need to refresh storage domain to get list of images:
                    templates_module._get_export_domain_service().images_service().list()

                    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()
                else:
                    images_service = templates_module._get_export_domain_service().templates_service()
                template_name = module.params['image_disk'] or module.params['name']
                entity = search_by_name(images_service, template_name)
                if entity is None:
                    raise Exception("Image/template '%s' was not found." % template_name)

                images_service.service(entity.id).import_(
                    storage_domain=otypes.StorageDomain(
                        name=module.params['storage_domain']
                    ) if module.params['storage_domain'] else None,
                    cluster=otypes.Cluster(
                        name=module.params['cluster']
                    ) if module.params['cluster'] else None,
                    **kwargs
                )
                # Wait for template to appear in system:
                template = templates_module.wait_for_import(
                    condition=lambda t: t.status == otypes.TemplateStatus.OK
                )
                ret = templates_module.create(result_state=otypes.TemplateStatus.OK)
                ret = {
                    'changed': True,
                    'id': template.id,
                    'template': get_dict_of_struct(template),
                }
        elif state == 'registered':
            storage_domains_service = connection.system_service().storage_domains_service()
            # Find the storage domain with unregistered template:
            sd_id = get_id_by_name(storage_domains_service, module.params['storage_domain'])
            storage_domain_service = storage_domains_service.storage_domain_service(sd_id)
            templates_service = storage_domain_service.templates_service()

            # Find the unregistered Template we want to register:
            templates = templates_service.list(unregistered=True)
            template = next(
                (t for t in templates if (t.id == module.params['id'] or t.name == module.params['name'])),
                None
            )
            changed = False
            if template is None:
                template = templates_module.search_entity()
                if template is None:
                    raise ValueError(
                        "Template '%s(%s)' wasn't found." % (module.params['name'], module.params['id'])
                    )
            else:
                # Register the template into the system:
                changed = True
                template_service = templates_service.template_service(template.id)
                template_service.register(
                    allow_partial_import=module.params['allow_partial_import'],
                    cluster=otypes.Cluster(
                        name=module.params['cluster']
                    ) if module.params['cluster'] else None,
                    vnic_profile_mappings=_get_vnic_profile_mappings(module)
                    if module.params['vnic_profile_mappings'] else None,
                    registration_configuration=otypes.RegistrationConfiguration(
                        cluster_mappings=_get_cluster_mappings(module),
                        role_mappings=_get_role_mappings(module),
                        domain_mappings=_get_domain_mappings(module),
                    ) if (module.params['cluster_mappings']
                          or module.params['role_mappings']
                          or module.params['domain_mappings']) else None
                )

                if module.params['wait']:
                    template = templates_module.wait_for_import()
                else:
                    # Fetch template to initialize return.
                    template = template_service.get()
                ret = templates_module.create(result_state=otypes.TemplateStatus.OK)
            ret = {
                'changed': changed,
                'id': template.id,
                'template': get_dict_of_struct(template)
            }
        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', 'maintenance', 'unattached', 'imported', 'update_ovf_store'],
            default='present',
        ),
        id=dict(default=None),
        name=dict(default=None),
        description=dict(default=None),
        comment=dict(default=None),
        data_center=dict(default=None),
        domain_function=dict(choices=['data', 'iso', 'export'], default='data', aliases=['type']),
        host=dict(default=None),
        localfs=dict(default=None, type='dict'),
        nfs=dict(default=None, type='dict'),
        iscsi=dict(default=None, type='dict'),
        posixfs=dict(default=None, type='dict'),
        glusterfs=dict(default=None, type='dict'),
        fcp=dict(default=None, type='dict'),
        wipe_after_delete=dict(type='bool', default=None),
        backup=dict(type='bool', default=None),
        critical_space_action_blocker=dict(type='int', default=None),
        warning_low_space=dict(type='int', default=None),
        destroy=dict(type='bool', default=None),
        format=dict(type='bool', default=None),
        discard_after_delete=dict(type='bool', default=None)
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        storage_domains_service = connection.system_service().storage_domains_service()
        storage_domains_module = StorageDomainModule(
            connection=connection,
            module=module,
            service=storage_domains_service,
        )

        state = module.params['state']
        control_state(storage_domains_module)
        if state == 'absent':
            # Pick random available host when host parameter is missing
            host_param = module.params['host']
            if not host_param:
                host = search_by_attributes(connection.system_service().hosts_service(), status='up')
                if host is None:
                    raise Exception(
                        "Not possible to remove storage domain '%s' "
                        "because no host found with status `up`." % module.params['name']
                    )
                host_param = host.name
            ret = storage_domains_module.remove(
                destroy=module.params['destroy'],
                format=module.params['format'],
                host=host_param,
            )
        elif state == 'present' or state == 'imported':
            sd_id = storage_domains_module.create()['id']
            storage_domains_module.post_create_check(sd_id)
            ret = storage_domains_module.action(
                action='activate',
                action_condition=lambda s: s.status == sdstate.MAINTENANCE,
                wait_condition=lambda s: s.status == sdstate.ACTIVE,
                fail_condition=failed_state,
                search_params={'id': sd_id} if state == 'imported' else None
            )
        elif state == 'maintenance':
            sd_id = storage_domains_module.create()['id']
            storage_domains_module.post_create_check(sd_id)
            ret = storage_domains_module.action(
                action='deactivate',
                action_condition=lambda s: s.status == sdstate.ACTIVE,
                wait_condition=lambda s: s.status == sdstate.MAINTENANCE,
                fail_condition=failed_state,
            )
        elif state == 'unattached':
            ret = storage_domains_module.create()
            storage_domains_module.pre_remove(
                storage_domain=storage_domains_service.service(ret['id']).get()
            )
            ret['changed'] = storage_domains_module.changed
        elif state == 'update_ovf_store':
            ret = storage_domains_module.action(
                action='update_ovf_store'
            )
        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)