Repository: ansible/ansible-modules-extras

Issue:
zabbix_host cannot delete host entry due to the SQL statement error.
##### Issue Type:
- Bug Report
##### Plugin Name:

zabbix_host
##### Ansible Version:

```
ansible 2.0.1.0
```
##### Ansible Configuration:

Please mention any settings you've changed/added/removed in ansible.cfg
(or using the ANSIBLE_\* environment variables).
##### Environment:
- Ansible : CentOS7 with zabbix-api 0.4
- Zabbix:  Zabbix Server 2.4.7-1.el7 on CentOS7
##### Summary:

Adding host entry to zabbix server with `zabbix_host` module succeeded. 
However, deleting it failed with `Application error., SQL statement execution has failed`
##### Steps To Reproduce:

Add a host entry to zabbix server, then remove it.
Adding succeeds, but not the removing.

```
- name: initialize zabbix server entry
  hosts: localhost
  gather_facts: no
  become: no
  tasks:
      - name: Register merge request hosts to zabbix server
        zabbix_host:
          server_url: http://192.168.0.7/zabbix
          login_user: admin
          login_password: zabbix
          host_name: "{{item}}"
          state: present
          status: disabled
          host_groups:
            - "Linux Servers"
            - "Discovered hosts"
          interfaces:
            - type: 1
              main: 1
              useip: 1
              ip: 192.168.0.222
              dns: ""
              port: 10050
        with_items:
          - mytest

      - name: UnRegister merge request hosts from zabbix server
        zabbix_host:
          server_url: http://192.168.0.7/zabbix
          login_user: admin
          login_password: zabbix
          host_name: "{{item}}"
          state: absent
          status: disabled
          host_groups:
            - "Linux Servers"
            - "Discovered hosts"
          interfaces:
            - type: 1
              main: 1
              useip: 1
              ip: 192.168.0.222
              dns: ""
              port: 10050
        with_items:
          - mytest
```
##### Expected Results:

Add a host entry to zabbix, then delete the same entry from zabbix.
##### Actual Results:

First adding code succeeded, but removing failed with SQL statement execution. Ultimately `mytest` host exists in zabbix entry.

I also noticed `server_url` somewhat masked, but it may be irrelevant because adding task's `server_url` is also masked.

```
TASK [Register merge request hosts from zabbix server] *************************
changed: [localhost] => (item=mytest) => {"changed": true, "invocation": {"module_args": {"force": true, "host_groups": ["Linux Servers", "Discovered hosts"], "host_name": "mytest", "interfaces": [{"dns": "", "interfaceid": "24", "ip": "192.168.0.222", "main": 1, "port": 10050, "type": 1, "useip": 1}], "link_templates": null, "login_password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER", "login_user": "admin", "proxy": null, "server_url": "http://192.168.0.7/********", "state": "present", "status": "disabled", "timeout": 10}, "module_name": "zabbix_host"}, "item": "mytest", "result": "Successfully update host mytest (192.168.0.222) and linked with template 'None'"}

TASK [UnRegister merge request hosts from zabbix server] ***********************
failed: [localhost] => (item=mytest) => 
{
  "msg": "Failed to delete host myTesthost: (u'Error -32500: Application error., SQL statement execution has failed \"DELETE FROM scre
ens_items WHERE resourceid=Array AND resourcetype=\\'16\\'\" while sending {\"params\": {\"hostid\": \"10128\"}, \"jsonrpc\": \"2.0\", \"method\": \"host.delete\", \"auth\": \"ac129a6263de70928c8859ecd017c773\", \"id\": 6}', -32500)",
  "invocation": {
    "module_name": "zabbix_host",
    "module_args": {
      "timeout": 10,
      "status": "disabled",
      "state": "absent",
      "server_url": "http://192.168.0.7/********",
      "force": true,
      "host_groups": [
        "Linux Servers",
        "Discovered hosts"
      ],
      "host_name": "myTesthost",
      "interfaces": [
        {
          "useip": 1,
          "type": 1,
          "port": 10050,
          "main": 1,
          "ip": "192.168.0.222",
          "dns": ""
        }
      ],
      "link_templates": null,
      "login_password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
      "login_user": "admin",
      "proxy": null
    }
  },
  "failed": true,
  "changed": false
}
```

Thank you!



Discussion:
That appears to be a bug in the Zabbix server/its API and can't be fixed on the Ansible side. All the code does is call host.delete on the API. If/when that fails in this way, that's a bug in Zabbix, not the Ansible module calling its API :)

Thanks for comment, eikef.

I looked further into Zabbix API documentation and noticed that `host.delete` parameter has been changed at version 2.4.
[2.2 manual](https://www.zabbix.com/documentation/2.2/manual/api/reference/host/delete) says `The method can also accept an array of host objects with the hostid property defined. This format is deprecated.` 

It means this part of code shoud be..

```
    def delete_host(self, host_id, host_name):
        try:
            if self._module.check_mode:
                self._module.exit_json(changed=True)
            self._zapi.host.delete({'hostid': host_id})
```

this.

```
    def delete_host(self, host_id, host_name):
        try:
            if self._module.check_mode:
                self._module.exit_json(changed=True)
            self._zapi.host.delete([host_id])
```

So we need to change code.
I'll test new one and try to pull request later.

Thank you.

Thank you, I had overlooked this API change/deprecation. It is still quite a weird error to return in that case, though. Thank you for looking into this more and the future PR. :-)


Resolving patch:
diff --git a/monitoring/zabbix_host.py b/monitoring/zabbix_host.py
--- a/monitoring/zabbix_host.py
+++ b/monitoring/zabbix_host.py
@@ -26,7 +26,7 @@
 description:
    - This module allows you to create, modify and delete Zabbix host entries and associated group and template data.
 version_added: "2.0"
-author: 
+author:
     - "(@cove)"
     - "Tony Minfei Ding"
     - "Harrison Gu (@harrisongu)"
@@ -240,7 +240,7 @@ def delete_host(self, host_id, host_name):
         try:
             if self._module.check_mode:
                 self._module.exit_json(changed=True)
-            self._zapi.host.delete({'hostid': host_id})
+            self._zapi.host.delete([host_id])
         except Exception, e:
             self._module.fail_json(msg="Failed to delete host %s: %s" % (host_name, e))
 
@@ -440,7 +440,7 @@ def main():
             proxy_id = host.get_proxyid_by_proxy_name(proxy)
         else:
             proxy_id = None
-        
+
         # get host id by host name
         zabbix_host_obj = host.get_host_by_host_name(host_name)
         host_id = zabbix_host_obj['hostid']
@@ -485,6 +485,10 @@ def main():
                 else:
                     module.exit_json(changed=False)
     else:
+        if state == "absent":
+            # the host is already deleted.
+            module.exit_json(changed=False)
+
         # Use proxy specified, or set to 0 when adding new host
         if proxy:
             proxy_id = host.get_proxyid_by_proxy_name(proxy)
@@ -505,4 +509,3 @@ def main():
 
 from ansible.module_utils.basic import *
 main()
-


Test patch: