Skip to content

Instantly share code, notes, and snippets.

@mikew
Last active December 31, 2015 04:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikew/7938355 to your computer and use it in GitHub Desktop.
Save mikew/7938355 to your computer and use it in GitHub Desktop.
Gitlab -> Jenkins

Installation

  • Set JENKINS_USER and JENKINS_TOKEN environment variables

  • Edit mappings.json and add a push hook in Gitlab to http://localhost:5678/push.php

    OR

    Simply add a push hook in gitlab to http://localhost:5678/push.php?project=Jenkins+Project&token=ABCDEF

  • Start the server with php -s 0.0.0.0:5678

{
"gitlab_project": "Jenkins Project:token",
"gitlab_project:refs/heads/live": "Jenkins Project - Live:token"
}
<?php
define('JENKINS_URL', empty(getenv('JENKINS_URL')) ? 'http://127.0.0.1:8080' : getenv('JENKINS_URL'));
define('JENKINS_USER', getenv('JENKINS_USER'));
define('JENKINS_TOKEN', getenv('JENKINS_TOKEN'));
$data = file_get_contents('php://input');
$mappings = json_decode(file_get_contents('mappings.json'));
if (strlen($data) === 0) {
exit('No POST body.');
}
$json = json_decode($data);
$project_name = $json->repository->name;
$ref = $json->ref;
$project_and_ref = "{$project_name}:{$ref}";
if (!empty($_GET['token']) && !empty($_GET['project'])) {
trigger_jenkins_build($_GET['project'], $_GET['token']);
return;
}
if (array_key_exists($project_name, $mappings)) {
$pair = split_project_and_key($mappings[$project_name]);
trigger_jenkins_build($pair[0], $pair[1]);
}
if (array_key_exists($project_and_ref, $mappings)) {
$pair = split_project_and_key($mappings[$project_and_ref]);
trigger_jenkins_build($pair[0], $pair[1]);
}
function split_project_and_key($haystack) {
$pos = strrpos($haystack, ':');
$jenkins_project = substr($haystack, 0, $pos);
$jenkins_token = substr($haystack, $pos + 1);
return array($jenkins_project, $jenkins_token);
}
function trigger_jenkins_build($project, $token) {
global $json;
$ch = curl_init();
$user_name = $json->user_name;
$project_encoded = rawurlencode($project);
$cause_encoded = rawurlencode("Git Push from {$user_name}");
$url = JENKINS_URL . "/job/{$project_encoded}/build?token={$token}&cause={$cause_encoded}";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, JENKINS_USER . ':' . JENKINS_TOKEN);
$buffer = curl_exec($ch);
curl_close($ch);
return $buffer;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment