Integrating GitLab with CI/CD Tools
local graph
Chapter 13 — Integrating GitLab with CI/CD Tools
Section titled “Chapter 13 — Integrating GitLab with CI/CD Tools”In this chapter, we will cover some of the integrations that are possible with GitLab. Most of the time, companies will not use one tool for their complete DevOps journey. GitLab encourages this for small to midsize companies, but the reality is that big enterprise customers use a mix of different tools and technologies. We will connect Jira to GitLab, as this tool is in use in a big portion of the enterprise market. Of course, the venerable Jenkins server has to be mentioned and tried, and modern organizations use Slack/Mattermost or other chat tools for real-time collaboration. We will finish this chapter with an example of how to utilize a basic webhook.
In this chapter, we will cover the following topics:
- Using Jira with GitLab
- Connecting with Jenkins
- Integrating with Mattermost
- Using webhooks for events
For managing omnibus installs, there is one central configuration file called gitlab.rb. You need to create it or copy an example. There is a template available that you can find at https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/files/gitlab-config-template/gitlab.rb.template. It isn’t updated after upgrades. In large parts of this chapter, I will quote and discuss parts of this file.
The code examples for this chapter are available in this book’s GitHub repository at https://github.com/PacktPublishing/Mastering-GitLab-12/tree/master/Chapter13.
Jira is an IT project management tool that was created by Atlassian in 2002 and was first created as software for developers.
Jira was originally an issue tracking tool, that is, a tool to list and manage tasks. A task can be anything: a problem that needs to be solved, a simple TODO, an application, and so on. However, you can also go much further and put your products, customers, companies, and so on into this tool.
JIRA is also a workflow engine. This means that you can define workflows (in other words, processes) that your tasks must follow. This way, you can impose different processes per project or per task. An example of a simple workflow for a task of the TODO type is OPEN | IN PROGRESS | READY.
For a different type of task, for example, an application to do something, you can set up this workflow: OPEN | CONFIRMED | APPROVED | READY.
Through its integrations, GitLab can interface with Jira. Although GitLab already offers a lot of the project management features that Jira provides, in larger organizations, it can help integrate these tools. For instance, when overall project management is done in Jira, you can make sure that specific links are accessible in the GitLab workflow through commit messages, merge requests, and so on.
As an example, let’s create a project in Jira:
- We created an account on the Cloud offering from Atlassian (https://www.atlassian.com/enterprise/cloud). When you have set up your instance in the Atlassian Cloud or on premise, continue to create a new project:

- When your project has been created, you will see the following screen:

- The next step is to create an issue in this project. Let’s do that with minimal information and call it Integrate GitLab and Jira. You will see it create an issue with an ID of GI-1. We now have an issue in our project management tool, which we like to link to our GitLab instance:

- Now, we will create a special token in Jira, which we will use in GitLab to update the issue. Please visit https://id.atlassian.com, click Security, and then click Create and manage API tokens:

- Click Create API token:

- After you have given it a nice name and clicked Create, it will appear in the list:

- Now, we need to head over to our GitLab instance to create the project that we want to connect to Jira:

- When the project has been created, go to the settings for this project and look for Jira in integrations:

- You can choose whether comments can be created in Jira by following references in a Commit or a Merge request. You need to give the web URL for your Jira instance, which in our case is https://joustie.atlassian.net.
Your username is the email address, and you can fill in your token that you created in Jira earlier.
Now comes the harder part. When you change a Jira issue to another state, you need to provide a transition ID. In our example, this is 11, 21, 31. Now, what is that and where do we find it? This is a good question, and all you need to do is call Jira’s API. They represent the state an issue can be in, and you need to know this state in order to change them.
In the following example, we called https://joustie.atlassian.net/rest/api/2/issue/GI-1/transitions.
When you’ve found those IDs and saved the changes, Jira will test them, and hopefully, you’ll receive the following feedback:

If you go back to the Integrations page, note that the Jira integration is green. Green is good:

If something goes wrong or you would like to know more about these calls, you can consult integrations_json.log in the rails log directory. For instance, the successful call to activate Jira integration is as follows:
{"severity":"INFO","time":"2019-03-02T16:48:49.466Z","correlation_id":"28a67335-4f3d-40ed-826d-8ca0d6d34f84","service_class":"JiraService","project_id":12,"project_path":"root/gitlab-integration","message":"Successfully posted","client_url":"https://joustie.atlassian.net"}Now, you can resolve an issue in Jira through GitLab:
Joosts-iMac:gitlab-integration joostevertse$ git commit -m "Initial commit: Resolves GI-1"[master (root-commit) 0418211] Initial commit: Resolves GI-11 file changed, 0 insertions(+), 0 deletions(-)create mode 100644 test.txtIn the project overview, you will find that the issue has moved to Done:

If you look in the issue itself, you will find that is has a status of Closed:

As you can see, it is possible to integrate project management tools like Jira with GitLab and keep issues in sync. In this section, we have demonstrated how to integrate a cloud-based Jira offering with a local on-premise GitLab installation. Now, let’s move on and connect with Jenkins.
Jenkins (a fork of the Hudson project) is a Continuous Integration platform. The platform is primarily intended for the repeated execution and monitoring of build tasks, as well as the automated building and testing of applications. The many freely available plugins make it very easy to expand the functionality of Jenkins. An example of this is its integration with other systems (such as Sonar, Jira, or CloudBees) or changing its look and feel. It is possible to build a complete Continuous Delivery pipeline by using the right plugins.
There is also a GitLab plugin available to integrate Jenkins in a GitLab workflow. You can download and host Jenkins yourself, or buy capacity in the cloud.
As an example, we have used a local Jenkins container and pulled a container from https://hub.docker.com/_/jenkins. Let’s get started:
- When your Jenkins container has been configured and started, you need to make sure that the GitLab plugin has been installed:

- Click on Manage Jenkins | Manage Plugins:

- If you click on the Available tab and filter for GitLab, you can choose the GitLab plugin:

- When it has been installed, you will see it appearing as a Success:

- Now, go back to the Manage Jenkins page, click Configure System, and scroll to the GitLab section.
- Give the connection a name of your choice, provide the correct URL, and click Add to get a GitLab API token. This API token can be generated in GitLab in the settings:

- You only need to fill in the API token here:

- The next step is to create projects in Jenkins and GitLab (for this example). For this occasion, we chose a freestyle project and named it petclinic:

- We did the same for GitLab:

- In your Jenkins project, scroll down to the Source Code Management section and fill in the URL of your GitLab source code repository:

- Next, click Add to add credentials. You need to add a username and password to connect to your HTTP Git repository (or an SSH user/key or an API key):

- Then, close the popup and scroll down to the Build Triggers section. You can then enable Build when a change is pushed to GitLab. For this example, we have chosen to trigger on push events and opened merge request events:

- Click on Save to save your settings.
For testing and fast development, I recommend using ngrok. This is a secure tunnel program that you can use to connect a localhost to a dynamic URL hosting service. You can find the tool at http://ngrok.com. Download the binary and place it on the local path.
We can use it to tunnel from the internet (where our GitLab lives in a cloud container) to our local Docker container running Jenkins.
Start ngrok to connect an internet URL to our local Jenkins running on 8080 in Docker:
Joosts-iMac:images_chapter12 joostevertse$ ngrok http 8080After starting ngrok, you will be presented with the following output:

Now, change some code in the repository and push the code to GitLab:
Joosts-iMac:petclinic joostevertse$ git push -u origin master Enumerating objects: 130, done. Counting objects: 100% (130/130), done. Delta compression using up to 16 threads Compressing objects: 100% (119/119), done. Writing objects: 100% (130/130), 352.91 KiB | 12.17 MiB/s, done. Total 130 (delta 26), reused 0 (delta 0) remote: Resolving deltas: 100% (26/26), done. To https://gitlab.joustie.nl/root/petclinic.git * [new branch] master -> master Branch 'master' set up to track remote branch 'master' from 'origin'. Joosts-iMac:petclinic joostevertse$You will notice the hook being triggered in ngrok:

By going to Jenkins, you will see that it receives an event and starts building the project:

As you can see, it’s quite easy to connect Jenkins to GitLab. You can choose to let Jenkins react to different kinds of events in GitLab.
Mattermost is the number one open source Slack alternative, and can be hosted on a proprietary platform that you manage yourself.
When teams use these tools, they can become more productive because of direct communication via chat in specialized channels. There, they can exchange quick information bits – even files (images/video, anything) and datafiles that are used by applications.
You can use Mattermost via a browser, or use the platform-specific app on your mobile device. No specific personal data is used other than your email address.
What is also one of its killer features is that it easily connects to third-party applications and systems such as GitLab, Jira Jenkins, Nagios, Zabbix, Kopano, and many more! The company has actually been bought by GitLab, and Mattermost is part of the omnibus installation. In other words, you can easily enable it and run it together with GitLab. ChatOps has been supported since GitLab Ultimate 10.6, but came to GitLab Core in 11.9.
As an example, we will set up a new Mattermost server to integrate with a GitLab instance in order to use slash commands.
Because Mattermost is part of the GitLab omnibus package, you can enable/install it by editing the gitlab.rb file, and use gitlab-ctl afterwards to reconfigure your instance.
The configuration key to change in gitlab.rb is as follows:
mattermost['enable'] = trueAfter Mattermost has been started, you can go the integrations page of the settings of your project and search for the Mattermost slash command service. Click on Add to Mattermost. This will only work automatically on Mattermost 3.4, so make sure that your omnibus package isn’t too old.
If Mattermost isn’t installed on your server, you can pull a simple Mattermost image from Docker Hub. mattermost/mattermost-preview will do fine. Let’s get started:
- When you log in for the first time in your container (by default, this is via http://localhost:8065), you have to create a user:

- After you have created the user, you will want to create a team:

- That team needs a URL as well:

- You can click the hamburger menu to reveal options for the team:

- Go to the system console:

- Look for Custom Integrations and check that slash commands are enabled. Save the settings:

- After this, click the hamburger menu and click Switch back to… Clicking the hamburger menu in the team context, you can click Integrations. Here, you can click on Slash Command, where you will find a page where you can define a slash command that can be triggered by Mattermost:

- The information we need to fill in here can be got from GitLab:

- Log in to GitLab and go to Integrations in the settings part of your repository. Then, click Mattermost slash command. Here is the information you need to fill in in Mattermost:

- In the following screenshot, you can see the settings as we copied them. Click Save or Update when you are done:

- You will now be presented with a token to be used in GitLab. Copy the Mattermost token:

- Paste it into the settings page for your Mattermost integration in GitLab, and save the changes:

- Now, go to your team channel in Mattermost and press /. If you issue /gitlab help, Mattermost will ask you to connect your GitLab account:

- You will be redirected to GitLab, where you will have to authorize the connection:

- Now, by going back to Mattermost and issuing /gitlab help once more, you will be presented with the options for the command. There are several, and these can help your support people run ChatOps:

- Let’s create a new issue called gitlab issue new test:

- If you go back to GitLab, you will find that a new issue has been created for the GitLab project:

The ultimate integration is to use CI command functions, as described here: https://docs.gitlab.com/ee/ci/chatops/.
Since GitLab 11.9, ChatOps is even part of GitLab Core, so its functionality isn’t limited to the GitLab Enterprise Edition.
In this section, we have showed you how to integrate your GitLab repository issues with the Mattermost chat application. There are endless possibilities if you create your own slash commands. Now, let’s take a look at using webhooks for events.
Webhooks are used as a signal between applications. You can see it as a callback from a different context. This call is made with the HTTP protocol (possibly with SSL). An attempt is made to provide information as efficiently as possible and in real time, and JSON is usually used as a data format.
The strength lies in the fact that as few operations as possible are necessary in order to get feedback. Usually, the most work lies in the implementation of the signal.
For a proof of concept, consider the following. Let’s assume that when we push new code to GitLab, we have to send a signal from GitLab to an application that we have built ourselves.
To implement this model, we’ve chose the lightweight Flask micro-framework for Python:
from flask import Flask, requestimport jsonapp = Flask(__name__)
def runsomething(): print "This is triggered"
@app.route('/',methods=['POST'])def trigger(): data = json.loads(request.data) print "New commit by: {}".format(data['commits'][0]['author']['name']) print "New commit by: {}".format(data['commits'][0]['author']['email']) print "New commit by: {}".format(data['commits'][0]['message'])
runsomething() return "OK"
if __name__ == '__main__': app.run()Let’s run through this code step by step. In the following code, the basic app has been initiated. The imports are purely the basic Flask framework and, in particular, the request object. The app is instantiated:
from flask import Flask, requestimport json
app = Flask(__name__)The following function can be used to do the real work:
def runsomething():print "This is triggered"Then follows the method that is decorated with a route, and parses the request for certain information. There’s no check here – just reading the information from the JSON webhook, running the real work function, and returning OK:
@app.route('/',methods=['POST']) def trigger(): data = json.loads(request.data) print "New commit by: {}".format(data['commits'][0]['author']['name']) print "New commit by: {}".format(data['commits'][0]['author']['email']) print "New commit by: {}".format(data['commits'][0]['message'])
runsomething() return "OK"The following main part, combined with the first block, is part of the basic Flask implementation:
if __name__ == '__main__':app.run()When you run this code with python server.py, it will open port 5000 on the localhost:
Joosts-iMac:gitlab-webhook joostevertse$ python server.py* Running on http://127.0.0.1:5000/If we want something on the internet to connect to it, we can use the venerable ngrok to link the port:
Joosts-iMac:Downloads joostevertse$ ngrok http 5000ngrok is now running, as shown in the following screenshot:

We can now define the webhook in GitLab. You can find it in the Settings | Integrations section of your GitLab project. After you have defined the hook, you can run a test to verify its operation:

We get the following result when a call is triggered through GitLab. This is the connection going through the ngrok proxy:

In GitLab, if you click the Edit button, you will see the result of the webhook call. It will contain the body that was sent:

You will also see the response that was given by the other end. You can see the OK response clearly:

The result of this call was that our custom method was triggered and some specific information such as author, email, and message was printed on stdout:
Joosts-iMac:gitlab-webhook joostevertse$ python server.py* Running on http://127.0.0.1:5000/New commit by: JoostNew commit by: [email protected]New commit by: Added textThis is triggered127.0.0.1 - - [03/Mar/2019 17:10:39] "POST / HTTP/1.1" 200 -We have seen that it is also possible to use a generic event mechanism such as webhooks. You can modify your own software or commercial-off-the-shelf (COTS) application to receive events from GitLab.
In this chapter, we discussed the ways of integrating GitLab with other products. Every integration has its own special instruction, but the basic idea is that you have to set up trust relationships and map attributes. GitLab is already shipped with a lot of possible integrations out of the box. These are called project services, and the documentation can be found here: https://docs.gitlab.com/ee/user/project/integrations/project_services.html. This chapter concludes the third section of this book, in which we’ve discussed the GitLab workflow and the underlying rationale behind it.
In the next part of this book, we will discuss the most successful part of GitLab: GitLab CI and runners. We will start by talking about how to set up a project for GitLab CI.
- What is Jira used for?
- Jira is from which company?
- Which ID or IDs are needed to manipulate issues in Jira?
- Which project is Jenkins forked from?
- What mechanism does Jenkins use to extend functionality?
- What is ChatOps?
- How can you control things from a Mattermost channel?
- In GitLab, where can you find the status of a webhook?
- Jira 8 Essentials - Fifth Edition, by Patrick Lee:
- Jenkins 2.x Continuous Integration Cookbook - Third Edition, by Mitesh Soni and Alan Mark Berg:
- Jenkins Fundamentals, by Joseph Muli and Arnold Okoth:
- GitLab ChatOps: https://docs.gitlab.com/ee/ci/chatops/