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

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

        module.exit_json(
            changed=False,
            ansible_facts=dict(ovirt_permissions=permissions),
        )
    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'))
        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)
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        id=dict(default=None),
        address=dict(default=None),
        path=dict(default=None),
        nfs_version=dict(default=None),
        nfs_timeout=dict(default=None, type='int'),
        nfs_retrans=dict(default=None, type='int'),
        mount_options=dict(default=None),
        password=dict(default=None),
        username=dict(default=None),
        port=dict(default=None, type='int'),
        target=dict(default=None),
        type=dict(default=None),
        vfs_type=dict(default=None),
        force=dict(type='bool', default=False),
        storage=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 4
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, required=True),
        template=dict(default=None),
        cluster=dict(default=None),
        description=dict(default=None),
        comment=dict(default=None),
        vm_per_user=dict(default=None, type='int'),
        prestarted=dict(default=None, type='int'),
        vm_count=dict(default=None, type='int'),
        type=dict(default=None, choices=['automatic', 'manual']),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)
    check_params(module)

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

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

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None),
        description=dict(default=None),
        type=dict(
            default=None,
            required=True,
            choices=[
                'os_image', 'os_network', 'os_volume',  'foreman',
            ],
            aliases=['provider'],
        ),
        url=dict(default=None),
        username=dict(default=None),
        password=dict(default=None, no_log=True),
        tenant_name=dict(default=None, aliases=['tenant']),
        authentication_url=dict(default=None, aliases=['auth_url']),
        data_center=dict(default=None, aliases=['data_center']),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)
    check_params(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        provider_type, external_providers_service = _external_provider_service(
            provider_type=module.params.pop('type'),
            system_service=connection.system_service(),
        )
        external_providers_module = ExternalProviderModule(
            connection=connection,
            module=module,
            service=external_providers_service,
        )
        external_providers_module.provider_type(provider_type)

        state = module.params.pop('state')
        if state == 'absent':
            ret = external_providers_module.remove()
        elif state == 'present':
            ret = external_providers_module.create()

        module.exit_json(**ret)
    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(
        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_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)
Esempio n. 8
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, required=True),
        description=dict(default=None),
        local=dict(type='bool'),
        compatibility_version=dict(default=None),
        quota_mode=dict(choices=['disabled', 'audit', 'enabled']),
        comment=dict(default=None),
        mac_pool=dict(default=None),
        force=dict(default=None, type='bool'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

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

    check_sdk(module)
    check_params(module)

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['restore', 'present', 'absent'],
            default='present',
        ),
        vm_name=dict(required=True),
        snapshot_id=dict(default=None),
        description=dict(default=None),
        use_memory=dict(
            default=None,
            type='bool',
            aliases=['restore_memory', 'save_memory'],
        ),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           required_if=[
                               ('state', 'absent', ['snapshot_id']),
                               ('state', 'restore', ['snapshot_id']),
                           ])
    check_sdk(module)

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

    vm_service = vms_service.vm_service(vm.id)
    snapshots_service = vms_service.vm_service(vm.id).snapshots_service()
    try:
        state = module.params['state']
        if state == 'present':
            ret = create_snapshot(module, vm_service, snapshots_service)
        elif state == 'restore':
            ret = restore_snapshot(module, vm_service, snapshots_service)
        elif state == 'absent':
            ret = remove_snapshot(module, vm_service, snapshots_service)
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Esempio n. 10
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(required=True),
        authz_name=dict(required=True, aliases=['domain']),
        namespace=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)
    check_params(module)

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

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

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

    check_sdk(module)
    check_params(module)

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 12
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'attached', 'detached'],
            default='present',
        ),
        id=dict(default=None),
        name=dict(required=True),
        description=dict(default=None),
        parent=dict(default=None),
        vms=dict(default=None, type='list'),
        hosts=dict(default=None, type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

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

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        tags_service = connection.system_service().tags_service()
        tags_module = TagsModule(
            connection=connection,
            module=module,
            service=tags_service,
        )

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        datacenter=dict(default=None, required=True),
        name=dict(default=None, required=True),
        description=dict(default=None),
        comment=dict(default=None),
        vlan_tag=dict(default=None, type='int'),
        vm_network=dict(default=None, type='bool'),
        mtu=dict(default=None, type='int'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)
    check_params(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        networks_service = connection.system_service().networks_service()
        networks_module = NetworksModule(
            connection=connection,
            module=module,
            service=networks_service,
        )
        state = module.params['state']
        network = networks_module.search_entity(search_params={
            'name':
            module.params['name'],
            'datacenter':
            module.params['datacenter'],
        }, )
        if state == 'present':
            ret = networks_module.create(entity=network)
        elif state == 'absent':
            ret = networks_module.remove(entity=network)

        module.exit_json(**ret)
    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(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        datacenter=dict(default=None, required=True),
        name=dict(default=None, required=True),
        description=dict(default=None),
        comment=dict(default=None),
        vlan_tag=dict(default=None, type='int'),
        vm_network=dict(default=None, type='bool'),
        mtu=dict(default=None, type='int'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)
    check_params(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        networks_service = connection.system_service().networks_service()
        networks_module = NetworksModule(
            connection=connection,
            module=module,
            service=networks_service,
        )
        state = module.params['state']
        network = networks_module.search_entity(
            search_params={
                'name': module.params['name'],
                'datacenter': module.params['datacenter'],
            },
        )
        if state == 'present':
            ret = networks_module.create(entity=network)
        elif state == 'absent':
            ret = networks_module.remove(entity=network)

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Esempio n. 15
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(required=True),
        authz_name=dict(required=True, aliases=['domain']),
        namespace=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)
    check_params(module)

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Esempio n. 16
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(required=True),
        authz_name=dict(required=True, aliases=['domain']),
        namespace=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

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

    check_sdk(module)
    check_params(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        groups_service = connection.system_service().groups_service()
        groups_module = GroupsModule(
            connection=connection,
            module=module,
            service=groups_service,
        )
        group = _group(connection, module)
        state = module.params['state']
        if state == 'present':
            ret = groups_module.create(entity=group)
        elif state == 'absent':
            ret = groups_module.remove(entity=group)

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 17
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        cluster=dict(default=None),
        name=dict(default=None, required=True),
        vms=dict(default=None, type='list'),
        hosts=dict(default=None, type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ('state', 'present', ['cluster']),
        ],
    )

    check_sdk(module)

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

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

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

        vnic_services = connection.system_service().vnic_profiles_service()

        entitynics_module = EntityVnicPorfileModule(
            connection=connection,
            module=module,
            service=vnic_services,
        )
        state = module.params['state']
        if state == 'present':
            ret = entitynics_module.create()
        elif state == 'absent':
            ret = entitynics_module.remove()

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_full_argument_spec(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)
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)
Esempio n. 21
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(required=True),
        authz_name=dict(required=True, aliases=['domain']),
        namespace=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

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

    check_sdk(module)
    check_params(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        groups_service = connection.system_service().groups_service()
        groups_module = GroupsModule(
            connection=connection,
            module=module,
            service=groups_service,
        )
        group = _group(connection, module)
        state = module.params['state']
        if state == 'present':
            ret = groups_module.create(entity=group)
        elif state == 'absent':
            ret = groups_module.remove(entity=group)

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 22
0
def main():
    argument_spec = ovirt_full_argument_spec(
        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(
                    struct=c,
                    connection=connection,
                    fetch_nested=module.params.get('fetch_nested'),
                    attributes=module.params.get('nested_attributes'),
                ) for c in quotas
            ], ),
        )
    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(
        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)
Esempio n. 24
0
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(
                    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=False)
Esempio n. 25
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(required=True),
        id=dict(default=None),
        allow_duplicates=dict(default=None, type='bool'),
        description=dict(default=None),
        ranges=dict(default=None, type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        mac_pools_service = connection.system_service().mac_pools_service()
        mac_pools_module = MACPoolModule(
            connection=connection,
            module=module,
            service=mac_pools_service,
        )

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 26
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        cluster=dict(default=None),
        name=dict(default=None, required=True),
        vms=dict(default=None, type='list'),
        hosts=dict(default=None, type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ('state', 'present', ['cluster']),
        ],
    )
    check_sdk(module)

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Esempio n. 27
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'attached', 'detached'],
            default='present',
        ),
        name=dict(default=None, required=True),
        description=dict(default=None),
        parent=dict(default=None),
        vms=dict(default=None, type='list'),
        hosts=dict(default=None, type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        tags_service = connection.system_service().tags_service()
        tags_module = TagsModule(
            connection=connection,
            module=module,
            service=tags_service,
        )

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 28
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        id=dict(default=None),
        name=dict(default=None),
        description=dict(default=None),
        administrative=dict(type='bool', default=False),
        permits=dict(type='list', default=[]),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[['id', 'name']],
    )

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        roles_service = connection.system_service().roles_service()
        roles_module = RoleModule(
            connection=connection,
            module=module,
            service=roles_service,
        )
        state = module.params['state']
        if state == 'present':
            ret = roles_module.create()
        elif state == 'absent':
            ret = roles_module.remove()
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 29
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, required=True),
        description=dict(default=None),
        parent=dict(default=None),
        vms=dict(default=None, type='list'),
        hosts=dict(default=None, type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        tags_service = connection.system_service().tags_service()
        tags_module = TagsModule(
            connection=connection,
            module=module,
            service=tags_service,
        )

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=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)
Esempio n. 31
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, required=True),
        allow_duplicates=dict(default=None, type='bool'),
        description=dict(default=None),
        ranges=dict(default=None, type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        mac_pools_service = connection.system_service().mac_pools_service()
        mac_pools_module = MACPoolModule(
            connection=connection,
            module=module,
            service=mac_pools_service,
        )

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
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)
Esempio n. 33
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)
Esempio n. 34
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        datacenter=dict(default=None, required=True),
        name=dict(default=None, required=True),
        description=dict(default=None),
        comment=dict(default=None),
        vlan_tag=dict(default=None, type='int'),
        vm_network=dict(default=None, type='bool'),
        mtu=dict(default=None, type='int'),
        clusters=dict(default=None, type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)
    check_params(module)

    try:
        connection = create_connection(module.params.pop('auth'))
        clusters_service = connection.system_service().clusters_service()
        networks_service = connection.system_service().networks_service()
        networks_module = NetworksModule(
            connection=connection,
            module=module,
            service=networks_service,
        )
        state = module.params['state']
        network = networks_module.search_entity(
            search_params={
                'name': module.params['name'],
                'datacenter': module.params['datacenter'],
            },
        )
        if state == 'present':
            ret = networks_module.create(entity=network)

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Esempio n. 35
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)
Esempio n. 36
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, required=True),
        ballooning=dict(default=None, type='bool', aliases=['balloon']),
        gluster=dict(default=None, type='bool'),
        virt=dict(default=None, type='bool'),
        threads_as_cores=dict(default=None, type='bool'),
        ksm_numa=dict(default=None, type='bool'),
        ksm=dict(default=None, type='bool'),
        ha_reservation=dict(default=None, type='bool'),
        trusted_service=dict(default=None, type='bool'),
        vm_reason=dict(default=None, type='bool'),
        host_reason=dict(default=None, type='bool'),
        memory_policy=dict(default=None, choices=['disabled', 'server', 'desktop']),
        rng_sources=dict(default=None, type='list'),
        spice_proxy=dict(default=None),
        fence_enabled=dict(default=None, type='bool'),
        fence_skip_if_sd_active=dict(default=None, type='bool'),
        fence_skip_if_connectivity_broken=dict(default=None, type='bool'),
        fence_connectivity_threshold=dict(default=None, type='int'),
        resilience_policy=dict(default=None, choices=['migrate_highly_available', 'migrate', 'do_not_migrate']),
        migration_bandwidth=dict(default=None, choices=['auto', 'hypervisor_default', 'custom']),
        migration_bandwidth_limit=dict(default=None, type='int'),
        migration_auto_converge=dict(default=None, choices=['true', 'false', 'inherit']),
        migration_compressed=dict(default=None, choices=['true', 'false', 'inherit']),
        migration_policy=dict(
            default=None,
            choices=['legacy', 'minimal_downtime', 'suspend_workload', 'post_copy']
        ),
        serial_policy=dict(default=None, choices=['vm', 'host', 'custom']),
        serial_policy_value=dict(default=None),
        scheduling_policy=dict(default=None),
        data_center=dict(default=None),
        description=dict(default=None),
        comment=dict(default=None),
        network=dict(default=None),
        cpu_arch=dict(default=None, choices=['ppc64', 'undefined', 'x86_64']),
        cpu_type=dict(default=None),
        switch_type=dict(default=None, choices=['legacy', 'ovs']),
        compatibility_version=dict(default=None),
        mac_pool=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

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

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        clusters_service = connection.system_service().clusters_service()
        clusters_module = ClustersModule(
            connection=connection,
            module=module,
            service=clusters_service,
        )

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 37
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'maintenance', 'unattached', 'imported',
                'update_ovf_store'
            ],
            default='present',
        ),
        id=dict(default=None),
        name=dict(default=None),
        description=dict(default=None),
        comment=dict(default=None),
        data_center=dict(default=None),
        domain_function=dict(choices=['data', 'iso', 'export'],
                             default='data',
                             aliases=['type']),
        host=dict(default=None),
        localfs=dict(default=None, type='dict'),
        nfs=dict(default=None, type='dict'),
        iscsi=dict(default=None, type='dict'),
        posixfs=dict(default=None, type='dict'),
        glusterfs=dict(default=None, type='dict'),
        fcp=dict(default=None, type='dict'),
        wipe_after_delete=dict(type='bool', default=None),
        backup=dict(type='bool', default=None),
        critical_space_action_blocker=dict(type='int', default=None),
        warning_low_space=dict(type='int', default=None),
        destroy=dict(type='bool', default=None),
        format=dict(type='bool', default=None),
        discard_after_delete=dict(type='bool', default=None))
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

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

    check_sdk(module)

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

        state = module.params['state']
        control_state(storage_domains_module)
        if state == 'absent':
            # Pick random available host when host parameter is missing
            host_param = module.params['host']
            if not host_param:
                host = search_by_attributes(
                    connection.system_service().hosts_service(), status='up')
                if host is None:
                    raise Exception(
                        "Not possible to remove storage domain '%s' "
                        "because no host found with status `up`." %
                        module.params['name'])
                host_param = host.name
            ret = storage_domains_module.remove(
                destroy=module.params['destroy'],
                format=module.params['format'],
                host=host_param,
            )
        elif state == 'present' or state == 'imported':
            sd_id = storage_domains_module.create()['id']
            storage_domains_module.post_create_check(sd_id)
            ret = storage_domains_module.action(
                action='activate',
                action_condition=lambda s: s.status == sdstate.MAINTENANCE,
                wait_condition=lambda s: s.status == sdstate.ACTIVE,
                fail_condition=failed_state,
                search_params={'id': sd_id} if state == 'imported' else None)
        elif state == 'maintenance':
            sd_id = storage_domains_module.create()['id']
            storage_domains_module.post_create_check(sd_id)
            ret = storage_domains_module.action(
                action='deactivate',
                action_condition=lambda s: s.status == sdstate.ACTIVE,
                wait_condition=lambda s: s.status == sdstate.MAINTENANCE,
                fail_condition=failed_state,
            )
        elif state == 'unattached':
            ret = storage_domains_module.create()
            storage_domains_module.pre_remove(
                storage_domain=storage_domains_service.service(
                    ret['id']).get())
            ret['changed'] = storage_domains_module.changed
        elif state == 'update_ovf_store':
            ret = storage_domains_module.action(action='update_ovf_store')
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 38
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, required=True),
        ballooning=dict(default=None, type='bool', aliases=['balloon']),
        gluster=dict(default=None, type='bool'),
        virt=dict(default=None, type='bool'),
        threads_as_cores=dict(default=None, type='bool'),
        ksm_numa=dict(default=None, type='bool'),
        ksm=dict(default=None, type='bool'),
        ha_reservation=dict(default=None, type='bool'),
        trusted_service=dict(default=None, type='bool'),
        vm_reason=dict(default=None, type='bool'),
        host_reason=dict(default=None, type='bool'),
        memory_policy=dict(default=None,
                           choices=['disabled', 'server', 'desktop']),
        rng_sources=dict(default=None, type='list'),
        spice_proxy=dict(default=None),
        fence_enabled=dict(default=None, type='bool'),
        fence_skip_if_sd_active=dict(default=None, type='bool'),
        fence_skip_if_connectivity_broken=dict(default=None, type='bool'),
        fence_connectivity_threshold=dict(default=None, type='int'),
        resilience_policy=dict(
            default=None,
            choices=['migrate_highly_available', 'migrate', 'do_not_migrate']),
        migration_bandwidth=dict(
            default=None, choices=['auto', 'hypervisor_default', 'custom']),
        migration_bandwidth_limit=dict(default=None, type='int'),
        migration_auto_converge=dict(default=None,
                                     choices=['true', 'false', 'inherit']),
        migration_compressed=dict(default=None,
                                  choices=['true', 'false', 'inherit']),
        migration_policy=dict(
            default=None,
            choices=['legacy', 'minimal_downtime', 'suspend_workload']),
        serial_policy=dict(default=None, choices=['vm', 'host', 'custom']),
        serial_policy_value=dict(default=None),
        scheduling_policy=dict(default=None),
        data_center=dict(default=None),
        description=dict(default=None),
        comment=dict(default=None),
        network=dict(default=None),
        cpu_arch=dict(default=None, choices=['ppc64', 'undefined', 'x86_64']),
        cpu_type=dict(default=None),
        switch_type=dict(default=None, choices=['legacy', 'ovs']),
        compatibility_version=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        clusters_service = connection.system_service().clusters_service()
        clusters_module = ClustersModule(
            connection=connection,
            module=module,
            service=clusters_service,
        )

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 39
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(choices=['present', 'absent', 'plugged', 'unplugged'],
                   default='present'),
        vm=dict(required=True),
        name=dict(required=True),
        interface=dict(default=None),
        profile=dict(default=None),
        network=dict(default=None),
        mac_address=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

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

        # Locate the VM, where we will manage NICs:
        vm_name = module.params.get('vm')
        vm = search_by_name(vms_service, vm_name)
        if vm is None:
            raise Exception("VM '%s' was not found." % vm_name)

        # Locate the service that manages the virtual machines NICs:
        vm_service = vms_service.vm_service(vm.id)
        nics_service = vm_service.nics_service()
        vmnics_module = VmNicsModule(
            connection=connection,
            module=module,
            service=nics_service,
        )

        # Find vNIC id of the network interface (if any):
        profile = module.params.get('profile')
        if profile and module.params['network']:
            cluster_name = get_link_name(connection, vm.cluster)
            dcs_service = connection.system_service().data_centers_service()
            dc = dcs_service.list(search='Clusters.name=%s' % cluster_name)[0]
            networks_service = dcs_service.service(dc.id).networks_service()
            network = search_by_name(networks_service,
                                     module.params['network'])
            for vnic in connection.system_service().vnic_profiles_service(
            ).list():
                if vnic.name == profile and vnic.network.id == network.id:
                    vmnics_module.vnic_id = vnic.id

        # Handle appropriate action:
        state = module.params['state']
        if state == 'present':
            ret = vmnics_module.create()
        elif state == 'absent':
            ret = vmnics_module.remove()
        elif state == 'plugged':
            vmnics_module.create()
            ret = vmnics_module.action(
                action='activate',
                action_condition=lambda nic: not nic.plugged,
                wait_condition=lambda nic: nic.plugged,
            )
        elif state == 'unplugged':
            vmnics_module.create()
            ret = vmnics_module.action(
                action='deactivate',
                action_condition=lambda nic: nic.plugged,
                wait_condition=lambda nic: not nic.plugged,
            )

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 40
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'maintenance', 'unattached'],
            default='present',
        ),
        name=dict(required=True),
        description=dict(default=None),
        comment=dict(default=None),
        data_center=dict(required=True),
        domain_function=dict(choices=['data', 'iso', 'export'], default='data', aliases=['type']),
        host=dict(default=None),
        nfs=dict(default=None, type='dict'),
        iscsi=dict(default=None, type='dict'),
        posixfs=dict(default=None, type='dict'),
        glusterfs=dict(default=None, type='dict'),
        fcp=dict(default=None, type='dict'),
        destroy=dict(type='bool', default=False),
        format=dict(type='bool', default=False),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

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

        state = module.params['state']
        control_state(storage_domains_module)
        if state == 'absent':
            ret = storage_domains_module.remove(
                destroy=module.params['destroy'],
                format=module.params['format'],
                host=module.params['host'],
            )
        elif state == 'present':
            sd_id = storage_domains_module.create()['id']
            storage_domains_module.post_create_check(sd_id)
            ret = storage_domains_module.action(
                action='activate',
                action_condition=lambda s: s.status == sdstate.MAINTENANCE,
                wait_condition=lambda s: s.status == sdstate.ACTIVE,
                fail_condition=failed_state,
            )
        elif state == 'maintenance':
            sd_id = storage_domains_module.create()['id']
            storage_domains_module.post_create_check(sd_id)
            ret = storage_domains_module.action(
                action='deactivate',
                action_condition=lambda s: s.status == sdstate.ACTIVE,
                wait_condition=lambda s: s.status == sdstate.MAINTENANCE,
                fail_condition=failed_state,
            )
        elif state == 'unattached':
            ret = storage_domains_module.create()
            storage_domains_module.pre_remove(
                storage_domain=storage_domains_service.service(ret['id']).get()
            )
            ret['changed'] = storage_domains_module.changed

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Esempio n. 41
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'attached', 'detached', 'exported', 'imported'],
            default='present'
        ),
        id=dict(default=None),
        name=dict(default=None, aliases=['alias']),
        description=dict(default=None),
        vm_name=dict(default=None),
        vm_id=dict(default=None),
        size=dict(default=None),
        interface=dict(default=None,),
        storage_domain=dict(default=None),
        storage_domains=dict(default=None, type='list'),
        profile=dict(default=None),
        quota_id=dict(default=None),
        format=dict(default='cow', choices=['raw', 'cow']),
        content_type=dict(
            default='data',
            choices=['data', 'iso', 'hosted_engine', 'hosted_engine_sanlock', 'hosted_engine_metadata', 'hosted_engine_configuration']
        ),
        sparse=dict(default=None, type='bool'),
        bootable=dict(default=None, type='bool'),
        shareable=dict(default=None, type='bool'),
        logical_unit=dict(default=None, type='dict'),
        download_image_path=dict(default=None),
        upload_image_path=dict(default=None, aliases=['image_path']),
        force=dict(default=False, type='bool'),
        sparsify=dict(default=None, type='bool'),
        openstack_volume_type=dict(default=None),
        image_provider=dict(default=None),
        host=dict(default=None),
        wipe_after_delete=dict(type='bool', default=None),
        activate=dict(default=None, type='bool'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    lun = module.params.get('logical_unit')
    host = module.params['host']
    # Fail when host is specified with the LUN id. Lun id is needed to identify
    # an existing disk if already available inthe environment.
    if (host and lun is None) or (host and lun.get("id") is None):
        module.fail_json(
            msg="Can not use parameter host ({0!s}) without "
            "specifying the logical_unit id".format(host)
        )

    check_sdk(module)
    check_params(module)

    try:
        disk = None
        state = module.params['state']
        auth = module.params.get('auth')
        connection = create_connection(auth)
        disks_service = connection.system_service().disks_service()
        disks_module = DisksModule(
            connection=connection,
            module=module,
            service=disks_service,
        )

        force_create = False
        vm_service = get_vm_service(connection, module)
        if lun:
            disk = _search_by_lun(disks_service, lun.get('id'))
        else:
            disk = disks_module.search_entity(search_params=searchable_attributes(module))
            if vm_service and disk:
                # If the VM don't exist in VMs disks, but still it's found it means it was found
                # for template with same name as VM, so we should force create the VM disk.
                force_create = disk.id not in [a.disk.id for a in vm_service.disk_attachments_service().list() if a.disk]

        ret = None
        # First take care of creating the VM, if needed:
        if state in ('present', 'detached', 'attached'):
            # Always activate disk when its being created
            if vm_service is not None and disk is None:
                module.params['activate'] = True
            ret = disks_module.create(
                entity=disk if not force_create else None,
                result_state=otypes.DiskStatus.OK if lun is None else None,
                fail_condition=lambda d: d.status == otypes.DiskStatus.ILLEGAL if lun is None else False,
                force_create=force_create,
            )
            is_new_disk = ret['changed']
            ret['changed'] = ret['changed'] or disks_module.update_storage_domains(ret['id'])
            # We need to pass ID to the module, so in case we want detach/attach disk
            # we have this ID specified to attach/detach method:
            module.params['id'] = ret['id']

            # Upload disk image in case it's new disk or force parameter is passed:
            if module.params['upload_image_path'] and (is_new_disk or module.params['force']):
                uploaded = upload_disk_image(connection, module)
                ret['changed'] = ret['changed'] or uploaded
            # Download disk image in case it's file don't exist or force parameter is passed:
            if (
                module.params['download_image_path'] and (not os.path.isfile(module.params['download_image_path']) or module.params['force'])
            ):
                downloaded = download_disk_image(connection, module)
                ret['changed'] = ret['changed'] or downloaded

            # Disk sparsify, only if disk is of image type:
            if not module.check_mode:
                disk = disks_service.disk_service(module.params['id']).get()
                if disk.storage_type == otypes.DiskStorageType.IMAGE:
                    ret = disks_module.action(
                        action='sparsify',
                        action_condition=lambda d: module.params['sparsify'],
                        wait_condition=lambda d: d.status == otypes.DiskStatus.OK,
                    )

        # Export disk as image to glance domain
        elif state == 'exported':
            disk = disks_module.search_entity()
            if disk is None:
                module.fail_json(
                    msg="Can not export given disk '%s', it doesn't exist" %
                        module.params.get('name') or module.params.get('id')
                )
            if disk.storage_type == otypes.DiskStorageType.IMAGE:
                ret = disks_module.action(
                    action='export',
                    action_condition=lambda d: module.params['image_provider'],
                    wait_condition=lambda d: d.status == otypes.DiskStatus.OK,
                    storage_domain=otypes.StorageDomain(name=module.params['image_provider']),
                )
        elif state == 'imported':
            glance_service = connection.system_service().openstack_image_providers_service()
            image_provider = search_by_name(glance_service, module.params['image_provider'])
            images_service = glance_service.service(image_provider.id).images_service()
            entity_id = get_id_by_name(images_service, module.params['name'])
            images_service.service(entity_id).import_(
                storage_domain=otypes.StorageDomain(
                    name=module.params['storage_domain']
                ) if module.params['storage_domain'] else None,
                disk=otypes.Disk(
                    name=module.params['name']
                ),
                import_as_template=False,
            )
            # Wait for disk to appear in system:
            disk = disks_module.wait_for_import(
                condition=lambda t: t.status == otypes.DiskStatus.OK
            )
            ret = disks_module.create(result_state=otypes.DiskStatus.OK)
        elif state == 'absent':
            ret = disks_module.remove()

        # If VM was passed attach/detach disks to/from the VM:
        if vm_service:
            disk_attachments_service = vm_service.disk_attachments_service()
            disk_attachments_module = DiskAttachmentsModule(
                connection=connection,
                module=module,
                service=disk_attachments_service,
                changed=ret['changed'] if ret else False,
            )

            if state == 'present' or state == 'attached':
                ret = disk_attachments_module.create()
                if lun is None:
                    wait(
                        service=disk_attachments_service.service(ret['id']),
                        condition=lambda d: follow_link(connection, d.disk).status == otypes.DiskStatus.OK,
                        wait=module.params['wait'],
                        timeout=module.params['timeout'],
                    )
            elif state == 'detached':
                ret = disk_attachments_module.remove()

        # When the host parameter is specified and the disk is not being
        # removed, refresh the information about the LUN.
        if state != 'absent' and host:
            hosts_service = connection.system_service().hosts_service()
            host_id = get_id_by_name(hosts_service, host)
            disks_service.disk_service(disk.id).refresh_lun(otypes.Host(id=host_id))

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 42
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'plugged', 'unplugged'],
            default='present'
        ),
        vm=dict(required=True),
        name=dict(required=True),
        interface=dict(default=None),
        profile=dict(default=None),
        network=dict(default=None),
        mac_address=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

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

        # Locate the VM, where we will manage NICs:
        vm_name = module.params.get('vm')
        vm = search_by_name(vms_service, vm_name)
        if vm is None:
            raise Exception("VM '%s' was not found." % vm_name)

        # Locate the service that manages the virtual machines NICs:
        vm_service = vms_service.vm_service(vm.id)
        nics_service = vm_service.nics_service()
        vmnics_module = VmNicsModule(
            connection=connection,
            module=module,
            service=nics_service,
        )

        # Find vNIC id of the network interface (if any):
        profile = module.params.get('profile')
        if profile and module.params['network']:
            cluster_name = get_link_name(connection, vm.cluster)
            dcs_service = connection.system_service().data_centers_service()
            dc = dcs_service.list(search='Clusters.name=%s' % cluster_name)[0]
            networks_service = dcs_service.service(dc.id).networks_service()
            network = search_by_name(networks_service, module.params['network'])
            for vnic in connection.system_service().vnic_profiles_service().list():
                if vnic.name == profile and vnic.network.id == network.id:
                    vmnics_module.vnic_id = vnic.id

        # Handle appropriate action:
        state = module.params['state']
        if state == 'present':
            ret = vmnics_module.create()
        elif state == 'absent':
            ret = vmnics_module.remove()
        elif state == 'plugged':
            vmnics_module.create()
            ret = vmnics_module.action(
                action='activate',
                action_condition=lambda nic: not nic.plugged,
                wait_condition=lambda nic: nic.plugged,
            )
        elif state == 'unplugged':
            vmnics_module.create()
            ret = vmnics_module.action(
                action='deactivate',
                action_condition=lambda nic: nic.plugged,
                wait_condition=lambda nic: not nic.plugged,
            )

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Esempio n. 43
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(type='str', default='present',
                   choices=['absent', 'present']),
        name=dict(type='str'),
        id=dict(type='str'),
        memory=dict(type='str'),
        memory_guaranteed=dict(type='str'),
        memory_max=dict(type='str'),
        cpu_sockets=dict(type='int'),
        cpu_cores=dict(type='int'),
        cpu_threads=dict(type='int'),
        operating_system=dict(type='str'),
        boot_devices=dict(type='list', choices=['cdrom', 'hd', 'network']),
        serial_console=dict(type='bool'),
        usb_support=dict(type='bool'),
        high_availability=dict(type='bool'),
        high_availability_priority=dict(type='int'),
        watchdog=dict(type='dict'),
        host=dict(type='str'),
        graphical_console=dict(type='dict'),
        description=dict(type='str'),
        cpu_mode=dict(type='str'),
        rng_device=dict(type='str'),
        rng_bytes=dict(type='int', default=None),
        rng_period=dict(type='int', default=None),
        placement_policy=dict(type='str'),
        cpu_pinning=dict(type='list'),
        soundcard_enabled=dict(type='bool', default=None),
        virtio_scsi=dict(type='bool', default=None),
        smartcard_enabled=dict(type='bool', default=None),
        io_threads=dict(type='int', default=None),
        nics=dict(type='list', default=[]),
        ballooning_enabled=dict(type='bool', default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[['id', 'name']],
    )

    check_sdk(module)
    check_params(module)

    try:
        state = module.params['state']
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        its_service = connection.system_service().instance_types_service()
        its_module = InstanceTypeModule(
            connection=connection,
            module=module,
            service=its_service,
        )
        it = its_module.search_entity()

        if state == 'present':
            ret = its_module.create(
                entity=it
            )
            its_module.post_present(ret['id'])
            ret['changed'] = its_module.changed
        elif state == 'absent':
            ret = its_module.remove()
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 44
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'attached', 'detached', 'exported'],
            default='present'
        ),
        id=dict(default=None),
        name=dict(default=None, aliases=['alias']),
        description=dict(default=None),
        vm_name=dict(default=None),
        vm_id=dict(default=None),
        size=dict(default=None),
        interface=dict(default=None,),
        storage_domain=dict(default=None),
        storage_domains=dict(default=None, type='list'),
        profile=dict(default=None),
        quota_id=dict(default=None),
        format=dict(default='cow', choices=['raw', 'cow']),
        sparse=dict(default=None, type='bool'),
        bootable=dict(default=None, type='bool'),
        shareable=dict(default=None, type='bool'),
        logical_unit=dict(default=None, type='dict'),
        download_image_path=dict(default=None),
        upload_image_path=dict(default=None, aliases=['image_path']),
        force=dict(default=False, type='bool'),
        sparsify=dict(default=None, type='bool'),
        openstack_volume_type=dict(default=None),
        image_provider=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

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

    check_sdk(module)
    check_params(module)

    try:
        disk = None
        state = module.params['state']
        auth = module.params.get('auth')
        connection = create_connection(auth)
        disks_service = connection.system_service().disks_service()
        disks_module = DisksModule(
            connection=connection,
            module=module,
            service=disks_service,
        )

        lun = module.params.get('logical_unit')
        if lun:
            disk = _search_by_lun(disks_service, lun.get('id'))

        ret = None
        # First take care of creating the VM, if needed:
        if state in ('present', 'detached', 'attached'):
            ret = disks_module.create(
                entity=disk,
                result_state=otypes.DiskStatus.OK if lun is None else None,
                fail_condition=lambda d: d.status == otypes.DiskStatus.ILLEGAL if lun is None else False,
            )
            is_new_disk = ret['changed']
            ret['changed'] = ret['changed'] or disks_module.update_storage_domains(ret['id'])
            # We need to pass ID to the module, so in case we want detach/attach disk
            # we have this ID specified to attach/detach method:
            module.params['id'] = ret['id'] if disk is None else disk.id

            # Upload disk image in case it's new disk or force parameter is passed:
            if module.params['upload_image_path'] and (is_new_disk or module.params['force']):
                uploaded = upload_disk_image(connection, module)
                ret['changed'] = ret['changed'] or uploaded
            # Download disk image in case it's file don't exist or force parameter is passed:
            if (
                module.params['download_image_path'] and (not os.path.isfile(module.params['download_image_path']) or module.params['force'])
            ):
                downloaded = download_disk_image(connection, module)
                ret['changed'] = ret['changed'] or downloaded

            # Disk sparsify, only if disk is of image type:
            disk = disks_service.disk_service(module.params['id']).get()
            if disk.storage_type == otypes.DiskStorageType.IMAGE:
                ret = disks_module.action(
                    action='sparsify',
                    action_condition=lambda d: module.params['sparsify'],
                    wait_condition=lambda d: d.status == otypes.DiskStatus.OK,
                )

        # Export disk as image to glance domain
        elif state == 'exported':
            disk = disks_module.search_entity()
            if disk is None:
                module.fail_json(
                    msg="Can not export given disk '%s', it doesn't exist" %
                        module.params.get('name') or module.params.get('id')
                )
            if disk.storage_type == otypes.DiskStorageType.IMAGE:
                ret = disks_module.action(
                    action='export',
                    action_condition=lambda d: module.params['image_provider'],
                    wait_condition=lambda d: d.status == otypes.DiskStatus.OK,
                    storage_domain=otypes.StorageDomain(name=module.params['image_provider']),
                )
        elif state == 'absent':
            ret = disks_module.remove()

        # If VM was passed attach/detach disks to/from the VM:
        if module.params.get('vm_id') is not None or module.params.get('vm_name') is not None and state != 'absent':
            vms_service = connection.system_service().vms_service()

            # If `vm_id` isn't specified, find VM by name:
            vm_id = module.params['vm_id']
            if vm_id is None:
                vm_id = getattr(search_by_name(vms_service, module.params['vm_name']), 'id', None)

            if vm_id is None:
                module.fail_json(
                    msg="VM don't exists, please create it first."
                )

            disk_attachments_service = vms_service.vm_service(vm_id).disk_attachments_service()
            disk_attachments_module = DiskAttachmentsModule(
                connection=connection,
                module=module,
                service=disk_attachments_service,
                changed=ret['changed'] if ret else False,
            )

            if state == 'present' or state == 'attached':
                ret = disk_attachments_module.create()
                if lun is None:
                    wait(
                        service=disk_attachments_service.service(ret['id']),
                        condition=lambda d: follow_link(connection, d.disk).status == otypes.DiskStatus.OK,
                        wait=module.params['wait'],
                        timeout=module.params['timeout'],
                    )
            elif state == 'detached':
                ret = disk_attachments_module.remove()

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 45
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        role=dict(default='UserRole'),
        object_type=dict(
            default='vm',
            choices=[
                'data_center',
                'cluster',
                'host',
                'storage_domain',
                'network',
                'disk',
                'vm',
                'vm_pool',
                'template',
                'cpu_profile',
                'disk_profile',
                'vnic_profile',
                'system',
            ]
        ),
        authz_name=dict(required=True, aliases=['domain']),
        object_id=dict(default=None),
        object_name=dict(default=None),
        user_name=dict(rdefault=None),
        group_name=dict(default=None),
        namespace=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

    if (
        (module.params['object_name'] is None and module.params['object_id'] is None)
        and module.params['object_type'] != 'system'
    ):
        module.fail_json(msg='"object_name" or "object_id" is required')

    if module.params['user_name'] is None and module.params['group_name'] is None:
        module.fail_json(msg='"user_name" or "group_name" is required')

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        permissions_service = _object_service(connection, module).permissions_service()
        permissions_module = PermissionsModule(
            connection=connection,
            module=module,
            service=permissions_service,
        )

        permission = _permission(module, permissions_service, connection)
        state = module.params['state']
        if state == 'present':
            ret = permissions_module.create(entity=permission)
        elif state == 'absent':
            ret = permissions_module.remove(entity=permission)

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 46
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(choices=['present', 'absent', 'attached', 'detached'],
                   default='present'),
        id=dict(default=None),
        name=dict(default=None, aliases=['alias']),
        vm_name=dict(default=None),
        vm_id=dict(default=None),
        size=dict(default=None),
        interface=dict(default=None, ),
        storage_domain=dict(default=None),
        storage_domains=dict(default=None, type='list'),
        profile=dict(default=None),
        format=dict(default='cow', choices=['raw', 'cow']),
        bootable=dict(default=None, type='bool'),
        shareable=dict(default=None, type='bool'),
        logical_unit=dict(default=None, type='dict'),
        download_image_path=dict(default=None),
        upload_image_path=dict(default=None, aliases=['image_path']),
        force=dict(default=False, type='bool'),
        sparsify=dict(default=None, type='bool'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)
    check_params(module)

    try:
        disk = None
        state = module.params['state']
        auth = module.params.get('auth')
        connection = create_connection(auth)
        disks_service = connection.system_service().disks_service()
        disks_module = DisksModule(
            connection=connection,
            module=module,
            service=disks_service,
        )

        lun = module.params.get('logical_unit')
        if lun:
            disk = _search_by_lun(disks_service, lun.get('id'))

        ret = None
        # First take care of creating the VM, if needed:
        if state == 'present' or state == 'detached' or state == 'attached':
            ret = disks_module.create(
                entity=disk,
                result_state=otypes.DiskStatus.OK if lun is None else None,
            )
            is_new_disk = ret['changed']
            ret['changed'] = ret[
                'changed'] or disks_module.update_storage_domains(ret['id'])
            # We need to pass ID to the module, so in case we want detach/attach disk
            # we have this ID specified to attach/detach method:
            module.params['id'] = ret['id'] if disk is None else disk.id

            # Upload disk image in case it's new disk or force parameter is passed:
            if module.params['upload_image_path'] and (is_new_disk or
                                                       module.params['force']):
                uploaded = upload_disk_image(connection, module)
                ret['changed'] = ret['changed'] or uploaded
            # Download disk image in case it's file don't exist or force parameter is passed:
            if (module.params['download_image_path'] and
                (not os.path.isfile(module.params['download_image_path'])
                 or module.params['force'])):
                downloaded = download_disk_image(connection, module)
                ret['changed'] = ret['changed'] or downloaded

            # Disk sparsify, only if disk is of image type:
            disk = disks_service.disk_service(module.params['id']).get()
            if disk.storage_type == otypes.DiskStorageType.IMAGE:
                ret = disks_module.action(
                    action='sparsify',
                    action_condition=lambda d: module.params['sparsify'],
                    wait_condition=lambda d: d.status == otypes.DiskStatus.OK,
                )
        elif state == 'absent':
            ret = disks_module.remove()

        # If VM was passed attach/detach disks to/from the VM:
        if module.params.get('vm_id') is not None or module.params.get(
                'vm_name') is not None and state != 'absent':
            vms_service = connection.system_service().vms_service()

            # If `vm_id` isn't specified, find VM by name:
            vm_id = module.params['vm_id']
            if vm_id is None:
                vm_id = getattr(
                    search_by_name(vms_service, module.params['vm_name']),
                    'id', None)

            if vm_id is None:
                module.fail_json(
                    msg="VM don't exists, please create it first.")

            disk_attachments_service = vms_service.vm_service(
                vm_id).disk_attachments_service()
            disk_attachments_module = DiskAttachmentsModule(
                connection=connection,
                module=module,
                service=disk_attachments_service,
                changed=ret['changed'] if ret else False,
            )

            if state == 'present' or state == 'attached':
                ret = disk_attachments_module.create()
                if lun is None:
                    wait(
                        service=disk_attachments_service.service(ret['id']),
                        condition=lambda d: follow_link(connection, d.disk).
                        status == otypes.DiskStatus.OK,
                        wait=module.params['wait'],
                        timeout=module.params['timeout'],
                    )
            elif state == 'detached':
                ret = disk_attachments_module.remove()

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'maintenance', 'unattached'],
            default='present',
        ),
        name=dict(required=True),
        description=dict(default=None),
        comment=dict(default=None),
        data_center=dict(required=True),
        domain_function=dict(choices=['data', 'iso', 'export'],
                             default='data',
                             aliases=['type']),
        host=dict(default=None),
        nfs=dict(default=None, type='dict'),
        iscsi=dict(default=None, type='dict'),
        posixfs=dict(default=None, type='dict'),
        glusterfs=dict(default=None, type='dict'),
        fcp=dict(default=None, type='dict'),
        destroy=dict(type='bool', default=False),
        format=dict(type='bool', default=False),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

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

        state = module.params['state']
        control_state(storage_domains_module)
        if state == 'absent':
            ret = storage_domains_module.remove(
                destroy=module.params['destroy'],
                format=module.params['format'],
                host=module.params['host'],
            )
        elif state == 'present':
            sd_id = storage_domains_module.create()['id']
            storage_domains_module.post_create_check(sd_id)
            ret = storage_domains_module.action(
                action='activate',
                action_condition=lambda s: s.status == sdstate.MAINTENANCE,
                wait_condition=lambda s: s.status == sdstate.ACTIVE,
                fail_condition=failed_state,
            )
        elif state == 'maintenance':
            sd_id = storage_domains_module.create()['id']
            storage_domains_module.post_create_check(sd_id)
            ret = storage_domains_module.action(
                action='deactivate',
                action_condition=lambda s: s.status == sdstate.ACTIVE,
                wait_condition=lambda s: s.status == sdstate.MAINTENANCE,
                fail_condition=failed_state,
            )
        elif state == 'unattached':
            ret = storage_domains_module.create()
            storage_domains_module.pre_remove(
                storage_domain=storage_domains_service.service(
                    ret['id']).get())
            ret['changed'] = storage_domains_module.changed

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 48
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, required=True, aliases=['host']),
        address=dict(default=None),
        username=dict(default=None),
        password=dict(default=None),
        type=dict(default=None),
        port=dict(default=None, type='int'),
        slot=dict(default=None),
        options=dict(default=None, type='dict'),
        encrypt_options=dict(default=None, type='bool', aliases=['encrypt']),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

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

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

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Esempio n. 49
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(type='str', default='present', choices=['absent', 'plugged', 'present', 'unplugged']),
        vm=dict(type='str'),
        template=dict(type='str'),
        name=dict(type='str', required=True),
        interface=dict(type='str'),
        profile=dict(type='str'),
        network=dict(type='str'),
        mac_address=dict(type='str'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_one_of=[['vm', 'template']],
    )
    check_sdk(module)

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

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

        # TODO: We have to modify the search_by_name function to accept raise_error=True/False,
        entity = search_by_name(collection_service, entity_name)
        if entity is None:
            raise Exception("Vm/Template '%s' was not found." % entity_name)

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

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

        # Find vNIC id of the network interface (if any):
        profile = module.params.get('profile')
        if profile and module.params['network']:
            cluster_name = get_link_name(connection, cluster_id)
            dcs_service = connection.system_service().data_centers_service()
            dc = dcs_service.list(search='Clusters.name=%s' % cluster_name)[0]
            networks_service = dcs_service.service(dc.id).networks_service()
            network = next(
                (n for n in networks_service.list()
                 if n.name == module.params['network']),
                None
            )
            if network is None:
                raise Exception(
                    "Network '%s' was not found in datacenter '%s'." % (
                        module.params['network'],
                        dc.name
                    )
                )
            for vnic in connection.system_service().vnic_profiles_service().list():
                if vnic.name == profile and vnic.network.id == network.id:
                    entitynics_module.vnic_id = vnic.id

        # Handle appropriate action:
        state = module.params['state']
        if state == 'present':
            ret = entitynics_module.create()
        elif state == 'absent':
            ret = entitynics_module.remove()
        elif state == 'plugged':
            entitynics_module.create()
            ret = entitynics_module.action(
                action='activate',
                action_condition=lambda nic: not nic.plugged,
                wait_condition=lambda nic: nic.plugged,
            )
        elif state == 'unplugged':
            entitynics_module.create()
            ret = entitynics_module.action(
                action='deactivate',
                action_condition=lambda nic: nic.plugged,
                wait_condition=lambda nic: not nic.plugged,
            )

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent', 'attached', 'detached'],
            default='present'
        ),
        id=dict(default=None),
        name=dict(default=None, aliases=['alias']),
        vm_name=dict(default=None),
        vm_id=dict(default=None),
        size=dict(default=None),
        interface=dict(default=None,),
        storage_domain=dict(default=None),
        storage_domains=dict(default=None, type='list'),
        profile=dict(default=None),
        format=dict(default=None, choices=['raw', 'cow']),
        bootable=dict(default=None, type='bool'),
        shareable=dict(default=None, type='bool'),
        logical_unit=dict(default=None, type='dict'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)
    check_params(module)

    try:
        disk = None
        state = module.params['state']
        connection = create_connection(module.params.pop('auth'))
        disks_service = connection.system_service().disks_service()
        disks_module = DisksModule(
            connection=connection,
            module=module,
            service=disks_service,
        )

        lun = module.params.get('logical_unit')
        if lun:
            disk = _search_by_lun(disks_service, lun.get('id'))

        ret = None
        # First take care of creating the VM, if needed:
        if state == 'present' or state == 'detached' or state == 'attached':
            ret = disks_module.create(
                entity=disk,
                result_state=otypes.DiskStatus.OK if lun is None else None,
            )
            ret['changed'] = ret['changed'] or disks_module.update_storage_domains(ret['id'])
            # We need to pass ID to the module, so in case we want detach/attach disk
            # we have this ID specified to attach/detach method:
            module.params['id'] = ret['id'] if disk is None else disk.id
        elif state == 'absent':
            ret = disks_module.remove()

        # If VM was passed attach/detach disks to/from the VM:
        if module.params['vm_id'] or module.params['vm_name'] and state != 'absent':
            vms_service = connection.system_service().vms_service()

            # If `vm_id` isn't specified, find VM by name:
            vm_id = module.params['vm_id']
            if vm_id is None:
                vm_id = getattr(search_by_name(vms_service, module.params['vm_name']), 'id', None)

            if vm_id is None:
                module.fail_json(
                    msg="VM don't exists, please create it first."
                )

            disk_attachments_service = vms_service.vm_service(vm_id).disk_attachments_service()
            disk_attachments_module = DiskAttachmentsModule(
                connection=connection,
                module=module,
                service=disk_attachments_service,
                changed=ret['changed'] if ret else False,
            )

            if state == 'present' or state == 'attached':
                ret = disk_attachments_module.create()
                if lun is None:
                    wait(
                        service=disk_attachments_service.service(ret['id']),
                        condition=lambda d:follow_link(connection, d.disk).status == otypes.DiskStatus.OK,
                        wait=module.params['wait'],
                        timeout=module.params['timeout'],
                    )
            elif state == 'detached':
                ret = disk_attachments_module.remove()

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Esempio n. 51
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 or job.status in [
                    otypes.JobStatus.FINISHED, otypes.JobStatus.FAILED
            ]:
                job = jobs_service.add(build_job(module.params['description']))
                changed = True
            changed = attach_steps(module, job.id, jobs_service) or changed

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

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 52
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None),
        description=dict(default=None),
        type=dict(
            default=None,
            required=True,
            choices=[
                'os_image', 'network', 'os_volume', 'foreman',
            ],
            aliases=['provider'],
        ),
        url=dict(default=None),
        username=dict(default=None),
        password=dict(default=None, no_log=True),
        tenant_name=dict(default=None, aliases=['tenant']),
        authentication_url=dict(default=None, aliases=['auth_url']),
        data_center=dict(default=None),
        read_only=dict(default=None, type='bool'),
        network_type=dict(
            default='external',
            choices=['external', 'neutron'],
        ),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

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

    check_sdk(module)
    check_params(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        provider_type, external_providers_service = _external_provider_service(
            provider_type=module.params.get('type'),
            system_service=connection.system_service(),
        )
        external_providers_module = ExternalProviderModule(
            connection=connection,
            module=module,
            service=external_providers_service,
        )
        external_providers_module.provider_type(provider_type)

        state = module.params.pop('state')
        if state == 'absent':
            ret = external_providers_module.remove()
        elif state == 'present':
            ret = external_providers_module.create()

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 53
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'maintenance', 'upgraded', 'started',
                'restarted', 'stopped', 'reinstalled', 'iscsidiscover',
                'iscsilogin'
            ],
            default='present',
        ),
        name=dict(required=True),
        comment=dict(default=None),
        cluster=dict(default=None),
        address=dict(default=None),
        password=dict(default=None, no_log=True),
        public_key=dict(default=False, type='bool',
                        aliases=['ssh_public_key']),
        kdump_integration=dict(default=None, choices=['enabled', 'disabled']),
        spm_priority=dict(default=None, type='int'),
        override_iptables=dict(default=None, type='bool'),
        force=dict(default=False, type='bool'),
        timeout=dict(default=600, type='int'),
        override_display=dict(default=None),
        kernel_params=dict(default=None, type='list'),
        hosted_engine=dict(default=None, choices=['deploy', 'undeploy']),
        power_management_enabled=dict(default=None, type='bool'),
        activate=dict(default=True, type='bool'),
        iscsi=dict(default=None, type='dict'),
        check_upgrade=dict(default=True, type='bool'),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           required_if=[['state', 'iscsidiscover', ['iscsi']],
                                        ['state', 'iscsilogin', ['iscsi']]])
    check_sdk(module)

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

        state = module.params['state']
        host = control_state(hosts_module)
        if state == 'present':
            ret = hosts_module.create(
                deploy_hosted_engine=(module.params.get('hosted_engine')
                                      == 'deploy')
                if module.params.get('hosted_engine') is not None else None,
                result_state=hoststate.UP if host is None else None,
                fail_condition=hosts_module.failed_state_after_reinstall
                if host is None else lambda h: False,
            )
            if module.params['activate'] and host is not None:
                ret = hosts_module.action(
                    action='activate',
                    action_condition=lambda h: h.status != hoststate.UP,
                    wait_condition=lambda h: h.status == hoststate.UP,
                    fail_condition=failed_state,
                )
        elif state == 'absent':
            ret = hosts_module.remove()
        elif state == 'maintenance':
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status != hoststate.MAINTENANCE,
                wait_condition=lambda h: h.status == hoststate.MAINTENANCE,
                fail_condition=failed_state,
            )
            ret = hosts_module.create()
        elif state == 'upgraded':
            result_state = hoststate.MAINTENANCE if host.status == hoststate.MAINTENANCE else hoststate.UP
            events_service = connection.system_service().events_service()
            last_event = events_service.list(max=1)[0]

            if module.params['check_upgrade']:
                hosts_module.action(
                    action='upgrade_check',
                    action_condition=lambda host: not host.update_available,
                    wait_condition=lambda host: host.update_available or (len([
                        event for event in events_service.list(
                            from_=int(last_event.id),
                            search='type=885 and host.name=%s' % host.name,
                        )
                    ]) > 0),
                    fail_condition=lambda host: len([
                        event for event in events_service.list(
                            from_=int(last_event.id),
                            search='type=839 or type=887 and host.name=%s' %
                            host.name,
                        )
                    ]) > 0,
                )
                # Set to False, because upgrade_check isn't 'changing' action:
                hosts_module._changed = False
            ret = hosts_module.action(
                action='upgrade',
                action_condition=lambda h: h.update_available,
                wait_condition=lambda h: h.status == result_state,
                post_action=lambda h: time.sleep(module.params['poll_interval']
                                                 ),
                fail_condition=hosts_module.failed_state_after_reinstall,
            )
        elif state == 'iscsidiscover':
            host_id = get_id_by_name(hosts_service, module.params['name'])
            iscsi_param = module.params['iscsi']
            iscsi_targets = hosts_service.service(host_id).iscsi_discover(
                iscsi=otypes.IscsiDetails(
                    port=int(iscsi_param.get('port', 3260)),
                    username=iscsi_param.get('username'),
                    password=iscsi_param.get('password'),
                    address=iscsi_param.get('address'),
                ), )
            ret = {
                'changed': False,
                'id': host_id,
                'iscsi_targets': iscsi_targets,
            }
        elif state == 'iscsilogin':
            host_id = get_id_by_name(hosts_service, module.params['name'])
            iscsi_param = module.params['iscsi']
            ret = hosts_module.action(
                action='iscsi_login',
                iscsi=otypes.IscsiDetails(
                    port=int(iscsi_param.get('port', 3260)),
                    username=iscsi_param.get('username'),
                    password=iscsi_param.get('password'),
                    address=iscsi_param.get('address'),
                    target=iscsi_param.get('target'),
                ),
            )
        elif state == 'started':
            ret = hosts_module.action(
                action='fence',
                action_condition=lambda h: h.status == hoststate.DOWN,
                wait_condition=lambda h: h.status in
                [hoststate.UP, hoststate.MAINTENANCE],
                fail_condition=failed_state,
                fence_type='start',
            )
        elif state == 'stopped':
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status not in
                [hoststate.MAINTENANCE, hoststate.DOWN],
                wait_condition=lambda h: h.status in
                [hoststate.MAINTENANCE, hoststate.DOWN],
                fail_condition=failed_state,
            )
            ret = hosts_module.action(
                action='fence',
                action_condition=lambda h: h.status != hoststate.DOWN,
                wait_condition=lambda h: h.status == hoststate.DOWN
                if module.params['wait'] else True,
                fail_condition=failed_state,
                fence_type='stop',
            )
        elif state == 'restarted':
            ret = hosts_module.action(
                action='fence',
                wait_condition=lambda h: h.status == hoststate.UP,
                fail_condition=failed_state,
                fence_type='restart',
            )
        elif state == 'reinstalled':
            # Deactivate host if not in maintanence:
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status not in
                [hoststate.MAINTENANCE, hoststate.DOWN],
                wait_condition=lambda h: h.status in
                [hoststate.MAINTENANCE, hoststate.DOWN],
                fail_condition=failed_state,
            )

            # Reinstall host:
            hosts_module.action(
                action='install',
                action_condition=lambda h: h.status == hoststate.MAINTENANCE,
                post_action=hosts_module.post_reinstall,
                wait_condition=lambda h: h.status == hoststate.MAINTENANCE,
                fail_condition=hosts_module.failed_state_after_reinstall,
                host=otypes.Host(
                    override_iptables=module.params['override_iptables'], )
                if module.params['override_iptables'] else None,
                root_password=module.params['password'],
                ssh=otypes.Ssh(authentication_method=otypes.
                               SshAuthenticationMethod.PUBLICKEY, )
                if module.params['public_key'] else None,
                deploy_hosted_engine=(module.params.get('hosted_engine')
                                      == 'deploy')
                if module.params.get('hosted_engine') is not None else None,
                undeploy_hosted_engine=(module.params.get('hosted_engine')
                                        == 'undeploy')
                if module.params.get('hosted_engine') is not None else None,
            )

            # Activate host after reinstall:
            ret = hosts_module.action(
                action='activate',
                action_condition=lambda h: h.status == hoststate.MAINTENANCE,
                wait_condition=lambda h: h.status == hoststate.UP,
                fail_condition=failed_state,
            )
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(required=True),
        datacenter=dict(required=True),
        description=dict(default=None),
        cluster_threshold=dict(default=None, type='int', aliases=['cluster_soft_limit']),
        cluster_grace=dict(default=None, type='int', aliases=['cluster_hard_limit']),
        storage_threshold=dict(default=None, type='int', aliases=['storage_soft_limit']),
        storage_grace=dict(default=None, type='int', aliases=['storage_hard_limit']),
        clusters=dict(default=[], type='list'),
        storages=dict(default=[], type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

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

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

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

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

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Esempio n. 55
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        data_center=dict(required=True),
        id=dict(default=None),
        name=dict(required=True),
        description=dict(default=None),
        comment=dict(default=None),
        external_provider=dict(default=None),
        vlan_tag=dict(default=None, type='int'),
        vm_network=dict(default=None, type='bool'),
        mtu=dict(default=None, type='int'),
        clusters=dict(default=None, type='list'),
        label=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)
    check_params(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        clusters_service = connection.system_service().clusters_service()
        networks_service = connection.system_service().networks_service()
        networks_module = NetworksModule(
            connection=connection,
            module=module,
            service=networks_service,
        )
        state = module.params['state']
        search_params = {
            'name': module.params['name'],
            'datacenter': module.params['data_center'],
        }
        if state == 'present':
            if module.params.get('external_provider'):
                ret = networks_module.import_external_network()
            else:
                ret = networks_module.create(search_params=search_params)
            # Update clusters networks:
            if module.params.get('clusters') is not None:
                for param_cluster in module.params.get('clusters'):
                    cluster = search_by_name(clusters_service, param_cluster.get('name'))
                    if cluster is None:
                        raise Exception("Cluster '%s' was not found." % param_cluster.get('name'))
                    cluster_networks_service = clusters_service.service(cluster.id).networks_service()
                    cluster_networks_module = ClusterNetworksModule(
                        network_id=ret['id'],
                        cluster_network=param_cluster,
                        connection=connection,
                        module=module,
                        service=cluster_networks_service,
                    )
                    if param_cluster.get('assigned', True):
                        ret = cluster_networks_module.create()
                    else:
                        ret = cluster_networks_module.remove()

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 56
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'maintenance', 'upgraded', 'started',
                'restarted', 'stopped', 'reinstalled', 'iscsidiscover', 'iscsilogin'
            ],
            default='present',
        ),
        name=dict(required=True),
        comment=dict(default=None),
        cluster=dict(default=None),
        address=dict(default=None),
        password=dict(default=None, no_log=True),
        public_key=dict(default=False, type='bool', aliases=['ssh_public_key']),
        kdump_integration=dict(default=None, choices=['enabled', 'disabled']),
        spm_priority=dict(default=None, type='int'),
        override_iptables=dict(default=None, type='bool'),
        force=dict(default=False, type='bool'),
        timeout=dict(default=600, type='int'),
        override_display=dict(default=None),
        kernel_params=dict(default=None, type='list'),
        hosted_engine=dict(default=None, choices=['deploy', 'undeploy']),
        power_management_enabled=dict(default=None, type='bool'),
        activate=dict(default=True, type='bool'),
        iscsi=dict(default=None, type='dict'),
        check_upgrade=dict(default=True, type='bool'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ['state', 'iscsidiscover', ['iscsi']],
            ['state', 'iscsilogin', ['iscsi']]
        ]
    )
    check_sdk(module)

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

        state = module.params['state']
        host = control_state(hosts_module)
        if state == 'present':
            ret = hosts_module.create(
                deploy_hosted_engine=(
                    module.params.get('hosted_engine') == 'deploy'
                ) if module.params.get('hosted_engine') is not None else None,
                result_state=hoststate.UP if host is None else None,
                fail_condition=failed_state if host is None else lambda h: False,
            )
            if module.params['activate'] and host is not None:
                ret = hosts_module.action(
                    action='activate',
                    action_condition=lambda h: h.status != hoststate.UP,
                    wait_condition=lambda h: h.status == hoststate.UP,
                    fail_condition=failed_state,
                )
        elif state == 'absent':
            ret = hosts_module.remove()
        elif state == 'maintenance':
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status != hoststate.MAINTENANCE,
                wait_condition=lambda h: h.status == hoststate.MAINTENANCE,
                fail_condition=failed_state,
            )
            ret = hosts_module.create()
        elif state == 'upgraded':
            result_state = hoststate.MAINTENANCE if host.status == hoststate.MAINTENANCE else hoststate.UP
            events_service = connection.system_service().events_service()
            last_event = events_service.list(max=1)[0]

            if module.params['check_upgrade']:
                hosts_module.action(
                    action='upgrade_check',
                    action_condition=lambda host: not host.update_available,
                    wait_condition=lambda host: host.update_available or (
                        len([
                            event
                            for event in events_service.list(
                                from_=int(last_event.id),
                                search='type=885 and host.name=%s' % host.name,
                            )
                        ]) > 0
                    ),
                    fail_condition=lambda host: len([
                        event
                        for event in events_service.list(
                            from_=int(last_event.id),
                            search='type=839 or type=887 and host.name=%s' % host.name,
                        )
                    ]) > 0,
                )
                # Set to False, because upgrade_check isn't 'changing' action:
                hosts_module._changed = False
            ret = hosts_module.action(
                action='upgrade',
                action_condition=lambda h: h.update_available,
                wait_condition=lambda h: h.status == result_state,
                post_action=lambda h: time.sleep(module.params['poll_interval']),
                fail_condition=failed_state,
            )
        elif state == 'iscsidiscover':
            host_id = get_id_by_name(hosts_service, module.params['name'])
            iscsi_targets = hosts_service.service(host_id).iscsi_discover(
                iscsi=otypes.IscsiDetails(
                    port=int(module.params['iscsi']['port']) if module.params['iscsi']['port'].isdigit() else None,
                    username=module.params['iscsi']['username'],
                    password=module.params['iscsi']['password'],
                    address=module.params['iscsi']['address'],
                ),
            )
            ret = {
                'changed': False,
                'id': host_id,
                'iscsi_targets': iscsi_targets,
            }
        elif state == 'iscsilogin':
            host_id = get_id_by_name(hosts_service, module.params['name'])
            ret = hosts_module.action(
                action='iscsi_login',
                iscsi=otypes.IscsiDetails(
                    port=int(module.params['iscsi']['port']) if module.params['iscsi']['port'].isdigit() else None,
                    username=module.params['iscsi']['username'],
                    password=module.params['iscsi']['password'],
                    address=module.params['iscsi']['address'],
                    target=module.params['iscsi']['target'],
                ),
            )
        elif state == 'started':
            ret = hosts_module.action(
                action='fence',
                action_condition=lambda h: h.status == hoststate.DOWN,
                wait_condition=lambda h: h.status in [hoststate.UP, hoststate.MAINTENANCE],
                fail_condition=failed_state,
                fence_type='start',
            )
        elif state == 'stopped':
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status not in [hoststate.MAINTENANCE, hoststate.DOWN],
                wait_condition=lambda h: h.status in [hoststate.MAINTENANCE, hoststate.DOWN],
                fail_condition=failed_state,
            )
            ret = hosts_module.action(
                action='fence',
                action_condition=lambda h: h.status != hoststate.DOWN,
                wait_condition=lambda h: h.status == hoststate.DOWN if module.params['wait'] else True,
                fail_condition=failed_state,
                fence_type='stop',
            )
        elif state == 'restarted':
            ret = hosts_module.action(
                action='fence',
                wait_condition=lambda h: h.status == hoststate.UP,
                fail_condition=failed_state,
                fence_type='restart',
            )
        elif state == 'reinstalled':
            # Deactivate host if not in maintanence:
            hosts_module.action(
                action='deactivate',
                action_condition=lambda h: h.status not in [hoststate.MAINTENANCE, hoststate.DOWN],
                wait_condition=lambda h: h.status in [hoststate.MAINTENANCE, hoststate.DOWN],
                fail_condition=failed_state,
            )

            # Reinstall host:
            hosts_module.action(
                action='install',
                action_condition=lambda h: h.status == hoststate.MAINTENANCE,
                post_action=hosts_module.post_reinstall,
                wait_condition=lambda h: h.status == hoststate.MAINTENANCE,
                fail_condition=failed_state,
                host=otypes.Host(
                    override_iptables=module.params['override_iptables'],
                ) if module.params['override_iptables'] else None,
                root_password=module.params['password'],
                ssh=otypes.Ssh(
                    authentication_method=otypes.SshAuthenticationMethod.PUBLICKEY,
                ) if module.params['public_key'] else None,
                deploy_hosted_engine=(
                    module.params.get('hosted_engine') == 'deploy'
                ) if module.params.get('hosted_engine') is not None else None,
                undeploy_hosted_engine=(
                    module.params.get('hosted_engine') == 'undeploy'
                ) if module.params.get('hosted_engine') is not None else None,
            )

            # Activate host after reinstall:
            ret = hosts_module.action(
                action='activate',
                action_condition=lambda h: h.status == hoststate.MAINTENANCE,
                wait_condition=lambda h: h.status == hoststate.UP,
                fail_condition=failed_state,
            )
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(required=True),
        template=dict(default=None),
        cluster=dict(default=None),
        description=dict(default=None),
        comment=dict(default=None),
        vm_per_user=dict(default=None, type='int'),
        prestarted=dict(default=None, type='int'),
        vm_count=dict(default=None, type='int'),
        type=dict(default=None, choices=['automatic', 'manual']),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

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

    check_sdk(module)
    check_params(module)

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

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

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 58
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(required=True),
        datacenter=dict(required=True),
        description=dict(default=None),
        cluster_threshold=dict(default=None,
                               type='int',
                               aliases=['cluster_soft_limit']),
        cluster_grace=dict(default=None,
                           type='int',
                           aliases=['cluster_hard_limit']),
        storage_threshold=dict(default=None,
                               type='int',
                               aliases=['storage_soft_limit']),
        storage_grace=dict(default=None,
                           type='int',
                           aliases=['storage_hard_limit']),
        clusters=dict(default=[], type='list'),
        storages=dict(default=[], type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

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

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

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

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

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

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

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Esempio n. 59
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=[
                'present', 'absent', 'exported', 'imported', 'registered'
            ],
            default='present',
        ),
        name=dict(default=None, required=True),
        vm=dict(default=None),
        description=dict(default=None),
        cluster=dict(default=None),
        cpu_profile=dict(default=None),
        disks=dict(default=[], type='list'),
        clone_permissions=dict(type='bool'),
        export_domain=dict(default=None),
        storage_domain=dict(default=None),
        exclusive=dict(type='bool'),
        image_provider=dict(default=None),
        image_disk=dict(default=None, aliases=['glance_image_disk_name']),
        template_image_disk_name=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)

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

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

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

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

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

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

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

            ret = {
                'changed': changed,
                'id': template.id,
                'template': get_dict_of_struct(template)
            }
        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Esempio n. 60
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)