Extending the Reach of CI/CD Pipelines
local graph
Chapter 10 — Extending the Reach of CI/CD Pipelines
Section titled “Chapter 10 — Extending the Reach of CI/CD Pipelines”In this chapter, we aim to extend the reach of CI/CD pipelines into common automation use cases. By the end of this chapter, you should have an idea of what’s possible with CI/CD pipelines. You’ll see that they are not necessarily just for build and deployment tasks, but also automation tasks, which make the job of an engineer easier, repeatable, and more reliable. CI/CD pipelines are always meant to ease the burden of work on an engineer so that they can focus on more novel and important tasks.
The following topics will be covered in this chapter:
- Using CI/CD pipelines to spot performance problems
- Integrating third-party tools into your CI/CD pipelines
- Using CI/CD pipelines for developing mobile apps
Using CI/CD pipelines to spot performance problems
Section titled “Using CI/CD pipelines to spot performance problems”There is no better time to do performance testing than during an automated CI/CD pipeline. With performance tests, you want them to be routine and against a stable unchanging environment or deployment. If you run performance tests against an environment or deployment that constantly changes, you will not have reliable results. Without reliable results, the entire notion of performance tests goes out the window. You want to understand how your changes affect your performance; without stable results, you can’t infer that understanding.
With GitLab, there are multiple ways to run performance tests. For web or API-based deployments, GitLab includes a native performance tool that will cover in this chapter and go over its integration. However, you, the end user, can take this a step further and cover more metrics such as CPU/memory/storage usage in a CI/CD pipeline. We will not be covering how to collect these metrics in this chapter since that is unique to every user’s environment. However, we strongly recommend that you capture these metrics as part of your CI/CD pipeline.
GitLab’s native integrated performance testing tool for API and web-based deployments will check numerous metrics for active deployment. Some of those metrics include page load time, first page paint time, and total blocking time. In a merge request (pictured in the following screenshot) you can see how your code changes will impact the performance of the web/API deployment:

