Webhook 脚本范例

概述

尽管Zabbix提供了大量现成的webhook集成,但您可能想要创建自己的webhook。本节提供了自定义webhook脚本的示例. (在 Script 参数中使用). 有关其他webhook参数的说明,请参见webhook

Jira webhook (自定义)

Webhook 脚本范例 - 图1

此脚本将创建一个JIRA问题,并返回关于所创建问题的一些信息。

  1. try {
  2. Zabbix.log(4, '[ Jira webhook ] Started with params: ' + value);
  3. var result = {
  4. 'tags': {
  5. 'endpoint': 'jira'
  6. }
  7. },
  8. params = JSON.parse(value),
  9. req = new HttpRequest(),
  10. fields = {},
  11. resp;
  12. if (params.HTTPProxy) {
  13. req.setProxy(params.HTTPProxy);
  14. }
  15. req.addHeader('Content-Type: application/json');
  16. req.addHeader('Authorization: Basic ' + params.authentication);
  17. fields.summary = params.summary;
  18. fields.description = params.description;
  19. fields.project = {key: params.project_key};
  20. fields.issuetype = {id: params.issue_id};
  21. resp = req.post('https://tsupport.zabbix.lan/rest/api/2/issue/',
  22. JSON.stringify({"fields": fields})
  23. );
  24. if (req.getStatus() != 201) {
  25. throw 'Response code: ' + req.getStatus();
  26. }
  27. resp = JSON.parse(resp);
  28. result.tags.issue_id = resp.id;
  29. result.tags.issue_key = resp.key;
  30. return JSON.stringify(result);
  31. }
  32. catch (error) {
  33. Zabbix.log(4, '[ Jira webhook ] Issue creation failed json : ' + JSON.stringify({"fields": fields}));
  34. Zabbix.log(3, '[ Jira webhook ] issue creation failed : ' + error);
  35. throw 'Failed with error: ' + error;
  36. }

Slack webhook (自定义)

此webhook将把Zabbix的通知转发到Slack channel中。

Webhook 脚本范例 - 图2

  1. try {
  2. var params = JSON.parse(value),
  3. req = new HttpRequest(),
  4. response;
  5. if (params.HTTPProxy) {
  6. req.setProxy(params.HTTPProxy);
  7. }
  8. req.addHeader('Content-Type: application/x-www-form-urlencoded');
  9. Zabbix.log(4, '[ Slack webhook ] Webhook request with value=' + value);
  10. response = req.post(params.hook_url, 'payload=' + encodeURIComponent(value));
  11. Zabbix.log(4, '[ Slack webhook ] Responded with code: ' + req.Status() + '. Response: ' + response);
  12. try {
  13. response = JSON.parse(response);
  14. }
  15. catch (error) {
  16. if (req.getStatus() < 200 || req.getStatus() >= 300) {
  17. throw 'Request failed with status code ' + req.getStatus();
  18. }
  19. else {
  20. throw 'Request success, but response parsing failed.';
  21. }
  22. }
  23. if (req.getStatus() !== 200 || !response.ok || response.ok === 'false') {
  24. throw response.error;
  25. }
  26. return 'OK';
  27. }
  28. catch (error) {
  29. Zabbix.log(3, '[ Jira webhook ] Sending failed. Error: ' + error);
  30. throw 'Failed with error: ' + error;
  31. }