Skip to content

Instantly share code, notes, and snippets.

@maorfr
Last active July 18, 2018 09:23
Show Gist options
  • Save maorfr/088912eab0c49f6faa377de3a9fa7f4f to your computer and use it in GitHub Desktop.
Save maorfr/088912eab0c49f6faa377de3a9fa7f4f to your computer and use it in GitHub Desktop.
#!/opt/gitlab/embedded/bin/python3
import sys, json, urllib.request, urllib.parse
try:
data = json.load(sys.stdin)
except ValueError:
sys.exit()
if 'object_kind' not in data or 'object_attributes' not in data or data['object_kind'] != 'merge_request':
sys.exit()
object_attributes = data['object_attributes']
state = object_attributes['state']
ref = object_attributes['source_branch']
project_id = object_attributes['source']['id']
# if project_id not in (proj_id1, proj_id2, ...): # Enable only for selected projects
# sys.exit()
headers = {'PRIVATE-TOKEN': '<service_account_private_token>'}
base_url = "http://localhost/api/v4/projects/{}".format(project_id)
if state == "opened" or state == "updated":
action = object_attributes['action']
if action == "open" or action == "update":
# Create project trigger
url = "{}/triggers".format(base_url)
data = urllib.parse.urlencode({'description': "auto generated"}).encode()
req = urllib.request.Request(url, data=data, headers=headers)
res = urllib.request.urlopen(req)
res_json = json.loads(res.read().decode())
trigger_id = res_json['id']
trigger_token = res_json['token']
# Trigger pipeline with variables
ci_commit_sha_short = object_attributes['last_commit']['id'][0:6]
target_branch = object_attributes['target_branch']
url = "{}/ref/{}/trigger/pipeline?token={}&variables[CI_COMMIT_SHA_SHORT]={}&variables[TARGET_BRANCH]={}".format(base_url, ref, trigger_token, ci_commit_sha_short, target_branch)
req = urllib.request.Request(url)
req.get_method = lambda: 'POST'
urllib.request.urlopen(req)
# Remove project trigger
url = "{}/triggers/{}".format(base_url, trigger_id)
req = urllib.request.Request(url, headers=headers)
req.get_method = lambda: 'DELETE'
urllib.request.urlopen(req)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment