Пример #1
0
def create_snapshot(module, vm_service, snapshots_service, connection):
    changed = False
    snapshot = get_entity(
        snapshots_service.snapshot_service(module.params['snapshot_id']))
    if snapshot is None:
        if not module.check_mode:
            disk_attachments_id = set(
                get_disk_attachment(
                    disk,
                    vm_service.disk_attachments_service().list(),
                    connection).id for disk in module.params.get(
                        'disks')) if module.params.get('disks') else None

            snapshot = snapshots_service.add(
                otypes.Snapshot(
                    description=module.params.get('description'),
                    persist_memorystate=module.params.get('use_memory'),
                    disk_attachments=[
                        otypes.DiskAttachment(id=da_id)
                        for da_id in disk_attachments_id
                    ] if disk_attachments_id else None))
        changed = True
        wait(
            service=snapshots_service.snapshot_service(snapshot.id),
            condition=lambda snap: snap.snapshot_status == otypes.
            SnapshotStatus.OK,
            wait=module.params['wait'],
            timeout=module.params['timeout'],
        )
    return {
        'changed': changed,
        'id': snapshot.id,
        'snapshot': get_dict_of_struct(snapshot),
    }
Пример #2
0
def restore_snapshot(module, vm_service, snapshots_service):
    changed = False
    snapshot_service = snapshots_service.snapshot_service(
        module.params['snapshot_id'])
    snapshot = get_entity(snapshot_service)
    if snapshot is None:
        raise Exception("Snapshot with id '%s' doesn't exist" %
                        module.params['snapshot_id'])

    if snapshot.snapshot_status != otypes.SnapshotStatus.IN_PREVIEW:
        if not module.check_mode:
            snapshot_service.restore(
                restore_memory=module.params.get('use_memory'), )
        changed = True
    else:
        if not module.check_mode:
            vm_service.commit_snapshot()
        changed = True

    if changed:
        wait(
            service=snapshot_service,
            condition=lambda snap: snap.snapshot_status == otypes.
            SnapshotStatus.OK,
            wait=module.params['wait'],
            timeout=module.params['timeout'],
        )
    return {
        'changed': changed,
        'id': snapshot.id if snapshot else None,
        'snapshot': get_dict_of_struct(snapshot),
    }
Пример #3
0
def main():
    argument_spec = ovirt_facts_full_argument_spec(pattern=dict(
        default='', required=False), )
    module = AnsibleModule(argument_spec)

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

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        datacenters_service = connection.system_service().data_centers_service(
        )
        datacenters = datacenters_service.list(search=module.params['pattern'])
        module.exit_json(
            changed=False,
            ansible_facts=dict(ovirt_datacenters=[
                get_dict_of_struct(
                    struct=d,
                    connection=connection,
                    fetch_nested=module.params.get('fetch_nested'),
                    attributes=module.params.get('nested_attributes'),
                ) for d in datacenters
            ], ),
        )
    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(
        pattern=dict(default='', required=False),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        vms_service = connection.system_service().vms_service()
        vms = vms_service.list(search=module.params['pattern'])
        module.exit_json(
            changed=False,
            ansible_facts=dict(
                ovirt_vms=[
                    get_dict_of_struct(
                        struct=c,
                        connection=connection,
                        fetch_nested=1,
                        attributes=['name', 'description'],
                    ) for c in vms
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Пример #5
0
 def import_external_network(self):
     ons_service = self._connection.system_service().openstack_network_providers_service()
     on_service = ons_service.provider_service(get_id_by_name(ons_service, self.param('external_provider')))
     networks_service = on_service.networks_service()
     network_service = networks_service.network_service(get_id_by_name(networks_service, self.param('name')))
     network_service.import_(data_center=otypes.DataCenter(name=self._module.params['data_center']))
     return {"network": get_dict_of_struct(network_service.get()), "changed": True}
Пример #6
0
def main():
    argument_spec = ovirt_full_argument_spec(
        datacenter=dict(required=True),
        name=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        datacenters_service = connection.system_service().data_centers_service(
        )
        dc_name = module.params['datacenter']
        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()

        module.exit_json(
            changed=False,
            ansible_facts=dict(
                ovirt_quotas=[get_dict_of_struct(c) for c in quotas], ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Пример #7
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_group_facts'
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_group_facts' module has been renamed to 'ovirt_group_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)
        groups_service = connection.system_service().groups_service()
        groups = groups_service.list(search=module.params['pattern'])
        result = dict(ovirt_groups=[
            get_dict_of_struct(
                struct=c,
                connection=connection,
                fetch_nested=module.params.get('fetch_nested'),
                attributes=module.params.get('nested_attributes'),
            ) for c in groups
        ], )
        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)
Пример #8
0
def main():
    argument_spec = ovirt_facts_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)
        vmpools_service = connection.system_service().vm_pools_service()
        vmpools = vmpools_service.list(search=module.params['pattern'])
        module.exit_json(
            changed=False,
            ansible_facts=dict(ovirt_vm_pools=[
                get_dict_of_struct(
                    struct=c,
                    connection=connection,
                    fetch_nested=module.params.get('fetch_nested'),
                    attributes=module.params.get('nested_attributes'),
                ) for c in vmpools
            ], ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Пример #9
0
def main():
    argument_spec = ovirt_facts_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)
        module.exit_json(
            changed=False,
            ansible_facts=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
            ], ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Пример #10
0
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:
                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)
Пример #11
0
def main():
    argument_spec = ovirt_facts_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)
        users_service = connection.system_service().users_service()
        users = users_service.list(search=module.params['pattern'])
        module.exit_json(
            changed=False,
            ansible_facts=dict(
                ovirt_users=[
                    get_dict_of_struct(
                        struct=c,
                        connection=connection,
                        fetch_nested=module.params.get('fetch_nested'),
                        attributes=module.params.get('nested_attributes'),
                    ) for c in users
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Пример #12
0
def main():
    argument_spec = ovirt_facts_full_argument_spec(
        pattern=dict(default='', required=False),
        all_content=dict(default=False, type='bool'),
        case_sensitive=dict(default=True, type='bool'),
        max=dict(default=None, type='int'),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('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'],
        )
        module.exit_json(
            changed=False,
            ansible_facts=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
            ], ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Пример #13
0
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)
Пример #14
0
def main():
    argument_spec = ovirt_facts_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

        module.exit_json(
            changed=False,
            ansible_facts=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
            ], ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Пример #15
0
def create_snapshot(module, vm_service, snapshots_service):
    changed = False
    snapshot = get_entity(
        snapshots_service.snapshot_service(module.params['snapshot_id'])
    )
    if snapshot is None:
        if not module.check_mode:
            snapshot = snapshots_service.add(
                otypes.Snapshot(
                    description=module.params.get('description'),
                    persist_memorystate=module.params.get('use_memory'),
                )
            )
        changed = True
        wait(
            service=snapshots_service.snapshot_service(snapshot.id),
            condition=lambda snap: snap.snapshot_status == otypes.SnapshotStatus.OK,
            wait=module.params['wait'],
            timeout=module.params['timeout'],
        )
    return {
        'changed': changed,
        'id': snapshot.id,
        'snapshot': get_dict_of_struct(snapshot),
    }
Пример #16
0
def main():
    argument_spec = ovirt_facts_full_argument_spec(
        pattern=dict(default='', required=False),
    )
    module = AnsibleModule(argument_spec)

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

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        datacenters_service = connection.system_service().data_centers_service()
        datacenters = datacenters_service.list(search=module.params['pattern'])
        module.exit_json(
            changed=False,
            ansible_facts=dict(
                ovirt_datacenters=[
                    get_dict_of_struct(
                        struct=d,
                        connection=connection,
                        fetch_nested=module.params.get('fetch_nested'),
                        attributes=module.params.get('nested_attributes'),
                    ) for d in datacenters
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Пример #17
0
def remove_snapshot(module, vm_service, snapshots_service, snapshot_id=None):
    changed = False
    if not snapshot_id:
        snapshot_id = module.params['snapshot_id']
    snapshot = get_entity(
        snapshots_service.snapshot_service(snapshot_id)
    )

    if snapshot:
        snapshot_service = snapshots_service.snapshot_service(snapshot.id)
        if not module.check_mode:
            snapshot_service.remove()
        changed = True
        wait(
            service=snapshot_service,
            condition=lambda snapshot: snapshot is None,
            wait=module.params['wait'],
            timeout=module.params['timeout'],
        )

    return {
        'changed': changed,
        'id': snapshot.id if snapshot else None,
        'snapshot': get_dict_of_struct(snapshot),
    }
Пример #18
0
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)
    is_old_facts = module._name == 'ovirt_host_storage_facts'
    if is_old_facts:
        module.deprecate("The 'ovirt_host_storage_facts' module has been renamed to 'ovirt_host_storage_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)

        # 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
            ],
        )
        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_facts_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()
            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()
            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

        module.exit_json(
            changed=False,
            ansible_facts=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
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Пример #20
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)
Пример #21
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)
Пример #22
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)
def main():
    argument_spec = ovirt_facts_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]

        module.exit_json(
            changed=False,
            ansible_facts=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
                ],
            ),
        )
    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(
        name=dict(default=None),
        host=dict(default=None),
        vm=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('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()
            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()
            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

        module.exit_json(
            changed=False,
            ansible_facts=dict(
                affinity_labels=[
                    get_dict_of_struct(l) for l in labels
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
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)
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_vm_facts'
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_storage_vm_facts' module has been renamed to 'ovirt_storage_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)
        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
        ], )
        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)
Пример #27
0
def main():
    argument_spec = ovirt_facts_full_argument_spec(
        vm=dict(required=True),
        description=dict(default=None),
        snapshot_id=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)

        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()

        module.exit_json(
            changed=False,
            ansible_facts=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
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Пример #28
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)
Пример #29
0
def main():
    argument_spec = ovirt_full_argument_spec(pattern=dict(default="", required=False))
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop("auth"))
        datacenters_service = connection.system_service().data_centers_service()
        datacenters = datacenters_service.list(search=module.params["pattern"])
        module.exit_json(
            changed=False, ansible_facts=dict(ovirt_datacenters=[get_dict_of_struct(c) for c in datacenters])
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
def main():
    argument_spec = ovirt_facts_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)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('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()

        module.exit_json(
            changed=False,
            ansible_facts=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
            ], ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Пример #31
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)
Пример #32
0
def main():
    argument_spec = ovirt_facts_full_argument_spec(
        vm=dict(required=True),
        name=dict(default=None),
    )
    module = AnsibleModule(argument_spec)

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

    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()

        module.exit_json(
            changed=False,
            ansible_facts=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
            ], ),
        )
    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_facts_full_argument_spec(
        vm=dict(required=True),
        description=dict(default=None),
        snapshot_id=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('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()

        module.exit_json(
            changed=False,
            ansible_facts=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
            ], ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Пример #34
0
def main():
    argument_spec = ovirt_facts_full_argument_spec(
        storage_domain=dict(default=None),
        max=dict(default=None, type='int'),
        unregistered=dict(default=False, type='bool'),
    )
    module = AnsibleModule(argument_spec)

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

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        storage_domains_service = connection.system_service(
        ).storage_domains_service()
        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'])
        module.exit_json(
            changed=False,
            ansible_facts=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
            ], ),
        )
    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_facts_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()

        module.exit_json(
            changed=False,
            ansible_facts=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
                ],
            ),
        )
    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(pattern=dict(default='',
                                                          required=False), )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        groups_service = connection.system_service().groups_service()
        groups = groups_service.list(search=module.params['pattern'])
        module.exit_json(
            changed=False,
            ansible_facts=dict(
                ovirt_groups=[get_dict_of_struct(c) for c in groups], ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Пример #37
0
def main():
    argument_spec = ovirt_facts_full_argument_spec(
        all_content=dict(default=False, type='bool'),
        case_sensitive=dict(default=True, type='bool'),
        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 the unregistered VM we want to register:
        if module.params.get('unregistered'):
            vms = vms_service.list(unregistered=True)
        else:
            vms = vms_service.list()
        module.exit_json(
            changed=False,
            ansible_facts=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
            ], ),
        )
    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_facts_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()

        module.exit_json(
            changed=False,
            ansible_facts=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
                ],
            ),
        )
    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_facts_full_argument_spec(
        all_content=dict(default=False, type='bool'),
        case_sensitive=dict(default=True, type='bool'),
        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 the unregistered VM we want to register:
        if module.params.get('unregistered'):
            vms = vms_service.list(unregistered=True)
        else:
            vms = vms_service.list()
        module.exit_json(
            changed=False,
            ansible_facts=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
                ],
            ),
        )
    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(
        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)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('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()

        module.exit_json(
            changed=False,
            ansible_facts=dict(
                ovirt_external_providers=[
                    get_dict_of_struct(c) for c in external_providers
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
def main():
    argument_spec = ovirt_full_argument_spec(
        pattern=dict(default='', required=False),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        storage_domains_service = connection.system_service().storage_domains_service()
        storage_domains = storage_domains_service.list(search=module.params['pattern'])
        module.exit_json(
            changed=False,
            ansible_facts=dict(
                ovirt_storage_domains=[
                    get_dict_of_struct(c) for c in storage_domains
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Пример #42
0
def main():
    argument_spec = ovirt_full_argument_spec(
        datacenter=dict(required=True),
        name=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        datacenters_service = connection.system_service().data_centers_service()
        dc_name = module.params['datacenter']
        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()

        module.exit_json(
            changed=False,
            ansible_facts=dict(
                ovirt_quotas=[
                    get_dict_of_struct(c) for c in quotas
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Пример #43
0
def main():
    argument_spec = ovirt_facts_full_argument_spec(
        pattern=dict(default='', required=False),
        all_content=dict(default=False, type='bool'),
        case_sensitive=dict(default=True, type='bool'),
        max=dict(default=None, type='int'),
    )
    module = AnsibleModule(argument_spec)
    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'],
        )
        module.exit_json(
            changed=False,
            ansible_facts=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
                ],
            ),
        )
    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(
        vm=dict(required=True),
        name=dict(default=None),
    )
    module = AnsibleModule(argument_spec)
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('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()

        module.exit_json(
            changed=False,
            ansible_facts=dict(
                ovirt_nics=[
                    get_dict_of_struct(c) for c in nics
                ],
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Пример #45
0
def main():
    argument_spec = ovirt_facts_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()
        module.exit_json(
            changed=False,
            ansible_facts=dict(
                ovirt_api=get_dict_of_struct(
                    struct=api,
                    connection=connection,
                    fetch_nested=module.params.get('fetch_nested'),
                    attributes=module.params.get('nested_attributes'),
                )
            ),
        )
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Пример #46
0
 def __compare_options(self, new_options, old_options):
     return sorted(get_dict_of_struct(opt) for opt in new_options) != sorted(get_dict_of_struct(opt) for opt in old_options)
Пример #47
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, aliases=['host'], required=True),
        bond=dict(default=None, type='dict'),
        interface=dict(default=None),
        networks=dict(default=None, type='list'),
        labels=dict(default=None, type='list'),
        check=dict(default=None, type='bool'),
        save=dict(default=None, 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)

        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:
            host_networks_module.action(
                entity=host,
                action='setup_networks',
                post_action=host_networks_module._action_save_configuration,
                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,
                                ),
                            ),
                        ],
                    ) for network in networks
                ] if networks else None,
            )
        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:
                host_networks_module.action(
                    entity=host,
                    action='setup_networks',
                    post_action=host_networks_module._action_save_configuration,
                    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,
                )

        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)
Пример #48
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, aliases=['host'], required=True),
        bond=dict(default=None, type='dict'),
        interface=dict(default=None),
        networks=dict(default=None, type='list'),
        labels=dict(default=None, type='list'),
        check=dict(default=None, type='bool'),
        save=dict(default=None, 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']

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

        state = module.params['state']
        if (
            state == 'present' and
            (nic is None or host_networks_module.has_update(nics_service.service(nic.id)))
        ):
            host_networks_module.action(
                entity=host,
                action='setup_networks',
                post_action=host_networks_module._action_save_configuration,
                check_connectivity=module.params['check'],
                modified_bonds=[
                    otypes.HostNic(
                        name=bond.get('name'),
                        bonding=otypes.Bonding(
                            options=[
                                otypes.Option(
                                    name="mode",
                                    value=str(bond.get('mode')),
                                )
                            ],
                            slaves=[
                                otypes.HostNic(name=i) for i in bond.get('interfaces', [])
                            ],
                        ),
                    ),
                ] if bond else None,
                modified_labels=[
                    otypes.NetworkLabel(
                        name=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(
                        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,
                                ),
                            ),
                        ],
                    ) for network in networks
                ] if networks else None,
            )
        elif state == 'absent' and nic:
            attachments_service = nics_service.nic_service(nic.id).network_attachments_service()
            attachments = attachments_service.list()
            if networks:
                network_names = [network['name'] for network in networks]
                attachments = [
                    attachment for attachment in attachments
                    if get_link_name(connection, attachment.network) in network_names
                ]
            if labels or bond or attachments:
                host_networks_module.action(
                    entity=host,
                    action='setup_networks',
                    post_action=host_networks_module._action_save_configuration,
                    check_connectivity=module.params['check'],
                    removed_bonds=[
                        otypes.HostNic(
                            name=bond.get('name'),
                        ),
                    ] if bond else None,
                    removed_labels=[
                        otypes.NetworkLabel(
                            name=str(name),
                        ) for name in labels
                    ] if labels else None,
                    removed_network_attachments=list(attachments),
                )

        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)
Пример #49
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'exported', 'imported'],
            default='present',
        ),
        name=dict(default=None, required=True),
        vm=dict(default=None),
        description=dict(default=None),
        cluster=dict(default=None),
        cpu_profile=dict(default=None),
        disks=dict(default=[], type='list'),
        clone_permissions=dict(type='bool'),
        export_domain=dict(default=None),
        storage_domain=dict(default=None),
        exclusive=dict(type='bool'),
        image_provider=dict(default=None),
        image_disk=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

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

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

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

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

                    glance_service = connection.system_service().openstack_image_providers_service()
                    image_provider = search_by_name(glance_service, module.params['image_provider'])
                    images_service = glance_service.service(image_provider.id).images_service()
                else:
                    images_service = templates_module._get_export_domain_service().templates_service()
                template_name = module.params['image_disk'] or module.params['name']
                entity = search_by_name(images_service, template_name)
                if entity is None:
                    raise Exception("Image/template '%s' was not found." % template_name)

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

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

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

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

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

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

                    glance_service = connection.system_service().openstack_image_providers_service()
                    image_provider = search_by_name(glance_service, module.params['image_provider'])
                    images_service = glance_service.service(image_provider.id).images_service()
                else:
                    images_service = templates_module._get_export_domain_service().templates_service()
                template_name = module.params['image_disk'] or module.params['name']
                entity = search_by_name(images_service, template_name)
                if entity is None:
                    raise Exception("Image/template '%s' was not found." % template_name)

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

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

                if module.params['wait']:
                    template = templates_module.wait_for_import()
                else:
                    # Fetch template to initialize return.
                    template = template_service.get()
                ret = templates_module.create(result_state=otypes.TemplateStatus.OK)
            ret = {
                'changed': changed,
                'id': template.id,
                'template': get_dict_of_struct(template)
            }
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)