Add script to add/update webhook on gitlab

This commit is contained in:
Brian Tarricone 2023-09-16 03:16:18 -07:00
parent 3daab2f3f8
commit faba9d8b69

58
scripts/set-webook.py Executable file
View File

@ -0,0 +1,58 @@
#!/usr/bin/env python3
import re
import os
import requests
import secrets
import sys
def die(s):
print(s, file=sys.stderr)
sys.exit(1)
gitlab_token = os.getenv('GITLAB_TOKEN')
if gitlab_token is None:
die("GITLAB_TOKEN must be set in the environment")
if len(sys.argv) < 4:
die("Usage: {} GITLAB_INSTANCE HOOK_URL_BASE NAMESPACE/REPO\n\nExample: {} gitlab.example.com https://bot.example.com/bebot stuff/myrepo")
gitlab_instance = sys.argv[1]
hook_url = f"{sys.argv[2]}/hooks/gitlab"
repo_name = sys.argv[3]
gl_base = 'https://{}/api/v4/projects/{}/hooks'.format(
gitlab_instance,
re.sub('/', '%2F', repo_name)
)
headers = {
'authorization': 'Bearer {}'.format(gitlab_token),
}
payload = {
"merge_requests_events": True,
"pipeline_events": True,
"push_events": True,
"tag_push_events": True,
}
resp = requests.get(gl_base, headers=headers)
if resp.status_code != 200:
resp.raise_for_status()
existing = resp.json()
for hook in existing:
if hook['url'] == hook_url:
upd_url = '{}/{}'.format(gl_base, hook['id'])
resp = requests.put(upd_url, headers=headers, json=payload)
print("Updated existing hook")
sys.exit(0)
token = secrets.token_urlsafe(32)
payload["url"] = hook_url
payload["token"] = token
resp = requests.post(gl_base, headers=headers, json=payload)
resp.raise_for_status()
print(' "{}/{}":'.format(gitlab_instance, repo_name))
print(' token: "{}"'.format(token))