Skip to content

Commit

Permalink
Merge pull request #38 from tribe29/fix-discovery-34
Browse files Browse the repository at this point in the history
Improve the error messages for non-OK HTTP return codes.
  • Loading branch information
robin-checkmk committed May 11, 2022
2 parents 834047a + e371b6f commit a05d541
Showing 1 changed file with 41 additions and 33 deletions.
74 changes: 41 additions & 33 deletions plugins/modules/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

__metaclass__ = type

DOCUMENTATION = r'''
DOCUMENTATION = r"""
---
module: discovery
Expand Down Expand Up @@ -35,9 +35,9 @@
author:
- Robin Gierse (@robin-tribe29)
'''
"""

EXAMPLES = r'''
EXAMPLES = r"""
# Create a single host.
- name: "Add newly discovered services on host."
tribe29.checkmk.discovery:
Expand All @@ -55,9 +55,9 @@
automation_secret: "$SECRET"
host_name: "my_host"
state: "fix_all"
'''
"""

RETURN = r'''
RETURN = r"""
http_code:
description: The HTTP code the Checkmk API returns.
type: int
Expand All @@ -68,30 +68,34 @@
type: str
returned: always
sample: 'Host created.'
'''
"""

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
import json


def run_module():
module_args = dict(
server_url=dict(type='str', required=True),
site=dict(type='str', required=True),
automation_user=dict(type='str', required=True),
automation_secret=dict(type='str', required=True, no_log=True),
host_name=dict(type='str', required=True),
state=dict(type='str', default='new', choices=['new', 'remove', 'fix_all', 'refresh', 'only_host_labels']),
server_url=dict(type="str", required=True),
site=dict(type="str", required=True),
automation_user=dict(type="str", required=True),
automation_secret=dict(type="str", required=True, no_log=True),
host_name=dict(type="str", required=True),
state=dict(
type="str",
default="new",
choices=["new", "remove", "fix_all", "refresh", "only_host_labels"],
),
)

result = dict(changed=False, failed=False, http_code='', msg='')
result = dict(changed=False, failed=False, http_code="", msg="")

module = AnsibleModule(argument_spec=module_args,
supports_check_mode=False)
module = AnsibleModule(argument_spec=module_args, supports_check_mode=False)

changed = False
failed = False
http_code = ''
http_code = ""

http_code_mapping = {
# http_code: (changed, failed, "Message")
Expand All @@ -101,16 +105,13 @@ def run_module():
404: (False, True, "Not Found: Host could not be found."),
406: (False, True, "Not Acceptable."),
415: (False, True, "Unsupported Media Type."),
500:
(False, True,
"General Server Error. This might be related to a host not being discoverable at all. Check the affected host in the UI."
),
500: (False, True, "General Server Error."),
}

# Declare headers including authentication to send to the Checkmk API
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer %s %s"
% (
module.params.get("automation_user", ""),
Expand All @@ -119,31 +120,38 @@ def run_module():
}

params = {
'mode': module.params.get("state", ""),
"mode": module.params.get("state", ""),
}

base_url = "%s/%s/check_mk/api/1.0" % (
module.params.get("server_url", ""),
module.params.get("site", ""),
)

api_endpoint = '/objects/host/' + module.params.get("host_name") + '/actions/discover_services/invoke'
api_endpoint = (
"/objects/host/" + module.params.get("host_name") + "/actions/discover_services/invoke"
)
url = base_url + api_endpoint
response, info = fetch_url(module, url, module.jsonify(params), headers=headers, method='POST')
http_code = info['status']
response, info = fetch_url(module, url, module.jsonify(params), headers=headers, method="POST")
http_code = info["status"]

# Kudos to Lars G.!
if http_code in http_code_mapping.keys():
changed, failed, msg = http_code_mapping[http_code]
else:
changed, failed, msg = (False, True, 'Error calling API')
http_body = json.loads(info["body"])["detail"]
changed, failed, msg = (False, True, "Error calling API.")

if failed:
http_body = json.loads(info["body"])["detail"]
msg += " Details: %s" % http_body

result['msg'] = msg
result['changed'] = changed
result['failed'] = failed
result['http_code'] = http_code
result["msg"] = msg
result["changed"] = changed
result["failed"] = failed
result["http_code"] = http_code

if result['failed']:
if result["failed"]:
module.fail_json(**result)

module.exit_json(**result)
Expand All @@ -153,5 +161,5 @@ def main():
run_module()


if __name__ == '__main__':
if __name__ == "__main__":
main()

0 comments on commit a05d541

Please sign in to comment.