Skip to content
ImagineWorld

Packaging and Deploying Code

node_idnode-book_automating-devops-with-gitlab_chapter-08-packaging-and-deploying-code
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titlePackaging and Deploying Code
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 8 — Packaging and Deploying Code

Section titled “Chapter 8 — Packaging and Deploying Code”

In the previous chapters, you learned how to use GitLab for source code management, as well as to set up CI/CD pipelines that build, test, and perform security scanning against the code you’ve checked in. You have hopefully now developed a confident understanding of both the infrastructure around GitLab CI/CD and the syntax used to author pipelines.

In this chapter, we will continue our journey through the stages of software development, focusing now on packaging and deploying code. We will use a combination of GitLab’s built-in features and common industry tools to deploy our code to an endpoint or environment. The goal is to answer the question, how do we make the application we have built and tested available to our users?

This chapter will introduce new vocabulary, adding to our knowledge of GitLab CI/CD syntax. It will also mention, and the examples will use, third-party tools such as Docker, as well as cloud service providers such as Google Cloud Platform. Since this book’s core focus is on GitLab’s features and we don’t have the space for a technical deep dive into every tool that could be used with GitLab, you may be unfamiliar with some of the technologies referenced in this chapter. We will therefore strive to use industry-standard language, focus on each tool’s integration with GitLab, and provide examples that can be replicated without requiring further knowledge from the reader. After completing this chapter, you will be equipped with the skills needed to use GitLab’s native package and container registry features for hosting completed builds. You will also extend your knowledge of GitLab CI/CD to include deploying to review and production environments, using traditional or cloud-native infrastructures.

Here is how we’ll cover the topics in this chapter:

  • Storing code in GitLab’s package registry for later re-use
  • Storing code in GitLab’s container and package registries for later deployment
  • Deploying to different environments using GitLab Flow
  • Deploying to a review app for testing
  • Deploying to real-world production environments
  • Deploying to a Kubernetes cluster

Like the previous chapters, you’ll get the most out of this chapter if you have an account on a GitLab instance (SaaS or self-managed). Moreover, the topics and examples in this chapter will increasingly focus on deploying to environments that live outside GitLab. The infrastructure tools that are referenced include the following:

  • A server hosting GitLab (or GitLab.com)
  • Self-hosted runners (or SaaS runners hosted on GitLab.com)
  • Docker (also available on SaaS runners hosted on Gitlab.com)
  • Kubernetes
  • Cloud platform services (such as Amazon Web Services, Google Cloud Platform, or Heroku)

If you wish to minimize the amount of tooling you need to install and maintain yourself, we recommend using GitLab.com with SaaS runners. We also recommend creating an account on a cloud service platform if you wish to practice deploying to live or complex infrastructure. Just be aware of the potential charges when using these services.

Storing code in GitLab’s package registry for later re-use

Section titled “Storing code in GitLab’s package registry for later re-use”

As part of the goal of serving as a complete DevOps platform, GitLab includes the option to enable package and container registries in each project. The package registry supports hosting software packages and language packs in a variety of formats, and the container registry serves as a repository of purpose-built container images. These features allow teams to conveniently host, organize, and version-control completed builds alongside their source code. We will discuss the package and container registries in turn.

Locating GitLab’s container and package registries

Section titled “Locating GitLab’s container and package registries”

GitLab projects technically support three types of built-in registries. They are package, container, and infrastructure registries that can be used to store completed code, whether for use by end users or other software projects. This book will focus on the package and container registries; the infrastructure registry is a recent addition to GitLab that is specifically for hosting Terraform modules. GitLab also supports pushing artifacts to external or third-party registries, though that is beyond the scope of what we will cover here.

Figure 8*.1* shows where GitLab’s packages and container registries can be found at both the project and group level, under Packages and registries in the left navigation pane.

Figure 8.1 – Packages and registries in the left sidebar

Figure 8.1 – Packages and registries in the left sidebar

When you hover over Packages and registries, you will see that each of the package, container, and infrastructure registries have a dedicated page to navigate to, as shown in Figure 8*.2*.

Figure 8.2 – Packages and registries sub-menu items

Figure 8.2 – Packages and registries sub-menu items

If we have not yet configured or pushed artifacts to any of the registries, we will see an appropriate message when we navigate to the registry page. Figure 8*.3* shows the message we see on the Package Registry page, along with a reference to the GitLab documentation for using the package registry.

Figure 8.3 – Project package registry with no packages

Figure 8.3 – Project package registry with no packages

Figure 8*.4* shows us an unpopulated Container Registry. Here, GitLab suggests Docker commands we could use to build a containerized version of our application that we then push to the container registry.

Figure 8.4 – Project container registry with no container images

Figure 8.4 – Project container registry with no container images

We will soon see that a typical way to push to GitLab’s registries is to configure CI/CD jobs that execute commands to build an artifact, authenticate it with the registry, and push the artifact to the registry, often using GitLab’s API.

The package registry is enabled by default in GitLab, though it can be disabled by GitLab administrators at the instance level. In project settings, you can also choose to toggle the package registry feature on or off under Settings | General | Visibility, project features, permissions. If Packages is toggled off, the feature will not be available in the left sidebar. Figure 8*.5* shows where the package registry can be enabled or disabled in the project settings.

Figure 8.5 – Enabling the package registry in project settings

Figure 8.5 – Enabling the package registry in project settings

The question now arises, how do we use the package registry? That is, how do we populate it with our software? There are two primary steps to populate the package registry: authenticate to the registry, and build and upload packages using CI/CD jobs. But before diving into those steps, let’s first list the package formats supported by GitLab.

As of this writing, the following package manager formats are generally available and fully supported in GitLab’s package registry:

  • Generic packages
  • Maven
  • npm
  • NuGet
  • PyPI

The following package formats are either behind a feature flag or have known issues with their use:

  • Composer
  • Conan
  • Debian
  • Go
  • Helm
  • Ruby Gems

Each package manager has its own configuration format and syntax. To maintain consistency, as well as to keep our focus on the concepts underlying GitLab’s package, we will show examples using generic package formats. We will start with authenticating to GitLab’s package registry.

We mentioned earlier in this chapter that working with GitLab’s registries takes place largely through CI/CD jobs. The actions of authenticating, uploading to, and using packages from the package registry should be represented by job tasks defined in GitLab CI/CD configurations. In general, you can authenticate to GitLab’s package registry with one of the following four types of credentials:

  • A personal access token, to authenticate with a user’s permissions
  • A project deploy token, for accessing all packages in a project
  • A group deploy token, for accessing all packages in all projects in a group or its subgroups
  • A job token, for accessing packages in the project for which the CI/CD job is defined

Deploy tokens and job tokens are not tied to users

Unlike personal access tokens, deploy tokens and job tokens are special kinds of GitLab credentials that are not tied to a particular user, but rather can serve as an alternative way to authenticate without specifying user credentials. Deploy tokens and job tokens are often used to programmatically access a repository, or in our case, read and write to the package registry.

In our example, we’ll create a project-level deploy token in the Hats for Cats project. Figure 8*.6* shows where we can create a new deploy token under project Settings | Repository | Deploy Tokens. Here, we can give the token a human-readable name, an optional expiration date, and an optional username that’s specific to the token (if we don’t enter an optional username, GitLab will auto-generate one for us).

Finally, we select which permissions we want to grant the token. The permission names can appear slightly ambiguous, but read_registry and write_registry refer to reading and writing to the container registry only, while read_package_registry and write_package_registry refer to reading and writing to the package registry.

Figure 8.6 – Creating a new deploy token

Figure 8.6 – Creating a new deploy token

Once we create a deploy token, GitLab will provide a password that we’ll need to save somewhere safe (see Figure 8*.7*). We will use the deploy token password to authenticate our commands to the package or container registry.

Figure 8.7 – Deploy token password

Figure 8.7 – Deploy token password

Don’t forget to save your deploy token!

Be sure to save the password for the deploy token somewhere safe and secure! Once you leave the page, you will not be able to recover the password, as GitLab will not persistently store the credential.

After you finish creating the deploy token and saving the password, GitLab will show the token and its details under Active Deploy Tokens, as shown in Figure 8*.8*. A project maintainer or owner can choose to revoke the token if it should no longer be used.

