def main():
    argument_spec = ovirt_info_full_argument_spec(
        name=dict(default=None),
        host=dict(default=None),
        vm=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        affinity_labels_service = connection.system_service(
        ).affinity_labels_service()
        labels = []
        all_labels = affinity_labels_service.list()
        if module.params['name']:
            labels.extend([
                l for l in all_labels
                if fnmatch.fnmatch(l.name, module.params['name'])
            ])
        if module.params['host']:
            hosts_service = connection.system_service().hosts_service()
            if search_by_name(hosts_service, module.params['host']) is None:
                raise Exception("Host '%s' was not found." %
                                module.params['host'])
            labels.extend([
                label for label in all_labels
                for host in connection.follow_link(label.hosts)
                if fnmatch.fnmatch(
                    hosts_service.service(host.id).get().name,
                    module.params['host'])
            ])
        if module.params['vm']:
            vms_service = connection.system_service().vms_service()
            if search_by_name(vms_service, module.params['vm']) is None:
                raise Exception("Vm '%s' was not found." % module.params['vm'])
            labels.extend([
                label for label in all_labels
                for vm in connection.follow_link(label.vms) if fnmatch.fnmatch(
                    vms_service.service(vm.id).get().name, module.params['vm'])
            ])

        if not (module.params['vm'] or module.params['host']
                or module.params['name']):
            labels = all_labels

        result = dict(ovirt_affinity_labels=[
            get_dict_of_struct(
                struct=l,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for l in labels
        ], )
        module.exit_json(changed=False, **result)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Exemplo n.º 2
0
def main():
    argument_spec = ovirt_info_full_argument_spec(
        name=dict(default=None),
        host=dict(default=None),
        vm=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        tags_service = connection.system_service().tags_service()
        tags = []
        all_tags = tags_service.list()
        if module.params['name']:
            tags.extend([
                t for t in all_tags
                if fnmatch.fnmatch(t.name, module.params['name'])
            ])
        if module.params['host']:
            hosts_service = connection.system_service().hosts_service()
            host = search_by_name(hosts_service, module.params['host'])
            if host is None:
                raise Exception("Host '%s' was not found." % module.params['host'])
            tags.extend([
                tag for tag in hosts_service.host_service(host.id).tags_service().list()
            ])
        if module.params['vm']:
            vms_service = connection.system_service().vms_service()
            vm = search_by_name(vms_service, module.params['vm'])
            if vm is None:
                raise Exception("Vm '%s' was not found." % module.params['vm'])
            tags.extend([
                tag for tag in vms_service.vm_service(vm.id).tags_service().list()
            ])

        if not (module.params['vm'] or module.params['host'] or module.params['name']):
            tags = all_tags

        result = dict(
            ovirt_tags=[
                get_dict_of_struct(
                    struct=t,
                    connection=connection,
                    fetch_nested=module.params['fetch_nested'],
                    attributes=module.params['nested_attributes'],
                ) for t in tags
            ],
        )
        module.exit_json(changed=False, **result)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Exemplo n.º 3
0
 def __get_vnic_profile_id(self, nic):
     """
     Return VNIC profile ID looked up by it's name, because there can be
     more VNIC profiles with same name, other criteria of filter is cluster.
     """
     vnics_service = self._connection.system_service().vnic_profiles_service()
     clusters_service = self._connection.system_service().clusters_service()
     cluster = search_by_name(clusters_service, self.param('cluster'))
     profiles = [
         profile for profile in vnics_service.list()
         if profile.name == nic.get('profile_name')
     ]
     cluster_networks = [
         net.id for net in self._connection.follow_link(cluster.networks)
     ]
     try:
         return next(
             profile.id for profile in profiles
             if profile.network.id in cluster_networks
         )
     except StopIteration:
         raise Exception(
             "Profile '%s' was not found in cluster '%s'" % (
                 nic.get('profile_name'),
                 self.param('cluster')
             )
         )
Exemplo n.º 4
0
 def _get_mac_pool(self):
     mac_pool = None
     if self._module.params.get('mac_pool'):
         mac_pool = search_by_name(
             self._connection.system_service().mac_pools_service(),
             self._module.params.get('mac_pool'),
         )
     return mac_pool
 def _get_storage_domain_service(self):
     sds_service = self._connection.system_service().storage_domains_service()
     sd = search_by_name(sds_service, self.param('storage'))
     if sd is None:
         raise Exception(
             "Storage '%s' was not found." % self.param('storage')
         )
     return sd, sds_service.storage_domain_service(sd.id)
    def _get_sched_policy(self):
        sched_policy = None
        if self.param('scheduling_policy'):
            sched_policies_service = self._connection.system_service().scheduling_policies_service()
            sched_policy = search_by_name(sched_policies_service, self.param('scheduling_policy'))
            if not sched_policy:
                raise Exception("Scheduling policy '%s' was not found" % self.param('scheduling_policy'))

        return sched_policy
 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(),
     )
def main():
    argument_spec = ovirt_info_full_argument_spec(
        vm=dict(required=True),
        description=dict(default=None),
        snapshot_id=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    is_old_facts = module._name in ('ovirt_snapshot_facts',
                                    'community.general.ovirt_snapshot_facts')
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_snapshot_facts' module has been renamed to 'ovirt_snapshot_info', "
            "and the renamed one no longer returns ansible_facts",
            version='2.13')

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        vms_service = connection.system_service().vms_service()
        vm_name = module.params['vm']
        vm = search_by_name(vms_service, vm_name)
        if vm is None:
            raise Exception("VM '%s' was not found." % vm_name)

        snapshots_service = vms_service.service(vm.id).snapshots_service()
        if module.params['description']:
            snapshots = [
                e for e in snapshots_service.list()
                if fnmatch.fnmatch(e.description, module.params['description'])
            ]
        elif module.params['snapshot_id']:
            snapshots = [
                snapshots_service.snapshot_service(
                    module.params['snapshot_id']).get()
            ]
        else:
            snapshots = snapshots_service.list()

        result = dict(ovirt_snapshots=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in snapshots
        ], )
        if is_old_facts:
            module.exit_json(changed=False, ansible_facts=result)
        else:
            module.exit_json(changed=False, **result)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
    def _get_export_domain_service(self):
        provider_name = self._module.params['export_domain'] or self._module.params['image_provider']
        export_sds_service = self._connection.system_service().storage_domains_service()
        export_sd = search_by_name(export_sds_service, provider_name)
        if export_sd is None:
            raise ValueError(
                "Export storage domain/Image Provider '%s' wasn't found." % provider_name
            )

        return export_sds_service.service(export_sd.id)
    def _attached_sds_service(self, dc_name):
        # Get data center object of the storage domain:
        dcs_service = self._connection.system_service().data_centers_service()

        # Search the data_center name, if it does not exist, try to search by guid.
        dc = search_by_name(dcs_service, dc_name)
        if dc is None:
            dc = get_entity(dcs_service.service(dc_name))
            if dc is None:
                return None

        dc_service = dcs_service.data_center_service(dc.id)
        return dc_service.storage_domains_service()
def main():
    argument_spec = ovirt_info_full_argument_spec(
        data_center=dict(required=True),
        name=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    is_old_facts = module._name in ('ovirt_quota_facts',
                                    'community.general.ovirt_quota_facts')
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_quota_facts' module has been renamed to 'ovirt_quota_info', "
            "and the renamed one no longer returns ansible_facts",
            version='2.13')

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        datacenters_service = connection.system_service().data_centers_service(
        )
        dc_name = module.params['data_center']
        dc = search_by_name(datacenters_service, dc_name)
        if dc is None:
            raise Exception("Datacenter '%s' was not found." % dc_name)

        quotas_service = datacenters_service.service(dc.id).quotas_service()
        if module.params['name']:
            quotas = [
                e for e in quotas_service.list()
                if fnmatch.fnmatch(e.name, module.params['name'])
            ]
        else:
            quotas = quotas_service.list()

        result = dict(ovirt_quotas=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in quotas
        ], )
        if is_old_facts:
            module.exit_json(changed=False, ansible_facts=result)
        else:
            module.exit_json(changed=False, **result)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Exemplo n.º 12
0
def main():
    argument_spec = ovirt_info_full_argument_spec(
        vm=dict(default=None),
        template=dict(default=None),
        name=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec,
        required_one_of=[['vm', 'template']],
    )
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)

        if module.params.get('vm'):
            # Locate the VM, where we will manage NICs:
            entity_name = module.params.get('vm')
            collection_service = connection.system_service().vms_service()
        elif module.params.get('template'):
            entity_name = module.params.get('template')
            collection_service = connection.system_service().templates_service(
            )
        entity = search_by_name(collection_service, entity_name)
        if entity is None:
            raise Exception("VM/Template '%s' was not found." % entity_name)

        nics_service = collection_service.service(entity.id).nics_service()
        if module.params['name']:
            nics = [
                e for e in nics_service.list()
                if fnmatch.fnmatch(e.name, module.params['name'])
            ]
        else:
            nics = nics_service.list()

        result = dict(ovirt_nics=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in nics
        ], )
        module.exit_json(changed=False, **result)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
    def update_storage_domains(self, disk_id):
        changed = False
        disk_service = self._service.service(disk_id)
        disk = disk_service.get()
        sds_service = self._connection.system_service(
        ).storage_domains_service()

        # We don't support move&copy for non file based storages:
        if disk.storage_type != otypes.DiskStorageType.IMAGE:
            return changed
        if disk.content_type in [
                otypes.DiskContentType(x) for x in [
                    'hosted_engine', 'hosted_engine_sanlock',
                    'hosted_engine_metadata', 'hosted_engine_configuration'
                ]
        ]:
            return changed
        # Initiate move:
        if self._module.params['storage_domain']:
            new_disk_storage_id = get_id_by_name(
                sds_service, self._module.params['storage_domain'])
            if new_disk_storage_id in [sd.id for sd in disk.storage_domains]:
                return changed
            changed = self.action(
                action='move',
                entity=disk,
                action_condition=lambda d: new_disk_storage_id != d.
                storage_domains[0].id,
                wait_condition=lambda d: d.status == otypes.DiskStatus.OK,
                storage_domain=otypes.StorageDomain(id=new_disk_storage_id, ),
                post_action=lambda _: time.sleep(self._module.params[
                    'poll_interval']),
            )['changed']

        if self._module.params['storage_domains']:
            for sd in self._module.params['storage_domains']:
                new_disk_storage = search_by_name(sds_service, sd)
                changed = changed or self.action(
                    action='copy',
                    entity=disk,
                    action_condition=(lambda disk: new_disk_storage.id not in
                                      [sd.id for sd in disk.storage_domains]),
                    wait_condition=lambda disk: disk.status == otypes.
                    DiskStatus.OK,
                    storage_domain=otypes.StorageDomain(
                        id=new_disk_storage.id, ),
                )['changed']

        return changed
def _permissions_service(connection, module):
    if module.params['user_name']:
        service = connection.system_service().users_service()
        entity = next(
            iter(
                service.list(search='usrname={0}'.format('{0}@{1}'.format(
                    module.params['user_name'],
                    module.params['authz_name'])))), None)
    else:
        service = connection.system_service().groups_service()
        entity = search_by_name(service, module.params['group_name'])

    if entity is None:
        raise Exception("User/Group wasn't found.")

    return service.service(entity.id).permissions_service()
Exemplo n.º 15
0
 def __attach_nics(self, entity):
     # Attach NICs to instance type, if specified:
     nics_service = self._service.service(entity.id).nics_service()
     for nic in self.param('nics'):
         if search_by_name(nics_service, nic.get('name')) is None:
             if not self._module.check_mode:
                 nics_service.add(
                     otypes.Nic(
                         name=nic.get('name'),
                         interface=otypes.NicInterface(
                             nic.get('interface', 'virtio')),
                         vnic_profile=otypes.VnicProfile(
                             id=self.__get_vnic_profile_id(nic), )
                         if nic.get('profile_name') else None,
                         mac=otypes.Mac(address=nic.get('mac_address'))
                         if nic.get('mac_address') else None,
                     ))
             self.changed = True
def main():
    argument_spec = ovirt_info_full_argument_spec(
        vm=dict(required=True),
        name=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        vms_service = connection.system_service().vms_service()
        vm_name = module.params['vm']
        vm = search_by_name(vms_service, vm_name)
        if vm is None:
            raise Exception("VM '%s' was not found." % vm_name)

        nics_service = vms_service.service(vm.id).nics_service()
        if module.params['name']:
            nics = [
                e for e in nics_service.list()
                if fnmatch.fnmatch(e.name, module.params['name'])
            ]
        else:
            nics = nics_service.list()

        result = dict(ovirt_nics=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in nics
        ], )
        module.exit_json(changed=False, **result)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Exemplo n.º 17
0
def _object_service(connection, module):
    object_type = module.params['object_type']
    objects_service = _objects_service(connection, object_type)
    if object_type == 'system':
        return objects_service

    object_id = module.params['object_id']
    if object_id is None:
        sdk_object = search_by_name(objects_service,
                                    module.params['object_name'])
        if sdk_object is None:
            raise Exception(
                "'%s' object '%s' was not found." %
                (module.params['object_type'], module.params['object_name']))
        object_id = sdk_object.id

    object_service = objects_service.service(object_id)
    if module.params['quota_name'] and object_type == 'data_center':
        quotas_service = object_service.quotas_service()
        return quotas_service.quota_service(
            get_id_by_name(quotas_service, module.params['quota_name']))
    return object_service
Exemplo n.º 18
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['restore', 'present', 'absent'],
            default='present',
        ),
        vm_name=dict(required=True),
        snapshot_id=dict(default=None),
        disks=dict(type='list',
                   options=dict(
                       name=dict(default=None, type='str'),
                       id=dict(default=None, type='str'),
                   )),
        disk_id=dict(default=None),
        disk_name=dict(default=None),
        description=dict(default=None),
        download_image_path=dict(default=None),
        upload_image_path=dict(default=None),
        keep_days_old=dict(default=None, type='int'),
        use_memory=dict(
            default=None,
            type='bool',
            aliases=['restore_memory', 'save_memory'],
        ),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           required_if=[
                               ('state', 'absent', ['snapshot_id']),
                               ('state', 'restore', ['snapshot_id']),
                           ])

    check_sdk(module)
    ret = {}
    vm_name = module.params.get('vm_name')
    auth = module.params['auth']
    connection = create_connection(auth)
    vms_service = connection.system_service().vms_service()
    vm = search_by_name(vms_service, vm_name)
    if not vm:
        module.fail_json(
            msg="Vm '{name}' doesn't exist.".format(name=vm_name), )

    vm_service = vms_service.vm_service(vm.id)
    snapshots_service = vms_service.vm_service(vm.id).snapshots_service()
    try:
        state = module.params['state']
        if state == 'present':
            if module.params.get('disk_id') or module.params.get('disk_name'):
                module.params['disk_id'] = get_snapshot_disk_id(
                    module, snapshots_service)
                if module.params['upload_image_path']:
                    ret['changed'] = upload_disk_image(connection, module)
                if module.params['download_image_path']:
                    ret['changed'] = download_disk_image(connection, module)
            if module.params.get('keep_days_old') is not None:
                ret = remove_old_snapshosts(module, vm_service,
                                            snapshots_service)
            else:
                ret = create_snapshot(module, vm_service, snapshots_service,
                                      connection)
        elif state == 'restore':
            ret = restore_snapshot(module, vm_service, snapshots_service)
        elif state == 'absent':
            ret = remove_snapshot(module, vm_service, snapshots_service)
        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',
        ),
        id=dict(default=None),
        name=dict(required=True),
        data_center=dict(required=True),
        description=dict(default=None),
        cluster_threshold=dict(default=None,
                               type='int',
                               aliases=['cluster_soft_limit']),
        cluster_grace=dict(default=None,
                           type='int',
                           aliases=['cluster_hard_limit']),
        storage_threshold=dict(default=None,
                               type='int',
                               aliases=['storage_soft_limit']),
        storage_grace=dict(default=None,
                           type='int',
                           aliases=['storage_hard_limit']),
        clusters=dict(default=[], type='list'),
        storages=dict(default=[], type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        datacenters_service = connection.system_service().data_centers_service(
        )
        dc_name = module.params['data_center']
        dc_id = getattr(search_by_name(datacenters_service, dc_name), 'id',
                        None)
        if dc_id is None:
            raise Exception("Datacenter '%s' was not found." % dc_name)

        quotas_service = datacenters_service.service(dc_id).quotas_service()
        quotas_module = QuotasModule(
            connection=connection,
            module=module,
            service=quotas_service,
        )

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

            # Manage cluster limits:
            cl_limit_service = quotas_service.service(
                ret['id']).quota_cluster_limits_service()
            for cluster in module.params.get('clusters'):
                cl_limit_service.add(limit=otypes.QuotaClusterLimit(
                    memory_limit=float(cluster.get('memory')),
                    vcpu_limit=cluster.get('cpu'),
                    cluster=search_by_name(
                        connection.system_service().clusters_service(),
                        cluster.get('name')),
                ), )

            # Manage storage limits:
            sd_limit_service = quotas_service.service(
                ret['id']).quota_storage_limits_service()
            for storage in module.params.get('storages'):
                sd_limit_service.add(limit=otypes.QuotaStorageLimit(
                    limit=storage.get('size'),
                    storage_domain=search_by_name(
                        connection.system_service().storage_domains_service(),
                        storage.get('name')),
                ))

        elif state == 'absent':
            ret = quotas_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)
Exemplo n.º 20
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', elements='dict'),
        cluster_mappings=dict(default=[], type='list', elements='dict'),
        role_mappings=dict(default=[], type='list', elements='dict'),
        domain_mappings=dict(default=[], type='list', elements='dict'),
        operating_system=dict(type='str'),
        memory=dict(type='str'),
        memory_guaranteed=dict(type='str'),
        memory_max=dict(type='str'),
        nics=dict(type='list', default=[], elements='dict'),
        cloud_init=dict(type='dict'),
        cloud_init_nics=dict(type='list', default=[], elements='dict'),
        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
                )
                if template is None:
                    raise TimeoutError("Image/template '%s' could not be imported. Try again with larger timeout." % template_name)
                ret = templates_module.create(result_state=otypes.TemplateStatus.OK)
        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)
Exemplo n.º 21
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        data_center=dict(required=True),
        id=dict(default=None),
        name=dict(required=True),
        description=dict(default=None),
        comment=dict(default=None),
        external_provider=dict(default=None),
        vlan_tag=dict(default=None, type='int'),
        vm_network=dict(default=None, type='bool'),
        mtu=dict(default=None, type='int'),
        clusters=dict(default=None, type='list'),
        label=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)
        clusters_service = connection.system_service().clusters_service()
        networks_service = connection.system_service().networks_service()
        networks_module = NetworksModule(
            connection=connection,
            module=module,
            service=networks_service,
        )
        state = module.params['state']
        search_params = {
            'name': module.params['name'],
            'datacenter': module.params['data_center'],
        }
        if state == 'present':
            imported = False
            if module.params.get('external_provider') and module.params.get(
                    'name') not in [
                        net.name for net in networks_service.list()
                    ]:
                # Try to import network
                ons_service = connection.system_service(
                ).openstack_network_providers_service()
                on_service = ons_service.provider_service(
                    get_id_by_name(ons_service,
                                   module.params.get('external_provider')))
                on_networks_service = on_service.networks_service()
                if module.params.get('name') in [
                        net.name for net in on_networks_service.list()
                ]:
                    network_service = on_networks_service.network_service(
                        get_id_by_name(on_networks_service,
                                       module.params.get('name')))
                    network_service.import_(data_center=otypes.DataCenter(
                        name=module.params.get('data_center')))
                    imported = True

            ret = networks_module.create(search_params=search_params)
            ret['changed'] = ret['changed'] or imported
            # Update clusters networks:
            if module.params.get('clusters') is not None:
                for param_cluster in module.params.get('clusters'):
                    cluster = search_by_name(clusters_service,
                                             param_cluster.get('name'))
                    if cluster is None:
                        raise Exception("Cluster '%s' was not found." %
                                        param_cluster.get('name'))
                    cluster_networks_service = clusters_service.service(
                        cluster.id).networks_service()
                    cluster_networks_module = ClusterNetworksModule(
                        network_id=ret['id'],
                        cluster_network=param_cluster,
                        connection=connection,
                        module=module,
                        service=cluster_networks_service,
                    )
                    if param_cluster.get('assigned', True):
                        ret = cluster_networks_module.create()
                    else:
                        ret = cluster_networks_module.remove()

        elif state == 'absent':
            ret = networks_module.remove(search_params=search_params)

        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)
Exemplo n.º 22
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, required=True, aliases=['host']),
        address=dict(default=None),
        username=dict(default=None),
        password=dict(default=None, no_log=True),
        type=dict(default=None),
        port=dict(default=None, type='int'),
        order=dict(default=None, type='int'),
        options=dict(default=None, type='dict'),
        encrypt_options=dict(default=None, type='bool', aliases=['encrypt']),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        hosts_service = connection.system_service().hosts_service()
        host = search_by_name(hosts_service, module.params['name'])
        fence_agents_service = hosts_service.host_service(
            host.id).fence_agents_service()

        host_pm_module = HostPmModule(
            connection=connection,
            module=module,
            service=fence_agents_service,
        )
        host_module = HostModule(
            connection=connection,
            module=module,
            service=hosts_service,
        )

        state = module.params['state']
        if state == 'present':
            agent = host_pm_module.search_entity(
                search_params={
                    'address': module.params['address'],
                    'type': module.params['type'],
                })
            ret = host_pm_module.create(entity=agent)

            # Enable Power Management, if it's not enabled:
            host_module.create(entity=host)
        elif state == 'absent':
            agent = host_pm_module.search_entity(
                search_params={
                    'address': module.params['address'],
                    'type': module.params['type'],
                })
            ret = host_pm_module.remove(entity=agent)

        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,
                _wait=True if module.params['upload_image_path'] else
                module.params['wait'],
            )
            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']):
                if module.params['format'] == 'cow' and module.params[
                        'content_type'] == 'iso':
                    module.warn(
                        "To upload an ISO image 'format' parameter needs to be set to 'raw'."
                    )
                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)
Exemplo n.º 24
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(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'),
        iscsi_bonds=dict(type='list', default=None, elements='dict'),
    )
    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()
            if module.params.get('iscsi_bonds') is not None:
                iscsi_bonds_service = data_centers_service.data_center_service(
                    ret.get('id')).iscsi_bonds_service()
                before_iscsi_bonds = iscsi_bonds_service.list()
                networks_service = connection.system_service(
                ).networks_service()
                # Remove existing bonds
                for bond in iscsi_bonds_service.list():
                    iscsi_bonds_service.iscsi_bond_service(bond.id).remove()
                # Create new bond
                for new_bond in module.params.get('iscsi_bonds'):
                    iscsi_bond = otypes.IscsiBond(
                        name=new_bond.get('name'),
                        data_center=data_centers_service.data_center_service(
                            ret.get('id')).get(),
                        storage_connections=get_storage_connections(
                            new_bond, connection),
                        networks=[
                            search_by_name(networks_service, network_name)
                            for network_name in new_bond.get('networks')
                        ],
                    )
                    iscsi_bonds_service.add(iscsi_bond)
                ret['changed'] = ret['changed'] or serialize_iscsi_bond(
                    before_iscsi_bonds) != serialize_iscsi_bond(
                        iscsi_bonds_service.list())
        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)
Exemplo n.º 25
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present']),
        cluster=dict(type='str', required=True),
        name=dict(type='str', required=True),
        description=dict(type='str'),
        vm_enforcing=dict(type='bool'),
        vm_rule=dict(type='str', choices=['disabled', 'negative', 'positive']),
        host_enforcing=dict(type='bool'),
        host_rule=dict(type='str',
                       choices=['disabled', 'negative', 'positive']),
        vms=dict(type='list'),
        hosts=dict(type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)
    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        # Check if unsupported parameters were passed:
        supported_41 = ('host_enforcing', 'host_rule', 'hosts')
        if not check_support(
                version='4.1',
                connection=connection,
                module=module,
                params=supported_41,
        ):
            module.fail_json(
                msg='Following parameters are supported since 4.1: {params}'.
                format(params=supported_41, ))
        clusters_service = connection.system_service().clusters_service()
        vms_service = connection.system_service().vms_service()
        hosts_service = connection.system_service().hosts_service()
        cluster_name = module.params['cluster']
        cluster = search_by_name(clusters_service, cluster_name)
        if cluster is None:
            raise Exception("Cluster '%s' was not found." % cluster_name)
        cluster_service = clusters_service.cluster_service(cluster.id)
        affinity_groups_service = cluster_service.affinity_groups_service()

        # Fetch VM ids which should be assigned to affinity group:
        vm_ids = sorted([
            get_id_by_name(vms_service, vm_name)
            for vm_name in module.params['vms']
        ]) if module.params['vms'] is not None else None
        # Fetch host ids which should be assigned to affinity group:
        host_ids = sorted([
            get_id_by_name(hosts_service, host_name)
            for host_name in module.params['hosts']
        ]) if module.params['hosts'] is not None else None

        affinity_groups_module = AffinityGroupsModule(
            connection=connection,
            module=module,
            service=affinity_groups_service,
            vm_ids=vm_ids,
            host_ids=host_ids,
        )

        state = module.params['state']
        if state == 'present':
            ret = affinity_groups_module.create()
        elif state == 'absent':
            ret = affinity_groups_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)
