diff --git a/tasks/alerta.yml b/tasks/alerta.yml index 6de8090e27afdc887a5a73922903198ab082e25b..ef17e446ed6dd280f45e87f4d0820447aded99bf 100644 --- a/tasks/alerta.yml +++ b/tasks/alerta.yml @@ -21,6 +21,7 @@ - 'alerta-server' - 'alerta' - 'uwsgi' + - 'python-gitlab' - name: "Remove directories for web UI" file: diff --git a/templates/gitlab/alerta_gitlab.py b/templates/gitlab/alerta_gitlab.py index 8d2f0a582174516bf2715ca7c881cee78906fb93..d1546a8e557a9754280a28e69d81b7ff4444fa1c 100644 --- a/templates/gitlab/alerta_gitlab.py +++ b/templates/gitlab/alerta_gitlab.py @@ -1,3 +1,4 @@ +import gitlab import json import logging import requests @@ -7,7 +8,7 @@ from alerta.plugins import PluginBase, app LOG = logging.getLogger('alerta.plugins') ALERTA_URL = 'https://{{ alerta_domain }}' -GITLAB_URL = '{{ gitlab_issue.url }}/api/v4' +GITLAB_URL = '{{ gitlab_issue.url }}' GITLAB_ACCESS_TOKEN = '{{ gitlab_issue.token }}' @@ -30,21 +31,13 @@ class GitlabIssue(PluginBase): def take_action(self, alert, action, text, **kwargs): """should return internal id of external system""" - namespace = 'ansible-inventories/hosts/{}'.format(alert.environment) - base_url = '{}/projects'.format(GITLAB_URL) + LOG.info('Create GitLab issue for %s' % alert.environment) + git = gitlab.Gitlab(GITLAB_URL, GITLAB_ACCESS_TOKEN, ssl_verify=True) # type: gitlab + git.auth() + project = git.projects.get('ansible-inventories/hosts/{}/{}'.format(alert.environment, alert.origin.split('/').pop())) - origin = alert.origin.split('/').pop() - url = base_url + '?search={}'.format(origin) - r = requests.get(url, headers=self.headers) - pid = False - for p in r.json(): - if p.get('namespace').get('full_path') == namespace: - pid = p.get('id', None) - break - - LOG.info('Create GitLab issue for %s / %s / %s' % (alert.environment, origin, pid)) - if pid: - project_url = '{}/{}'.format(base_url, pid) + if project: + LOG.info('Project ID %s' % project.id) if action == 'createIssue': if 'issue_iid' not in alert.attributes: @@ -54,18 +47,14 @@ class GitlabIssue(PluginBase): except Exception as e: LOG.info('Exception %s' % str(e)) raw_data = alert.raw_data - query = urllib.parse.urlencode({ + issue = project.issues.create({ 'title': alert.text[0:128], 'description': '{}/alert/{}\n\nService: {}\n\nOrigin: {}\n\n```\n{}\n```\n'.format(ALERTA_URL, alert.id, alert.service, alert.origin, raw_data) - }) - url = '{}/issues?{}'.format(project_url, query) - #LOG.info('Post to %s' % url) - r = requests.post(url, headers=self.headers) - #LOG.info('Response %s' % r.headers) - alert.attributes['issue_iid'] = r.json().get('iid', None) + }) # type: gitlab.Issue + alert.attributes['issue_iid'] = issue.id alert.attributes['gitlabUrl'] = '<a href="{}" target="_blank">Issue #{}</a>'.format( - r.json().get('web_url', None), - r.json().get('iid', None) + issue.web_url, + issue.iid ) return alert, action, text