# Buggy code
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)


# Traceback (_raise_error)
Using module file /usr/lib/python2.7/site-packages/ansible/modules/cloud/ovirt/ovirt_host_networks.py
<127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: root
<127.0.0.1> EXEC /bin/sh -c 'echo ~ &amp;&amp; sleep 0'
<127.0.0.1> EXEC /bin/sh -c '( umask 77 &amp;&amp; mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1525945608.99-276413151072310 `" &amp;&amp; echo ansible-tmp-1525945608.99-276413151072310="` echo /root/.ansible/tmp/ansible-tmp-1525945608.99-276413151072310 `" ) &amp;&amp; sleep 0'
<127.0.0.1> PUT /root/.ansible/tmp/ansible-local-35654kFxTqf/tmpYG_fFL TO /root/.ansible/tmp/ansible-tmp-1525945608.99-276413151072310/ovirt_host_networks.py
<127.0.0.1> EXEC /bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp-1525945608.99-276413151072310/ /root/.ansible/tmp/ansible-tmp-1525945608.99-276413151072310/ovirt_host_networks.py &amp;&amp; sleep 0'
<127.0.0.1> EXEC /bin/sh -c '/usr/bin/python2 /root/.ansible/tmp/ansible-tmp-1525945608.99-276413151072310/ovirt_host_networks.py &amp;&amp; sleep 0'
<127.0.0.1> EXEC /bin/sh -c 'rm -f -r /root/.ansible/tmp/ansible-tmp-1525945608.99-276413151072310/ > /dev/null 2>&amp;1 &amp;&amp; sleep 0'
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_fy5UB6/ansible_module_ovirt_host_networks.py", line 412, in main
] if networks else None,
File "/tmp/ansible_fy5UB6/ansible_modlib.zip/ansible/module_utils/ovirt.py", line 729, in action
getattr(entity_service, action)(**kwargs)
File "/usr/lib64/python2.7/site-packages/ovirtsdk4/services.py", line 37188, in setup_networks
return self._internal_action(action, 'setupnetworks', None, headers, query, wait)
File "/usr/lib64/python2.7/site-packages/ovirtsdk4/service.py", line 299, in _internal_action
return future.wait() if wait else future
File "/usr/lib64/python2.7/site-packages/ovirtsdk4/service.py", line 55, in wait
return self._code(response)
File "/usr/lib64/python2.7/site-packages/ovirtsdk4/service.py", line 296, in callback
self._check_fault(response)
File "/usr/lib64/python2.7/site-packages/ovirtsdk4/service.py", line 132, in _check_fault
self._raise_error(response, body)
File "/usr/lib64/python2.7/site-packages/ovirtsdk4/service.py", line 118, in _raise_error
raise error
Error: Fault reason is "Operation Failed". Fault detail is "[Cannot setup Networks. The following Networks' definitions on the Network Interfaces are different than those on the Logical Networks. Please synchronize the Network Interfaces before editing the networks: ovirtmgmt.]". HTTP response code is 409.

fatal: [localhost]: FAILED! => {
"changed": false,
"invocation": {
"module_args": {
"bond": {
"interfaces": [
"eth0",
"eth1"
],
"mode": 1,
"name": "bond0"
},
"check": null,
"fetch_nested": false,
"interface": null,
"labels": null,
"name": "hostname",
"nested_attributes": [],
"networks": [
{
"boot_protocol": "dhcp",
"id": "d938c2c3-696d-4db1-84b2-1b5f9997d90e",
"name": "ovirtmgmt"
}
],
"poll_interval": 3,
"save": null,
"state": "present",
"timeout": 180,
"wait": true
}
},
"msg": "Fault reason is \"Operation Failed\". Fault detail is \"[Cannot setup Networks. The following Networks' definitions on the Network Interfaces are different than those on the Logical Networks. Please synchronize the Network Interfaces before editing the networks: ovirtmgmt.]\". HTTP response code is 409."
}

# Fixed code
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"),
        sync_networks=dict(default=False, type="bool"),
    )
    module = AnsibleModule(argument_spec=argument_spec)

    check_sdk(module)

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

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

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

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

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

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

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

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

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

            # Assign the networks:
            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)