Exemplo n.º 26
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'plugged', 'present', 'unplugged']),
        vm=dict(type='str'),
        id=dict(default=None),
        template=dict(type='str'),
        name=dict(type='str', required=True),
        interface=dict(type='str'),
        template_version=dict(type='int', default=None),
        profile=dict(type='str'),
        network=dict(type='str'),
        mac_address=dict(type='str'),
        linked=dict(type='bool'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[['vm', 'template']],
    )

    check_sdk(module)

    try:
        # Locate the service that manages the virtual machines and use it to
        # search for the NIC:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        entity_name = None

        if module.params.get('vm'):
            # Locate the VM, where we will manage NICs:
            entity_name = module.params.get('vm')
            collection_service = connection.system_service().vms_service()
        elif module.params.get('template'):
            entity_name = module.params.get('template')
            collection_service = connection.system_service().templates_service(
            )

        # TODO: We have to modify the search_by_name function to accept raise_error=True/False,
        if module.params['template_version'] is not None:
            entity = [
                t for t in collection_service.list() if
                t.version.version_number == module.params['template_version']
            ]
            if not entity:
                raise ValueError(
                    "Template with name '%s' and version '%s' was not found'" %
                    (module.params['template'],
                     module.params['template_version']))
            entity = entity[0]
        else:
            entity = search_by_name(collection_service, entity_name)
        if entity is None:
            raise Exception("Vm/Template '%s' was not found." % entity_name)

        service = collection_service.service(entity.id)
        cluster_id = entity.cluster

        nics_service = service.nics_service()
        entitynics_module = EntityNicsModule(
            connection=connection,
            module=module,
            service=nics_service,
        )

        # Find vNIC id of the network interface (if any):
        if module.params['network']:
            profile = module.params.get('profile')
            cluster_name = get_link_name(connection, cluster_id)
            dcs_service = connection.system_service().data_centers_service()
            dc = dcs_service.list(search='Clusters.name=%s' % cluster_name)[0]
            networks_service = dcs_service.service(dc.id).networks_service()
            network = next((n for n in networks_service.list()
                            if n.name == module.params['network']), None)
            if network is None:
                raise Exception(
                    "Network '%s' was not found in datacenter '%s'." %
                    (module.params['network'], dc.name))
            if profile:
                for vnic in connection.system_service().vnic_profiles_service(
                ).list():
                    if vnic.name == profile and vnic.network.id == network.id:
                        entitynics_module.vnic_id = vnic.id
            else:
                # When not specified which vnic use ovirtmgmt/ovirtmgmt
                vnics = get_vnics(networks_service, network, connection)
                if len(vnics) == 1:
                    entitynics_module.vnic_id = vnics[0].id
                else:
                    raise Exception(
                        "You didn't specify any vnic profile. "
                        "Following vnic profiles are in system: '%s', please specify one of them"
                        % ([vnic.name for vnic in vnics]))
        # Handle appropriate action:
        state = module.params['state']
        if state == 'present':
            ret = entitynics_module.create()
        elif state == 'absent':
            ret = entitynics_module.remove()
        elif state == 'plugged':
            entitynics_module.create()
            ret = entitynics_module.action(
                action='activate',
                action_condition=lambda nic: not nic.plugged,
                wait_condition=lambda nic: nic.plugged,
            )
        elif state == 'unplugged':
            entitynics_module.create()
            ret = entitynics_module.action(
                action='deactivate',
                action_condition=lambda nic: nic.plugged,
                wait_condition=lambda nic: not nic.plugged,
            )

        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)
