def main():
    argument_spec = ovirt_info_full_argument_spec(
        authz_name=dict(required=True, aliases=['domain']),
        user_name=dict(default=None),
        group_name=dict(default=None),
        namespace=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        permissions_service = _permissions_service(connection, module)
        permissions = []
        for p in permissions_service.list():
            newperm = dict()
            for key, value in p.__dict__.items():
                if value and isinstance(value, sdk.Struct):
                    newperm[key[1:]] = get_link_name(connection, value)
                    newperm['%s_id' % key[1:]] = value.id
            permissions.append(newperm)

        result = dict(ovirt_permissions=permissions)
        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)
Esempio n. 2
0
def main():
    argument_spec = ovirt_full_argument_spec(
        id=dict(default=None),
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(required=True),
        template=dict(default=None),
        cluster=dict(default=None),
        description=dict(default=None),
        vm=dict(default=None, type='dict'),
        comment=dict(default=None),
        vm_per_user=dict(default=None, type='int'),
        prestarted=dict(default=None, type='int'),
        vm_count=dict(default=None, type='int'),
        type=dict(default=None, choices=['automatic', 'manual']),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)
    check_params(module)

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

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

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_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)
Esempio n. 4
0
def main():
    argument_spec = ovirt_info_full_argument_spec(
        pattern=dict(default='', required=False),
        all_content=dict(default=False, type='bool'),
        cluster_version=dict(default=None, type='str'),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        hosts_service = connection.system_service().hosts_service()
        hosts = hosts_service.list(
            search=module.params['pattern'],
            all_content=module.params['all_content']
        )
        cluster_version = module.params.get('cluster_version')
        if cluster_version is not None:
            hosts = get_filtered_hosts(cluster_version, hosts, connection)
        result = dict(
            ovirt_hosts=[
                get_dict_of_struct(
                    struct=c,
                    connection=connection,
                    fetch_nested=module.params.get('fetch_nested'),
                    attributes=module.params.get('nested_attributes'),
                ) for c in hosts
            ],
        )
        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)
Esempio n. 5
0
def main():
    argument_spec = ovirt_info_full_argument_spec(pattern=dict(
        default='', required=False), )
    module = AnsibleModule(argument_spec)
    is_old_facts = module._name == 'ovirt_disk_facts'
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_disk_facts' module has been renamed to 'ovirt_disk_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)
        disks_service = connection.system_service().disks_service()
        disks = disks_service.list(search=module.params['pattern'], )
        result = dict(ovirt_disks=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in disks
        ], )
        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 main():
    argument_spec = ovirt_info_full_argument_spec(
        pattern=dict(default='', required=False),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        clusters_service = connection.system_service().clusters_service()
        clusters = clusters_service.list(search=module.params['pattern'])
        result = dict(
            ovirt_clusters=[
                get_dict_of_struct(
                    struct=c,
                    connection=connection,
                    fetch_nested=module.params.get('fetch_nested'),
                    attributes=module.params.get('nested_attributes'),
                ) for c in clusters
            ],
        )
        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 main():
    argument_spec = ovirt_info_full_argument_spec(
        max=dict(default=None, type='int'),
        name=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        vnic_profiles_service = connection.system_service().vnic_profiles_service()
        vnic_profiles = vnic_profiles_service.list(max=module.params.get('max'))
        if module.params.get('name') and vnic_profiles:
            vnic_profiles = [vnic_profile for vnic_profile in vnic_profiles if vnic_profile.name == module.params.get("name")]

        result = dict(
            ovirt_vnic_profiles=[
                get_dict_of_struct(
                    struct=c,
                    connection=connection,
                    fetch_nested=module.params.get('fetch_nested'),
                    attributes=module.params.get('nested_attributes'),
                ) for c in vnic_profiles
            ],
        )
        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)
Esempio n. 8
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        id=dict(default=None),
        address=dict(default=None),
        path=dict(default=None),
        nfs_version=dict(default=None),
        nfs_timeout=dict(default=None, type='int'),
        nfs_retrans=dict(default=None, type='int'),
        mount_options=dict(default=None),
        password=dict(default=None, no_log=True),
        username=dict(default=None),
        port=dict(default=None, type='int'),
        target=dict(default=None),
        type=dict(default=None),
        vfs_type=dict(default=None),
        force=dict(type='bool', default=False),
        storage=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        storage_connections_service = connection.system_service(
        ).storage_connections_service()
        storage_connection_module = StorageConnectionModule(
            connection=connection,
            module=module,
            service=storage_connections_service,
        )
        entity = None
        if module.params['id'] is None:
            entity = find_sc_by_attributes(module, storage_connections_service)

        state = module.params['state']
        if state == 'present':
            ret = storage_connection_module.create(
                entity=entity,
                update_params={'force': True},
            )
            storage_connection_module.post_present(ret['id'])
        elif state == 'absent':
            storage_connection_module.pre_remove(module.params['id'])
            ret = storage_connection_module.remove(entity=entity)

        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_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)
