def _get_cluster_mappings(module):
    clusterMappings = list()

    for clusterMapping in module.params['cluster_mappings']:
        clusterMappings.append(
            otypes.RegistrationClusterMapping(
                from_=otypes.Cluster(
                    name=clusterMapping['source_name'],
                ),
                to=otypes.Cluster(
                    name=clusterMapping['dest_name'],
                ),
            )
        )
    return clusterMappings
예제 #2
0
 def build_entity(self):
     return otypes.Host(
         id=self._module.params.get('id'),
         name=self.param('name'),
         cluster=otypes.Cluster(
             name=self.param('cluster')
         ) if self.param('cluster') else None,
         comment=self.param('comment'),
         address=self.param('address'),
         root_password=self.param('password'),
         ssh=otypes.Ssh(
             authentication_method=otypes.SshAuthenticationMethod.PUBLICKEY,
         ) if self.param('public_key') else None,
         spm=otypes.Spm(
             priority=self.param('spm_priority'),
         ) if self.param('spm_priority') else None,
         override_iptables=self.param('override_iptables'),
         display=otypes.Display(
             address=self.param('override_display'),
         ) if self.param('override_display') else None,
         os=otypes.OperatingSystem(
             custom_kernel_cmdline=' '.join(self.param('kernel_params')),
         ) if self.param('kernel_params') else None,
         power_management=otypes.PowerManagement(
             enabled=self.param('power_management_enabled'),
             kdump_detection=self.param('kdump_integration') == 'enabled',
         ) if self.param('power_management_enabled') is not None or self.param('kdump_integration') else None,
         vgpu_placement=otypes.VgpuPlacement(
             self.param('vgpu_placement')
         ) if self.param('vgpu_placement') is not None else None,
     )
 def build_entity(self):
     return otypes.Template(
         id=self._module.params['id'],
         name=self._module.params['name'],
         cluster=otypes.Cluster(
             name=self._module.params['cluster']
         ) if self._module.params['cluster'] else None,
         vm=otypes.Vm(
             name=self._module.params['vm']
         ) if self._module.params['vm'] else None,
         description=self._module.params['description'],
         cpu_profile=otypes.CpuProfile(
             id=search_by_name(
                 self._connection.system_service().cpu_profiles_service(),
                 self._module.params['cpu_profile'],
             ).id
         ) if self._module.params['cpu_profile'] else None,
         display=otypes.Display(
             smartcard_enabled=self.param('smartcard_enabled')
         ) if self.param('smartcard_enabled') is not None else None,
         os=otypes.OperatingSystem(
             type=self.param('operating_system'),
         ) if self.param('operating_system') else None,
         memory=convert_to_bytes(
             self.param('memory')
         ) if self.param('memory') else None,
         soundcard_enabled=self.param('soundcard_enabled'),
         usb=(
             otypes.Usb(enabled=self.param('usb_support'))
         ) if self.param('usb_support') is not None else None,
         sso=(
             otypes.Sso(
                 methods=[otypes.Method(id=otypes.SsoMethod.GUEST_AGENT)] if self.param('sso') else []
             )
         ) if self.param('sso') is not None else None,
         time_zone=otypes.TimeZone(
             name=self.param('timezone'),
         ) if self.param('timezone') else None,
         version=otypes.TemplateVersion(
             base_template=self._get_base_template(),
             version_name=self.param('version').get('name'),
         ) if self.param('version') else None,
         memory_policy=otypes.MemoryPolicy(
             guaranteed=convert_to_bytes(self.param('memory_guaranteed')),
             ballooning=self.param('ballooning_enabled'),
             max=convert_to_bytes(self.param('memory_max')),
         ) if any((
             self.param('memory_guaranteed'),
             self.param('ballooning_enabled'),
             self.param('memory_max')
         )) else None,
         io=otypes.Io(
             threads=self.param('io_threads'),
         ) if self.param('io_threads') is not None else None,
         initialization=self.get_initialization(),
     )
예제 #4
0
 def build_entity(self):
     vm = self.param('vm')
     return otypes.VmPool(
         id=self._module.params['id'],
         name=self._module.params['name'],
         description=self._module.params['description'],
         comment=self._module.params['comment'],
         cluster=otypes.Cluster(
             name=self._module.params['cluster']
         ) if self._module.params['cluster'] else None,
         template=otypes.Template(
             name=self._module.params['template']
         ) if self._module.params['template'] else None,
         max_user_vms=self._module.params['vm_per_user'],
         prestarted_vms=self._module.params['prestarted'],
         size=self._module.params['vm_count'],
         type=otypes.VmPoolType(
             self._module.params['type']
         ) if self._module.params['type'] else None,
         vm=self.build_vm(vm) if self._module.params['vm'] else None,
     )
def main():
    argument_spec = jctanner.cloud_ovirt.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)
