Gitlab runner for windows

  • Tier: Free, Premium, Ultimate
  • Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated

To install and run GitLab Runner on Windows you need:

  • Git, which can be installed from the official site
  • A password for your user account, if you want to run it under your user
    account rather than the Built-in System Account.
  • The system locale set to English (United States) to avoid character encoding issues.
    For more information, see issue 38702.

Installation

  1. Create a folder somewhere in your system, for example, C:\GitLab-Runner.

  2. Download the binary for 64-bit or 32-bit and put it into the folder you
    created. The following assumes you have renamed the binary to gitlab-runner.exe (optional).
    You can download a binary for every available version as described in
    Bleeding Edge — download any other tagged release.

  3. Make sure to restrict the Write permissions on the GitLab Runner directory and executable.
    If you do not set these permissions, regular users can replace the executable with their own and run arbitrary code with elevated privileges.

  4. Run an elevated command prompt:

  5. Register a runner.

  6. Install GitLab Runner as a service and start it. You can either run the service
    using the Built-in System Account (recommended) or using a user account.

    Run service using Built-in System Account (under the example directory created in step 1, C:\GitLab-Runner)

    cd C:\GitLab-Runner
    .\gitlab-runner.exe install
    .\gitlab-runner.exe start

    Run service using user account (under the example directory created in step 1, C:\GitLab-Runner)

    You have to enter a valid password for the current user account, because
    it’s required to start the service by Windows:

    cd C:\GitLab-Runner
    .\gitlab-runner.exe install --user ENTER-YOUR-USERNAME --password ENTER-YOUR-PASSWORD
    .\gitlab-runner.exe start

    See the troubleshooting section if you encounter any
    errors during the GitLab Runner installation.

  7. (Optional) Update the runner’s concurrent value in C:\GitLab-Runner\config.toml
    to allow multiple concurrent jobs as detailed in advanced configuration details.
    Additionally, you can use the advanced configuration details to update your
    shell executor to use Bash or PowerShell rather than Batch.

Voila! Runner is installed, running, and starts again after each system reboot.
Logs are stored in Windows Event Log.

Upgrade

  1. Stop the service (you need an elevated command prompt as before):

    cd C:\GitLab-Runner
    .\gitlab-runner.exe stop
  2. Download the binary for 64-bit or 32-bit and replace runner’s executable.
    You can download a binary for every available version as described in
    Bleeding Edge — download any other tagged release.

  3. Start the service:

    .\gitlab-runner.exe start

Uninstall

From an elevated command prompt:

cd C:\GitLab-Runner
.\gitlab-runner.exe stop
.\gitlab-runner.exe uninstall
cd ..
rmdir /s GitLab-Runner

Windows troubleshooting

Make sure that you read the FAQ section which describes
some of the most common problems with GitLab Runner.

If you encounter an error like The account name is invalid, try:

# Add \. before the username
.\gitlab-runner.exe install --user ".\ENTER-YOUR-USERNAME" --password "ENTER-YOUR-PASSWORD"

If you encounter a The service did not start due to a logon failure error
while starting the service, see the FAQ section to check how to resolve the problem.

If you don’t have a Windows Password, you cannot start the GitLab Runner service but you can
use the Built-in System Account.

For Built-in System Account issues, see
Configure the Service to Start Up with the Built-in System Account
on the Microsoft support website.

Get runner logs

When you run .\gitlab-runner.exe install it installs gitlab-runner
as a Windows service. You can find the logs in the Event Viewer
with the provider name gitlab-runner.

If you don’t have access to the GUI, in PowerShell, you can run
Get-WinEvent.

PS C:\> Get-WinEvent -ProviderName gitlab-runner

   ProviderName: gitlab-runner

TimeCreated                     Id LevelDisplayName Message
-----------                     -- ---------------- -------
2/4/2021 6:20:14 AM              1 Information      [session_server].listen_address not defined, session endpoints disabled  builds=0...
2/4/2021 6:20:14 AM              1 Information      listen_address not defined, metrics & debug endpoints disabled  builds=0...
2/4/2021 6:20:14 AM              1 Information      Configuration loaded                                builds=0...
2/4/2021 6:20:14 AM              1 Information      Starting multi-runner from C:\config.toml...        builds=0...

I get a PathTooLongException during my builds on Windows

This error is caused by tools like npm which sometimes generate directory structures
with paths more than 260 characters in length. To solve the problem, adopt one of the
following solutions.

  • Use Git with core.longpaths enabled:

    You can avoid the problem by using Git to clean your directory structure.

    1. Run git config --system core.longpaths true from the command line.
    2. Set your project to use git fetch from the GitLab CI project settings page.
  • Use NTFSSecurity tools for PowerShell:

    The NTFSSecurity PowerShell module provides
    a “Remove-Item2” method which supports long paths. GitLab Runner
    detects it if it is available and automatically make use of it.

A regression introduced in GitLab Runner 16.9.1 is fixed in GitLab Runner 17.10.0.
If you intend to use the GitLab Runner versions with regressions, use one of the following workarounds:

  • Use pre_get_sources_script to re-enable Git system-level settings (by unsetting Git_CONFIG_NOSYSTEM).
    This action enables core.longpaths by default on Windows.

    build:
      hooks:
        pre_get_sources_script:
          - $env:GIT_CONFIG_NOSYSTEM=''
  • Build a custom GitLab-runner-helper image:

    FROM registry.gitlab.com/gitlab-org/gitlab-runner/gitlab-runner-helper:x86_64-v17.8.3-servercore21H2
    ENV GIT_CONFIG_NOSYSTEM=

I can’t run Windows bash scripts; I’m getting The system cannot find the batch label specified - buildscript

You need to prepend call to your Batch file line in .gitlab-ci.yml so that it looks like call C:\path\to\test.bat. Here
is a more complete example:

before_script:
  - call C:\path\to\test.bat

For more information, see issue 1025.

How can I get colored output on the web terminal?

Short answer:

Make sure that you have the ANSI color codes in your program’s output. For the purposes of text formatting, assume that you’re
running in a UNIX ANSI terminal emulator (because it is the web interface output).

Long Answer:

The web interface for GitLab CI emulates a UNIX ANSI terminal (at least partially). The gitlab-runner pipes any output from the build
directly to the web interface. That means that any ANSI color codes that are present are honored.

Older versions of Windows’ command prompt terminal (before Windows 10, version 1511) do not support
ANSI color codes. They use win32 (ANSI.SYS) calls instead which are not present in
the string to be displayed. When writing cross-platform programs, developers typically use ANSI color codes by default. These codes are converted
to win32 calls when running on a Windows system, for example, Colorama.

If your program is doing the above, you must disable that conversion for the CI builds so that the ANSI codes remain in the string.

For more information, see GitLab CI YAML documentation
for an example using PowerShell and issue 332.

The service did not start due to a logon failure error when starting service

When installing and starting the GitLab Runner service on Windows you can
meet with such error:

gitlab-runner install --password WINDOWS_MACHINE_PASSWORD
gitlab-runner start
FATA[0000] Failed to start GitLab Runner: The service did not start due to a logon failure.

This error can occur when the user used to execute the service doesn’t have
the SeServiceLogonRight permission. In this case, you need to add this
permission for the chosen user and then try to start the service again.

  1. Go to Control Panel > System and Security > Administrative Tools.
  2. Open the Local Security Policy tool.
  3. Select Security Settings > Local Policies > User Rights Assignment on the
    list on the left.
  4. Open the Log on as a service on the list on the right.
  5. Select Add User or Group….
  6. Add the user (“by hand” or using Advanced…) and apply the settings.

According to Microsoft documentation,
this should work for:

  • Windows Vista
  • Windows Server 2008
  • Windows 7
  • Windows 8.1
  • Windows Server 2008 R2
  • Windows Server 2012 R2
  • Windows Server 2012
  • Windows 8

The Local Security Policy tool may be not available in some
Windows versions, for example in “Home Edition” variant of each version.

After adding the SeServiceLogonRight for the user used in service configuration,
the command gitlab-runner start should finish without failures
and the service should be started properly.

Job marked as success or failed incorrectly

Most Windows programs output exit code 0 for success. However, some programs don’t
return an exit code or have a different value for success. An example is the Windows
tool robocopy. The following .gitlab-ci.yml fails, even though it should be successful,
due to the exit code output by robocopy:

test:
  stage: test
  script:
    - New-Item -type Directory -Path ./source
    - New-Item -type Directory -Path ./dest
    - Write-Output "Hello World!" > ./source/file.txt
    - robocopy ./source ./dest
  tags:
    - windows

In the case above, you need to manually add an exit code check to the script:. For example,
you can create a PowerShell script:

$exitCodes = 0,1

robocopy ./source ./dest

if ( $exitCodes.Contains($LastExitCode) ) {
    exit 0
} else {
    exit 1
}

And change the .gitlab-ci.yml file to:

test:
  stage: test
  script:
    - New-Item -type Directory -Path ./source
    - New-Item -type Directory -Path ./dest
    - Write-Output "Hello World!" > ./source/file.txt
    - ./robocopyCommand.ps1
  tags:
    - windows

Also, be careful of the difference between return and exit when using PowerShell
functions. While exit 1 marks a job as failed, return 1 does not.

Job marked as success and terminated midway using Kubernetes executor

For more information, see Job execution.

Docker executor: unsupported Windows Version

GitLab Runner checks the version of Windows Server to verify that it’s supported.

It does this by running docker info.

If GitLab Runner fails to start and displays an error without
specifying a Windows Server version, then the Docker
version might be outdated.

Preparation failed: detecting base image: unsupported Windows Version: Windows Server Datacenter

The error should contain detailed information about the Windows Server
version, which is then compared with the versions that GitLab Runner supports.

unsupported Windows Version: Windows Server Datacenter Version (OS Build 18363.720)

Docker 17.06.2 on Windows Server returns the following in the output
of docker info.

Operating System: Windows Server Datacenter

The fix in this case is to upgrade the Docker version of similar age, or later,
than the Windows Server release.