Esempio n. 10
0
def main():
    argument_spec = ovirt_info_full_argument_spec(case_sensitive=dict(
        default=True, type='bool', required=False),
                                                  from_=dict(default=None,
                                                             type='int',
                                                             required=False),
                                                  max=dict(default=None,
                                                           type='int',
                                                           required=False),
                                                  search=dict(default='',
                                                              required=False),
                                                  headers=dict(default='',
                                                               required=False),
                                                  query=dict(default='',
                                                             required=False),
                                                  wait=dict(default=True,
                                                            type='bool',
                                                            required=False))
    module = AnsibleModule(argument_spec)
    is_old_facts = module._name == 'ovirt_event_facts'
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_event_facts' module has been renamed to 'ovirt_event_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)
        events_service = connection.system_service().events_service()
        events = events_service.list(
            case_sensitive=module.params['case_sensitive'],
            from_=module.params['from_'],
            max=module.params['max'],
            search=module.params['search'],
            headers=module.params['headers'],
            query=module.params['query'],
            wait=module.params['wait'])

        result = dict(ovirt_events=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in events
        ], )
        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 main():
    argument_spec = ovirt_info_full_argument_spec(
        host=dict(required=True),
        iscsi=dict(default=None, type='dict'),
        fcp=dict(default=None, type='dict'),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

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

        # Get Host
        hosts_service = connection.system_service().hosts_service()
        host_id = get_id_by_name(hosts_service, module.params['host'])
        storage_type = _get_storage_type(module.params)
        host_service = hosts_service.host_service(host_id)

        if storage_type == 'iscsi':
            # Login
            iscsi = module.params.get('iscsi')
            _login(host_service, iscsi)

        # Get LUNs exposed from the specified target
        host_storages = host_service.storage_service().list()

        if storage_type == 'iscsi':
            filterred_host_storages = [
                host_storage for host_storage in host_storages
                if host_storage.type == otypes.StorageType.ISCSI
            ]
            if 'target' in iscsi:
                filterred_host_storages = [
                    host_storage for host_storage in filterred_host_storages if
                    iscsi.get('target') == host_storage.logical_units[0].target
                ]
        elif storage_type == 'fcp':
            filterred_host_storages = [
                host_storage for host_storage in host_storages
                if host_storage.type == otypes.StorageType.FCP
            ]

        result = dict(ovirt_host_storages=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in filterred_host_storages
        ], )
        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)
Esempio n. 12
0
def main():
    argument_spec = ovirt_info_full_argument_spec(
        name=dict(default=None, required=False),
        type=dict(
            default=None,
            required=True,
            choices=[
                'os_image',
                'os_network',
                'os_volume',
                'foreman',
            ],
            aliases=['provider'],
        ),
    )
    module = AnsibleModule(argument_spec)
    is_old_facts = module._name == 'ovirt_external_provider_facts'
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_external_provider_facts' module has been renamed to 'ovirt_external_provider_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)
        external_providers_service = _external_provider_service(
            provider_type=module.params.pop('type'),
            system_service=connection.system_service(),
        )
        if module.params['name']:
            external_providers = [
                e for e in external_providers_service.list()
                if fnmatch.fnmatch(e.name, module.params['name'])
            ]
        else:
            external_providers = external_providers_service.list()

        result = dict(ovirt_external_providers=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in external_providers
        ], )
        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)
Esempio n. 13
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        description=dict(default=None),
        severity=dict(
            choices=['error', 'normal', 'warning'],
            default='normal',
        ),
        origin=dict(default=None),
        custom_id=dict(default=None, type='int'),
        id=dict(default=None),
        cluster=dict(default=None),
        data_center=dict(default=None),
        host=dict(default=None),
        storage_domain=dict(default=None),
        template=dict(default=None),
        user=dict(default=None),
        vm=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True
    )

    check_sdk(module)

    # Wait must be set to false if state == absent

    if module.params['state'] == 'absent' and module.params['wait'] is not False:
        module.fail_json(msg='When "state" is absent, "wait" must be set to false.')

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        events_service = connection.system_service().events_service()
        events_module = EventsModule(
            connection=connection,
            module=module,
            service=events_service,
        )

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'started', 'finished', 'failed'],
            default='present',
        ),
        description=dict(default=None),
        steps=dict(default=None, type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
    )

    check_sdk(module)

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

        state = module.params['state']
        job = get_entity(jobs_service, module.params['description'])
        changed = False
        if state in ['present', 'started']:
            if job is None or job.status in [otypes.JobStatus.FINISHED, otypes.JobStatus.FAILED]:
                job = jobs_service.add(build_job(module.params['description']))
                changed = True
            changed = attach_steps(module, job.id, jobs_service) or changed

        if job is not None and job.status not in [otypes.JobStatus.FINISHED, otypes.JobStatus.FAILED]:
            if state in ['absent', 'finished']:
                jobs_service.job_service(job.id).end(succeeded=True)
                changed = True

            elif state == 'failed':
                jobs_service.job_service(job.id).end(succeeded=False)
                changed = True

        ret = {
            'changed': changed,
            'id': getattr(job, 'id', None),
            'job': get_dict_of_struct(
                struct=job,
                connection=connection,
                fetch_nested=True,
                attributes=module.params.get('nested_attributes'),
            ),
        }

        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)
