Beispiel #1
0
 def update_check(self, entity):
     return (
         equal(self.param('cluster'),
               get_link_name(self._connection, entity.cluster))
         and equal(convert_to_bytes(self.param('memory')), entity.memory)
         and equal(convert_to_bytes(self.param('memory_guaranteed')),
                   entity.memory_policy.guaranteed)
         and equal(self.param('cpu_cores'), entity.cpu.topology.cores)
         and equal(self.param('cpu_sockets'), entity.cpu.topology.sockets)
         and equal(self.param('type'), str(entity.type))
         and equal(self.param('operating_system'), str(entity.os.type))
         and equal(self.param('high_availability'),
                   entity.high_availability.enabled)
         and equal(self.param('stateless'), entity.stateless)
         and equal(self.param('cpu_shares'), entity.cpu_shares)
         and equal(self.param('delete_protected'), entity.delete_protected)
         and equal(self.param('use_latest_template_version'),
                   entity.use_latest_template_version)
         and equal(self.param('boot_devices'),
                   [str(dev) for dev in getattr(entity.os, 'devices', [])])
         and equal(self.param('instance_type'),
                   get_link_name(self._connection, entity.instance_type),
                   ignore_case=True)
         and equal(self.param('description'), entity.description)
         and equal(self.param('comment'), entity.comment)
         and equal(self.param('timezone'), entity.time_zone.name)
         and equal(self.param('serial_policy'),
                   str(getattr(entity.serial_number, 'policy', None)))
         and equal(self.param('serial_policy_value'),
                   getattr(entity.serial_number, 'value', None)))
Beispiel #2
0
 def update_check(self, entity):
     return (equal(self._module.params.get('cluster'),
                   get_link_name(self._connection, entity.cluster))
             and equal(self._module.params.get('description'),
                       entity.description)
             and equal(self._module.params.get('cpu_profile'),
                       get_link_name(self._connection, entity.cpu_profile)))
Beispiel #3
0
 def update_check(self, entity):
     template_display = entity.display
     return (
         equal(self._module.params.get('cluster'),
               get_link_name(self._connection, entity.cluster)) and
         equal(self._module.params.get('description'), entity.description)
         and equal(self.param('operating_system'), str(entity.os.type))
         and equal(self.param('name'), str(entity.name))
         and equal(self.param('smartcard_enabled'),
                   getattr(template_display, 'smartcard_enabled', False))
         and equal(self.param('soundcard_enabled'),
                   entity.soundcard_enabled)
         and equal(self.param('ballooning_enabled'),
                   entity.memory_policy.ballooning)
         and equal(self.param('sso'), True if entity.sso.methods else False)
         and equal(self.param('timezone'),
                   getattr(entity.time_zone, 'name', None))
         and equal(self.param('usb_support'), entity.usb.enabled)
         and equal(convert_to_bytes(self.param('memory_guaranteed')),
                   entity.memory_policy.guaranteed)
         and equal(convert_to_bytes(self.param('memory_max')),
                   entity.memory_policy.max)
         and equal(convert_to_bytes(self.param('memory')), entity.memory)
         and equal(self._module.params.get('cpu_profile'),
                   get_link_name(self._connection, entity.cpu_profile))
         and equal(self.param('io_threads'), entity.io.threads))
Beispiel #4
0
def _permission(module, permissions_service, connection):
    for permission in permissions_service.list():
        user = follow_link(connection, permission.user)
        if (
            equal(module.params['user_name'], user.principal if user else None) and
            equal(module.params['group_name'], get_link_name(connection, permission.group)) and
            equal(module.params['role'], get_link_name(connection, permission.role))
        ):
            return permission
Beispiel #5
0
def _permission(module, permissions_service, connection):
    for permission in permissions_service.list():
        user = follow_link(connection, permission.user)
        if (
            equal(module.params['user_name'], user.principal if user else None) and
            equal(module.params['group_name'], get_link_name(connection, permission.group)) and
            equal(module.params['role'], get_link_name(connection, permission.role))
        ):
            return permission
 def update_check(self, entity):
     return (
         equal(self._module.params.get('cluster'), get_link_name(self._connection, entity.cluster)) and
         equal(self._module.params.get('description'), entity.description) and
         equal(self.param('operating_system'), str(entity.os.type)) and
         equal(convert_to_bytes(self.param('memory_guaranteed')), entity.memory_policy.guaranteed) and
         equal(convert_to_bytes(self.param('memory_max')), entity.memory_policy.max) and
         equal(convert_to_bytes(self.param('memory')), entity.memory) and
         equal(self._module.params.get('cpu_profile'), get_link_name(self._connection, entity.cpu_profile))
     )
Beispiel #7
0
 def update_check(self, entity):
     if self._module.params.get('vm'):
         return (
             equal(self._module.params.get('interface'), str(entity.interface)) and
             equal(self._module.params.get('profile'), get_link_name(self._connection, entity.vnic_profile)) and
             equal(self._module.params.get('mac_address'), entity.mac.address)
         )
     elif self._module.params.get('template'):
         return (
             equal(self._module.params.get('interface'), str(entity.interface)) and
             equal(self._module.params.get('profile'), get_link_name(self._connection, entity.vnic_profile))
         )
Beispiel #8
0
 def update_check(self, entity):
     if self._module.params.get('vm'):
         return (
             equal(self._module.params.get('interface'), str(entity.interface)) and
             equal(self._module.params.get('profile'), get_link_name(self._connection, entity.vnic_profile)) and
             equal(self._module.params.get('mac_address'), entity.mac.address)
         )
     elif self._module.params.get('template'):
         return (
             equal(self._module.params.get('interface'), str(entity.interface)) and
             equal(self._module.params.get('profile'), get_link_name(self._connection, entity.vnic_profile))
         )
 def update_check(self, entity):
     return (equal(self._module.params.get('cluster'),
                   get_link_name(self._connection, entity.cluster))
             and equal(self._module.params.get('description'),
                       entity.description)
             and equal(self.param('operating_system'), str(entity.os.type))
             and equal(convert_to_bytes(self.param('memory_guaranteed')),
                       entity.memory_policy.guaranteed)
             and equal(convert_to_bytes(self.param('memory_max')),
                       entity.memory_policy.max) and
             equal(convert_to_bytes(self.param('memory')), entity.memory)
             and equal(self._module.params.get('cpu_profile'),
                       get_link_name(self._connection, entity.cpu_profile)))
Beispiel #10
0
    def has_update(self, nic_service):
        update = False
        bond = self._module.params['bond']
        networks = self._module.params['networks']
        labels = self._module.params['labels']
        nic = get_entity(nic_service)

        if nic is None:
            return update

        # Check if bond configuration should be updated:
        if bond:
            update = self.__compare_options(
                get_bond_options(bond.get('mode'), bond.get('options')),
                getattr(nic.bonding, 'options', []))
            update = update or not equal(
                sorted(bond.get('interfaces'))
                if bond.get('interfaces') else None,
                sorted(
                    get_link_name(self._connection, s)
                    for s in nic.bonding.slaves))

        # Check if labels need to be updated on interface/bond:
        if labels:
            net_labels = nic_service.network_labels_service().list()
            # If any lables which user passed aren't assigned, relabel the interface:
            if sorted(labels) != sorted([lbl.id for lbl in net_labels]):
                return True

        if not networks:
            return update

        # Check if networks attachments configuration should be updated:
        attachments_service = nic_service.network_attachments_service()
        network_names = [network.get('name') for network in networks]

        attachments = {}
        for attachment in attachments_service.list():
            name = get_link_name(self._connection, attachment.network)
            if name in network_names:
                attachments[name] = attachment

        for network in networks:
            attachment = attachments.get(network.get('name'))
            # If attachment don't exists, we need to create it:
            if attachment is None:
                return True

            self.update_address(attachments_service, attachment, network)

        return update
    def has_update(self, nic_service):
        update = False
        bond = self._module.params['bond']
        networks = self._module.params['networks']
        labels = self._module.params['labels']
        nic = get_entity(nic_service)

        if nic is None:
            return update

        # Check if bond configuration should be updated:
        if bond:
            update = not (equal(str(bond.get('mode')),
                                nic.bonding.options[0].value) and equal(
                                    sorted(bond.get('interfaces'))
                                    if bond.get('interfaces') else None,
                                    sorted(
                                        get_link_name(self._connection, s)
                                        for s in nic.bonding.slaves)))

        # Check if labels need to be updated on interface/bond:
        if labels:
            net_labels = nic_service.network_labels_service().list()
            if sorted(labels) != sorted([lbl.id for lbl in net_labels]):
                return True

        if not networks:
            return update

        # Check if networks attachments configuration should be updated:
        attachments_service = nic_service.network_attachments_service()
        network_names = [network.get('name') for network in networks]

        attachments = {}
        for attachment in attachments_service.list():
            name = get_link_name(self._connection, attachment.network)
            if name in network_names:
                attachments[name] = attachment

        for network in networks:
            attachment = attachments.get(network.get('name'))
            # If attachment don't exsits, we need to create it:
            if attachment is None:
                return True

            self.update_address(attachments_service, attachment, network)

        return update
Beispiel #12
0
 def update_check(self, entity):
     return (equal(self._module.params.get('cluster'),
                   get_link_name(self._connection, entity.cluster))
             and equal(convert_to_bytes(self._module.params['memory']),
                       entity.memory)
             and equal(
                 convert_to_bytes(self._module.params['memory_guaranteed']),
                 entity.memory_policy.guaranteed)
             and equal(self._module.params.get('cpu_cores'),
                       entity.cpu.topology.cores)
             and equal(self._module.params.get('cpu_sockets'),
                       entity.cpu.topology.sockets)
             and equal(self._module.params.get('type'), str(entity.type))
             and equal(self._module.params.get('operating_system'),
                       str(entity.os.type))
             and equal(self._module.params.get('high_availability'),
                       entity.high_availability.enabled) and
             equal(self._module.params.get('stateless'), entity.stateless)
             and equal(self._module.params.get('cpu_shares'),
                       entity.cpu_shares)
             and equal(self._module.params.get('delete_protected'),
                       entity.delete_protected)
             and equal(
                 self._module.params.get('use_latest_template_version'),
                 entity.use_latest_template_version) and
             equal(self._module.params.get('boot_devices'),
                   [str(dev) for dev in getattr(entity.os, 'devices', [])]))
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)
Beispiel #14
0
def main():
    argument_spec = ovirt_facts_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:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        permissions_service = _permissions_service(connection, module)
        permissions = []
        for p in permissions_service.list():
            newperm = dict()
            for key, value in p.__dict__.items():
                if value and isinstance(value, sdk.Struct):
                    newperm[key[1:]] = get_link_name(connection, value)
            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=auth.get('token') is None)
    def has_update(self, nic_service):
        update = False
        bond = self._module.params['bond']
        networks = self._module.params['networks']
        labels = self._module.params['labels']
        nic = get_entity(nic_service)

        if nic is None:
            return update

        # Check if bond configuration should be updated:
        if bond:
            update = self.__compare_options(get_bond_options(bond.get('mode'), bond.get('options')), getattr(nic.bonding, 'options', []))
            update = update or not equal(
                sorted(bond.get('interfaces')) if bond.get('interfaces') else None,
                sorted(get_link_name(self._connection, s) for s in nic.bonding.slaves)
            )

        # Check if labels need to be updated on interface/bond:
        if labels:
            net_labels = nic_service.network_labels_service().list()
            # If any lables which user passed aren't assigned, relabel the interface:
            if sorted(labels) != sorted([lbl.id for lbl in net_labels]):
                return True

        if not networks:
            return update

        # Check if networks attachments configuration should be updated:
        attachments_service = nic_service.network_attachments_service()
        network_names = [network.get('name') for network in networks]

        attachments = {}
        for attachment in attachments_service.list():
            name = get_link_name(self._connection, attachment.network)
            if name in network_names:
                attachments[name] = attachment

        for network in networks:
            attachment = attachments.get(network.get('name'))
            # If attachment don't exists, we need to create it:
            if attachment is None:
                return True

            self.update_address(attachments_service, attachment, network)

        return update
Beispiel #16
0
 def update_check(self, entity):
     return (
         equal(self._module.params.get('cluster'), get_link_name(self._connection, entity.cluster)) and
         equal(self._module.params.get('description'), entity.description) and
         equal(self._module.params.get('comment'), entity.comment) and
         equal(self._module.params.get('vm_per_user'), entity.max_user_vms) and
         equal(self._module.params.get('prestarted'), entity.prestarted_vms) and
         equal(self._module.params.get('vm_count'), entity.size)
     )
Beispiel #17
0
    def has_update(self, nic_service):
        update = False
        bond = self._module.params['bond']
        networks = self._module.params['networks']
        nic = get_entity(nic_service)

        if nic is None:
            return update

        # Check if bond configuration should be updated:
        if bond:
            update = not (
                equal(str(bond.get('mode')), nic.bonding.options[0].value) and
                equal(
                    sorted(bond.get('interfaces')) if bond.get('interfaces') else None,
                    sorted(get_link_name(self._connection, s) for s in nic.bonding.slaves)
                )
            )

        if not networks:
            return update

        # Check if networks attachments configuration should be updated:
        attachments_service = nic_service.network_attachments_service()
        network_names = [network.get('name') for network in networks]

        attachments = {}
        for attachment in attachments_service.list():
            name = get_link_name(self._connection, attachment.network)
            if name in network_names:
                attachments[name] = attachment

        for network in networks:
            attachment = attachments.get(network.get('name'))
            # If attachment don't exsits, we need to create it:
            if attachment is None:
                return True

            self.update_address(attachments_service, attachment, network)

        return update
    def update_storage_limits(self, entity):
        new_limits = {}
        for storage in self._module.params.get('storages'):
            new_limits[storage.get('name', '')] = {
                'size': storage.get('size'),
            }

        old_limits = {}
        sd_limit_service = self._service.service(entity.id).quota_storage_limits_service()
        for limit in sd_limit_service.list():
            storage = get_link_name(self._connection, limit.storage_domain) if limit.storage_domain else ''
            old_limits[storage] = {
                'size': limit.limit,
            }
            sd_limit_service.service(limit.id).remove()

        return new_limits == old_limits
    def update_storage_limits(self, entity):
        new_limits = {}
        for storage in self._module.params.get('storages'):
            new_limits[storage.get('name', '')] = {
                'size': storage.get('size'),
            }

        old_limits = {}
        sd_limit_service = self._service.service(entity.id).quota_storage_limits_service()
        for limit in sd_limit_service.list():
            storage = get_link_name(self._connection, limit.storage_domain) if limit.storage_domain else ''
            old_limits[storage] = {
                'size': limit.limit,
            }
            sd_limit_service.service(limit.id).remove()

        return new_limits == old_limits
 def update_check(self, entity):
     migration_policy = getattr(entity.migration, 'policy', None)
     return (
         equal(self.param('comment'), entity.comment) and
         equal(self.param('description'), entity.description) and
         equal(self.param('switch_type'), str(entity.switch_type)) and
         equal(self.param('cpu_arch'), str(entity.cpu.architecture)) and
         equal(self.param('cpu_type'), entity.cpu.type) and
         equal(self.param('ballooning'), entity.ballooning_enabled) and
         equal(self.param('gluster'), entity.gluster_service) and
         equal(self.param('virt'), entity.virt_service) and
         equal(self.param('threads_as_cores'), entity.threads_as_cores) and
         equal(self.param('ksm_numa'), not entity.ksm.merge_across_nodes and entity.ksm.enabled) and
         equal(self.param('ksm'), entity.ksm.merge_across_nodes and entity.ksm.enabled) and
         equal(self.param('ha_reservation'), entity.ha_reservation) and
         equal(self.param('trusted_service'), entity.trusted_service) and
         equal(self.param('host_reason'), entity.maintenance_reason_required) and
         equal(self.param('vm_reason'), entity.optional_reason) and
         equal(self.param('spice_proxy'), getattr(entity.display, 'proxy', None)) and
         equal(self.param('fence_enabled'), entity.fencing_policy.enabled) and
         equal(self.param('fence_skip_if_sd_active'), entity.fencing_policy.skip_if_sd_active.enabled) and
         equal(self.param('fence_skip_if_connectivity_broken'), entity.fencing_policy.skip_if_connectivity_broken.enabled) and
         equal(self.param('fence_connectivity_threshold'), entity.fencing_policy.skip_if_connectivity_broken.threshold) and
         equal(self.param('resilience_policy'), str(entity.error_handling.on_error)) and
         equal(self.param('migration_bandwidth'), str(entity.migration.bandwidth.assignment_method)) and
         equal(self.param('migration_auto_converge'), str(entity.migration.auto_converge)) and
         equal(self.param('migration_compressed'), str(entity.migration.compressed)) and
         equal(self.param('serial_policy'), str(getattr(entity.serial_number, 'policy', None))) and
         equal(self.param('serial_policy_value'), getattr(entity.serial_number, 'value', None)) and
         equal(self.param('scheduling_policy'), get_link_name(self._connection, entity.scheduling_policy)) and
         equal(self._get_policy_id(), getattr(migration_policy, 'id', None)) and
         equal(self._get_memory_policy(), entity.memory_policy.over_commit.percent) and
         equal(self.__get_minor(self.param('compatibility_version')), self.__get_minor(entity.version)) and
         equal(self.__get_major(self.param('compatibility_version')), self.__get_major(entity.version)) and
         equal(
             self.param('migration_bandwidth_limit') if self.param('migration_bandwidth') == 'custom' else None,
             entity.migration.bandwidth.custom_value
         ) and
         equal(
             sorted(self.param('rng_sources')) if self.param('rng_sources') else None,
             sorted([
                 str(source) for source in entity.required_rng_sources
             ])
         )
     )
    def update_cluster_limits(self, entity):
        new_limits = {}
        for cluster in self._module.params.get('clusters'):
            new_limits[cluster.get('name', '')] = {
                'cpu': cluster.get('cpu'),
                'memory': float(cluster.get('memory')),
            }

        old_limits = {}
        cl_limit_service = self._service.service(entity.id).quota_cluster_limits_service()
        for limit in cl_limit_service.list():
            cluster = get_link_name(self._connection, limit.cluster) if limit.cluster else ''
            old_limits[cluster] = {
                'cpu': limit.vcpu_limit,
                'memory': limit.memory_limit,
            }
            cl_limit_service.service(limit.id).remove()

        return new_limits == old_limits
    def update_cluster_limits(self, entity):
        new_limits = {}
        for cluster in self._module.params.get('clusters'):
            new_limits[cluster.get('name', '')] = {
                'cpu': cluster.get('cpu'),
                'memory': float(cluster.get('memory')),
            }

        old_limits = {}
        cl_limit_service = self._service.service(entity.id).quota_cluster_limits_service()
        for limit in cl_limit_service.list():
            cluster = get_link_name(self._connection, limit.cluster) if limit.cluster else ''
            old_limits[cluster] = {
                'cpu': limit.vcpu_limit,
                'memory': limit.memory_limit,
            }
            cl_limit_service.service(limit.id).remove()

        return new_limits == old_limits
Beispiel #23
0
def main():
    argument_spec = ovirt_info_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)
    is_old_facts = module._name == 'ovirt_permission_facts'
    if is_old_facts:
        module.deprecate(
            "The 'ovirt_permission_facts' module has been renamed to 'ovirt_permission_info', "
            "and the renamed one no longer returns ansible_facts",
            version='2.13')

    check_sdk(module)

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

        result = dict(ovirt_permissions=permissions)
        if is_old_facts:
            module.exit_json(changed=False, ansible_facts=result)
        else:
            module.exit_json(changed=False, **result)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Beispiel #24
0
 def update_check(self, entity):
     return (
         equal(self._module.params.get('cluster'), get_link_name(self._connection, entity.cluster)) and
         equal(self._module.params.get('description'), entity.description) and
         equal(self._module.params.get('cpu_profile'), get_link_name(self._connection, entity.cpu_profile))
     )
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, aliases=['host'], required=True),
        bond=dict(default=None, type='dict'),
        interface=dict(default=None),
        networks=dict(default=None, type='list'),
        labels=dict(default=None, type='list'),
        check=dict(default=None, type='bool'),
        save=dict(default=None, type='bool'),
    )
    module = AnsibleModule(argument_spec=argument_spec)
    check_sdk(module)

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

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

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

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

        network_names = [network['name'] for network in networks or []]
        state = module.params['state']
        if (
            state == 'present' and
            (nic is None or host_networks_module.has_update(nics_service.service(nic.id)))
        ):
            # Remove networks which are attached to different interface then user want:
            attachments_service = host_service.network_attachments_service()

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

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

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

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

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

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

        nic = search_by_name(nics_service, nic_name)
        module.exit_json(**{
            'changed': host_networks_module.changed,
            'id': nic.id if nic else None,
            'host_nic': get_dict_of_struct(nic),
        })
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Beispiel #26
0
def get_disk_attachment(disk, disk_attachments, connection):
    for disk_attachment in disk_attachments:
        if get_link_name(connection, disk_attachment.disk) == disk.get('name') or\
                disk_attachment.disk.id == disk.get('id'):
            return disk_attachment
Beispiel #27
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)
Beispiel #28
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(choices=['present', 'absent', 'plugged', 'unplugged'],
                   default='present'),
        vm=dict(required=False),
        template=dict(required=False),
        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,
                           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)
Beispiel #29
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)
Beispiel #30
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)
Beispiel #31
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)
Beispiel #32
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(aliases=['host'], required=True),
        bond=dict(default=None, type='dict'),
        interface=dict(default=None),
        networks=dict(default=None, type='list'),
        labels=dict(default=None, type='list'),
        check=dict(default=None, type='bool'),
        save=dict(default=None, type='bool'),
    )
    module = AnsibleModule(argument_spec=argument_spec)

    check_sdk(module)

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

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

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

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

        network_names = [network['name'] for network in networks or []]
        state = module.params['state']
        if (state == 'present'
                and (nic is None or host_networks_module.has_update(
                    nics_service.service(nic.id)))):
            # Remove networks which are attached to different interface then user want:
            attachments_service = host_service.network_attachments_service()

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

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

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

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

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

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

        nic = search_by_name(nics_service, nic_name)
        module.exit_json(
            **{
                'changed': host_networks_module.changed,
                'id': nic.id if nic else None,
                'host_nic': get_dict_of_struct(nic),
            })
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Beispiel #33
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(
                        id=str(name),
                        host_nic=otypes.HostNic(
                            name=bond.get('name') if bond else interface),
                    ) for name in labels
                ] if labels else None,
                modified_network_attachments=[
                    otypes.NetworkAttachment(
                        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)