End-to-End Example
local graph
Chapter 11 — End-to-End Example
Section titled “Chapter 11 — End-to-End Example”By now, you’ve seen how the different parts of GitLab help you write, review, verify, secure, package, and deploy software. These features have been presented one at a time, so let’s put them all together in a single end-to-end example so you can see the whole process in one fell swoop. There won’t be any new material in this chapter, so it will be a great chance to review what you’ve learned in earlier chapters and see it all consolidated in one extended workflow.
This chapter is broken into many subsections, each showing how to use GitLab to help with a different part of the software development life cycle:
- Setting up your environment
- Writing code
- Establishing the pipeline infrastructure
- Verifying your code
- Securing your code
- Improving your pipeline
- Delivering your code to the right environment
Technical requirements
Section titled “Technical requirements”If you’d like to follow along as we develop a piece of software with GitLab, all you need is an account on a GitLab instance, whether Software-as-a-Service (SaaS) or self-hosted.
Setting up your environment
Section titled “Setting up your environment”Before you start writing any code, you need to organize a few preliminary things. Specifically, you need to make a GitLab project for storing your code and running your pipelines, you need to make some GitLab issues to help plan and track your work, and you need to clone the project’s repository to your local computer so that you can write code using your favorite IDE instead of entirely within the GitLab GUI.
Making a GitLab project
Section titled “Making a GitLab project”Let’s rewind to the beginning of our journey with the Hats for Cats web app. We know we want to make a web app for our online feline accessories store, so let’s start by making a GitLab project to hold not only our web app’s code but also the additional GitLab components that we’ll be using as we build the app.
A note about the GUI
Throughout this chapter, we’ll continue our practice of showing you code snippets but generally not showing the steps for using the GitLab GUI. This is because we want to avoid having the screenshots drift away from reality as the GitLab GUI changes in future releases.
We could make a Hats for Cats project directly within the top-level namespace of our GitLab account, but it seems likely that we’ll want to make more projects in the future—perhaps for other web apps, perhaps for other versions of the web app aimed at different platforms—so first, let’s make a GitLab group to hold all of our projects. Let’s pretend that our company is called Acme Software, so we’ll start with a group called, unsurprisingly, Acme Software:

Figure 11.1 – The Acme Software group
Within this group, we can add a new project that holds the Hats for Cats web app. Let’s call it Hats for Cats, and let’s choose the Create blank project option rather than creating it from a project template. This means that it will begin its life with a boilerplate README.md file in its Git repository, but nothing else. Here’s what the new project looks like immediately after creation:

Figure 11.2 – The Hats for Cats project
As you already know, this project will hold not only the code for our web app but also the configuration file for our CI/CD pipeline, branches and Merge Requests (MRs) related to our code, packaged bits of code ready for deployment, and issues to help us plan and track our work. That leads nicely into the next step of our workflow: creating GitLab issues.
Placing all projects within a group
For technical reasons, the screenshots in the rest of this chapter show the Hats for Cats project directly under the user’s account instead of within the Acme Software group. However, the best practice is to create all of your company or organization’s projects within a single master group.
Planning work with GitLab issues
Section titled “Planning work with GitLab issues”Using GitLab issues to plan and track your work is an optional but highly recommended part of writing software with GitLab. You can, of course, use other tools such as Jira or Trello to map out your work, but many developers find that GitLab issues give them all the power they need for standard project management tasks.
GitLab projects for non-trivial pieces of software might contain tens, hundreds, or, in extreme cases, thousands of issues—for instructional purposes, let’s create just four issues for our project. To build the minimum viable product (MVP) for our web app, let’s make issues with these titles:
Allow user tolog inAllow user tosearch inventoryAllow user to buya hatAllow user tolog out
Once those are in place, let’s think about GitLab labels. Some teams use multiple labels on each issue to indicate ownership, assign priority, or perform other administrative functions. Let’s create and assign an unscoped security label to show that the login and log-out issues need extra scrutiny from our security team. Let’s also make scoped priority::high and priority::low labels to indicate which features should be worked on first and which came come later. For now, just assign priority::high to the login issue—we’ll decide as a team later what priority labels to give to the rest of the issues.
Next, let’s tackle the metadata for the login issue, which is the feature we want to develop first. We open that issue, assign it to a developer, set the Weight field to 5 (which, after some discussion, we decide is a reasonable weight for a medium-sized task), use a quick action to estimate that it will take 15 hours of work to complete, and set a due date. Setting metadata at the same time that the issue is created is a practice that you often see among teams that use the Kanban workflow; if we were using the Scrum workflow, we might have saved assigning a due date, weight, or estimated hours until the next backlog grooming ceremony.
After creating these four issues, creating and assigning appropriate labels, and filling in metadata for one issue, clicking Issues | List in the left-hand navigation pane should show something like this. Notice that the metadata is displayed right in the issue list, which is handy:

Figure 11.3 – Hats for Cats issues and issue metadata
You’re done with getting your GitLab environment set up: you’ve created a GitLab group, made a GitLab project inside it, and made some issues to work against. Now, you’re ready to start writing code and storing it in that project.
Setting up a local Git repository
Section titled “Setting up a local Git repository”Although we could do all of our development work within the GitLab instance, that would make writing code difficult and testing impossible. Instead, let’s clone the repository to a local computer so that we can develop using whatever desktop IDEs or other tools we’re most comfortable with.
First, we need to make sure that we’ve generated a public/private key pair on our workstation and uploaded the public key to our GitLab account. This only needs to be done once for any GitLab instance we’re working with, so let’s assume that we’ve already taken care of this. The GitLab documentation has more information about this process.
Next, we need to grab the address that we’ll use to clone the Hats for Cats project’s repository. Since we’re using key-based security instead of manually entering authentication credentials with every Git command, we copy the project’s SSH address using the GUI, and then clone it by running this command on our local machine (if you’re following along at home, you’ll see a slightly different address based on your GitLab account name):
git clone [email protected]:acme-software/hats-for-cats.gitWe can then move into the directory created by the clone operation and look around. If everything has worked as expected, we should see local copies of the same files that exist in the GitLab-hosted copy of the repository—which at this point is just one README.md file:
~$ cd hats-for-cats~/hats-for-cats$ lsREADME.mdNow, we’re all set to do local development, push any changes we make up to the copy of the repository on GitLab, and pull down any changes that coworkers have pushed up.
Writing code
Section titled “Writing code”You’re almost at the point where you can start coding. First, you’ll need a Git branch to commit the code to. Then, you’ll need a MR so that you can see the results of pipeline tasks that run against that code, and also so that you can eventually merge the code into the main branch. Let’s go over those steps, and then make and push your first commit.
Creating a Git branch to work on
Section titled “Creating a Git branch to work on”Now that we’re ready to add the login feature requested by our first assigned issue, we need a Git branch to commit to. We might as well name our branch after the title of the issue we’re working on:
git branch add-login-featureSwitch onto the new branch so any new commits end up on that branch and not on the main branch:
git checkout add-login-featureAt this point, we might as well push this branch up to the GitLab-hosted copy of the repository so that it exists in both places. For the first push, we need to use a slightly longer command:
git push --set-upstream origin add-login-featureFor subsequent pushes, after we’ve added some commits, we can rely on a simpler command:
git pushIf we look at the project’s repository in GitLab, we can see that it now lists add-login-feature within the dropdown of the project’s branches.
Creating an MR
Section titled “Creating an MR”Let’s follow GitLab best practices and immediately make an MR associated with the branch we just created. Navigate to Ns in the left-hand navigation pane and click on New merge request. Select add-login-feature as the source branch and main as the target branch, and click Compare branches and continue.
Title the MR Draft: add login feature and add Closes #X in the description field, where X is replaced by the number of the Allow user to log in issue (tip: as soon as you type # in the description, the GUI will present you with a dropdown showing all the issues you’ve created, so you don’t need to look up the issue number manually). Now, we’ve created the “three amigos” of issue, branch, and MR, so we’re ready to get to work developing our feature.
Committing and pushing code
Section titled “Committing and pushing code”It’s time to write some code! Instead of writing an actual login page with real GUI elements and logic, let’s use our local computer to make a file called login.py in the root of the add-login-feature branch of our project’s Git repository. Populate that file with placeholder code, such as print("Welcome to Hats for Cats!"). Since we’re doing this on our local computer rather than on GitLab, we need to use Git terminal commands or a GUI tool for Git (such as Sourcetree or Tower, or the Git tools built into IDEs such as IntelliJ IDEA or Visual Studio Code) to add our new file to the Git staging area and then commit it with an appropriate message. Perform these operations on the command line like this:
git add login.pygit commit -m "add initial version of log in page"It’s important to reiterate at this point that the local commit will not trigger a CI/CD pipeline. The GitLab instance doesn’t know that the commit exists, and even if it did, it doesn’t have any way of seeing the code included in that commit. However, as soon as we push any local commits up to GitLab, it will detect those commits in its own copy of the repository and run a pipeline against whatever commits we pushed up.
Let’s push the add-login-feature branch now:
git pushPushing frequently is important!
We could have waited to push this branch until we had made several local commits to it, but since much of the power of GitLab’s CI/CD pipelines comes from having them run frequently against small code changes, it’s usually wisest to push after every local commit.
This was such a simple edit—adding a single file that contains a single line of code—that you might be wondering why we didn’t just make the edit and commit the change within the GitLab GUI instead of going through the hassle of editing and committing locally and then pushing that edit up to GitLab. Honestly, with a change this small, we could easily have gotten away with performing the edit right on GitLab. If this were a real-world project, that’s exactly what we would advise you to do, but since most development work is quite a bit more complicated than the placeholder code included here, we thought it would be helpful to show you the typical edit-and-commit-locally-and-then-push workflow that you’ll be using for most of your development work.
Establishing the pipeline infrastructure
Section titled “Establishing the pipeline infrastructure”You’ve stored some code in the repository, so now it’s time to set up a pipeline to run a variety of tasks to build, verify, and secure your code. In some cases, you might also want to set up a GitLab Runner to execute those pipeline tasks, although that task is usually taken care of for you by your GitLab administrator or the GitLab SaaS platform.
Creating a pipeline
Section titled “Creating a pipeline”Pushing commits to GitLab so that it can run CI/CD pipelines on our new code won’t work unless we define what tasks we’d like our pipeline to perform. We’ll add several tasks to our Hats for Cats project’s pipeline as we go through the rest of this chapter, but for now, let’s get a bare-bones pipeline in place.
Just as we did with our initial file, we could create the .gitlab-ci.yml pipeline configuration file locally, commit it, and push it up to GitLab, but since the GitLab GUI offers a handy editor dedicated to writing and debugging pipeline configuration files, it often makes more sense to edit it on GitLab. Having a local copy of .gitlab-ci.yml isn’t important since we can’t use it to run pipelines on our local machine anyway.
In the left-hand navigation pane, select CI/CD | Editor to fire up the dedicated pipeline editor, select the add-login-feature branch from the dropdown, and create a new .gitlab-ci.yml. At this point, we’re not sure what stages we’re going to end up needing in our pipeline. It could be reasonably argued that there’s no point defining stages until you actually need them, but we’re fairly confident that we’ll need the basic trio of build, test, and deploy, so in the interest of fleshing out this example, let’s add all three right now:
stages: - build - test - deploySince Python is an interpreted rather than compiled language, we don’t have any jobs to define within the build stage yet. We also haven’t written any automated tests yet, so there’s no point in adding jobs to execute tests. We’ll want to run some security scans and do other verification tasks, but we’ll define those jobs later. We’re also going to need to deploy our code to various environments, but that too will be tackled down the road. For now, let’s just add a dummy job so that GitLab doesn’t complain about the lack of any job definitions in our pipeline (if we didn’t, GitLab would actually consider the pipeline configuration file to be malformed, and the linter that appears at the top of the dedicated editor would squawk at us). Paste this below the stages: section:
# temporary job that we'll delete laterjob1: stage: build script: - echo "in job1"After committing this change, we navigate to CI/CD | Pipelines in the GitLab GUI to confirm that the pipeline ran—it should have triggered automatically when we committed the changes to .gitlab-ci.yml —and that it executed job1 on a shared runner without any problems. Of course, if you’re working on a GitLab instance that doesn’t offer any shared runners, you’ll need to create your own runners for this project before the pipeline will run. Fortunately, that’s the very next step in our workflow.
Creating a runner
Section titled “Creating a runner”As you know, users of the SaaS version of GitLab can run their pipelines on the GitLab Runners provided as part of their software subscription, but if you’re using a self-hosted version of GitLab, or if you want to run some pipelines on your own hardware to avoid exhausting your subscription’s GitLab Runner minutes, you’ll want to set up one or more of your own GitLab Runners. Let’s create some specific runners that are dedicated to our Hats for Cats project.
We decide to create runners on a spare Linux box that’s lying around. Remembering that the versions of the GitLab Runner binary that’s included in major Linux distribution repositories are often a few versions old, we consult the GitLab documentation to find out how to add the official GitLab repository to our Linux box’s package management system, download the latest GitLab Runner binary, install it as a service, and make sure it’s running. Since the exact process for this varies by the operating system and Linux distribution, we won’t include explicit instructions here.
GitLab Runner versions
Although GitLab Runners usually work even when they are a few minor versions away from the version of the GitLab instance (15.0 vs. 15.3, for example), they will operate most reliably if you keep the two versions in sync.
Once the gitlab-runner binary is installed on the computer that will host the runners, we need to create runners by registering them. Before doing so, we need to collect some information. We’ve already decided that the runners will be specific to the Hats for Cats project, so we navigate to Settings | CI/CD | Runners and make note of both the GitLab instance’s URL and the project’s registration token, as displayed on that screen. Let’s say that we’re using a self-hosted GitLab instance at https://gitlab.hats-for-cats.com, and that the registration token for the Hats for Cats project is abc123.
We decide to register two runners. We could call them anything we want, but we settle on the most obvious naming scheme: Hats for Cats 1 and Hats for Cats 2.
Next, we choose to use the Docker executor with both runners since that gives them the most flexibility: they can handle any CI/CD pipeline job because they can execute jobs within a Docker image that has all of the required tools already installed. We decide to specify alpine:latest as the default Docker image that the runners will use for jobs that don’t specify an image since that’s the smallest full-featured Linux distribution and therefore the quickest to download. Finally, we decide not to add any tags to the runners since we don’t intend either runner to be special-purpose in any way.
Of course, we can’t register runners with the Docker executor unless Docker is installed and running on the machine that’s hosting the runners. Installation instructions for Docker change occasionally and vary according to the operating system, so the official Docker documentation is your best source of information for this step.
Once Docker is up and running on the same host machine as the runners we could register a single runner interactively with gitlab-runner register, but in this case, let’s register the runners non-interactively by passing in all the details as options to a single terminal command. We register the first runner using this command on the Linux box that will host the runners (changing the --url and --registration-token values as appropriate):
sudo gitlab-runner register \ --non-interactive \ --url "https://gitlab.hats-for-cats.com/" \ --registration-token "abc123" \ --executor "docker" \ --docker-image "alpine:latest" \ --description "Hats for Cats 1"Do I need to use sudo?
Check the GitLab documentation to find out whether the gitlab-runner binary requires sudo or administrator permissions on your operating system; the command behaves differently on different platforms.
We can run the same command, changing the value of the --description option, to create the second runner.
Now that both runners have been registered, let’s double-check that they’re both up and running:
~$ sudo gitlab-runner verifyRuntime platform arch=amd64 os=linux pid=6365revision=bbcb5aba version=15.3.0Running in system-mode.Verifying runner... is alive runner=LuKAFv53Verifying runner... is alive runner=Rtq7yC5eFinally, let’s refresh the GitLab page that we reached via Settings | CI/CD | Runners and make sure both runners were able to check in with our GitLab instance and declare themselves ready to accept jobs from the Hats for Cats project. Here’s the relevant portion of that screen:

Figure 11.4 – Specific runners for the Hats for Cats project
Before proceeding, you might want to review the GitLab documentation to learn more about the concurrent and check_interval options in the master configuration file for your registered runners. Sometimes, adjusting the values of these two options can help runners pick up jobs more quickly. This configuration file is /etc/gitlab-runner/config.toml on Linux systems that run the gitlab-runner binary as root, but might exist in other locations when gitlab-runner is not run as root or is run on other operating systems. Running gitlab-runner list (with or without sudo, depending on how you registered your runners) should reveal the location of this file on your system.
Optional: disabling shared runners
If you’re following along in your own GitLab account, you might want to go to Settings | CI/CD | Runners and disable all the shared runners for the Hats for Cats project. This ensures that all of the project’s CI/CD pipeline jobs will be assigned to one of the two runners we just registered.
With a basic CI/CD pipeline configuration file in place and two runners registered, we’ve completed the setup of the basic pipeline infrastructure for our project. Now, we need to start filling the pipeline with jobs so that it can run all the tests and scans that make GitLab pipelines such a powerful software development tool.
Verifying your code
Section titled “Verifying your code”Let’s configure your pipeline so that it can verify your code by running functional tests, Code Quality scanning, and fuzz tests.
Adding functional tests to the pipeline
Section titled “Adding functional tests to the pipeline”Many teams start populating their pipelines by adding tasks to run automated functional tests to make sure their code is behaving the way it was designed to. You learned in previous chapters that there are many different sorts of functional tests. In this example, we’ll add some basic automated unit tests written with the pytest framework. Our project’s code is not yet complicated enough to require real unit tests, but for the sake of this example, we can add dummy tests so that GitLab can run them and display their results.
Before adding any tests, let’s make our login code slightly more complicated by adding a function that our tests can exercise, and a “to-do” comment that not only reminds us to flesh out this placeholder function later but also gives the Code Quality scanner something to detect when we add it to our pipeline down the road. Either locally (in which case you need to follow up with a commit and a push) or in the GitLab GUI, add this simple code to the add-login-feature branch’s copy of the login.py file:
def log_user_in(username, password): return (username == "Dana") and (password == "p@ssw0rd")# TODO: replace this placeholder code with real logicWe also need to declare a dependency on the pytest framework so that GitLab can install it before running the automated tests. Since this is a Python project, we declare this dependency in a new requirements.txt file at the top level of the project repository (still on the add-login-feature branch) with a single line of content:
pytest==7.1.3There are different ways to group automated unit tests in files and directories, but let’s keep things simple by adding a single test_login.py file at the root level of the repository, in the same add-login-feature branch that we’ve been working in.
We’ll put three tests in that file: one to check our login feature with good credentials, one to test logging in with a bad username, and one to test logging in with a bad password. We also need to import the function being tested so that it can be called by the unit tests. Add this code to test_login.py:
from login import log_user_indef test_login_good_credentials(): assert log_user_in("Dana", "p@ssw0rd")def test_login_bad_username(): assert not log_user_in("foo", "p@ssw0rd")def test_login_bad_password(): assert not log_user_in("Dana", "foo")Expanding your automated tests
These unit test examples are simpler than what you would typically use in a real project. Most unit test frameworks—regardless of which language they test—offer a wide variety of options and additional features to make your tests more comprehensive and powerful. We advise you to get to know your chosen test framework thoroughly since automated tests are such an important part of writing high-quality code.
Let’s add a job to the test stage of our pipeline to install the pytest library (as listed in requirements.txt) and run the tests. The job should ask the runner to execute its commands in a Docker container that has a recent version of Python. The pytest test framework automatically identifies any files that contain tests, so we don’t need to specify which test file to execute. We do need to tell pytest to generate an output file in the junit format, which is a test results format that GitLab knows how to ingest and display. Add this job definition to your existing .gitlab-ci.yml file on the add-login-feature branch:
unit-tests: stage: test image: python:3.10 script: - pip install -r requirements.txt - pytest --junit-xml=unit_test_results.xmlNow that we have defined a real job in our CI/CD pipeline, you can delete the definition for the temporary job1 job if you want to declutter the pipeline configuration file.
After the pipeline triggered by this commit completes, you’ll notice that even though the unit-tests job ran successfully, the pipeline details page doesn’t show any test results. That’s because we didn’t tell GitLab to preserve the results as an artifact. Let’s fix that by adding this code to the end of the unit-tests job definition, making sure all lines are indented correctly so that this code is understood by GitLab as part of the existing job definition:
artifacts: reports: junit: unit_test_results.xml when: alwaysThis should get us to a state where our unit tests are running and passing, which is a huge step forward in ensuring that our code lives up to its design specifications. If you’ve been following along, you should see output similar to this on the Tests tab of the most recent pipeline details page, showing that all three of our unit tests are running and passing:

Figure 11.5 – Test results on a pipeline details page
Once your automated tests pass, you can be confident that your code is doing what it was designed to do. However, just behaving correctly isn’t good enough: your code also needs to be written well. This helps to ensure that your code is readable and maintainable and will be less likely to develop bugs when you extend it with new features in the future, so now, let’s look at how to make sure your code is of high quality.
Adding Code Quality scanning to the pipeline
Section titled “Adding Code Quality scanning to the pipeline”Let’s add a task to our pipeline called Code Quality scanning, which will help us assess the quality of our code. As with all of GitLab’s scanners, Code Quality only works with certain computer languages. However—as described in the GitLab documentation for this feature—it supports all of the usual suspects, including Python.
We enable the scanner by including its template at the end of our project’s CI/CD configuration file, on the same add-login-feature branch where we’ve done all of our work:
include: - template: Code-Quality.gitlab-ci.ymlIf you inspect the pipeline that was triggered by committing this change to .gitlab-ci.yml, you’ll notice that the Code Quality scanning job failed. Don’t panic! This failure stems from Code Quality being something of an odd duck among GitLab’s scanners. It uses a technique called Docker-in-Docker, which requires that the runner assigned to the Code Quality job must be configured in a certain way. Although all shared runners provided by GitLab for SaaS customers are capable of running Code Quality jobs, the runners we registered earlier are not, so let’s create a new runner just to handle Code Quality. The GitLab documentation has more information about why the special configuration is necessary for this one type of scanning, but the details are not important for most GitLab users to understand. For the purposes of this demonstration, you just need to know that we can register a new runner called runner for code quality by typing this command on the same machine that’s hosting our other runners. Just like when we registered those runners, you’ll need to replace the --url and --registration-token values with the appropriate values for your system:
sudo gitlab-runner register \ --non-interactive \ --url "https://gitlab.hats-for-cats.com/" \ --registration-token "abc123" \ --executor "docker" \ --docker-image "docker:stable" \ --description "runner for code quality" \ --tag-list "code-quality-capable " \ --builds-dir "/tmp/builds" \ --docker-volumes "/cache"\ --docker-volumes "/tmp/builds:/tmp/builds" \ --docker-volumes "/var/run/docker.sock:/var/run/docker.sock"We configured this new runner with a code-quality-capable tag, which indicates that it can handle running Code Quality jobs. In order to make sure that our job is assigned to this specific runner, we need to override the Code Quality scanner’s job definition and assign it the same tag. While we tinker with the pipeline configuration file, let’s also disable a service that’s used by some runners to handle this job but that isn’t required by our runner. Add this job definition override to the end of your .``gitlab-ci.yml file:
code_quality: tags: - code-quality-capable services: [] # disable all servicesAs soon as we commit this last change, GitLab kicks off a pipeline run and presents the Code Quality results in a new Code Quality tab on the pipeline details page:

Figure 11.6 – Code Quality results on a pipeline details page
The Code Quality scanner reminds us to take care of the “to-do” comment we added to login.py earlier. Good advice, but let’s ignore it for now so we can move on to fuzz testing.
Adding a fuzz test to the pipeline
Section titled “Adding a fuzz test to the pipeline”Let’s set up a fuzz test to see whether the log_user_in function has any bugs that weren’t caught by our automated unit tests. Chapter 6 has a thorough description of the architectural elements involved in fuzz testing, so please refer back to that chapter if you need a refresher on what role each piece of code plays.
Reminder
Fuzz testing, like several other features discussed throughout the book, is only available with a GitLab Ultimate license. The GitLab documentation for each feature tells you which license tier that feature requires. The reason that this book doesn’t mention which licenses are required for which features is that GitLab frequently makes features available at lower tiers after they’ve been tested in higher tiers for a while.
The fuzz test will test the log_user_in function that lives in the login.py file. If you remember from Chapter 6, this code is called the code under test. As it’s written right now, this function is simple enough that we can tell just by looking at it that fuzz testing won’t find any problems. In other words, fuzz testing is overkill for such a simple function, but we can imagine that the function might become more complicated in the future, and as it becomes more complicated, it will be more likely to have bugs. Therefore, it’s a good idea to create a fuzz test for this simple code under test now so that it can find new bugs if we rewrite the function using more complicated and error-prone code in the future.
Let’s put the fuzz target code in a file called log_in_user_fuzz_target.py in the root of the repository’s add-login-feature branch. The file should contain this Python code:
from login import log_user_infrom pythonfuzz.main import PythonFuzz@PythonFuzzdef fuzz(bytes): try: string = str(bytes, 'UTF-8') divider = int(len(string) / 2) username = string[:divider] password = string[divider:] log_user_in(username, password) except UnicodeDecodeError: passif __name__ == '__main__': fuzz()Most of this is boilerplate code copied from sample fuzz targets in the GitLab documentation. The section that requires some programming creativity on our part is the logic in the fuzz() method. This code converts the random bytes sent by the fuzz engine into a random string, uses the first half of the string as the username and the second half as the password, and passes the username and password to the code under test.
Next, we need to include the GitLab fuzz testing template in the .gitlab-ci.yml file in the add-login-feature branch. Add the Coverage-Fuzzing.gitlab-ci.yml template within the existing include: section after the Code Quality template that we’ve already added. The complete include: section should end up looking like this:
include: - template: Code-Quality.gitlab-ci.yml - template: Coverage-Fuzzing.gitlab-ci.ymlBecause this template declares that fuzz test jobs run in their own fuzz stage, we must add that stage under the stages: keyword at the top of .gitlab-ci.yml in the add-login-feature branch. When you’re done, the complete stage definition section should look like this:
stages: - build - test - deploy - fuzzFinally, let’s create a pipeline job to trigger the fuzz test against our code under test. Add this job definition to the end of .gitlab-ci.yml on the add-login-feature branch:
fuzz-test-for-log-user-in: image: python:3.10 extends: .fuzz_base script: - pip install --extra-index-url https://gitlab.com/api/v4/projects/19904939/packages/pypi/simple pythonfuzz - ./gitlab-cov-fuzz run --engine pythonfuzz -- log_user_in_fuzz_target.pyIf you check the pipeline details page for the pipeline that was triggered by this commit, you should see jobs for unit tests, Code Quality, and now fuzz testing. If you click into the fuzz testing job to see its output, you’ll notice that it’s sending a seemingly infinite number of sets of random data to the code under test, with no signs of stopping. However, we know from Chapter 6 that it will stop as soon as it either finds a bug or times out. Because this pipeline is running on a non-default branch, the timeout is set to a hefty 60 minutes (default branches have 10-minute timeouts). While that might be a reasonable amount of time to uncover deep bugs in complicated code, it’s overkill for our dead-simple login code.
Let’s speed up our pipeline by configuring the job to send 1,000 sets of random bytes to the function being tested, and then stop if it hasn’t found any bugs. Of course, we can bump up the maximum number of random data sets later if we think more complicated login code would benefit from more thorough fuzz testing.
To limit the number of runs performed by the fuzz test, cancel the currently running pipeline (there’s no need to wait for it to time out after 60 minutes), and add these lines anywhere within the fuzz-test-for-log-user-in job definition. Make sure they’re indented correctly so that you’re defining a job-scoped variable and not a global variable:
variables: COVFUZZ_ARGS: '--runs=1000'Also in the fuzz-test-for-log-user-in job definition, replace the second line in the script: section with the following (note that this is all a single long line of code):
- ./gitlab-cov-fuzz run --engine pythonfuzz --additional-args $COVFUZZ_ARGS -- log_user_in_fuzz_target.pyIf you look at the output of a fuzz test job that runs after these changes, you’ll see that it stops after the first 1,000 unsuccessful attempts to find a bug. You’ll also notice that no Security tab shows up on the pipeline details page because the fuzz test has no findings to report (fuzz testing is considered by GitLab to be a type of security scanner rather than a type of code quality scanner, despite its aim of finding bugs rather than security vulnerabilities).
Our pipeline is really coming along! Let’s keep the momentum going by adding some security scanners.
Securing your code
Section titled “Securing your code”For this sample use case, you’re going to add four scanners to your pipeline: Static Application Security Testing (SAST), Secret Detection, Dependency Scanning, and License Compliance. You’ll also review how to add a third-party scanner.
Adding SAST to the pipeline
Section titled “Adding SAST to the pipeline”In general, adding a GitLab-provided security scanner to a pipeline is a trivial process. To enable SAST and make sure our Hats for Cats source code doesn’t contain security vulnerabilities, we simply need to include a new template in .gitlab-ci.yml on the add-login-feature branch. Add this line anywhere within the existing include: section, making sure that it’s indented correctly:
- template: Security/SAST.gitlab-ci.ymlThis enables SAST, but we also want to configure it so that it doesn’t scan our automated test file or our fuzz target file. The GitLab documentation tells us which variable to set to accomplish this. Add a new section to the end of .gitlab-ci.yml in order to set the correct global variable:
variables: SAST_EXCLUDED_PATHS: "test_login.py,log_user_in_fuzz_target.py"Note
There are only two lines in this code: the second line is long enough that it wraps in a possibly confusing way.
Wait for the pipeline to finish and check out its details page. Under the Security tab, you’ll see that SAST has reported a vulnerability about a hardcoded password in login.py. We will ignore this vulnerability for the sake of keeping the demo moving along, but it’s comforting to see that SAST is up and running:

Figure 11.7 – SAST results on a pipeline details page
Adding Secret Detection to the pipeline
Section titled “Adding Secret Detection to the pipeline”Let’s add SAST’s cousin, Secret Detection, to our CI/CD pipeline. On the add-login-feature branch, include a new template in the existing include: section of .gitlab-ci.yml. Double-check your indentation and we should be good to go:
- template: Security/Secret-Detection.gitlab-ci.ymlWe should consider some of the configuration options for Secret Detection. There’s no need to enable “historic” mode since our repository only has a few commits and we’re confident that we haven’t added any secrets to it so far. However, it makes sense to tell Secret Detection not to scan our test files since any secrets kept in them will be made-up secrets for testing purposes only. In the future, we might group all of our test-related code into a tests/ directory, but since we don’t have that directory yet, we’ll explicitly exclude individual files. Do this by overriding the appropriate job definition and setting a job-scoped variable:
secret_detection: variables: SECRET_DETECTION_EXCLUDED_PATHS: "login_test.py,log_user_in_fuzz_target.py"Note
The last line in this code snippet is actually one line that wraps awkwardly, so be sure to paste it in as a single line.
Finally, let’s give Secret Detection a secret to detect. Let’s pretend that our intern Carl accidentally pastes an AWS access token into login.py. Add this line to the end of that file on the add-login-feature branch:
AWS_access_token = 'AKIAABCDEFGH12345678'When the resulting pipeline finishes, check that the Security tab on its pipeline details page reports a security vulnerability from Secret Detection:

Figure 11.8 – Secret Detection results on a pipeline details page
Adding Dependency Scanning to the pipeline
Section titled “Adding Dependency Scanning to the pipeline”So far, the only dependency that our project has declared is the pytest automated testing framework. Since that dependency won’t be used in production, we probably don’t care if it has security vulnerabilities, but it’s smart to add Dependency Scanning to our pipeline so that we’ll be alerted to any security problems in dependencies that we might add in the future.
On the add-login-feature branch, add this new line to the existing include: section:
- template: Security/Dependency-Scanning.gitlab-ci.ymlNow that Dependency Scanning is up and running, let’s give it something to find. Let’s say that the Hats for Cats web app will be built on the Django web app framework for Python and that we decide to use an older version of Django that we’re already comfortable with. Add this new line to the end of the existing requirements.txt file on the add-login-feature branch, noting that it should be flush-left rather than indented:
django==3.2Since this version is significantly behind the current version of 4.1.1, we might expect Dependency Scanning to find security vulnerabilities in it. Lo and behold, if we trigger a pipeline and then look at the Security tab on the pipeline details page, we see at least 15 potential problems with our dependency! You might find it helpful to use the Severity and Tool filters above the results table to reduce clutter and focus on the most important vulnerabilities:

Figure 11.9 – Critical severity Dependency Scanning results on a pipeline details page
Adding License Compliance to the pipeline
Section titled “Adding License Compliance to the pipeline”Since we’ve declared a few software dependencies for the Hats for Cats project, it’s a good idea to add License Compliance scanning to the pipeline so that we don’t run afoul of problems with incompatible licenses. On the add-login-feature branch, add a new template to the include: section, double-checking your indentation:
- template: Security/License-Scanning.gitlab-ci.ymlOn the details page for the pipeline that was triggered by this edit, click on the new Licenses tab to see the different software licenses used by the Django and pytest libraries, and also by their dependencies. Interestingly, the License Compliance scanner was unable to figure out what license Django itself uses, so it’s listed as unknown. Normally, you would consult with your legal team to decide whether to explicitly allow or deny each of these licenses by clicking on the Manage licenses button on this page, but in order to keep the demo moving along, we’ll skip that step.