예제 #6
0
 def build_entity(self):
     sched_policy = self._get_sched_policy()
     return otypes.Cluster(
         id=self.param('id'),
         name=self.param('name'),
         comment=self.param('comment'),
         description=self.param('description'),
         ballooning_enabled=self.param('ballooning'),
         gluster_service=self.param('gluster'),
         virt_service=self.param('virt'),
         threads_as_cores=self.param('threads_as_cores'),
         ha_reservation=self.param('ha_reservation'),
         trusted_service=self.param('trusted_service'),
         optional_reason=self.param('vm_reason'),
         maintenance_reason_required=self.param('host_reason'),
         scheduling_policy=otypes.SchedulingPolicy(
             id=sched_policy.id,
         ) if sched_policy else None,
         serial_number=otypes.SerialNumber(
             policy=otypes.SerialNumberPolicy(self.param('serial_policy')),
             value=self.param('serial_policy_value'),
         ) if (
             self.param('serial_policy') is not None or
             self.param('serial_policy_value') is not None
         ) else None,
         migration=otypes.MigrationOptions(
             auto_converge=otypes.InheritableBoolean(
                 self.param('migration_auto_converge'),
             ) if self.param('migration_auto_converge') else None,
             bandwidth=otypes.MigrationBandwidth(
                 assignment_method=otypes.MigrationBandwidthAssignmentMethod(
                     self.param('migration_bandwidth'),
                 ) if self.param('migration_bandwidth') else None,
                 custom_value=self.param('migration_bandwidth_limit'),
             ) if (
                 self.param('migration_bandwidth') or
                 self.param('migration_bandwidth_limit')
             ) else None,
             compressed=otypes.InheritableBoolean(
                 self.param('migration_compressed'),
             ) if self.param('migration_compressed') else None,
             policy=otypes.MigrationPolicy(
                 id=self._get_policy_id()
             ) if self.param('migration_policy') else None,
         ) if (
             self.param('migration_bandwidth') is not None or
             self.param('migration_bandwidth_limit') is not None or
             self.param('migration_auto_converge') is not None or
             self.param('migration_compressed') is not None or
             self.param('migration_policy') is not None
         ) else None,
         error_handling=otypes.ErrorHandling(
             on_error=otypes.MigrateOnError(
                 self.param('resilience_policy')
             ),
         ) if self.param('resilience_policy') else None,
         fencing_policy=otypes.FencingPolicy(
             enabled=self.param('fence_enabled'),
             skip_if_gluster_bricks_up=self.param('fence_skip_if_gluster_bricks_up'),
             skip_if_gluster_quorum_not_met=self.param('fence_skip_if_gluster_quorum_not_met'),
             skip_if_connectivity_broken=otypes.SkipIfConnectivityBroken(
                 enabled=self.param('fence_skip_if_connectivity_broken'),
                 threshold=self.param('fence_connectivity_threshold'),
             ) if (
                 self.param('fence_skip_if_connectivity_broken') is not None or
                 self.param('fence_connectivity_threshold') is not None
             ) else None,
             skip_if_sd_active=otypes.SkipIfSdActive(
                 enabled=self.param('fence_skip_if_sd_active'),
             ) if self.param('fence_skip_if_sd_active') is not None else None,
         ) if (
             self.param('fence_enabled') is not None or
             self.param('fence_skip_if_sd_active') is not None or
             self.param('fence_skip_if_connectivity_broken') is not None or
             self.param('fence_skip_if_gluster_bricks_up') is not None or
             self.param('fence_skip_if_gluster_quorum_not_met') is not None or
             self.param('fence_connectivity_threshold') is not None
         ) else None,
         display=otypes.Display(
             proxy=self.param('spice_proxy'),
         ) if self.param('spice_proxy') else None,
         required_rng_sources=[
             otypes.RngSource(rng) for rng in self.param('rng_sources')
         ] if self.param('rng_sources') else None,
         memory_policy=otypes.MemoryPolicy(
             over_commit=otypes.MemoryOverCommit(
                 percent=self._get_memory_policy(),
             ),
         ) if self.param('memory_policy') else None,
         ksm=otypes.Ksm(
             enabled=self.param('ksm'),
             merge_across_nodes=not self.param('ksm_numa'),
         ) if (
             self.param('ksm_numa') is not None or
             self.param('ksm') is not None
         ) else None,
         data_center=otypes.DataCenter(
             name=self.param('data_center'),
         ) if self.param('data_center') else None,
         management_network=otypes.Network(
             name=self.param('network'),
         ) if self.param('network') else None,
         cpu=otypes.Cpu(
             architecture=otypes.Architecture(
                 self.param('cpu_arch')
             ) if self.param('cpu_arch') else None,
             type=self.param('cpu_type'),
         ) if (
             self.param('cpu_arch') or self.param('cpu_type')
         ) else None,
         version=otypes.Version(
             major=self.__get_major(self.param('compatibility_version')),
             minor=self.__get_minor(self.param('compatibility_version')),
         ) if self.param('compatibility_version') else None,
         switch_type=otypes.SwitchType(
             self.param('switch_type')
         ) if self.param('switch_type') else None,
         mac_pool=otypes.MacPool(
             id=get_id_by_name(self._connection.system_service().mac_pools_service(), self.param('mac_pool'))
         ) if self.param('mac_pool') else None,
         external_network_providers=self._get_external_network_providers_entity(),
         custom_scheduling_policy_properties=[
             otypes.Property(
                 name=sp.get('name'),
                 value=str(sp.get('value')),
             ) for sp in self.param('scheduling_policy_properties') if sp
         ] if self.param('scheduling_policy_properties') is not None else None,
         firewall_type=otypes.FirewallType(
             self.param('firewall_type')
         ) if self.param('firewall_type') else None,
         gluster_tuned_profile=self.param('gluster_tuned_profile'),
     )