Figure 10.1: Performance metrics view in a merge request
Always double-check your testing criteria
Your testing results are going to be directly dependent on your testing criteria, test settings, and environments. You should always question if your testing criteria, settings, and environments are accurate. You should never assume they are accurate. If they are not accurate, your test results will never be accurate.
How to integrate browser performance testing
Section titled “How to integrate browser performance testing”Integrating browser performance testing is quite easy – you just need to include the GitLab templates as part of your CI/CD pipeline and then instruct GitLab where your API or web deployment can be accessed. See the following example.
include: - template: Verify/Browser-Performance.gitlab-ci.ymlbrowser_performance: variables: URL: https://myWebOrApiURL.local/With the preceding job template, we’re invoking the browser_performance: templates from GitLab. Then, we’re overwriting the URL variable of the job. This URL is what tells the Performance Testing Suite where to reach out and scan our application for performance. With this configuration, GitLab will check our application and report the results back to our merge request.
How to integrate load performance testing with k6
Section titled “How to integrate load performance testing with k6”The second type of testing that is used in GitLab CI/CD by default is load testing with a tool named k6, provided by the company Grafana. GitLab provides a template for running this tool as part of your CI/CD pipeline as well. However, there is an additional step of creating and specifying a k6 configuration file to run a proper k6 load test.
We’re going to go over this process here. Before we do, note that you should never run these load tests in production. Production load tests should run on an identical non-production environment. To get accurate load testing results, the load testing tool should be the only item communicating with your environment. Without further ado, let’s integrate load testing. Add the following code to your .``gitlab-ci.yml file:
include: - template: Verify/Load-Performance-Testing.gitlab-ci.ymlload_performance: variables: K6_TEST_FILE: '<PATH TO FILE>' #.gitlab/tests/k6.jsThe preceding code will execute k6 as part of our pipeline. However, now, we need to inform k6 how to test our application and provide GitLab with a test file to run. We’re going to assume that this file lives at the.gitlab/test/k6.js path. We’re going to walk through how to build this file.
The following code is going to load the libraries and functions that will affect our load test. Without these, the remainder of our load test file will fail. Next, we’re going to add our settings:
import { check, group, sleep } from 'k6';import http from 'k6/http';The following code is going to define the options for our test. For 5 minutes, we’re going to ramp up to 100 users accessing the website. Then, we’re going to hold at 100 users for 10 minutes. Finally, over 5 minutes, we’re going to ramp down to 0 users. That means this test will run for 20 minutes in total:
export const options = { stages: [ { duration: '5m', target: 100 }, { duration: '10m', target: 100 }, { duration: '5m', target: 0 }, ], thresholds: { 'http_req_duration': ['p(99)<1500'] },};Then, we must set the threshold for failure. We want to see 99% of all requests respond within 1,500 milliseconds. Anything outside that will fail. Next, we’re going to execute the actual load test.
The following code will execute our performance tests using k6 against our website. With this file now being successfully built, we can execute our pipeline and have repeatable load tests:
export default() => { const myResponse = http.get('<MY URL or ENV VAR>').json(); check(myResponse, { 'retrieved url: (obj) => obj.length > 0 }); sleep(1);};With the performance testing set up, we’re going to shift our focus to how to utilize feature flags to enable and disable parts of our application after deployment.
Using feature flags to allow business-driven release decisions
Section titled “Using feature flags to allow business-driven release decisions”GitLab comes with the ability to set up feature flags in the UI. It is based on the third-party unleash library. Once you set up the feature flags in the GitLab UI, you will need to set up your application to communicate with GitLab to check for feature flags. We’ll cover examples of both of these steps, but GitLab does not do this for you: it is up to your application developers to do this work.
Once the feature flags have been configured in the UI, an API call from the application is necessary to check the flag and change the logic of the application accordingly. Let’s walk through how to set up the feature flags in the UI:
- In a project, open the navigation pane on the left-hand side. Click Deployments | Feature Flags. This will take you to the main feature flag section. In the top right, click New feature flag. This will take you to a new view:

Figure 10.2: Feature Flags in GitLab’s navigation pane
- You will be presented with a form. Fill it out and plan your strategies accordingly. You can set multiple strategies based on environments, user lists, and user IDs, and assign percentages to different groups. Once submitted, it will look like this:

Figure 10.3: Main feature flag view
- Feature flags are exceptionally powerful when launching new features. By placing a new feature behind a feature flag, you can turn off part of your application by toggling a flag. This can help prevent a rollback of a release or an emergency support ticket:

Figure 10.4: Feature Flags detail view
In Figure 10*.4*, you can see the presence of our newly created feature flag. On the left-hand side, under Status, you can see a checkbox, which is used to enable or disable this flag.
How to configure your application for feature flags
Section titled “How to configure your application for feature flags”In this section, we’re going to cover a single use case for checking feature flags in an application. The following is a Ruby code sample that will check for feature flags and toggle a code path based on the flag that is set. Your team’s application developers will need to set up their applications based on their toolchains and language usage:
require 'unleash'require 'unleash/context'unleash = Unleash::Client.new({ url: 'http://gitlab.com/api/v4/feature_flags/unleash/42', app_name: 'production', instance_id: '29QmjsW6KngPR5JNPMWx'})unleash_context = Unleash::Context.newunleash_context.user_id = "123"if unleash.is_enabled?("my_feature_name", unleash_context) puts "Feature enabled"else puts "Feature disabled!"endIn this Ruby example, you begin by setting the GitLab information, including the URL of the GitLab instance, the app’s name (corresponding to the environment in GitLab), and the instance ID (the numeric ID of your GitLab project).
The user_id parameter is an example of passing information to GitLab. In this example, we’re passing a user ID that GitLab will match with your feature flag strategy if configured. The next step is invoking unclear.is_enabled, which accepts a feature name as a variable, then reaches out to GitLab to determine if you are in the group that has the flag enabled. Then, the code path that is enabled will be executed.
Now that we’ve covered the usage and purpose of feature flags, we’re going to work on how to integrate third-party tools into your CI/CD pipelines.
Integrating third-party tools into your CI/CD pipelines
Section titled “Integrating third-party tools into your CI/CD pipelines”In this section, we’re going to cover how to integrate third-party tools into a CI/CD pipeline. The preferred method to integrate a third-party tool into a CI/CD pipeline is to containerize it, create a CI/CD job that uses that container, and then invoke our tool as part of that job. In many cases, this is a requirement and is the first step in setting up an integration.
Tool format expectations
This section is based on the belief that the tool you want to integrate is already compiled and ready to be integrated into your pipeline. In the event it is not, you can add CI jobs before those mentioned here to compile or assemble the tool. Then, you can invoke the CI jobs and steps in this section.
Creating our tool container’s Dockerfile
Section titled “Creating our tool container’s Dockerfile”In the previous chapter, we discussed how to build purpose-built containers. We’re going to use that method here to integrate your tool. If you haven’t read the Securing and accelerating jobs with purpose-built containers section of the previous chapter yet, we highly recommend that you read it first and then come back.
The first step in this process is to set up a new GitLab project for your tool and container. Once you have this set up, commit the binaries, configuration, and other files you wish to be placed in the container. The next step is building the container and placing those items inside of it. Create a Dockerfile in your repository and add the following sample code. $mybinary is a placeholder for your binary’s filename; myTool will be your tool’s name.
As shown in the following code, we have created a new container derived from alpine:3.13.0. We updated the container, then created a directory for our tool. After that directory was created, we added all the files in our repository to that folder, permissioned them with a wide permission, and set our binary as executable:
FROM alpine:3.13.0RUN apk update && mkdir /opt/myToolADD . /opt/myToolRUN chmod 777 -R /opt/myTool && chmod +x /opt/myTool/$mybinaryUSER 1001CMD ["echo", "This is a purpose-built container. It is meant to be used in a pipeline and not executed."]This is a simplified example of how to integrate a third-party tool. You should always customize the permission’s values to the least privilege necessary to run your tool. You should also only put the files required for your tool to run in the container. For this example, we’re casting a wide net and including everything, as well as wide permissions.
Automating our container’s build
Section titled “Automating our container’s build”Now that we have a Dockerfile, we want to build the container. As a bonus, we’re also going to turn on container scanning. Create a .gitlab-ci.yml file in your repository if you haven’t already. We’re going to populate that .gitlab-ci.yml file with the following code:
Container_Build: stage: build image: docker:20.10:16 services: - docker:20.10:16-dind variables: DOCKER_HOST: tcp://docker:2376 DOCKER_TLS_VERIFY: 0 script: - docker login -u $CI_REGISTRY_USER –p $CI_REGISTRY_PASSWORD $CI_REGISTRY - docker build -t $CI_REGISTRY_IMAGE:latest . - docker push $CI_REGISTRY_IMAGE:latestAvoiding a pipeline run on every commit
When making multiple pipeline changes, you may not want to kick off a pipeline run every time you make a change. If you start your commit message with [CI SKIP], GitLab will not start a pipeline for that commit.
The preceding code is the most basic example of a Docker-in-Docker build. First, we utilize image: docker:20.10.16 to define the version of Docker we want to build against. Then, we define the Docker service we want to build with – that is, the dind container. Next, we set the DOCKER_HOST and DOCKER_TLS_VERIFY variables so that the Docker and dind containers can talk to each other. Finally, we invoke the docker build command to build our container, and the docker push command to upload it to GitLab’s container registry.
GitLab Runner requirements for Docker
Building a Docker container typically requires the usage of a GitLab Runner capable of doing Docker-in-Docker container builds. GitLab.com shared Runners come with this capability preconfigured. If you’re using a self-hosted Runner, you may need to reconfigure it. Refer to the GitLab documentation for how to achieve this.
Container scanning
Section titled “Container scanning”GitLab offers container scanning as part of the container-building process. We want to take advantage of this to identify any dependency or other vulnerabilities with our container. Enabling this is simple: you need to have a test stage defined in your .gitlab-ci.yml file. Then, simply add the following code block to the top of your .``gitlab-ci.yml file:
include: - template: Jobs/Container-Scanning.gitlab-ci.ymlInvoking the third-party tool
Section titled “Invoking the third-party tool”At this point, we should have a container with our third-party tool built, scanned, and placed inside the GitLab container registry. All that is left now is to invoke our tool. We can do this by creating a CI/CD job that’s pointing to our container and calling our executable in the container:
Test_Job: stage: test image: path/to/my/container script: - /opt/myTool/$myBinarySo far, we’ve walked through how to build a container with tools, how to scan a container, and how to invoke that tool via a CI/CD job. This is a basic example to show you the art of what is possible. With this process, you can clone third-party tools, custom scripts, custom configurations, or whatever else you want to include as part of your CI/CD pipeline.
There are major benefits to doing this. For example, any container that runs as part of a CI/CD pipeline has access to the GitLab API and GitLab repository. This means you can run a CI/CD job as part of your pipeline for something such as metrics collection or configuration verification as well. CI/CD jobs built in this way can automate almost anything.
If you build and containerize a custom tool, be sure to share it with the community.
In the next section, we’re going to discuss how to build mobile applications using GitLab CI/CD and Fastlane.
Using CI/CD pipelines for developing mobile apps
Section titled “Using CI/CD pipelines for developing mobile apps”In this section, we’re going to discuss how to set up CI/CD pipelines in GitLab for mobile application development. There are many benefits to automating the mobile development process at the packaging stage, most notably the fact that packaging a mobile application involves multiple certificates, entitlements, and configuration files, which take a substantial amount of time to assemble when packaging an application. In addition to that, the testing process around mobile applications can be manual and tedious. By automating things such as screenshots across multiple devices, we can shave hours off a developer’s workload.
This section assumes you have all the requirements listed next configured and working already. We’re not going to cover how to do mobile development, but rather how to automate your mobile development practices using Fastlane and GitLab.
Requirements
Section titled “Requirements”For this section, you will need the following:
- A macOS device or VM running the latest version of OS X, with Fastlane installed
- GitLab Runner installed on your macOS device
- An Apple developer account
- A Google developer account
- An application that can be built successfully on your macOS device
Read this before proceeding
If you can’t meet these requirements, you should stop here until you can. This guide assumes you have a working, provisioned macOS device. It also assumes you can build a mobile application on the device.
Fastlane
Section titled “Fastlane”In this chapter, we’re going to be utilizing the Fastlane CLI tool to automate our tests, builds, and deployments. Fastlane is a tool that works with both Android and iOS build processes. It is an opensource tool that can be installed for free on macOS and Windows platforms. You can read more about it in the Fastlane documentation located at https://docs.fastlane.tools/getting-started/ios/setup/.
We’re going to assume you have Fastlane installed on your machine. If not, please refer to the Fastlane documentation linked previously for your platform. The first step in this process is to open your mobile application project and create a Fastlane configuration file named Fastfile. Fastfile is the primary configuration file used by Fastlane. We’re going to make our Fastfile look like this:
lane :beta do build_app(Scheme: "MyApp") # For iOS gradle( task: 'assemble', build_type: 'Release') # For AndroidendTo build our mobile application for both iOS and Android, we simply need to run the fastlane beta command. Assuming your iOS and Android applications can already be built on the macOS device, this command should automate their building. We can put this into a GitLab CI file like this:
"Build Mobile Applications": stage: build tags: - my-osx-runner script: - fastlane betaThis GitLab CI job will automate the Fastlane process via GitLab pipelines. We are leveraging the tags: keyword to ensure that this build happens on a specific macOS device. Without this keyword, the build could happen on any GitLab Runner.
Fastlane – deployment
Section titled “Fastlane – deployment”You can deploy your mobile application to the Android and Apple stores. However, you will need to set up all mobile certificates for production use before setting up Fastlane. When those certificates expire, someone will need to update them on the macOS device. Nevertheless, if they have been set up, you can modify your Fastfile like this:
lane :appstore do sync_code_signing(type: "appstore") build_app(scheme: "MyApp") upload_to_app_storeendlane :playstore do gradle(task: 'assemble', build_type: 'Release') upload_to_play_storeendThe preceding additions to your Fastfile will build your application and release it to the respective app stores. You simply need to run the Fastlane appstore and Fastlane playstore commands. A corresponding GitLab CI/CD configuration file would look like this:
"Deliver Mobile Applications": stage: release tags: - my-osx-runner script: - fastlane appstore - fastlane playstoreFastlane – automated testing
Section titled “Fastlane – automated testing”Assuming you have unit tests set up for your projects already, Fastlane can automate those as well. It does not automatically set up the tests, but if you have them built as part of your project’s configuration, Fastlane can invoke them. This process is similar to every step before – we begin with Fastfile modifications, as seen in the following example:
lane :iosTest do run_tests( devices: ["iPhone 6s", "iPad Air"], scheme: "MyAppTests")endlane :androidTests do gradle(task: "test")endJust like before, we can amend our GitLab CI/CD configuration file to add automated testing as well:
"Test Mobile Applications": stage: test tags: - my-osx-runner script: - fastlane iOSTests - fastlane androidTestsAt times, using Fastlane may feel like you’re cheating. Once you have an established mobile project on a device, Fastlane can take it from there. Mobile development before Fastlane was a tedious and manual process. CI/CD pipelines were filled with a large amount of code and logic to make a build happen and then be deployed.
In this section, we discussed how to build a Fastfile to configure Fastlane, how to run Fastlane commands, and, most importantly, how to add them to a GitLab CI/CD configuration file. We’ve said it before, but in closing, it’s worth repeating: Fastlane and automating mobile development with GitLab CI/CD pipelines is best suited for a macOS device that is already provisioned and set up to build a mobile application. Start there, and then use GitLab CI and Fastlane to handle the rest.
Summary
Section titled “Summary”In this chapter, we covered the benefits of including performance checks inside your CI/CD pipeline. We also covered how to include GitLab’s native performance testing tools. Following that, we covered the benefits of feature flags and how they can protect your deployments and prevent time-consuming rollbacks. Then, we moved on to integrating third-party tools as part of your CI/CD pipeline and how to containerize them for use. Finally, we walked through how to automate the creation and deployment of mobile applications using Fastlane.
In the next chapter, we’re going to cover an end-to-end example that leverages everything you’ve learned about in this book.