Figure 8.8 – Active deploy tokens

Figure 8.8 – Active deploy tokens

We can now use the token we created to authenticate to the registry. The exact syntax we’d use for authentication would depend on our package manager, that is, the type of package we are creating or using. In the simplest case, we may include our credentials in the header of a curl command, as shown here:

curl --user "hfc-generic-build:<deploy token password>" ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/stable-releases/0.0.1/my_app.tar.gz

When run in a CI/CD job, the preceding command authenticates to the project’s package registry in which the pipeline is running. The authentication credentials are provided by the --user flag, where we provide the username and password (shown as a placeholder here) for our deploy key. The output of the command will be to download the my_app.tar.gz package.

Using a deploy key is a programmatic way to pull or download from the registry. Downloading package files can also be done via the UI. Figure 8*.9* shows an example of a stable_releases package, version 0.0.1, that has been added to the package registry.

Figure 8.9 – Entry in the package registry

Figure 8.9 – Entry in the package registry

If we click on stable_releases, we see downloadable application files under the Assets heading (see Figure 8*.10*). We see the filenames (and file types by their extensions), size, and creation date. Selecting the filename downloads the file to your local computer. Under History, we see when it was published to the registry, which pipeline build pushed the package, which commit launched the pipeline, and the package name and version.

Figure 8.10 – Package files and build history

Figure 8.10 – Package files and build history

Now that we understand how to authenticate to and access packages in the package registry, we will now use CI/CD jobs to build, push, and update packages in the registry.

Building and pushing packages to the package registry

Section titled “Building and pushing packages to the package registry”

As we’ve mentioned several times already, GitLab recommends using CI/CD jobs to build and publish to the registry. Technically, writing to the registry can just take place via API calls, so GitLab CI/CD isn’t strictly required. However, build and artifact management is well suited to GitLab Flow, and it is helpful to have the process standardized in a similar manner to your other software development workflows. For that reason, we will create a CI/CD pipeline to build and push to the registry.

The exact job syntax will be dependent on the programming languages and package managers you use to build software. The GitLab documentation has specific syntax examples for authenticating, reading, and writing to the registry using Python, Maven, and other tools. To keep things conceptual, and because we don’t have the space to showcase every supported language or tool, we will use generic packages as our example, and our commands will be curl -style API calls.

A CI/CD configuration may look like the following:

stages:
- build
- publish
build_app:
stage: build
script:
- make my_app
- tar -czvf my_app.tar.gz .
artifacts:
paths:
- my_app.tar.gz
publish_to_registry:
stage: publish
script:
- $PACKAGE_FILE=$(ls | grep *.tar.gz)
- curl --user "hfc-generic-build:<deploy token password>" --upload-file my_app.tar.gz "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/stable_releases/0.0.1/$PACKAGE_FILE"
dependencies:
- build_app

The preceding example .gitlab-ci.yml content contains two stages: a build stage that compiles a C-style application and a publish stage that pushes the build artifact to the package registry. The build stage contains one job that builds our code. We then create an archive file containing the completed build and supporting files. The archive file is specified as an artifact in the build job so that the downstream publish job will have access to it.

The publish_to_registry job authenticates to the registry and uploads the build artifact. Note the presence of some dynamic CI/CD variables in the curl command (that is, the terms beginning with CI_). These variables are a convenient way to reference the correct URL and path to the registry in your project. Note we also categorize the build as a generic package, part of “stable release” version 0.0.1.

We might also add a Unix timestamp to distinguish between different builds in the registry. We can modify the build job as follows to include a timestamp in the artifact filename:

build_app:
stage: build
script:
- make my_app
- TIMESTAMP=$(date +%s)
- tar -czvf my_app_$TIMESTAMP.tar.gz .
artifacts:
paths:
- ./*.tar.gz

Figure 8*.11* shows the updated file asset in the registry. Note the timestamp in the filename in the tar command in the build script. The archive size and creation date are also shown. A developer can then click the filename to download the archive, which they can then unpack on their local system.

Figure 8.11 – File in the package registry with a timestamp

Figure 8.11 – File in the package registry with a timestamp

Building and pushing packages to the container registry

Section titled “Building and pushing packages to the container registry”

GitLab also has a container registry for storing Docker images. Like the package registry, Docker images can be created and pushed to the registry with CI/CD jobs. Authentication is conceptually similar to the package registry, but you’d use container platform tools such as Docker to authenticate, build, push, and pull container images.

The following Docker command can be used to authenticate to the container registry, using our deploy token from earlier. We will use similar Docker commands to also build a containerized version of our application and push it to the registry:

docker login -–username "hfc-generic-build" --password "eBYj_qvLTFSMcFrS-4tA" $CI_REGISTRY

Our CI/CD job for “containerizing” our application and pushing it to the registry might look like the following:

publish_to_container_registry:
stage: publish
image: docker:stable
services:
- docker:dind
variables:
IMAGE: $CI_REGISTRY_IMAGE/my_app/0.0.1
script:
- docker login -u "hfc-generic-build" -p "<deploy token password>" $CI_REGISTRY
- docker build -t $IMAGE .
- docker push $IMAGE

Let’s explain what is happening in the preceding CI/CD job, step by step:

  1. We name the job publish_to_container_registry as part of the publish stage.
  2. We then include two containers in the CI/CD job runtime environment: a container with the official Docker tooling (image: docker:stable) and a service container with “Docker-in-Docker” tooling (docker:dind). The latter container type allows us to build containers inside our already-containerized CI/CD job environment (hence the Docker- in -Docker moniker).
  3. Next, we define a variable called IMAGE that will specify the name of our container image, as well as its destination endpoint in the container registry. The IMAGE variable will be referenced as arguments to the docker command.
  4. Finally, the script section of our CI/CD job contains three commands:
    • The first command, docker login, authenticates to the container registry using our deploy token
      • The second command, docker build, builds a containerized version of our application
      • The final command, docker push, then pushes the newly built container image to the container registry

Be careful when building containers with Docker-in-Docker

While it’s simple and straightforward, Docker-in-Docker uses the --docker-privileged flag by default, which can give the service running the containers root access to the host machine. If this is a security concern, GitLab also provides instructions for using a build tool called kaniko to build container images from a Dockerfile. See the GitLab documentation for more details.

It turns out that if we just add the preceding job to our CI/CD pipeline configuration and then run the pipeline, the job will fail. That is because we are missing another required component of building a container image. A file in our repository called Dockerfile is required to act as a “recipe” for how our container image will be built and what it should contain. Normally, a Dockerfile will contain instructions such as dependencies that should be installed, services that should be started, or ports that should be open. In this example, we will keep the Dockerfile extremely simple. A very minimal Dockerfile might contain the following:

FROM alpine:latest
# copy all of the files in this project into the Docker image
RUN mkdir public-app/
ADD . public-app/
WORKDIR public-app

The preceding Dockerfile does the following:

  • It uses a minimal Linux distribution called Alpine Linux as the base operating system for the container we are building
  • It creates a directory in the container called public-app/
  • It puts all our repository files in the public-app/ directory
  • It makes public-app/ the working directory when the container is launched

Figure 8*.12* shows how our project repository might look after we update our .gitlab-ci.yml file and create the Dockerfile.

Figure 8.12 – Our repository with the Dockerfile

Figure 8.12 – Our repository with the Dockerfile

Now, when we run a CI/CD pipeline, we can see the Docker commands represented in the publish_to_container_registry job log, as shown in the following screenshot (Figure 8*.13*). Notice how the output of the docker build command shows it following the recipe we specified in Dockerfile. The job script ends with confirmation that the container image was pushed to the project’s container registry.

Figure 8.13 – Job log for publishing to the container registry

Figure 8.13 – Job log for publishing to the container registry

Checking the container registry, we in fact see a reference to the container name as we specified in the CI/CD job (Figure 8*.14*).

Figure 8.14 – Image repository in the container registry

Figure 8.14 – Image repository in the container registry

If we click on the container name, we can see the builds themselves (Figure 8*.15*).

Figure 8.15 – Latest artifact in the project container registry

Figure 8.15 – Latest artifact in the project container registry

So far, everything we have discussed covers finding, authenticating to, and writing to GitLab’s package and container registries. In the next section of this chapter, we will actually use and deploy the assets we have created and uploaded.

Storing code in GitLab’s container and package registries for later deployment

Section titled “Storing code in GitLab’s container and package registries for later deployment”

GitLab’s package and container registries are useful not only for making software available for users to download but also for storing packages and libraries for use in CI/CD pipelines, or for deployment to an environment. In this section, we will discuss how to programmatically interact with the registries via CI/CD jobs.

In the previous section, we built a containerized version of our app and pushed the image to GitLab’s container registry. Recall that the CI/CD jobs we used to build the container image themselves run in containers, hence the reference to terms such as docker:stable and docker:dnd. In this example, we are pulling from a public container registry, that is, Docker Hub.

However, we can also pull container images we have pushed to GitLab’s container registry and use them as the basis for running our CI/CD jobs. We can use them in our pipelines just as we did with public container images, using the image keyword, like in the following snippet:

use_container_from_registry:
stage: run
image: registry.gitlab.com/nlotz1/pet-fashion/hats-for-cats/my_app/0.0.1:latest
script:
- ls –al # Show the current directory as our container's working directory

Figure 8*.16* shows our job output when we pull our container from the local registry to run our job.

.

Figure 8.16 – Using a local container in a CI/CD job

Figure 8.16 – Using a local container in a CI/CD job

Note that the job log shows GitLab pulling the image from the container registry, as well as the contents of the container’s filesystem (that is, the files we included when we built the container in the first place).

Using packages in the package registry follows a similar theme as publishing packages to the registry. The exact step and syntax for pulling from the registry will depend on the package type. In general, you’ll be required to specify the group and project where the package lives (i.e., the namespace in GitLab), the package name, and the package version. Consistent with the example from earlier, we might use a CI/CD job to pull down and run a generic package from our registry:

use_package_from_registry:
stage: run_package
script:
- 'wget --header="JOB-TOKEN: $CI_JOB_TOKEN" ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/stable_releases/0.0.1/my_app_1665515895.tar.gz'
- tar -xvf my_app_1665515895.tar.gz
- ./my_app

The job log in Figure 8*.17* shows the output of authenticating and pulling down the package file via GitLab’s API. In this example, the package is then extracted from its archive file and run.

Figure 8.17 – Using the package from the registry in a CI/CD job

Figure 8.17 – Using the package from the registry in a CI/CD job

GitLab’s documentation shows different steps to authenticate and download packages for different package managers, but the principles remain the same.

Now that we understand how we can publish download packages in the context of CI/CD jobs, we will next incorporate these steps into a typical GitLab development workflow.

Deploying to different environments using GitLab Flow

Section titled “Deploying to different environments using GitLab Flow”

We have so far discussed how to store and use our completed code by publishing to and pulling from GitLab’s package and container registries. Now, we will learn about some of GitLab’s features for organizing deployments of code to particular environments.

GitLab has two terms, environments and deployments, that are used to describe and categorize the location and version of a deployed application. An environment is represented by a name and a URL, which serve as organizational labels inside GitLab. Whenever an application is deployed to that environment via CI/CD, GitLab creates and categorizes it as a new deployment.

Environments are created via the environment keyword in a CI/CD job. That prompts GitLab CI/CD to associate the job and resulting deployment with that environment, along with the specified name and URL. In the following example, we’ve modified two of our previously created jobs to deploy our app to testing and production environments, respectively. The container version of the app is deployed to an environment called testing, and the generic app to an environment called production:

use_package_from_registry:
stage: run_package
script:
- 'wget --header="JOB-TOKEN: $CI_JOB_TOKEN" ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/generic/stable_releases/0.0.1/my_app_1665515895.tar.gz'
- tar -xvf my_app_1665515895.tar.gz
- ./my_app
environment:
name: testing
url: https://test.example.com
use_container_from_registry:
stage: run_container
image: registry.gitlab.com/nlotz1/pet-fashion/hats-for-cats/my_app/0.0.1:latest
script:
- ls -la
environment:
name: production
url: https://prod.example.com

Figure 8*.18* shows that environments are represented in the GitLab UI under Deployments | Environments.

Figure 8.18 – Environments in the GitLab UI

Figure 8.18 – Environments in the GitLab UI

Each environment is updated when a new commit creates a pipeline with a CI/CD job deploying to that environment. The GitLab UI shows the commit SHA for the latest deployment, the GitLab user who triggered the commit, the branch it was triggered on, and the CI/CD job deploying to that environment. The Open button on the top right serves as a link to the URL specified when the environment was defined (e.g., https://prod.example.com).

We can see that by integrating environments into GitLab CI/CD, we can set up more advanced workflows, such as using CI/CD keywords like rules to ensure certain environments are only updated when code changes on certain branches. The next section in this chapter will show such an example.

GitLab has a feature called a review app that allows developers to preview their changes directly within a merge request. Review apps use a special kind of environment called dynamic environments, whose names and URLs are set and changed based on the value of CI/CD variables. If you look back at Figure 8*.18*, you will notice a button that says Enable review app on the top right of the Environments page. Figure 8*.19* shows that selecting the button provides a block of code you can paste into your .gitlab-ci.yml file that creates a job that deploys to a review app environment.

Figure 8.19 – Enable Review App

Figure 8.19 – Enable Review App

There are two key items to note in the job content. The first is the use of predefined CI/CD variables to specify the environment name and URL. The name of the review environment will be dynamically updated based on the triggering branch, and the URL will be updated based on the dynamic environment name. This is useful for spinning up temporary ad hoc environments during the development process.

The second item to note in the review app CI/CD job is its only / except keywords. The review app environment will only be deployed when a pipeline is triggered on a Git branch, except the main branch. The logic is that a branch represents a development line, but the main branch might be a more stable staging or production environment that is static rather than dynamic.

One other useful element of review apps is their easy accessibility from a merge request. If a merge request pipeline has a review app job defined for the triggering branch, a link to the review app’s URL will be accessible from the merge request page (see Figure 8*.20*).

Figure 8.20 – View review app from a merge request

Figure 8.20 – View review app from a merge request

The link to the review environment can also be seen on the CI/CD job log (see Figure 8*.21*).

Figure 8.21 – Review app CI/CD job log

Figure 8.21 – Review app CI/CD job log

To summarize, review apps simply extend our understanding of environments to include dynamic creation and updates. They are best used to represent rapidly changing development environments and are easily accessible for developers and reviewers to preview the latest version of their applications.

Now that we have learned about previewing changes with review apps, let’s finally turn to how we might deploy into production.

Deploying to real-world production environments

Section titled “Deploying to real-world production environments”

In the examples presented so far, we have shown that environments are simply organizational categories in GitLab with associated names and URLs. In the real world, however, environments represent actual infrastructure, be it your computer’s or someone else’s. That means recognizing the constraints on the available resources and the importance of proper security and access control.

In this day and age, it is increasingly common to use cloud service providers such as AWS, Microsoft Azure, and Google Cloud Platform for application hosting. These services not only outsource the need for infrastructure management but they also provide programmatic interfaces for managing your environments.

Moreover, suites of developer tools for managing these resources have accompanied the rise of cloud service providers, apart from the cloud vendor-provided tools. Software such as Terraform, Ansible, and Chef is available to declaratively manage cloud resources. That is, they let you store descriptions of infrastructure as text in a Git repository. Thus, similar workflows for infrastructure change management can be used as those for managing application development.

There is more to cloud service utilization than we could possibly cover within this one chapter. However, it is worth pointing out how GitLab can assist with one of the most important aspects of application environment administration: secret management. We’ve already explained the concept of CI/CD variables and how they can be used in CI/CD configurations and exported to the environments where jobs run. For variables of a sensitive nature, such as deploy keys, GitLab provides a special place in group- or project-level settings so that their values are not exposed in the project’s repository.

Say, for example, you wish to deploy to an environment hosted in AWS. You will be required to provide credentials to authenticate to AWS, generally in the form of an AWS access key and a secret key. However, you would not want to directly enter those values into your CI/CD deployment scripts, as that leaks your credentials into the code base and its version history.

You can instead navigate to your project’s Settings | CI/CD and expand the Variables section, as shown in Figure 8*.22*. Here, you can create variables that you can reference in your .gitlab-ci.yml file, just like any other variable, without having to hardcode their values into the configuration.

Figure 8.22 – Project-level CI/CD variables

Figure 8.22 – Project-level CI/CD variables

Importantly, creating a variable in this way provides some additional gatekeeping on its use and exposure. Aside from setting the variable’s name and value, you can limit the environments in which it can be used. You can also choose to limit the variable to protected branches and tags (that is, branches and tags with restrictions on who can contribute to or modify them). And Figure 8*.23* shows you can also mask the variable, meaning that job logs would only display asterisks or [MASKED] if there were an attempt to leak its value.

Figure 8.23 – Project-level CI/CD variable settings

Figure 8.23 – Project-level CI/CD variable settings

These explanations only scratch the surface of deployment considerations in real-world environments. However, in these security-conscious times, we found it best to focus on the key area of secret management to demonstrate how GitLab can make the deployment process seamless and secure. In the next and final section, we’ll learn about GitLab’s integration with Kubernetes for cloud-native deployments.

We previously discussed the ubiquity of cloud services as alternatives to self-hosted infrastructure. In a similar vein, container orchestration systems such as Kubernetes have become increasingly popular as alternatives to the manual management of bare-metal servers or container hosts.

Deploying to Kubernetes with GitLab CI/CD can be conceptually similar to the workflows we have covered thus far. You can set up a GitLab runner with a Kubernetes executor, which communicates to the clusters using the Kubernetes API. Alternatively, GitLab optionally offers an additional approach called the GitOps workflow, which is not wholly reliant on CI/CD pipelines. We will summarize each of them in turn.

Using the concepts so far, you can use a normal CI/CD setup to deploy containerized applications to Kubernetes. This requires a runner registered with the Kubernetes executor. During runner registration, information such as cluster host and authentication information is provided. The CI/CD script will then include direct API calls in the cluster, specifying commands to build, test, or deploy your code.

Because this workflow involves runners sending imperative commands to a Kubernetes cluster, we call this a push-based workflow. It’s convenient in that there are no additional dependencies required to interact with Kubernetes. However, we can run into issues if the cluster or deployments have changed in any way outside the CI/CD workflow, causing potential problems if the cluster is in a state other than what the CI/CD jobs expect.

For this reason, GitLab increasingly recommends a different approach to working with Kubernetes called a GitOps workflow.

GitLab provides an alternative method of Kubernetes integration that does not use CI/CD directly. Rather, it uses an agent installed on a Kubernetes cluster that communicates back to the GitLab instance. These steps can be performed by navigating to Infrastructure | Kubernetes clusters in your project and then selecting Connect a cluster to follow the provided instructions for creating and registering a new agent (see Figure 8*.24*).

Figure 8.24 – Connecting a Kubernetes cluster to GitLab

Figure 8.24 – Connecting a Kubernetes cluster to GitLab

Once a connection is established, the agent will automatically detect changes when configuration and deployment files are updated in the repository and will change the cluster state accordingly. This is due to the bidirectional streaming between the cluster agent and GitLab server. Essentially, the agent initiates all communication to work around any networking restrictions that obstruct the Kubernetes cluster (see Figure 8*.25*).

Figure 8.25 – GitLab agent for Kubernetes architecture

Figure 8.25 – GitLab agent for Kubernetes architecture

GitLab therefore refers to the GitOps workflow as a pull-based approach, one that is increasingly favored over traditional pushes by CI/CD pipelines.

In this chapter, we described various ways of packaging and deploying our code. This included making use of GitLab’s package and container registries, CI/CD environments, and methods for interacting with cloud-native infrastructure.

Even if you may not use all of the discussed features or services in your day-to-day work, we hope this chapter provided a useful bridge to more practical, real-world use cases of GitLab’s features.

The next chapter will build upon what we’ve learned already. It will also introduce advanced features for improving CI/CD speed and performance, increasing developer productivity, and optimizing your ability to quickly build and ship software.