Skip to main content

Automating GitLab

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· 3 min read
Stephan Hochdörfer
Head of IT Business Operations

When we made the move to GitLab 1,5 years ago, it was clear to me that we would need some automation to simplify the creation of groups and projects and to sync the LDAP group memberships to the matching GitLab groups. I did a quick search on Packagist for GitLab client libraries and found the m4tthumphrey/php-gitlab-api package.

Installing the library via Composer is quite easy:

composer.phar require m4tthumphrey/php-gitlab-api

To be able to connect to a GitLab instance you need to provide the url of the GitLab instance as well as an authentication token for a specific user. The actions you issue will be taken on behalf of that specific user. Which means you might not see all groups or projects if your user does not have access to those.

$gitlabUrl = 'http://gitlab.loc';
$gitlabAuthToken = 'xGfHMB69yEjnTxS23aPf';

$client = new \Gitlab\Client($gitlabUrl);

You can now either use the provided API classes, e.g. \Gitlab\Api\Projects or \Gitlab\Api\Groups to interact with the GitLab API - all those API classes provide some kind of high-level abstraction of the GitLab API - or you could use the built-in HTTP client to interact on a lower level with the GitLab API. The high-level interaction should be preferred as you do not need to take a deep dive into the GitLab API documentation. However, some newer features or options might not yet be exposed in the high-level API, thus you can use the low-level HTTP request mechanism to talk to GitLab.

$groupName = 'MyGroup';
$description = 'Some description';

// high-level API
$groupsApi = new \Gitlab\Api\Groups($tclient);
$groupsApi->create($groupName, $groupName, $description);

// low-level HTTP API
'name' => $groupName,
'path' => $groupName,
'description' => $description,
'visibility_level' => 0,
'request_access_enabled' => false,

What is really cool about the GitLab API is that you are able to do basically anything in GitLab. For example the GitLab API let's you create files in a repository like this:

$projectId = 123;
$content = 'Here may be dragons';

$repositoriesApi = new \Gitlab\Api\Repositories($client);
'Add file'

Or you could create a webhook to that commits to a repository trigger a Jenkins build - which was our setup before migrating to GitLab CI:

$projectId = 123;
$gitUrl = 'http://gitlab.loc/group/project.git;
$jenkinsUrl = 'http://jenkins.loc/jenkins/git/notifyCommit?url=' . $gitUrl;
$options = [
'push_events' => true,
'merge_requests_events' => true,
'tag_push_events' => true,
'build_events' => true,
'issues_events' => false,
'note_events' => false,
'enable_ssl_verification' => true,

$projectsApi = new \Gitlab\Api\Projects($client);
$projectsApi->addHook($projectId, $jenkinsUrl, $options);