Figure 11.10 – Licenses used by project dependencies
Some scanners are excluded from this demo
You may have noticed that we didn’t add DAST, Container Scanning, or Infrastructure as Code Scanning to our pipeline. We’ve excluded them partly because the Hats for Cats demo web app doesn’t include enough functioning code to package into a Docker image and interact with as a normal user would, and because we don’t need to use infrastructure-as-code tools to configure any new machines as part of the Hats for Cats project. Equally, we also want to show that not all scanners are relevant to all projects. You should enable and configure only the scanners that make sense for your particular project; adding unnecessary scanners complicates your CI/CD pipeline configuration file and bogs down your pipeline without adding any value.
Integrating a third-party security scanner into the pipeline
Section titled “Integrating a third-party security scanner into the pipeline”Imagine that there’s a third-party security scanner that we’ve used in the past and want to add to our Hats for Cats project pipeline. It’s called gui-proofreader and is a form of SAST scanning that checks for typos in user-facing text. Let’s say that it’s available as a Docker image on Docker Hub and that you can run the scanner against all the code in your repository by cloning the repository to a gui-proofreader Docker container and running the proofread-my-gui.sh shell script within that container.
Let’s add a job to our CI/CD pipeline that does exactly that. Add this job definition at the end of .gitlab-ci.yml on the add-login-feature branch:
proofread: stage: test image: gui-proofreader:latest script: - ./proofread-my-gui.shThat’s enough to trigger the third-party scanner, but we still need to integrate its output into the GitLab security reports. This step is simple: declare the scanner’s output as an artifact that contains a SAST report (there are several report types we could assign it to, but this particular scanner feels like a flavor of SAST, so let’s use that). Add this code to the bottom of the definition of the proofread job:
artifacts: reports: sast: gui-proofreader-report.jsonOf course, we would need to adjust the name of the results file specified in the job definition to match whatever file name the gui-proofreader scanner actually generates. Also, GitLab will only be able to parse and display those results if the file conforms to GitLab’s official JSON schema for SAST scanners (the details of the various security scanner results schemas are given in the GitLab documentation for each type of scanner). If the gui-proofreader scanner can’t generate output using that schema, we will need to write a small script that converts the scanner’s output into a JSON file with the appropriate schema, run that script in a separate job in a later pipeline stage, and move the artifact declaration from the proofread job into the new script’s job.
Since this job won’t work as written—as there’s no Docker image called gui-proofeader on Docker Hub—it’s best to either exclude this job definition from your .gitlab-ci.yml file or to comment it out. However, if you ever do want to integrate a third-party scanner, this is a model you can follow.
Improving your pipeline
Section titled “Improving your pipeline”You’ve set up a pipeline to make sure your code is of high quality and doesn’t have security vulnerabilities. In many cases, you can stop there. However, for this sample use case, you’ll go a step further and look into using a DAG to speed up the pipeline. You’ll also see whether it’s worth splitting the pipeline’s configuration code into multiple files to improve readability and maintainability.
Using a DAG to speed up the pipeline
Section titled “Using a DAG to speed up the pipeline”Our pipeline isn’t complicated enough to justify converting it into a DAG quite yet, but if we continue to add more jobs, we’ll eventually want to use DAGs for some or all of it for performance reasons. Let’s preview this by using the needs keyword now to add some DAG elements to our pipeline.
First, let’s say that we want the code_quality job to run only after the unit-tests job passes. After all, we might think that our code needs to work correctly before we worry about making it pretty and maintainable. We could accomplish that by putting code_quality in a later stage than unit-tests, but since they both feel like they conceptually belong to the test stage, let’s keep them in that stage and instead set up a DAG to enforce the job order we want. Add this code to the end of the code_quality job definition:
needs: ["unit-tests"]Now that one mini-DAG is set up, let’s make another. Perhaps we’re unhappy with the job that runs our fuzz test running after all of the other scanners are complete. This happens because the fuzz test job is in its own fuzz stage, which runs after the test stage. We could override its job definition and move it to the test stage, but in this case, we decide to use the DAG feature to allow it to run as soon as the pipeline starts instead of waiting around for its pipeline stage to be called. Add this code to the end of the job definition for fuzz-test-for-log-user-in:
needs: []When we run a pipeline that contains these edits, we see exactly the behavior we’d hoped for: fuzz-test-for-log-user-in runs immediately and code_quality is paused until unit-tests completes:

Figure 11.11 – DAG causing jobs to run not according to stage order
We can double-check our understanding of the pipeline’s flow by clicking on Job dependencies in the pipeline details page and toggling Show dependencies on. After the pipeline finishes, we can see which jobs ran in what order, due to “needs” relationships:

Figure 11.12 – Job dependencies view of the completed pipeline
Breaking the pipeline into several files
Section titled “Breaking the pipeline into several files”Now that we’ve set up our project’s CI/CD pipeline to verify and secure our code, let’s see whether we can keep our pipeline configuration well organized and easy to read. As the file stands right now, it’s much simpler than .gitlab-ci.yml files for real-world projects tend to be, and normally we would suggest that our configuration file is clean enough as is and doesn’t warrant any refactoring. However, in order to demonstrate how we might maintain it as it becomes more complicated, let’s separate it into two files anyway.
Say we decide to standardize our security scanning process across all of our team’s projects. A good way to do this is to separate our security-related job definitions into a different CI/CD pipeline configuration file, and then include it in each project’s CI/CD configuration file.
Create a new file called security-jobs.yml in the root of the Hats for Cats project’s repository, on the add-login-feature branch. Add this line to the new file:
include:Cut these lines from the include: section of .gitlab-ci.yml and paste them into the include: section of security-jobs.yml:
- template: Security/SAST.gitlab-ci.yml- template: Security/Secret-Detection.gitlab-ci.yml- template: Security/Dependency-Scanning.gitlab-ci.yml- template: Security/License-Scanning.gitlab-ci.ymlFinally, include the new configuration file in the original configuration file by adding this line anywhere within the include: section of .gitlab-ci.yml:
- local: security-jobs.ymlWhen the pipeline runs after you make these changes, you’ll see that it behaves exactly like it did before we refactored its configuration files. This demonstrates how you can break a long, complicated CI/CD pipeline configuration file into two or more subfiles, each of which can be reused in multiple projects if desired.
Note that because security-jobs.yml is in the same project as .gitlab-ci.yml, we used the include: keyword and local: sub-keyword to point to it. If we were including it from a different project, we’d need to use the include: and file: keywords instead. The GitLab documentation has more information on how to use different forms of include: in different situations, and is well worth reviewing.
Delivering your code to the right environment
Section titled “Delivering your code to the right environment”Your code is written, verified, and secured. The only step left is to deploy it.
Deploying the code
Section titled “Deploying the code”The final task of our pipeline is to deploy the Hats for Cats code to the right environment. Normally, we’d define separate jobs to deploy code to a review environment, the pre-production environment, or the production environment. Then, we would use GitLab’s rules: and if: keywords to control which one of those three jobs should run, depending on which Git branch the pipeline was running on.
To keep things simple in this example, let’s just walk through how to deploy it to the production environment. We’ll imagine that we want this to happen whenever we run the pipeline on the production branch.
As you learned in Chapter 8, there are countless techniques you can use to deploy code. Which technique you choose depends largely on what sort of environment you’re deploying to: an AWS EC2 VM, a Kubernetes cluster, a bare-metal machine, or something else. For this example, let’s imagine that we’re deploying our code to a machine with an IP address of 192.168.0.1, which is running an Apache web server that hosts the Hats for Cats site. Furthermore, let’s say that to deploy a new version of our web app, we simply need to copy our files to the right directory on the Apache host machine and issue a command to restart Apache.
This deployment process is very straightforward. Add this job definition to .gitlab-ci.yml on the add-login-feature branch:
deploy-to-production: stage: deploy image: registry.hats-for-cats.com/ubuntu-with-deploy-key:latest rules: - if: $CI_COMMIT_REF_NAME == "production" script: - scp -r . [email protected]:/home/hats-for-cats/production - ssh [email protected] service apache2 restartYou might wonder about the image specified in this job definition. There are several ways we could set up the public/private SSH key pair that the scp command relies on, but one way to accomplish this involves making our own Docker image, which we store in an internal Docker container registry. Of course, we could also store this image within the container registry of this project or a different project, but for now, let’s assume we have a separate, company-wide Docker container registry set up. The image contains a Linux distribution with the OpenSSH library (which provides the scp command) and also has a public/private key pair that was generated in advance. We then configure the Apache host computer to accept the private key from that Docker image. With that infrastructure in place, the GitLab Runner can execute scp from within the special Docker image, and the key pair takes care of authenticating to the Apache host.
The rules: and if: keywords in this job definition prevent the job from running unless the pipeline runs on the production branch. As mentioned previously, we’d normally create additional definitions for the deploy-to-review and deploy-to-staging jobs, which would each use different logic to specify which branches they should run on.
Since our deploy-to-production job won’t run on the add-login-feature branch to which we’re committing the edited .gitlab-ci.yml file, we won’t see it run when the commit triggers a new pipeline. However, we do want to make sure it deploys code correctly, so how can we test this job?
First, we need to merge the add-login-feature branch into the main branch. We’re done adding our code and configuring our pipeline, so now’s a perfect time to merge anyway. Navigate to our add login feature MR, removing Draft: from the beginning of its title to make it mergeable, and click on the Merge button. Since we linked this MR to the Allow user to log in issue, merging the MR will automatically close the issue as well.
This merge adds all of our pipeline configuration details to the main branch. It runs a pipeline on that branch, but we still won’t see the deploy-to-production job run since the pipeline isn’t running on the production branch. Navigate to Repository | Branches in the left-hand navigation pane and create a new branch called production. Creating this branch triggers a new pipeline. Finally, we’ll be able to see the deploy-to-production job running in that pipeline. Of course, we shouldn’t expect it to actually pass because we haven’t created the Docker image specified in the job definition, and we don’t have an actual production environment living at 192.168.0.1, but at least we can see that the job runs, which is all that we can realistically test at this point. Declare victory and crack open an iced beverage of your choice. This concludes the example workflow for the Hats for Cats project.
Summary
Section titled “Summary”In this chapter, we made a group and project to hold our code and other related components and made issues to plan and track our work. Then, we cloned the project’s repository to a local workstation so that we could write code using our favorite desktop tools. Then, we made a branch to commit our work to and an MR for that branch, linked it to an associated issue, and committed and pushed code for a new software feature. We set up a bare-bones CI/CD pipeline to which we can add a variety of tasks and registered specific runners for the project’s pipeline. We added automated unit tests to the pipeline to make sure the code satisfies its design specifications, as well as Code Quality scanning, and registered a special runner just for that scanner. We also added a fuzz test to the pipeline to find bugs in critical functions, and SAST to the pipeline to find security vulnerabilities in our code. We added Secret Detection to the pipeline to find any secrets that were inadvertently committed to the repository and added Dependency Scanning to the pipeline to learn about any security problems in the third-party libraries that our project relies on. Then, we added License Compliance to the pipeline to exclude third-party libraries that use software licenses that are incompatible with our project’s own license and integrated a third-party scanner into the pipeline, which is triggered automatically and integrates its results into existing GitLab dashboards and reports. We rewrote parts of the pipeline as a DAG to improve its performance and separated the pipeline configuration code into multiple files to improve its readability and maintainability and added logic so that code on the correct branch is automatically deployed to the production environment.
Although we covered a lot of ground, it’s important to remember that this was just one example workflow. We used only a portion of the countless features offered by GitLab CI/CD pipelines, and we barely investigated any of the different configuration options for those features. There are often multiple ways of accomplishing the same tasks in a pipeline, and there are limitless ways you can organize those tasks into stages and jobs, so don’t feel like this example is the One True Way to use GitLab CI/CD pipelines. Be creative, experiment, have fun figuring out what pipeline features are most useful for your projects, and enjoy discovering which configuration settings for those features make the most sense for you and your team.
In the next chapter, we will learn about troubleshooting and the road ahead with GitLab.