Kubernetes executor: unsupported Windows Version

Kubernetes executor on Windows might fail with the following error:

Using Kubernetes namespace: gitlab-runner
ERROR: Preparation failed: prepare helper image: detecting base image: unsupported Windows Version:
Will be retried in 3s ...
ERROR: Job failed (system failure): prepare helper image: detecting base image: unsupported Windows Version:

To fix it, add node.kubernetes.io/windows-build node selector in the section [runners.kubernetes.node_selector]
of your GitLab Runner configuration file, For example:

   [runners.kubernetes.node_selector]
     "kubernetes.io/arch" = "amd64"
     "kubernetes.io/os" = "windows"
     "node.kubernetes.io/windows-build" = "10.0.17763"

I’m using a mapped network drive and my build cannot find the correct path

When GitLab Runner runs under a standard user account instead of an administrator
account, it cannot access mapped network drives.
When you try to use mapped network drives, you get the
The system cannot find the path specified. error.
This error occurs because service logon sessions have
security limitations
when accessing resources. Use the UNC path
of your drive instead.

The build container is unable to connect to service containers

To use services with Windows containers:

  • Use the networking mode that creates a network for each job.
  • Ensure that the FF_NETWORK_PER_BUILD feature flag is enabled.

The job cannot create a build directory and fails with an error

When you use the GitLab-Runner with the Docker-Windows executor, a job might fail with an error like:

fatal: cannot chdir to c:/builds/gitlab/test: Permission denied`

When this error occurs, ensure the user the Docker engine is running as has full permissions to C:\Program Data\Docker.
The Docker engine must be able to write to this directory for certain actions, and without the correct permissions it fails.

Read more about configuring Docker Engine on Windows.

Blank lines for Windows Subsystem for Linux (WSL) STDOUT output in job logs

By default the STDOUT output for the Windows Subsystem for Linux (WSL) is not UTF8 encoded and displays as blank lines in the job logs. To display the STDOUT output, you can force UTF8 encoding for WSL by setting the WSL_UTF8 environment variable.

job:
  variables:
    WSL_UTF8: "1"

Last Updated :
16 Sep, 2024

GitLab is a popular DevOps platform that provides a robust solution for source code management, continuous integration/continuous deployment (CI/CD), and other development workflows. While GitLab is typically hosted on Linux servers, it can also be installed on Windows using a virtual machine or Docker.

In this article, we will walk you through the steps to install GitLab on Windows using Docker, which provides a manageable and efficient way to run GitLab without needing to configure a full Linux environment.

Prerequisites

Before installing GitLab on Windows, ensure you have the following prerequisites:

  • Windows 10 Pro, Enterprise, or Education: Required for Docker Desktop.
  • Docker Desktop: A platform that allows you to run Docker containers on Windows.
  • Sufficient System Resources: At least 4 CPU cores and 4GB of RAM for GitLab to run smoothly. Higher specifications are recommended for production environments.

Installing Docker on Windows

To run GitLab on Windows, you’ll need to install Docker Desktop, which enables running containers on Windows systems.

Step 1: Download Docker Desktop

Go to the Docker Desktop website and download the installer for Windows.

vhrt

Download Docker Desktop

Step 2: Install Docker Desktop

  • Run the installer and follow the on-screen instructions.
  • When prompted, enable the option for Windows Subsystem for Linux (WSL 2) for better performance.

Step 3: Start Docker Desktop

  • Once installed, launch Docker Desktop and ensure it is running. You should see the Docker icon in the system tray.

Step 4: Verify Docker Installation

Open Command Prompt or PowerShell and type:

docker --version

You should see the version of Docker installed, confirming that Docker is set up correctly.

Downloading and Running GitLab Using Docker

With Docker installed, you can now download and run GitLab using Docker containers.

Step 1: Pull the GitLab Docker Image

Open PowerShell or Command Prompt and pull the GitLab image from Docker Hub:

docker pull gitlab/gitlab-ee:latest

This command pulls the latest version of GitLab Enterprise Edition. If you prefer the Community Edition, use gitlab/gitlab-ce:latest.

Step 2: Run GitLab in a Docker Container

Create a new directory on your Windows system to store GitLab configuration and data. This ensures data persists even if the container is removed:

mkdir C:\gitlab\data
mkdir C:\gitlab\logs
mkdir C:\gitlab\config

Step 3: Start the GitLab container:

docker run --detach `
--hostname gitlab.local `
--publish 443:443 --publish 80:80 --publish 22:22 `
--name gitlab `
--restart always `
--volume C:\gitlab\config:/etc/gitlab `
--volume C:\gitlab\logs:/var/log/gitlab `
--volume C:\gitlab\data:/var/opt/gitlab `
gitlab/gitlab-ee:latest

Options:

  • —hostname: Sets the hostname for GitLab (e.g., gitlab.local).
  • —publish: Maps ports from the container to the host (HTTP, HTTPS, and SSH).
  • —name: Names the container gitlab.
  • —restart always: Ensures GitLab restarts automatically if the container stops or the host reboots.
  • —volume: Maps local directories to container directories for persistent storage.

Step 3: Wait for GitLab to Initialize:

It may take several minutes for GitLab to initialize. You can monitor the process using:

docker logs -f gitlab

Wait until you see the message indicating that GitLab is ready.

Configuring GitLab

After GitLab starts, you can configure it through the GitLab interface:

Step 1: Access GitLab

  • Open a web browser and navigate to http://localhost.
  • You should see the GitLab login screen.

Step 2: Set Up the Root Password

The first time you access GitLab, you’ll be prompted to set the root password. Enter a secure password and save it.

Step 3: Log In:

Log in using the username root and the password you just set.

Step 4: Configure GitLab Settings

Navigate to the Admin area to configure GitLab settings, such as email notifications, user management, and project settings.

Accessing GitLab

To access GitLab, simply navigate to the hostname you set during the Docker run command (e.g., http://localhost if using the default setup). If you mapped the ports differently or used a different hostname, adjust the URL accordingly.

Setting Up GitLab Runner (Optional)

GitLab Runner is a tool used for running CI/CD jobs on your GitLab instance. Installing GitLab Runner on Windows allows you to leverage GitLab’s powerful CI/CD pipelines.

Step 1: Download GitLab Runner

Visit the GitLab Runner downloads page and download the binary for Windows.

Step 2: Install GitLab Runner:

  • Extract the binary to a directory, for example, C:\GitLab-Runner.
  • Open Command Prompt as Administrator and register the runner:
C:\GitLab-Runner\gitlab-runner.exe register
  • Follow the prompts to configure the runner with your GitLab instance, including:
    • GitLab URL.
    • Registration token (found in GitLab’s Admin area under Runners).
    • Runner description, tags, and executor type (use shell for simplicity on Windows).

Step 3: Start the Runner

Install and start GitLab Runner as a service:

C:\GitLab-Runner\gitlab-runner.exe install
C:\GitLab-Runner\gitlab-runner.exe start

In this article we are going to cover How to download and install GitLab runner on windows, Register GitLab Runner and GitLab Runner commands.

Table of Contents

What is GitLab Runner ?

GitLab Runner is used in GitLab CI/CD(continuous integration/continuous delivery) to run jobs in a pipeline. It is open source continuous integration service. GitLab runner is a build instance which is used to run the jobs over multiple machines and send the results to GitLab and which can be placed on separate users, servers, and local machine. You can register the runner as shared or group or project after installing it.

Types of GitLab runner

  • Share Runners
  • Group Runners
  • Project Runner

Share Runners: Share runner are available for jobs that have same requirement for multiple projects. If you use multiple runner for many jobs/projects then it avoid using single runner or minimum runners for many projects. It is use FIFO (first in first out) queue. Share runners are available to all groups and projects in a GitLab executor.

Group Runners: Group Runner are available for many projects or multiple subgroup in single group to have access to a set of runners. It is use FIFO (first in first out) queue.

Project Runner: Project runner are available for specific requirement for jobs in one project at a time.

Step #1:Download and install GibLab Runner on windows

Go to official GitLab Runner download web page and download binary exe file.

download runner

After downloaded binary File copy it , Go to c drive and create new folder ex: C:\GitLab-Runner

Create folder

and paste binary in that folder which you created.

paste

Rename downloaded file ex: gitlab-runner

rename

Open command prompt and go to directory where GitLab Runner file saved using below command.

cd c:\GitLab-Runner
go to runner file

To install GitLab Runner run the below command.

.\gitlab-runner.exe install

To verify GitLab Runner version using below command

.\gitlab-runner –v
install runner1

Step #2:Register GitLab Runner on Windows

To register GitLab runner run below command

.\gitlab-runner.exe register

Enter the GitLab instance URL

https://gitlab.com/
register n url

Enter the registration token:

To get token, you have to go your GitLab project -> setting -> CI/CD -> Runner

setting cicd runner

Expand runner to access token

copy token

 glrt-TXoYSomxe2ANzBaHHbyy

Enter a description for the runner:

Project runner

Enter tags for the runner (comma-separated):

windows

Enter an executor:

instance

Then you will get Runner registered successfully.

registration 2

If you are refresh the gitlab page and again go to project -> setting -> CI/CD -> runner -> expand it then you can see assigned project runner.

assigned project runner

You can see the GitLab Runner configuration in the config.toml file under the GitLab-Runner folder as shown below.

config

Step #3:GitLab Runner Service command

To prints the status of the GitLab Runner service.

gitlab-runner status

To start gitlab runner service

gitlab-runner start

To stop the gitlab runner service.

gitlab-runner stop

To stop and then start the gitlab runner service

gitlab-runner restart
services

Step #4:Uninstall GitLab runner on Windows

To uninstall gitlab runner on your system.

gitlab-runner uninstall

In this article we have covered How to download and install GitLab runner on windows, Register GitLab Runner, GitLab Runner Services.

Conclusion:

In this article we have covered How to download and install GitLab runner on windows, Register GitLab Runner and GitLab Runner commands.

Related Articles:

How to Create Group and Users in GitLab [2 Steps]

This article serves as a comprehensive guide for individuals looking to install GitLab Runner on a Windows system. The guide will take you through the necessary steps, from preparing your system to integrating the Runner into your workflows. It covers system requirements, installation, configuration, optimization, and more, ensuring you have all the information needed to successfully set up GitLab Runner on a Windows environment.

Key Takeaways

  • Understanding system requirements and setting up necessary permissions are crucial steps before installing GitLab Runner on Windows.
  • The installation process includes choosing the right version, running the installer, and verifying the installation to ensure GitLab Runner is correctly set up.
  • Configuring GitLab Runner involves editing the config.toml file, registering the Runner with your GitLab instance, and setting up the appropriate executor types.
  • Managing GitLab Runner as a Windows service includes installing the service and knowing how to start, stop, restart, and troubleshoot service issues.
  • Staying updated with GitLab Runner releases, understanding deprecations, and following best practices for updates are essential for maintaining a secure and efficient CI/CD environment.

Preparing Your Windows System for GitLab Runner Installation

Preparing Your Windows System for GitLab Runner Installation

Ensuring System Requirements are Met

Before diving into the installation of GitLab Runner on your Windows system, it’s crucial to ensure that your machine meets the necessary specifications. GitLab Runner on Windows automates CI/CD pipelines, requiring a stable and compatible environment to function effectively. The minimum system requirements include Windows 7 or higher, a 1.4 GHz processor, 2 GB of RAM, and at least 50 MB of free storage space.

Compatibility is key when setting up GitLab Runner, as it needs to integrate seamlessly with your existing development tools and workflows. Here’s a quick checklist to help you verify your system’s readiness:

  • Operating System: Windows 7 or newer
  • Processor: 1.4 GHz or faster
  • Memory: 2 GB RAM or more
  • Storage: Minimum of 50 MB available space

Ensure that your system is up-to-date with the latest Windows updates and patches. This not only helps in maintaining compatibility but also in securing your system against vulnerabilities.

Once you’ve confirmed that your system aligns with these requirements, you’re all set to proceed with the installation process. The upcoming steps will guide you through downloading, installing, and configuring GitLab Runner to streamline your workflow.

Setting Up Necessary Permissions

Before diving into the installation of GitLab Runner on your Windows system, it’s crucial to ensure that the necessary permissions are set up correctly. Proper permissions are the bedrock of a secure and functional GitLab Runner environment.

To begin, you’ll need to have administrative privileges on the machine where GitLab Runner will be installed. This allows you to install software and make system-level changes. If you’re using GitLab Ultimate, consider setting up a dedicated user account for running the GitLab Runner service to enhance security and manage permissions more effectively.

It’s also important to verify that the user account has the correct permissions to interact with the GitLab instance. This includes network permissions and, if applicable, the ability to use self-signed certificates.

Here’s a quick checklist to guide you through the permission setup process:

  • Ensure administrative privileges are available for the installation.
  • Create a dedicated user account for the GitLab Runner service.
  • Assign the necessary network and system permissions to the user account.
  • Verify that the user account can communicate with your GitLab instance securely.

Understanding GitLab Runner and Its Components

Before diving into the installation process, it’s crucial to grasp the basics of GitLab Runner and its components. GitLab Runner is an application that works with GitLab CI/CD to run jobs in a pipeline. It’s a lightweight, highly scalable tool that can be installed on various environments, including Windows, Linux, and macOS.

GitLab Runner operates by using executors that define the environment in which the jobs will run. There are several types of executors, such as Shell, Docker, and Kubernetes, each suitable for different scenarios. Here’s a quick overview of the most common executors:

  • Shell: Executes jobs using the system’s shell. It’s the simplest executor and requires minimal configuration.
  • Docker: Runs jobs in Docker containers, providing a clean, isolated environment for each job.
  • Kubernetes: Utilizes Kubernetes clusters to run jobs, ideal for scalable and distributed environments.

Remember, choosing the right executor is key to ensuring your CI/CD pipeline runs efficiently and meets your project’s needs.

Each component of GitLab Runner plays a pivotal role in the automation of your development process. By understanding these components, you’ll be better equipped to tailor your Runner setup to your specific requirements.

Downloading and Installing GitLab Runner on Windows

Downloading and Installing GitLab Runner on Windows

Choosing the Right Version

Selecting the appropriate version of GitLab Runner for your Windows system is crucial for compatibility and feature access. Always opt for the latest stable release to ensure you have the most recent fixes and updates. However, be mindful of major version changes, as they may require manual intervention to upgrade.

When a new minor version is released, such as an update from 1.2 to 1.3, GitLab Runner can automatically utilize the new version. But for a new major release, like moving from version 1.x to 2.x, you’ll need to manually switch to the new version to take advantage of the latest features and improvements.

It’s important to verify the compatibility of the chosen version with your current setup to avoid any disruptions in your CI/CD workflows.

Remember to review the release notes for any breaking changes or additional requirements that might affect your build environment. Staying informed will help you make the best decision for your system’s needs.

Running the Installer

Once you’ve chosen the correct version of GitLab Runner for your Windows system, it’s time to run the installer. Ensure you execute the installer with administrative privileges to avoid any permission issues during the installation process. The installation wizard will guide you through the necessary steps, which typically include accepting the license agreement, choosing the installation directory, and configuring initial settings.

After the installation is complete, it’s crucial to verify that GitLab Runner has been installed correctly. You can do this by opening a command prompt and running gitlab-runner –version. This command should return the version number of the installed GitLab Runner, confirming that the installation was successful.

If you’re using GitLab Premium, additional features and support may be available to help you with the installation and configuration process. Remember to consult the official GitLab documentation for any enterprise-specific guidance. Lastly, document the installation details for future reference, as this will aid in troubleshooting and maintenance.

Verifying the Installation

Once you’ve run the installer, it’s crucial to verify that GitLab Runner has been installed correctly. Start by opening a command prompt and typing gitlab-runner --version. This command should return the version number of the GitLab Runner, confirming that it’s accessible from the command line.

Next, ensure that the GitLab Runner service is running. You can check this by executing Get-Service gitlab-runner in PowerShell. If the service is not running, you’ll need to troubleshoot the installation process.

Remember, successful installation is key to automating your CI/CD processes with GitLab Runner.

Finally, perform a test run by executing a simple job. If the job completes without errors, your GitLab Runner is ready to automate your CI/CD processes. If you encounter issues, refer to the GitLab documentation or the troubleshooting section for guidance.

Configuring GitLab Runner on Windows

Configuring GitLab Runner on Windows

Editing the config.toml File

After successfully installing GitLab Runner, the next crucial step is to edit the config.toml file, which is the main configuration file for your runners. This file dictates how your runners behave and is essential for their operation. To begin editing, locate the file in the GitLab Runner home directory.

The config.toml file contains various sections, including [[runners]] where you specify the details of each runner. For instance, you might need to set up a custom certificate file for secure communication with your GitLab instance, especially if you’re using self-signed certificates. Refer to the official documentation titled ‘docs/configuration/tls-self-signed.md’ for detailed instructions on this setup.

Remember to always back up your config.toml file before making any changes. This precaution ensures you can revert to a working configuration if needed.

Below is a list of common settings you might encounter and adjust in the config.toml file:

  • url: The URL of your GitLab instance.
  • token: The registration token for the runner.
  • executor: The type of executor you want to use, such as shell or docker.
  • [runners.custom_build_dir]: Custom build directories settings.
  • [runners.cache]: Configuration for caching to speed up builds.

It’s important to review and understand each setting to tailor the runner to your specific needs. After editing, save the file and restart the GitLab Runner service to apply the changes.

Registering the Runner with Your GitLab Instance

Once you have GitLab Runner installed on your Windows system, the next crucial step is to register the Runner with your GitLab instance. This process links your Runner to the GitLab server, allowing it to pick up jobs. To start, you’ll need the URL of your GitLab instance and a registration token, which can be found in the settings of your GitLab project under CI/CD settings.

Registration is a straightforward process, but it’s vital to ensure that the Runner is correctly configured to communicate with your GitLab server.

Follow these steps to register your GitLab Runner:

  1. Open a Command Prompt as an administrator.
  2. Navigate to the directory where GitLab Runner is installed.
  3. Run the gitlab-runner register command.
  4. Enter the URL of your GitLab instance when prompted.
  5. Input the registration token from your GitLab project’s settings.
  6. Choose a description and tags for the Runner (optional but recommended).
  7. Select the executor that the Runner will use (e.g., shell, docker).

After completing these steps, your Runner should be visible in the GitLab interface under the ‘Runners’ section of your project’s settings. If it’s not, double-check the information you provided during registration and try again. Remember, a properly registered Runner is key to automating your CI/CD pipeline effectively.

Setting Up Executor Types

After installing GitLab Runner, it’s crucial to select the right executor for your projects. Executors define the environment in which your jobs will run. For instance, if you’re using Docker, you’ll want to set up a Docker executor. Each executor has its own requirements and benefits, so choose according to your project’s needs.

GitLab Runner supports several executors; here’s a quick rundown:

  • Shell: Executes jobs directly on the machine where the runner is installed.
  • Docker: Runs jobs in Docker containers, providing a clean, isolated environment.
  • Docker Machine and Autoscaler: Ideal for auto-scaling in cloud environments.
  • Kubernetes: Integrates with Kubernetes to run jobs in pods.
  • VirtualBox, Parallels, SSH: Useful for specific use cases or environments.

Remember, the choice of executor will impact how your CI/CD pipelines operate. It’s worth spending time to understand the implications of each type.

Once you’ve chosen an executor, you’ll need to configure it in the config.toml file. This involves setting various parameters specific to the executor type, such as image names for Docker or connection details for SSH.

Managing GitLab Runner as a Windows Service

Managing GitLab Runner as a Windows Service

Installing the Service

Once you’ve successfully downloaded and installed GitLab Runner, the next crucial step is to install it as a Windows service. This allows the Runner to operate in the background, starting automatically with your system, and ensures that your CI/CD pipelines run smoothly without manual intervention.

To install GitLab Runner as a service, open an elevated Command Prompt and navigate to the directory where you installed GitLab Runner. Execute the following command: gitlab-runner install --user YOUR_USERNAME --password YOUR_PASSWORD. Replace YOUR_USERNAME and YOUR_PASSWORD with the credentials of the user under which the service will run. Ensure that this user has the necessary permissions to execute the builds.

After installation, you should configure the service to start automatically. Use the services.msc console to locate the GitLab Runner service, right-click on it, and set the Startup type to Automatic.

Remember, running GitLab Runner as a service is essential for maintaining uninterrupted operations of your CI/CD workflows.

If you encounter any issues during the service installation, consult the troubleshooting guide or reach out to the GitLab community for support.

Starting, Stopping, and Restarting the Runner Service

Managing the GitLab Runner service on a Windows system is crucial for ensuring continuous integration processes run smoothly. Starting the service is typically done through the Services management console or via command line with Start-Service gitlab-runner. To stop the service, you can use the Stop-Service gitlab-runner command, and to restart, simply use Restart-Service gitlab-runner.

Remember, any changes to the GitLab Runner configuration require a restart of the service to take effect.

Here’s a quick reference for service management commands:

  • Start: Start-Service gitlab-runner
  • Stop: Stop-Service gitlab-runner
  • Restart: Restart-Service gitlab-runner

It’s important to monitor the runner’s status after performing any of these actions to ensure it’s operating as expected. Use Get-Service gitlab-runner to check the current status. Regularly reviewing the service logs can also help identify and troubleshoot any issues that may arise.

Viewing Logs and Troubleshooting Service Issues

When it comes to maintaining a healthy GitLab Runner service on your Windows system, viewing logs is crucial for identifying and resolving issues. The logs provide detailed information about the runner’s operations and any errors that may occur. To access the logs, navigate to the GitLab Runner’s installation directory and look for the logs subfolder.

GitLab Runner logs can be quite extensive, so knowing what to look for is key. Here are some common log entries and what they might indicate:

  • ERROR: Indicates a problem that prevented a task from completing.
  • WARNING: Suggests a potential issue that should be monitored.
  • INFO: Provides general information about the runner’s activities.

Remember, consistent log monitoring can preempt many service issues before they escalate. Regularly check the logs to ensure your runner is performing optimally.

If you encounter persistent problems, consider the following troubleshooting steps:

  1. Verify that the GitLab Runner service is running.
  2. Check network connectivity to your GitLab instance.
  3. Ensure all configuration files are correctly set up.
  4. Look for common error patterns in the logs.
  5. If necessary, increase the log verbosity for more detailed information.

By systematically working through these steps, you can often resolve service issues without the need for external support.

Securing Your GitLab Runner Setup

Securing Your GitLab Runner Setup

Handling Self-Signed Certificates

When setting up GitLab Runner on a Windows system, you might encounter scenarios where you need to work with self-signed certificates, especially in a self-hosted environment. Ensuring the GitLab Runner trusts these certificates is crucial for secure communication between the Runner and your GitLab instance. To achieve this, you’ll need to import the self-signed certificate into the Windows Certificate Store.

Firstly, locate your self-signed certificate file. Then, follow these steps:

  1. Open the Microsoft Management Console (MMC).
  2. Add the Certificates snap-in for the Local Computer account.
  3. Navigate to the Trusted Root Certification Authorities store.
  4. Import your certificate here.

Remember, improperly handling certificates can lead to security vulnerabilities. Always follow best practices for certificate management.

After importing the certificate, configure the GitLab Runner to use it by editing the config.toml file. This ensures that the Runner will not reject the self-signed certificate during operations. Regularly review your certificate’s validity and renew it before expiration to avoid disruptions in your CI/CD pipelines.

Configuring Runner for Secure Networks

When configuring GitLab Runner for secure networks, it’s crucial to prioritize security measures that align with DevSecOps practices. Enabling authentication and using secure protocols are foundational steps to protect your CI/CD pipeline. Regular updates are also essential to maintain security integrity.

To ensure secure communication, consider the following:

  • Utilize HTTPS for all web transactions.
  • Implement SSH keys for secure shell access.
  • Configure GitLab Runner to work behind a proxy if your environment requires it.

Remember, a secure GitLab Runner setup is not just about the initial configuration; it’s an ongoing commitment to security.

For advanced users, setting up features like LDAP synchronization or integrating with cloud services such as AWS Cognito can further enhance security. Always refer to the latest GitLab documentation for detailed guidance on securing your runner.

Maintaining Security Updates and Patches

Keeping your GitLab Runner updated with the latest security patches is crucial for maintaining a secure CI/CD environment. Regularly update your GitLab Runner to protect against vulnerabilities that could compromise your system. This includes not only the application itself but also any dependencies and underlying system software.

  • Ensure firmware and software patches are applied
  • Follow the GitLab Application Security Inventory
  • Integrate automated security checks and scans

Proactive monitoring and early vulnerability resolution are key to a robust security posture.

Stay informed about new releases and security advisories from GitLab. The DevSecOps approach emphasizes security as an integral part of the development lifecycle, not just an afterthought. By automating security within your workflows, you can achieve early vulnerability identification and resolution.

Advanced Configuration for GitLab Runner

Setting Up Docker Executors

When configuring GitLab Runner to use Docker executors, you’re essentially instructing the Runner to execute each job inside a separate and isolated Docker container. This approach ensures a clean environment for each job, with no side effects from previous jobs. The Docker executor uses Docker Engine, which requires specific settings to function correctly.

To set up Docker executors, you’ll need to edit the config.toml file of your GitLab Runner. Here’s an example of what your configuration might look like:

[[runners]]
  ...
  executor = "docker"
  [runners.docker]
    ...
    privileged = true
    volumes = ["/cache", "/etc/gitlab-runner/certs/gitlab.example.com.crt:/etc/docker/certs.d/gitlab.example.com/ca.crt:ro"]

Ensure that the privileged mode is enabled if you require operations that need elevated permissions, such as building Docker images within Docker (Docker in Docker). Additionally, you may need to add volume mounts to allow access to certain directories or certificate files for private Docker registries.

Remember to replace gitlab.example.com with the actual domain of your Docker registry.

For advanced setups, you might consider integrating Kubernetes executors, which already support Docker in Docker setups for Code Quality jobs. This integration can streamline your CI/CD pipelines by leveraging the orchestration capabilities of Kubernetes.

Working with Kubernetes Executors

When integrating GitLab Runner with Kubernetes, you unlock the potential for scalable and efficient CI/CD pipelines. Kubernetes executors are designed to run your jobs in isolated pods, providing a clean environment for each job execution. To ensure smooth operation, it’s crucial to address common issues such as Docker in Docker (DinD) setups and TLS communication with the Docker daemon.

For instance, if you’re using TLS to communicate with the Docker daemon, the Kubernetes executor must be in privileged mode, and the certificate directory should be specified as a volume mount. Additionally, be aware of the potential for the DinD service to not fully start before the Code Quality job begins. This is a known limitation and can be addressed by following the troubleshooting guidelines in the GitLab documentation.

When configuring the Kubernetes executor, always consider the network and security implications, especially when dealing with self-signed certificates or running behind a proxy.

Remember to consult the GitLab documentation for detailed steps and best practices, such as the tutorial on configuring GitLab Runner to use the Google Kubernetes Engine. Troubleshooting is an integral part of managing Kubernetes executors, and being proactive can save you time and prevent disruptions in your CI/CD process.

Utilizing Autoscaling with Different Cloud Providers

Autoscaling is a critical feature for managing workloads and optimizing resources in the cloud. GitLab Runner’s autoscaling capabilities allow you to handle variable loads efficiently by automatically scaling your runners up or down based on demand. To get started, you’ll need to configure the autoscaling settings for your preferred cloud provider.

  • For AWS, you can use the EC2 autoscaling groups to manage runner instances.
  • Google Cloud Platform offers managed instance groups that can be utilized for autoscaling GitLab Runners.
  • Azure users can leverage Virtual Machine Scale Sets to achieve similar functionality.

Each cloud provider has its own set of APIs and tools for autoscaling. It’s essential to familiarize yourself with the documentation and best practices of your chosen provider to ensure a smooth setup. Remember to consider the cost implications of autoscaling, as it can lead to increased expenses if not configured properly.

When configuring autoscaling, always test your setup in a controlled environment before rolling it out to production. This helps in identifying any potential issues early on and ensures that your runners scale as expected under real-world conditions.

Optimizing GitLab Runner Performance

Optimizing GitLab Runner Performance

Tuning Performance Settings

Optimizing the performance of your GitLab Runner is crucial for maintaining efficient CI/CD pipelines. Carefully tuning the performance settings can lead to significant reductions in job processing times and overall system load. Start by assessing the concurrency level of your runner. This determines how many jobs can be run simultaneously. Too high a concurrency can overwhelm your system, while too low can underutilize resources.

To adjust concurrency and other performance-related settings, edit the config.toml file. Here’s an example of how to set concurrency settings:

[session_server]
  session_timeout = 1800

[[runners]]
  name = "Example Runner"
  url = "https://gitlab.example.com/"
  token = "TOKEN"
  executor = "shell"
  [runners.custom_build_dir]
  [runners.cache]
    [runners.cache.s3]
    [runners.cache.gcs]
  [runners.docker]
    tls_verify = false
    image = "ruby:2.6"
    privileged = true
    disable_entrypoint_overwrite = false
    oom_kill_disable = false
    disable_cache = false
    volumes = ["/cache"]
    shm_size = 0
  [runners.machine]
    IdleCount = 1
    IdleTime = 1800
    MaxBuilds = 100
    OffPeakPeriods = ["* * 0-9,18-23 * * mon-fri *", "* * * * * sat,sun *"]
    OffPeakTimezone = "UTC"
    OffPeakIdleCount = 0
    OffPeakIdleTime = 1200

Remember to monitor the runner’s metrics regularly to ensure that your settings are yielding the desired results. If you encounter issues, consult the GitLab Runner documentation for troubleshooting tips.

Managing Runner Caching

Efficient use of caching in GitLab Runner can significantly reduce build times by reusing data across multiple job executions. Caching is essential for optimizing performance, especially when dealing with large dependencies or frequently used files. To manage runner caching effectively, consider the following points:

  • Identify files and directories that are frequently unchanged between pipeline runs. These are prime candidates for caching.
  • Use glob patterns to specify cache paths in your .gitlab-ci.yml file, ensuring flexibility and precision.
  • Set appropriate cache expiration policies to prevent the cache from growing indefinitely, which can lead to increased storage costs and slower runner performance.

Remember, while caching can improve build times, it should not be used for sensitive data or artifacts that need to be secure or isolated between jobs.

Additionally, it’s important to monitor the cache usage and clean up the cache periodically to maintain an efficient CI/CD pipeline. Below is an example of how to configure caching in your .gitlab-ci.yml:

stages:
  - build

cache:
  paths:
    - node_modules/
    - .npm/

build_job:
  stage: build
  script:
    - npm install
    - npm run build

By following these guidelines, you can ensure that your GitLab Runner utilizes caching to its fullest potential, leading to faster and more efficient builds.

Leveraging Graphical Processing Units

Incorporating Graphical Processing Units (GPUs) into your GitLab Runner setup can significantly speed up job execution for compute-intensive tasks. By offloading certain processes to GPUs, you can take advantage of their parallel processing capabilities, which is especially beneficial for tasks involving machine learning, data analysis, and rendering.

To get started, ensure your Windows system has the necessary GPU hardware and drivers installed. Then, configure your GitLab Runner to recognize and utilize the GPU. This typically involves setting environment variables and adjusting the runner’s configuration file.

Remember, not all jobs will benefit from GPU acceleration. It’s important to profile your jobs to determine if leveraging a GPU will provide a performance boost.

Below is a checklist to help you integrate GPUs with GitLab Runner:

  • Verify GPU compatibility and install necessary drivers
  • Update the config.toml file to include GPU-specific settings
  • Test runner with a GPU-accelerated job to ensure proper configuration
  • Monitor performance and adjust settings as needed for optimal results

Integrating GitLab Runner with Development Workflows

Integrating GitLab Runner with Development Workflows

Automating Build and Test Pipelines

Automating your build and test pipelines is a cornerstone of modern DevOps practices. By integrating GitLab Runner into your development workflow, you can ensure that every commit or pull request triggers an automated build and test sequence, leading to faster feedback and more robust software.

To set up automation with GitLab Runner, follow these steps:

  1. Define your pipeline configuration in a .gitlab-ci.yml file within your repository.
  2. Configure GitLab Runner to watch for changes in your repository.
  3. Specify the conditions that will trigger the pipeline, such as commits to specific branches or tags.
  4. Utilize GitLab’s built-in features to manage and optimize pipeline execution.

Remember, the goal is to minimize human intervention and maximize consistency. A well-configured pipeline not only saves time but also significantly reduces the chance of human error.

Continuous Integration (CI) and Continuous Deployment (CD) are key to maintaining a steady flow of updates to your products. With GitLab Runner, you can easily implement these practices and keep your development cycle moving smoothly.

Implementing Continuous Integration/Continuous Deployment (CI/CD)

Implementing Continuous Integration/Continuous Deployment (CI/CD) is a cornerstone of modern software development, streamlining the process from code commit to production deployment. GitLab Runner is an open-source tool that plays a pivotal role in automating these workflows, ensuring that software delivery is both efficient and scalable.

To effectively implement CI/CD with GitLab Runner, consider the following steps:

  1. Define clear CI/CD pipelines in .gitlab-ci.yml for building, testing, and deploying your applications.
  2. Leverage GitLab Runner’s support for multiple executors to match your project’s needs.
  3. Utilize GitLab’s rich set of integrations to enhance your pipelines with static analysis, security scanning, and other quality checks.

Embracing CI/CD not only accelerates development cycles but also significantly reduces the risk of errors, making it an essential practice for any team aiming for rapid and reliable software releases.

Using GitLab Runner in Multi-Project Setups

When managing multiple projects, it’s crucial to configure GitLab Runner to handle diverse workflows efficiently. Each runner can be fine-tuned to specific projects or serve multiple projects, depending on your needs. To achieve this, you should:

  • Configure the Runner: Set properties such as tagLists, locked, and paused to ensure that the runner behaves as expected within your CI/CD workflows.
  • Optimize for concurrency: Adjust the number of jobs a runner can handle simultaneously to maximize resource utilization.
  • Use rules and tags: Define rules and tags to control which runners pick up certain jobs, allowing for a more organized and efficient CI/CD process.

Remember, a well-configured runner setup can significantly reduce build times and improve resource management across projects.

By carefully managing your runners, you can create a robust and scalable CI/CD environment that caters to the complexities of handling multiple projects. This not only streamlines the development process but also ensures that your team can focus on delivering quality code without being bogged down by infrastructure concerns.

Monitoring and Scaling GitLab Runner

Setting Up Instance Monitoring

Effective monitoring is crucial for maintaining the health and performance of your GitLab Runner. Start by setting up a comprehensive monitoring system that can alert you to potential issues before they escalate. Utilize GitLab’s built-in Health Check feature to monitor the system’s status and ensure it’s operating within normal parameters.

To facilitate a streamlined monitoring process, consider the following steps:

  • Configure Health Check endpoints for your GitLab Runner instance.
  • Integrate with monitoring tools like Prometheus or Grafana for real-time data visualization.
  • Set up alerts for critical metrics such as CPU usage, memory consumption, and job failure rates.

Remember, proactive monitoring can prevent downtime and ensure your CI/CD pipelines run smoothly.

Regularly review and analyze your logs to identify patterns or recurring issues. Tools like jq can be invaluable for parsing logs, especially when troubleshooting complex problems. Keep an eye on the correlation ID in trace logs to track specific jobs and their execution flow. By staying vigilant and responsive to the insights provided by your monitoring setup, you can maintain a robust and reliable GitLab Runner environment.

Scaling Runners Horizontally and Vertically

Scaling your GitLab Runner setup is crucial for handling increased loads and ensuring efficient CI/CD processes. Horizontal scaling involves adding more runners to your setup, which can be done by registering additional runners to your GitLab instance. This approach is beneficial when you need to distribute the load across multiple runners to handle concurrent jobs.

Vertical scaling, on the other hand, refers to increasing the resources of your existing runners. This might include upgrading the CPU, memory, or storage to improve performance for intensive tasks. It’s important to monitor your runners’ performance and scale appropriately to maintain an optimal balance between cost and efficiency.

When considering scaling, always evaluate the current load and performance metrics to make informed decisions.

Here’s a quick checklist for scaling your runners:

  • Monitor current runner performance and workload
  • Determine if horizontal or vertical scaling is needed based on the load
  • Register additional runners for horizontal scaling
  • Upgrade runner resources for vertical scaling
  • Re-evaluate performance post-scaling to ensure efficiency

Analyzing Runner Metrics and Logs

To ensure your GitLab Runner is performing optimally, regular analysis of metrics and logs is crucial. Metrics provide insights into the health and efficiency of your runners, while logs can help pinpoint issues that may affect performance or cause failures.

Start by accessing the metrics dictionary to understand the available metrics and what they represent. This will be your guide to interpreting the data collected. Next, utilize the metrics instrumentation guide to set up and customize the collection of metrics relevant to your setup.

Here’s a simple table to help you keep track of key metrics:

Metric Name Description Importance
CPU Usage Measures the CPU resources consumed by the runner High
Memory Usage Tracks the amount of memory used Medium
Job Duration Time taken to execute a job High
Error Rate Frequency of failed jobs High

Remember, consistent monitoring and analysis of these metrics can preempt many issues before they escalate.

Logs complement metrics by providing detailed narratives of events. Regularly review logs to identify any anomalies or patterns that could indicate underlying problems. Establish a routine for log analysis, and consider setting up alerts for specific error types or thresholds.

Staying Up-to-Date with GitLab Runner

Staying Up-to-Date with GitLab Runner

Following Best Practices for Updates

Keeping your GitLab Runner up-to-date is crucial for security, performance, and access to the latest features. Always update to the latest stable release to minimize the risk of vulnerabilities and to benefit from the latest improvements. When updating, it’s essential to review the release notes for any breaking changes or deprecations that could affect your current setup.

Backup your configuration and data before applying updates. This ensures that you can restore your system to a working state in case the update introduces issues. Here’s a simple checklist to follow when updating your GitLab Runner:

  • Check the official GitLab Runner changelog for the latest version information.
  • Review the release notes for any important changes or migration steps.
  • Backup your config.toml file and any other important data.
  • Apply the update following the official GitLab documentation.
  • Test your runner to ensure it operates correctly with your projects.

Remember, a well-maintained GitLab Runner is less prone to issues and can provide a more stable CI/CD environment. Regular updates are a key part of system maintenance and should be scheduled accordingly.

Understanding Deprecations and Support Policy

Staying informed about the deprecations and support policies of GitLab Runner is crucial for maintaining a stable CI/CD environment. GitLab provides a comprehensive list of deprecated features, which is essential for planning upgrades and avoiding unexpected issues. This list can be found in the GitLab documentation and is regularly updated to reflect the latest changes.

When it comes to support policies, GitLab Runner adheres to a clear lifecycle. Each version receives updates and support for a specific period after its release. It’s important to track these timelines to ensure your runners are always covered by the latest security patches and feature improvements. Below is a simplified overview of the support policy stages:

  • Active Support: Full support including bug fixes, security patches, and new features.
  • Maintenance Support: Only critical bug fixes and security patches.
  • End of Life: No further updates or support.

Remember to subscribe to GitLab’s notification channels to be alerted of upcoming breaking changes and end-of-life announcements for older versions.

By keeping an eye on the deprecation notices and support timelines, you can proactively manage your GitLab Runner instances and minimize disruptions to your development workflows.

Keeping Track of What’s New in GitLab Runner Releases

To stay ahead in the fast-paced world of continuous integration, it’s crucial to keep abreast of the latest updates and features in GitLab Runner. Regularly reviewing the ‘What’s new’ section on the GitLab documentation site is a best practice for all DevOps professionals. This section provides a concise overview of new features, improvements, and crucial fixes with each release.

GitLab Runner releases are frequent and may include important changes that can impact your CI/CD workflows. To ensure a smooth transition and take advantage of new capabilities, consider the following steps:

  • Monitor the official GitLab Runner changelog.
  • Test new versions in a staging environment before rolling out to production.
  • Keep an eye on deprecation notices to avoid future compatibility issues.

By proactively managing updates, you can maintain a robust and efficient CI/CD pipeline, minimizing disruptions and leveraging the latest advancements in GitLab Runner technology.

Conclusion

You’ve now successfully navigated through the intricacies of installing and configuring GitLab Runner on a Windows system. Whether you’re integrating with a Windows Professional desktop OS, a Windows Server environment, or leveraging Docker and Kubernetes configurations, the steps outlined should have provided a clear path to getting your CI/CD pipelines up and running. Remember, while this guide is tailored for Windows users, GitLab’s flexibility allows for a variety of setups across different platforms. As you move forward, keep an eye on GitLab’s updates and best practices to ensure your runners remain efficient and secure. Happy coding!

Frequently Asked Questions

What are the system requirements for installing GitLab Runner on a Windows system?

The system requirements include a version of Windows that is compatible with GitLab Runner, such as Windows Professional (Desktop OS) or Windows Server, along with sufficient memory and CPU resources to handle the expected workload. Virtualization or cloud instances can be used for support and development purposes.

Do I need special permissions to install GitLab Runner on Windows?

Yes, you will need administrative permissions to install and configure GitLab Runner, as well as to manage Windows services and handle system-level configurations.

How do I choose the right version of GitLab Runner for my Windows system?

You should choose a version of GitLab Runner that is compatible with your version of GitLab. Always refer to the official GitLab documentation for the supported GitLab Runner versions.

How can I verify that GitLab Runner has been installed successfully on Windows?

After installation, you can run the ‘gitlab-runner –version’ command in the command prompt to verify that GitLab Runner has been installed and to check the installed version.

How do I register GitLab Runner with my GitLab instance on Windows?

To register GitLab Runner with your GitLab instance, you will need to edit the ‘config.toml’ file with the correct registration token from your GitLab instance and run the ‘gitlab-runner register’ command.

What are the steps to install GitLab Runner as a Windows service?

To install GitLab Runner as a Windows service, use the ‘gitlab-runner install’ command followed by ‘gitlab-runner start’ to initiate the service. Ensure that you have administrative permissions to manage services.

How do I handle self-signed certificates when securing my GitLab Runner setup?

For self-signed certificates, you need to update the GitLab Runner’s ‘config.toml’ file to specify the location of the certificate and mount it properly if using Docker or Kubernetes executors.

What should I do if I encounter issues with my GitLab Runner service on Windows?

If you encounter issues with the GitLab Runner service, check the logs for error messages, ensure that the ‘config.toml’ file is correctly configured, and verify that all required services are running. You may also refer to the GitLab documentation for troubleshooting tips.

По натуре своей многие разработчики слишком ленивые не любят делать одно и то же действие много раз. Нам проще научить компьютер, чтобы он делал монотонные действия за нас.

Как только кто-либо из нашей команды вносит изменения в код (читай «мерджит feature-ветку в develop»), наш билд-сервер:

  • Собирает исходный код и установщик приложения
    • проставляет номер сборки, каждый раз увеличивая последнюю цифру. Например, текущая версия нашего ПО 3.3.0.202 – часть 3.3.0 когда-то ввёл разработчик (привет, SemVer), а «202» проставляется в процессе сборки.
    • В процессе анализирует качество кода (с использованием SonarQube) – и отправляет отчёт во внутренний SonarQube,
  • Сразу после сборки запускает автотесты (xUnit) и анализирует покрытие тестами (OpenCover),

Также, в зависимости от ветки, в которую были внесены изменения, могут быть выполнены:

  • отправка сборки (вместе с changelog-ом) в один или несколько телеграм-каналов (иногда удобнее брать сборки оттуда).
  • публикация файлов в систему автообновления ПО.

Под катом о том, как мы научили Gitlab CI делать за нас бОльшую часть этой муторной работы.

Оглавление

  1. Устанавливаем и регистрируем Gitlab Runner.
  2. Что нужно знать про .gitlab-ci.yml и переменные сборки.
  3. Активируем режим Developer PowerShell for VS.
  4. Используем CI для проставления версии во все сборки решения.
  5. Добавляем отправку данных в SonarQube.
  6. «Причёсываем» автотесты xUnit + добавляем вычисление покрытия тестами через OpenCover.
  7. Послесловие.

Перед началом

Чтобы быть уверенными, что написанное ниже работает, мы взяли на github небольшой проект, написанный на WPF и имеющий unit-тесты, и воспроизвели на нём описанные в статье шаги. Самые нетерпеливые могут сразу зайти в созданный на сайте gitlab.com репозиторий и посмотреть, как это выглядит.

Устанавливаем и регистрируем Gitlab Runner

Для того чтобы Gitlab CI мог что-либо собрать, сначала установите и настройте Gitlab Runner на машине, на которой будет осуществляться сборка. В случае проекта на .Net Framework это будет машина с ОС Windows.

Чтобы настроить Gitlab Runner, выполните следующие шаги:

  1. Установите Git для Windows с сайта git.
  2. Установите Visual Studio с сайта Microsoft. Мы поставили себе Build Tools для Visual Studio 2019. Чтобы скачать именно его, разверните список Инструменты для Visual Studio 2019.
  3. Создайте папку C:\GitLab-Runner и сохраните в неё программу gitlab runner. Скачать её можно со страницы [документации Gitlab] (https://docs.gitlab.com/runner/install/windows.html) — ссылки скрыты прямо в тексте: «Download the binary for x86 or amd64».
  4. Запустите cmd или powershell в режиме администратора, перейдите в папку C:\GitLab-Runner и запустите скачанный файл с параметром install (Gitlab runner установится как системная служба).
        .\gitlab-runner.exe install
  5. Посмотрите токен для регистрации Runner-а. В зависимости от того, где будет доступен ваш Runner:
    • только в одном проекте — смотрите токен в меню проекта Settings > CI/CD в разделе Runners,
    • в группе проектов — смотрите токен в меню группы Settings > CI/CD в разделе Runners,
    • для всех проектов Gitlab-а — смотрите токен в секции администрирования, меню Overview > Runners.
  6. Выполните регистрацию Runner-а, с помощью команды
        .\gitlab-runner.exe register

Далее надо ввести ответы на вопросы мастера регистрации Runner-а:

  • coordinator URL — http или https адрес вашего сервера gitlab;
  • gitlab-ci token — введите токен, полученный на предыдущем шаге;
  • gitlab-ci description — описание Runner-а, которое будет показываться в интерфейсе Gitlab-а;
  • gitlab-ci tags — через запятую введите тэги для Runner-а. Если вы не знакомы с этим механизмом, оставьте поле пустым — отредактировать его можно позднее через интерфейс самого gitlab-а. Тэги можно использовать для того, чтобы определённые задачи выполнялись на определённых Runner-ах (например, чтобы настроить сборку ПО на Runner-е, развёрнутом на копьютере ОС Windows, а подготовку документации на Runner-е с ОС Linux);
  • enter the executor — ответьте shell. На этом шаге указывается оболочка, в которой будут выполняться команды; при указании значения shell под windows выбирается оболочка powershell, а последующие скрипты написаны именно для неё.

Что нужно знать про .gitlab-ci.yml и переменные сборки

В процессе своей работы Gitlab CI берёт инструкции о том, что делать в процессе сборки того или иного репозитория из файла .gitlab-ci.yml, который следует создать в корне репозитория.

Вбив в поиске содержимое .gitlab-ci.yml для сборки приложения .NET Framework можно найти несколько шаблонов: 1, 2. Выглядят они примерно так:

variables:
  # Максимальное количество параллельно собираемых проектов при сборке решения; зависит от количества ядер ПК, выбранного для сборки
  MSBUILD_CONCURRENCY: 4
  # Тут куча путей до утилит, которые просто обязаны лежать там, где ожидается
  NUGET_PATH: 'C:\Tools\Nuget\nuget.exe'
  MSBUILD_PATH: 'C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\msbuild.exe'
  XUNIT_PATH: 'C:\Tools\xunit.runner.console.2.3.1\xunit.console.exe'
  TESTS_OUTPUT_FOLDER_PATH: '.\tests\CiCdExample.Tests\bin\Release\'

# Тут указываются стадии сборки. Указывайте любые названия которые вам нравятся, но по умолчанию используют три стадии: build, test и deploy.
# Стадии выполняются именно в такой последовательности.
stages:
  - build
  - test

# Далее описываются задачи (job-ы)

build_job:
  stage: build # указание, что задача принадлежит этапу build
  # tags: windows # если тут указать тэг, задача будет выполняться только на Runner-е с указанным тэгом 
  only: # для каких сущностей требуется выполнять задачу
    - branches
  script: # код шага
    - '& "$env:NUGET_PATH" restore'
    - '& "$env:MSBUILD_PATH" /p:Configuration=Release /m:$env:MSBUILD_CONCURRENCY /nr:false /clp:ErrorsOnly' # сборка; ключ clp:ErrorsOnlyоставляет только вывод ошибок; ключ nr:false завершает инстансы msbuild 
  artifacts: # где по завершении задачи будут результаты, которые надо сохранить в gitlab (т.н. артефакты) и которые можно будет передать другим задачам по цепочке
    expire_in: 2 days # сколько хранить артефакты
    paths: # список путей, по которым находятся файлы для сохранения
      - '$env:TESTS_OUTPUT_FOLDER_PATH'

test_job:
  stage: test
  only:
    - branches
  script:
    - '& "$env:XUNIT_PATH" "$env:TESTS_OUTPUT_FOLDER_PATH\CiCdExample.Tests.dll"'
  dependencies: # указание, что для запуска этой задачи требуется успешно завершенная задача build_job
    - build_job

И последнее: если нам требуется передавать в скрипт значение параметра, который мы не хотим хранить в самом скрипте (например, пароль для подключения куда-либо), мы можем использовать для этого объявление параметров в gitlab. Для этого зайдите в проекте (или в группе проекта) в Settings > CI/CD и найдите раздел Variables. Прописав в нём параметр с именем (key) SAMPLE_PARAMETER, вы сможете получить его значение в в скрипте .gitlab-ci.yml через обращение $env:SAMPLE_PARAMETER.

Также в этом разделе можно настроить передачу введенных параметров только при сборке защищённых веток (галочка Protected) и/или скрытие значения параметра из логов (галочка Masked).

Подробнее о параметрах окружения сборки смотрите в документации к Gitlab CI.

Активируем режим Developer PowerShell for VS

Скрипт, приведённый выше, уже можно использовать для сборки и вызова тестов. Правда, присутствует НО: крайне неудобно прописывать абсолютные пути к разным установкам Visual Studio. К примеру, если на одной билд-машине стоит Visual Studio 2017 BuildTools, а на другой Visual Studio Professional 2019, то такой скрипт будет работать только для одной из двух машин.

К счастью, с версии Visual Studio 2017 появился способ поиска всех инсталляций Visual Studio на компьютере. Для этого существует утилита vswhere, путь к которой не привязан ни к версии Visual Studio, ни к её редакции. А в Visual Studio 2019 (в версии 16.1 или более новой) есть библиотека, которая умеет «трансформировать» консоль Powershell в режим Developer Powershell, в котором уже прописаны пути к утилитам из поставки VS.

Как применить

Дописываем переменную к секции Variables:

variables:
  VSWHERE_PATH: '%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe'

Затем создаём новую секцию before_msbuild якорем enter_vsdevshell и следующим текстом:

.before_msbuild: &enter_vsdevshell
  before_script:
    - '$vsWherePath = [System.Environment]::ExpandEnvironmentVariables($env:VSWHERE_PATH)'
    - '& $vsWherePath -latest -format value -property installationPath -products Microsoft.VisualStudio.Product.BuildTools | Tee-Object -Variable visualStudioPath'
    - 'Join-Path "$visualStudioPath" "\Common7\Tools\Microsoft.VisualStudio.DevShell.dll" | Import-Module'
    - 'Enter-VsDevShell -VsInstallPath:"$visualStudioPath" -SkipAutomaticLocation'

И всюду, где нам надо использовать утилиты Visual Studio, добавляем этот якорь. После этого задача сборки начинает выглядеть намного более опрятно:

build_job:
  <<: *enter_vsdevshell
  stage: build
  only:
    - branches
  script:
    - 'msbuild /t:restore /m:$env:MSBUILD_CONCURRENCY /nr:false /clp:ErrorsOnly'
    - 'msbuild /p:Configuration=Release /m:$env:MSBUILD_CONCURRENCY /nr:false /clp:ErrorsOnly'
  artifacts:
    expire_in: 2 days
    paths:
      - '$env:TESTS_OUTPUT_FOLDER_PATH'

Подробно о том, что написано в .before_msbuild

  1. Утилита vswhere.exe умеет находить и выдавать список найденных инсталляций Visual Studio. Расположен она всегда по одному и тому же пути (этот путь записан в переменной VSWHERE_PATH). Поскольку в переменной фигурирует подстановка %programfiles%, её требуется раскрыть до пути к этой папке. Такое раскрытие проще всего сделать через статический метод .NET System.Environment.ExpandEnvironmentVariables.

Результат: мы имеем путь к vswhere.

  1. Вызовом vswhere получим путь к папке с установленной Visual Studio.
    Все параметры утилиты можно посмотреть, если запустить vswhere.exe с параметром -help, в статье же только перечислю использованные:

    • -latest (искать самые свежие установки),
    • -property installationPath (вывести параметр пути установки),
    • -format value (при печати параметра вывести только значение параметра, без его имени),
    • -products <список искомых инсталляций Visual Studio, пробел считается разделителем элементов списка> (указание искомых редакций Visual Studio). Например, при запуске с параметром -products Microsoft.VisualStudio.Product.Community Microsoft.VisualStudio.Product.BuildTools утилита попробует найти Visual Studio редакций Community или BuildTools. Подробнее об идентификаторах продуктов смотрите по ссылке https://aka.ms/vs/workloads.

Результат: в переменную $visualStudioPath записан путь к Visual Studio или пустая строка, если инсталляций Visual Studio не найдено (обработку этой ситуации мы ещё не добавили).

  1. Команда Import-Module загружает библиотеку Microsoft.VisualStudio.DevShell.dll, в которой прописаны командлеты трансформации консоли Powershell в Developer-консоль. А командлет Join-Path формирует путь к этой библиотеке относительно пути установки Visual Studio.
    На этом шаге нам прилетит ошибка, если библиотека Microsoft.VisualStudio.DevShell.dll отсутствует или путь к установке Visual Studio нужной редакции не был найден — Import-Module сообщит, что не может загрузить библиотеку.

Результат: загружен модуль Powershell с командлетом трансформации.

  1. Запускаем «переделку» консоли в Developer Powershell. Чтобы корректно прописать пути к утилитам, командлету требуется путь к установленной Visual Studio (параметр -VsInstallPath). А указаниеSkipAutomaticLocation требует от командлета не менять текущее расположение (без этого параметра путь меняется на <домашнаяя папка пользователя>\source\repos).

Результат: мы получили полноценную консоль Developer Powershell с прописанными путями к msbuild и многим другим утилитам, которые можно использовать при сборке.

Используем CI для проставления версии во все сборки решения

Раньше мы использовали t4 шаблоны для проставления версий: номер версии собиралась из содержимого файла в формате <major>.<minor>.<revision>, далее к ней добавлялся номер сборки из Gitlab CI и он передавался в tt-шаблон, добавляющий в решение везде, где требуется, номер версии. Однако некоторое время назад был найден более оптимальный способ — использование команд git tag и git describe.

Команда git tag устанавливает коммиту метку (тэг). Отметить таким образом можно любой коммит в любой момент времени. В отличие от веток, метка не меняется. То есть если после помеченного коммита вы добавите ещё один, метка останется на помеченном коммите. Если попробуете переписать отмеченный коммит командами git rebase или git commit —amend, метка также продолжит указывать на исходный коммит, а не на изменённый. Подробнее о метках смотрите в git book.

Команда git describe, к сожалению, в русскоязычном gitbook не описана. Но работает она примерно так: ищет ближайшего помеченного родителя текущего коммита. Если такого коммита нет — команда возвращает ошибку fatal: No tags can describe '<тут хэш коммита>'. А вот если помеченный коммит нашёлся — тогда команда возвращает строку, в которой участвует найденная метка, а также количество коммитов между помеченным и текущим.

На заметку: чтобы данная команда работала корректно во всех случаях, автор gitflow даже чуть-чуть поменял скрипты finish hotfix и finish release. Если кому интересно посмотреть обсуждение с автором gitflow, а также увидеть что изменилось (картинка с актуальной схемой в последнем сообщении в треде).

Кстати, по этой же причине если вы используете gitflow, после вливания feature-ветки в develop требуется удалить влитую локальную ветку, после чего пересоздать её от свежего develop:

(обратите внимание на историю git в левой части картинки: из-за отсутствия пути из текущего коммита до коммита с меткой 1.0.5, команда git describe выдаст неверный ответ)

Но вернёмся к автопроставлению версии. В нашем репозитории царит gitflow (точнее его rebase-версия), метки расставляются в ветке master и мы не забываем пересоздавать feature-ветки от develop, а также merge-ить master в develop после каждого релиза или хотфикса.

Тогда получить версию для любого коммита и сразу передать её в msbuild можно добавив всего пару строк к задаче сборки:

build_job:
  <<: *enter_vsdevshell
  stage: build
  only:
    - branches
  script:
    - 'msbuild /t:restore /m:$env:MSBUILD_CONCURRENCY /nr:false /clp:ErrorsOnly'
    - '$versionGroup = git describe --long | Select-String -Pattern "(?<major>[0-9]+)\.(?<minor>[0-9]*)\.(?<patch>[0-9]*)\-(?<commit>[0-9]+)\-g[0-9a-f]+" | Select-Object -First 1'
    - '[int]$major, [int]$minor, [int]$patch, [int]$commit = $versionGroup.Matches[0].Groups["major", "minor", "patch", "commit"].Value'
    - '[string]$version = "$major.$minor.$patch.$commit"'
    - 'msbuild /p:Configuration=Release /p:AssemblyVersionNumber=$version /m:$env:MSBUILD_CONCURRENCY /nr:false /clp:ErrorsOnly'
  artifacts:
    expire_in: 2 days
    paths:
      - '$env:TESTS_OUTPUT_FOLDER_PATH'

Как это работает:

  1. Мы проставляем метки в формате <major>.<minor>.<revision>.
  2. Тогда git describe --long возвращает нам строку, описывающую версию в формате <major>.<minor>.<revision>-<количество новых коммитов>-g<хэш текущего коммита>.
  3. Парсим полученную строку через регулярные выражения, выделяя нужные нам части — и записывем части в $versionGroup.
  4. Преобразовываем четыре найденные подстроки в 4 числа и пишем их в переменные $major, $minor, $patch, $commit, после чего собираем из них строку уже в нужном нам формате.
  5. Передаём указанную строку в msbuild чтобы он сам проставил версию файлов при сборке.

Обратите внимание: если вы, согласно gitflow, будете отмечать (тэгировать) ветку master после вливания в неё release или hofix, будьте внимательны: до простановки метки автосборка будет вестись относительно последней существующей ветки. Например, сейчас опубликована версия 3.4, а вы создаёте release-ветку для выпуска версии 3.5. Так вот: всё время существования этой ветки, а также после её вливания в master, но до простановки тэга, автосборка будет проставлять версию 3.4.

Добавляем отправку данных в SonarQube

SonarQube — это мощный инструмент контроля качества кода.

SonarQube имеет бесплатную Community-версию, которая способна проводить полный анализ. Правда, только одной ветки. Чтобы настроить её на контроль качества ветки разработки (develop), требуется выполнить следующие шаги (разумеется, помимо установки и развёртывания сервера SonarQube):

  1. Создайте в SonarQube новый проект, после чего запомните его ключ.
  2. Скачайте SonarScanner for MSBuild (с сайта sonarqube.org)[https://docs.sonarqube.org/latest/analysis/scan/sonarscanner-for-msbuild/] — мы используем версию .NET Framework 4.6+.
  3. Распакуйте содержимое архива в папку. Например, в C:\Tools\SonarScanner.
    На заметку: эту утилиту также можно скачать на сборочную машину через NuGet, но тогда надо будет чуть по-иному указывать её путь.
  4. Зайдите в параметры CI/CD в свойствах проекта Gitlab и добавьте следующие параметры:
    • SONARQUBE_PROJECT_KEY — ключ проекта,
    • SONARQUBE_AUTH_TOKEN — токен авторизации.

      Прописывать параметр ключа проекта необходимо для каждого проекта отдельно (ведь у каждого проекта свой уникальный ключ). А параметр токена авторизации желательно скрыть (отметить как Masked) чтобы он не был доступен всем, кто имете доступ к репозиторию или логам сборки.

  5. Допишите переменные к секции Variables:
        variables:
          SONARSCANNER_MSBUILD_PATH: 'C:\Tools\SonarScanner\SonarScanner.MSBuild.exe'
          SONARQUBE_HOST_URL: 'url вашего сервера SonarQube'
  6. Допишите в задачу тестирования ветки разработки (test_job) команды для запуска анализа кода и уберите зависимость от задачи build_job:
        test_job:
          stage: test
          only:
            - /^develop$/
          <<: *enter_vsdevshell
          script:
            - '$versionGroup = git describe --long | Select-String -Pattern "(?<major>[0-9]+)\.(?<minor>[0-9]*)\.(?<patch>[0-9]*)\-(?<commit>[0-9]+)\-g[0-9a-f]+" | Select-Object -First 1'
            - '[int]$major, [int]$minor, [int]$patch, [int]$commit = $versionGroup.Matches[0].Groups["major", "minor", "patch", "commit"].Value'
            - '[string]$version = "$major.$minor.$patch.$commit"'
            - '& "$env:SONARSCANNER_MSBUILD_PATH" begin /key:$env:SONARQUBE_PROJECT_KEY /d:sonar.host.url=$env:SONARQUBE_HOST_URL /d:sonar.login=$env:SONARQUBE_AUTH_TOKEN /d:sonar.gitlab.project_id=$CI_PROJECT_PATH /d:sonar.gitlab.ref_name=develop /v:$version /d:sonar.dotnet.excludeGeneratedCode=true'
            - 'msbuild /t:rebuild /m:$env:MSBUILD_CONCURRENCY /nr:false /clp:ErrorsOnly'
            - '& "$env:SONARSCANNER_MSBUILD_PATH" end /d:sonar.login=$env:SONARQUBE_AUTH_TOKEN'
            - '& "$env:XUNIT_PATH" "$env:TESTS_OUTPUT_FOLDER_PATH\CiCdExample.Tests.dll"'

Теперь при каждой сборке ветки develop в SonarQube будет отправляться подробный анализ нашего кода.

На заметку: вообще команда msbuild /t:rebuild полностью пересобирает решение. Вероятно, в большинстве проектов анализ можно было бы встроить прямо в стадию сборки. Но сейчас у нас анализ в отдельной задаче.

Пара слов об использованных параметрах:

  • key — ключ проекта на сервере SonarQube,
  • v — собираемая версия. Отлично комбинируется с предыдущим шагом автопроставления версии,
  • sonar.gitlab.project_id — ID проекта на сервере Gitlab,
  • sonar.gitlab.ref_name — название ветки, которое получает сервер SonarQube при передаче результатов анализа,
  • sonar.dotnet.excludeGeneratedCode — не включать в анализ объекты, отмеченные атрибутом System.CodeDom.Compiler.GeneratedCode (чтобы не оценивать качество автосгенерированного кода).

«Причёсываем» автотесты xUnit + добавляем вычисление покрытия тестами через OpenCover

Со сборкой более-менее разобрались — теперь приступаем к тестам. Доработаем код прогона тестов, чтобы он:

  • сам находил библиотеки с тестами,
  • прогонял их пачкой через xUnit,
  • вычислял тестовое покрытие через OpenConver,
  • отправлял результаты покрытия тестами в SonarQube.

На заметку: обычно в паре с OpenCover используют ReportGenerator, но при наличии SonarQube мы с тем же успехом можем смотреть результаты через его интерфейс.

Для настройки выполним следующие шаги:

  1. Скачайте OpenCover в виде zip-файла с сайта github.
  2. Распакуйте содержимое архива в папку. Например, в C:\Tools\OpenCover.
    На заметку: эту утилиту также можно скачать на сборочную машину через NuGet, но тогда надо будет чуть по-иному указывать её путь.
  3. Допишите переменные к секции Variables:
        variables:
          OBJECTS_TO_TEST_REGEX: '^Rt[^\n]*\.(dll|exe)$'
          OPENCOVER_PATH: 'C:\Tools\opencover-4.7.922\xunit.console.exe'
          OPENCOVER_FILTER: '+[Rt.*]* -[*UnitTests]* -[*AssemblyInfo]*'
          OPENCOVER_REPORT_FILE_PATH: '.\cover.xml'
  4. Модифицируйте задачу тестирования ветки разработки (test_job), чтобы она включала и команды вызова OpenCover:
        test_job:
          stage: test
          only:
            - /^develop$/
          <<: *enter_vsdevshell
          script:
            - '$versionGroup = git describe --long | Select-String -Pattern "(?<major>[0-9]+)\.(?<minor>[0-9]*)\.(?<patch>[0-9]*)\-(?<commit>[0-9]+)\-g[0-9a-f]+" | Select-Object -First 1'
            - '[int]$major, [int]$minor, [int]$patch, [int]$commit = $versionGroup.Matches[0].Groups["major", "minor", "patch", "commit"].Value'
            - '[string]$version = "$major.$minor.$patch.$commit"'
            - '& "$env:SONARSCANNER_MSBUILD_PATH" begin /key:$env:SONARQUBE_PROJECT_KEY /d:sonar.host.url=$env:SONARQUBE_HOST_URL /d:sonar.login=$env:SONARQUBE_AUTH_TOKEN /d:sonar.gitlab.project_id=$CI_PROJECT_PATH /d:sonar.gitlab.ref_name=develop /v:$version /d:sonar.cs.opencover.reportsPaths="$env:OPENCOVER_REPORT_FILE_PATH" /d:sonar.dotnet.excludeGeneratedCode=true'
            - 'msbuild /t:rebuild /m:$env:MSBUILD_CONCURRENCY /nr:false /clp:ErrorsOnly'
            - '$dllsToRunUnitTesting = @(Get-ChildItem "$env:TESTS_OUTPUT_FOLDER_PATH" -Recurse) | Where-Object {$_.Name -match $env:OBJECTS_TO_TEST_REGEX} | ForEach-Object { """""$_""""" } | Join-String -Separator " "'
            - '& "$env:OPENCOVER_PATH" -register -target:"$env:XUNIT_PATH" -targetargs:"$dllsToRunUnitTesting -noshadow" -filter:"$env:OPENCOVER_FILTER" -output:"$env:OPENCOVER_REPORT_FILE_PATH" | Write-Host'
            - 'if ($?) {'
            - '[xml]$coverXml = Get-Content "$env:OPENCOVER_REPORT_FILE_PATH"'
            - '$sequenceCoverage = $coverXml.CoverageSession.Summary.sequenceCoverage'
            - '$branchCoverage = $coverXml.CoverageSession.Summary.branchCoverage'
            - 'Write-Host "Total Sequence Coverage <!<$sequenceCoverage>!>"'
            - 'Write-Host "Total Branch Coverage [![$branchCoverage]!]"'
            - '} else {'
            - 'Write-Host "One or more tests failed!"'
            - 'Throw'
            - '}'
            - '& "$env:SONARSCANNER_MSBUILD_PATH" end /d:sonar.login=$env:SONARQUBE_AUTH_TOKEN'

    Обратите внимание: в begin-команде запуска sonar scanner-а появился дополнительный параметр — /d:sonar.cs.opencover.reportsPaths.

    (необязательный пункт) Ненадолго возвращаемся в Gitlab, заходим в меню проекта Settings > CI/CD и находим на странице настроек параметр Test coverage parsing. Указываем в нём регулярное выражение, которое позволит Gitlab-у также получать информацию о покрытии тестами приложения:

    • если хочется видеть значение покрытия тестов по строкам кода (его ешё называют Sequence Coverage или Statement Coverage), указываем выражение <!<([^>]+)>!>,
    • если хочется видеть значение покрытия тестов по веткам условных операторов (его называют Decision Coverage или Branch Coverage), указываем выражение \[!\[([^>]+)\]!\].

Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.

Какие примеры использования автосборки/автопубликации вам интересны?

10% Публикация артефактов сборки: на сайт, в телеграм-канал1

30% Создание и сборка инсталлера3

20% Оповещение об этапах сборки и ошибках: в телеграм, в слак, по почте2

90% Автосборка и тестирование в .NET 5/.NET Core9

10% Другое, напишу в комментариях1

Проголосовали 10 пользователей. Воздержались 2 пользователя.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Hot keys for windows
  • Пакеты обновления windows 2000
  • Rdp client windows 10 portable
  • Usb флешка восстановления windows 10
  • Ntbackup windows server 2012