# Buggy code
def grafana_delete_datasource(module, data):
    # define http headers
    headers = {"content-type": "application/json"}
    if "grafana_api_key" in data and data["grafana_api_key"]:
        headers["Authorization"] = "Bearer %s" % data["grafana_api_key"]
    else:
        auth = base64.b64encode(
            to_bytes(
                "%s:%s" % (data["grafana_user"], data["grafana_password"])
            ).replace("\n", "")
        )
        headers["Authorization"] = "Basic %s" % auth
        grafana_switch_organisation(
            module, data["grafana_url"], data["org_id"], headers
        )

    # test if datasource already exists
    datasource_exists, ds = grafana_datasource_exists(
        module, data["grafana_url"], data["name"], headers=headers
    )

    result = {}
    if datasource_exists is True:
        # delete
        r, info = fetch_url(
            module,
            "%s/api/datasources/name/%s" % (data["grafana_url"], data["name"]),
            headers=headers,
            method="DELETE",
        )
        if info["status"] == 200:
            res = json.loads(r.read())
            result["msg"] = "Datasource %s deleted : %s" % (
                data["name"],
                res["message"],
            )
            result["changed"] = True
            result["name"] = data["name"]
            result["id"] = 0
        else:
            raise GrafanaAPIException(
                "Unable to update the datasource id %s : %s" % (ds["id"], info)
            )
    else:
        # datasource does not exist, do nothing
        result = {
            "msg": "Datasource %s does not exist." % data["name"],
            "changed": False,
            "id": 0,
            "name": data["name"],
        }

    return result


# Traceback (nTypeError)
TASK [Create MySQL datasource] ***********************************************************************************************************************************************************************
Monday 26 November 2018  18:38:27 +0100 (0:00:00.386)       0:00:01.453 *******
fatal: [localhost]: FAILED! => {"changed": false, "module_stderr": "/Users/remirey/.ansible/tmp/ansible-tmp-1543253907.275441-99514604312595/AnsiballZ_grafana_datasource.py:17: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses\n  import imp\nTraceback (most recent call last):\n  File \"/Users/remirey/.ansible/tmp/ansible-tmp-1543253907.275441-99514604312595/AnsiballZ_grafana_datasource.py\", line 113, in <module>\n    _ansiballz_main()\n  File \"/Users/remirey/.ansible/tmp/ansible-tmp-1543253907.275441-99514604312595/AnsiballZ_grafana_datasource.py\", line 105, in _ansiballz_main\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\n  File \"/Users/remirey/.ansible/tmp/ansible-tmp-1543253907.275441-99514604312595/AnsiballZ_grafana_datasource.py\", line 48, in invoke_module\n    imp.load_module('__main__', mod, module, MOD_DESC)\n  File \"/Users/remirey/.virtualenvs/engie/lib/python3.7/imp.py\", line 234, in load_module\n    return load_source(name, filename, file)\n  File \"/Users/remirey/.virtualenvs/engie/lib/python3.7/imp.py\", line 169, in load_source\n    module = _exec(spec, sys.modules[name])\n  File \"<frozen importlib._bootstrap>\", line 630, in _exec\n  File \"<frozen importlib._bootstrap_external>\", line 728, in exec_module\n  File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\n  File \"/var/folders/nx/br96pdj13gd30xmz81_fpsw00000gn/T/ansible_grafana_datasource_payload_lo8baeic/__main__.py\", line 541, in <module>\n  File \"/var/folders/nx/br96pdj13gd30xmz81_fpsw00000gn/T/ansible_grafana_datasource_payload_lo8baeic/__main__.py\", line 523, in main\n  File \"/var/folders/nx/br96pdj13gd30xmz81_fpsw00000gn/T/ansible_grafana_datasource_payload_lo8baeic/__main__.py\", line 376, in grafana_create_datasource\nTypeError: a bytes-like object is required, not 'str'\n", "module_stdout": "", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

# Fixed code
def grafana_delete_datasource(module, data):
    # define http headers
    headers = {"content-type": "application/json"}
    if "grafana_api_key" in data and data["grafana_api_key"]:
        headers["Authorization"] = "Bearer %s" % data["grafana_api_key"]
    else:
        headers["Authorization"] = basic_auth_header(
            data["grafana_user"], data["grafana_password"]
        )
        grafana_switch_organisation(
            module, data["grafana_url"], data["org_id"], headers
        )

    # test if datasource already exists
    datasource_exists, ds = grafana_datasource_exists(
        module, data["grafana_url"], data["name"], headers=headers
    )

    result = {}
    if datasource_exists is True:
        # delete
        r, info = fetch_url(
            module,
            "%s/api/datasources/name/%s" % (data["grafana_url"], data["name"]),
            headers=headers,
            method="DELETE",
        )
        if info["status"] == 200:
            res = json.loads(r.read())
            result["msg"] = "Datasource %s deleted : %s" % (
                data["name"],
                res["message"],
            )
            result["changed"] = True
            result["name"] = data["name"]
            result["id"] = 0
        else:
            raise GrafanaAPIException(
                "Unable to update the datasource id %s : %s" % (ds["id"], info)
            )
    else:
        # datasource does not exist, do nothing
        result = {
            "msg": "Datasource %s does not exist." % data["name"],
            "changed": False,
            "id": 0,
            "name": data["name"],
        }

    return result