Esempio n. 15
0
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 == '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)
Esempio n. 16
0
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 == '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)
Esempio n. 17
0
def main():
    argument_spec = ovirt_info_full_argument_spec(
        pattern=dict(default='', required=False),
        all_content=dict(default=False, type='bool'),
        next_run=dict(default=None, type='bool'),
        case_sensitive=dict(default=True, type='bool'),
        max=dict(default=None, type='int'),
    )
    module = AnsibleModule(argument_spec)
    is_old_facts = module._name == 'ovirt_vm_facts'
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_vm_facts' module has been renamed to 'ovirt_vm_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()
        vms = vms_service.list(
            search=module.params['pattern'],
            all_content=module.params['all_content'],
            case_sensitive=module.params['case_sensitive'],
            max=module.params['max'],
        )
        if module.params['next_run']:
            vms = [
                vms_service.vm_service(vm.id).get(next_run=True) for vm in vms
            ]

        result = dict(ovirt_vms=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in vms
        ], )
        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)
Esempio n. 18
0
def main():
    argument_spec = ovirt_info_full_argument_spec(
        id=dict(default=None),
        name=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    is_old_facts = module._name == 'ovirt_scheduling_policy_facts'
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_scheduling_policy_facts' module has been renamed to 'ovirt_scheduling_policy_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)
        system_service = connection.system_service()
        sched_policies_service = system_service.scheduling_policies_service()
        if module.params['name']:
            sched_policies = [
                e for e in sched_policies_service.list()
                if fnmatch.fnmatch(e.name, module.params['name'])
            ]
        elif module.params['id']:
            sched_policies = [
                sched_policies_service.service(module.params['id']).get()
            ]
        else:
            sched_policies = sched_policies_service.list()

        result = dict(ovirt_scheduling_policies=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in sched_policies
        ], )
        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 main():
    argument_spec = ovirt_info_full_argument_spec(
        storage_domain=dict(default=None),
        max=dict(default=None, type='int'),
        unregistered=dict(default=False, type='bool'),
    )
    module = AnsibleModule(argument_spec)
    is_old_facts = module._name == 'ovirt_storage_template_facts'
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_storage_template_facts' module has been renamed to 'ovirt_storage_template_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)
        storage_domains_service = connection.system_service(
        ).storage_domains_service()
        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:
        if module.params.get('unregistered'):
            templates = templates_service.list(unregistered=True)
        else:
            templates = templates_service.list(max=module.params['max'])
        result = dict(ovirt_storage_templates=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in templates
        ], )
        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)
Esempio n. 20
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(required=True),
        authz_name=dict(required=True, aliases=['domain']),
        namespace=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)
    check_params(module)

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

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

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

    check_sdk(module)
    check_params(module)

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 22
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(type='str', default='present', choices=['absent', 'present']),
        network=dict(type='str', required=True),
        data_center=dict(type='str', required=True),
        description=dict(type='str'),
        name=dict(type='str', required=True),
        network_filter=dict(type='str'),
        custom_properties=dict(type='list'),
        qos=dict(type='str'),
        pass_through=dict(type='str', choices=['disabled', 'enabled']),
        port_mirroring=dict(type='bool'),
        migratable=dict(type='bool'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,

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

        vnic_services = connection.system_service().vnic_profiles_service()

        entitynics_module = EntityVnicPorfileModule(
            connection=connection,
            module=module,
            service=vnic_services,
        )
        state = module.params['state']
        entity = get_entity(vnic_services, entitynics_module)
        if state == 'present':
            ret = entitynics_module.create(entity=entity, force_create=entity is None)
        elif state == 'absent':
            if entity is not None:
                ret = entitynics_module.remove(entity=entity)
            else:
                raise Exception("Vnic profile '%s' in network '%s' was not found." % (module.params['name'], module.params['network']))
        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',
        ),
        cluster=dict(default=None),
        name=dict(default=None, required=True),
        vms=dict(default=None, type='list'),
        hosts=dict(default=None, type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ('state', 'present', ['cluster']),
        ],
    )

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        affinity_labels_service = connection.system_service(
        ).affinity_labels_service()
        affinity_labels_module = AffinityLabelsModule(
            connection=connection,
            module=module,
            service=affinity_labels_service,
        )

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_info_full_argument_spec()
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        api = connection.system_service().get()
        result = dict(ovirt_api=get_dict_of_struct(
            struct=api,
            connection=connection,
            fetch_nested=module.params.get('fetch_nested'),
            attributes=module.params.get('nested_attributes'),
        ))
        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)