Exemplo n.º 27
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(aliases=['host'], required=True),
        bond=dict(default=None, type='dict'),
        interface=dict(default=None),
        networks=dict(default=None, type='list', elements='dict'),
        labels=dict(default=None, type='list', elements='str'),
        check=dict(default=None, type='bool'),
        save=dict(default=True, type='bool'),
        sync_networks=dict(default=False, type='bool'),
    )
    module = AnsibleModule(argument_spec=argument_spec)

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        hosts_service = connection.system_service().hosts_service()
        host_networks_module = HostNetworksModule(
            connection=connection,
            module=module,
            service=hosts_service,
        )

        host = host_networks_module.search_entity()
        if host is None:
            raise Exception("Host '%s' was not found." % module.params['name'])

        bond = module.params['bond']
        interface = module.params['interface']
        networks = module.params['networks']
        labels = module.params['labels']
        nic_name = bond.get('name') if bond else module.params['interface']

        host_service = hosts_service.host_service(host.id)
        nics_service = host_service.nics_service()
        nic = search_by_name(nics_service, nic_name)

        if module.params["sync_networks"]:
            if needs_sync(nics_service):
                if not module.check_mode:
                    host_service.sync_all_networks()
                host_networks_module.changed = True

        network_names = [network['name'] for network in networks or []]
        state = module.params['state']

        if (state == 'present'
                and (nic is None or host_networks_module.has_update(
                    nics_service.service(nic.id)))):
            # Remove networks which are attached to different interface then user want:
            attachments_service = host_service.network_attachments_service()

            # Append attachment ID to network if needs update:
            for a in attachments_service.list():
                current_network_name = get_link_name(connection, a.network)
                if current_network_name in network_names:
                    for n in networks:
                        if n['name'] == current_network_name:
                            n['id'] = a.id

            # Check if we have to break some bonds:
            removed_bonds = []
            if nic is not None:
                for host_nic in nics_service.list():
                    if host_nic.bonding and nic.id in [
                            slave.id for slave in host_nic.bonding.slaves
                    ]:
                        removed_bonds.append(otypes.HostNic(id=host_nic.id))

            # Assign the networks:
            setup_params = dict(
                entity=host,
                action='setup_networks',
                check_connectivity=module.params['check'],
                removed_bonds=removed_bonds if removed_bonds else None,
                modified_bonds=[
                    otypes.HostNic(
                        name=bond.get('name'),
                        bonding=otypes.Bonding(
                            options=get_bond_options(bond.get('mode'),
                                                     bond.get('options')),
                            slaves=[
                                otypes.HostNic(name=i)
                                for i in bond.get('interfaces', [])
                            ],
                        ),
                    ),
                ] if bond else None,
                modified_labels=[
                    otypes.NetworkLabel(
                        id=str(name),
                        host_nic=otypes.HostNic(
                            name=bond.get('name') if bond else interface),
                    ) for name in labels
                ] if labels else None,
                modified_network_attachments=[
                    otypes.NetworkAttachment(
                        id=network.get('id'),
                        network=otypes.Network(
                            name=network['name']) if network['name'] else None,
                        host_nic=otypes.HostNic(
                            name=bond.get('name') if bond else interface),
                        ip_address_assignments=[
                            otypes.IpAddressAssignment(
                                assignment_method=otypes.BootProtocol(
                                    network.get('boot_protocol', 'none')),
                                ip=otypes.Ip(
                                    address=network.get('address'),
                                    gateway=network.get('gateway'),
                                    netmask=network.get('netmask'),
                                    version=otypes.IpVersion(
                                        network.get('version'))
                                    if network.get('version') else None,
                                ),
                            ),
                        ],
                        properties=[
                            otypes.Property(name=prop.get('name'),
                                            value=prop.get('value'))
                            for prop in network.get('custom_properties', [])
                        ]) for network in networks
                ] if networks else None,
            )
            if engine_supported(connection, '4.3'):
                setup_params['commit_on_success'] = module.params['save']
            elif module.params['save']:
                setup_params[
                    'post_action'] = host_networks_module._action_save_configuration
            host_networks_module.action(**setup_params)
        elif state == 'absent' and nic:
            attachments = []
            nic_service = nics_service.nic_service(nic.id)

            attached_labels = set([
                str(lbl.id)
                for lbl in nic_service.network_labels_service().list()
            ])
            if networks:
                attachments_service = nic_service.network_attachments_service()
                attachments = attachments_service.list()
                attachments = [
                    attachment for attachment in attachments if get_link_name(
                        connection, attachment.network) in network_names
                ]

            # Remove unmanaged networks:
            unmanaged_networks_service = host_service.unmanaged_networks_service(
            )
            unmanaged_networks = [(u.id, u.name)
                                  for u in unmanaged_networks_service.list()]
            for net_id, net_name in unmanaged_networks:
                if net_name in network_names:
                    if not module.check_mode:
                        unmanaged_networks_service.unmanaged_network_service(
                            net_id).remove()
                    host_networks_module.changed = True

            # Need to check if there are any labels to be removed, as backend fail
            # if we try to send remove non existing label, for bond and attachments it's OK:
            if (labels and set(labels).intersection(attached_labels)
                ) or bond or attachments:
                setup_params = dict(
                    entity=host,
                    action='setup_networks',
                    check_connectivity=module.params['check'],
                    removed_bonds=[
                        otypes.HostNic(name=bond.get('name'), ),
                    ] if bond else None,
                    removed_labels=[
                        otypes.NetworkLabel(id=str(name)) for name in labels
                    ] if labels else None,
                    removed_network_attachments=attachments
                    if attachments else None,
                )
                if engine_supported(connection, '4.3'):
                    setup_params['commit_on_success'] = module.params['save']
                elif module.params['save']:
                    setup_params[
                        'post_action'] = host_networks_module._action_save_configuration
                host_networks_module.action(**setup_params)

        nic = search_by_name(nics_service, nic_name)
        module.exit_json(
            **{
                'changed': host_networks_module.changed,
                'id': nic.id if nic else None,
                'host_nic': get_dict_of_struct(nic),
            })
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)