Esempio n. 25
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'attached', 'detached'],
            default='present',
        ),
        id=dict(default=None),
        name=dict(required=True),
        description=dict(default=None),
        parent=dict(default=None),
        vms=dict(default=None, type='list'),
        hosts=dict(default=None, 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)
        tags_service = connection.system_service().tags_service()
        tags_module = TagsModule(
            connection=connection,
            module=module,
            service=tags_service,
        )

        state = module.params['state']
        if state in ['present', 'attached', 'detached']:
            ret = tags_module.create()
        elif state == 'absent':
            ret = tags_module.remove()

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_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)
Esempio n. 27
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        id=dict(default=None),
        name=dict(default=None),
        description=dict(default=None),
        administrative=dict(type='bool', default=False),
        permits=dict(type='list', default=[]),
    )
    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)
        roles_service = connection.system_service().roles_service()
        roles_module = RoleModule(
            connection=connection,
            module=module,
            service=roles_service,
        )
        state = module.params['state']
        if state == 'present':
            ret = roles_module.create()
        elif state == 'absent':
            ret = roles_module.remove()
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_info_full_argument_spec(
        id=dict(default=None),
        name=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        system_service = connection.system_service()
        sched_policies_service = system_service.scheduling_policies_service()
        if module.params['name']:
            sched_policies = [
                e for e in sched_policies_service.list()
                if fnmatch.fnmatch(e.name, module.params['name'])
            ]
        elif module.params['id']:
            sched_policies = [
                sched_policies_service.service(module.params['id']).get()
            ]
        else:
            sched_policies = sched_policies_service.list()

        result = dict(ovirt_scheduling_policies=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in sched_policies
        ], )
        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)
Esempio n. 29
0
def main():
    argument_spec = ovirt_info_full_argument_spec(
        storage_domain=dict(default=None),
        max=dict(default=None, type='int'),
        unregistered=dict(default=False, type='bool'),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        storage_domains_service = connection.system_service(
        ).storage_domains_service()
        sd_id = get_id_by_name(storage_domains_service,
                               module.params['storage_domain'])
        storage_domain_service = storage_domains_service.storage_domain_service(
            sd_id)
        vms_service = storage_domain_service.vms_service()

        # Find the unregistered VM we want to register:
        if module.params.get('unregistered'):
            vms = vms_service.list(unregistered=True)
        else:
            vms = vms_service.list()
        result = dict(ovirt_storage_vms=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in vms
        ], )
        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 main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'maintenance', 'unattached', 'imported',
                'update_ovf_store'
            ],
            default='present',
        ),
        id=dict(default=None),
        name=dict(default=None),
        description=dict(default=None),
        comment=dict(default=None),
        data_center=dict(default=None),
        domain_function=dict(choices=['data', 'iso', 'export'],
                             default='data',
                             aliases=['type']),
        host=dict(default=None),
        localfs=dict(default=None, type='dict'),
        nfs=dict(default=None, type='dict'),
        iscsi=dict(default=None, type='dict'),
        managed_block_storage=dict(
            default=None,
            type='dict',
            options=dict(driver_options=dict(type='list'),
                         driver_sensitive_options=dict(type='list',
                                                       no_log=True))),
        posixfs=dict(default=None, type='dict'),
        glusterfs=dict(default=None, type='dict'),
        fcp=dict(default=None, type='dict'),
        wipe_after_delete=dict(type='bool', default=None),
        backup=dict(type='bool', default=None),
        critical_space_action_blocker=dict(type='int', default=None),
        warning_low_space=dict(type='int', default=None),
        destroy=dict(type='bool', default=None),
        format=dict(type='bool', default=None),
        discard_after_delete=dict(type='bool', default=None))
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)

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

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

            ret = OvirtRetry.backoff(tries=5, delay=1, backoff=2)(
                storage_domains_module.action)(
                    action='deactivate',
                    action_condition=lambda s: s.status == sdstate.ACTIVE,
                    wait_condition=lambda s: s.status == sdstate.MAINTENANCE,
                    fail_condition=failed_state,
                )
        elif state == 'unattached':
            ret = storage_domains_module.create()
            storage_domains_module.pre_remove(
                storage_domain=storage_domains_service.service(
                    ret['id']).get())
            ret['changed'] = storage_domains_module.changed
        elif state == 'update_ovf_store':
            ret = storage_domains_module.action(action='update_ovf_store')
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)