- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
Runner registration is the process that links the runner with one or more GitLab instances. You must register the runner so that it can pick up jobs from the GitLab instance.
Requirements
Before you register a runner:
- Install GitLab Runner on a server separate to where GitLab
is installed. - For runner registration with Docker, install GitLab Runner in a Docker container.
Register with a runner authentication token
Prerequisites:
- Obtain a runner authentication token. You can either:
- Create an instance,
group, or
project runner. - Locate the runner authentication token in the
config.toml
file. Runner authentication tokens have the prefix,glrt-
.
- Create an instance,
After you register the runner, the configuration is saved to the config.toml
.
To register the runner with a runner authentication token:
-
Run the register command:
sudo gitlab-runner register
If you are behind a proxy, add an environment variable and then run the
registration command:export HTTP_PROXY=http://yourproxyurl:3128 export HTTPS_PROXY=http://yourproxyurl:3128 sudo -E gitlab-runner register
.\gitlab-runner.exe register
sudo -u gitlab-runner -H /usr/local/bin/gitlab-runner register
To register with a container, you can either:
-
Use a short-lived
gitlab-runner
container with the correct configuration volume mount:-
For local system volume mounts:
docker run --rm -it -v /srv/gitlab-runner/config:/etc/gitlab-runner gitlab/gitlab-runner register
If you used a configuration volume other than
/srv/gitlab-runner/config
during installation, update the command with the correct volume. -
For Docker volume mounts:
docker run --rm -it -v gitlab-runner-config:/etc/gitlab-runner gitlab/gitlab-runner:latest register
-
-
Use the executable inside an active runner container:
docker exec -it gitlab-runner gitlab-runner register
-
-
Enter your GitLab URL:
- For runners on GitLab Self-Managed, use the URL for your GitLab instance. For example,
if your project is hosted ongitlab.example.com/yourname/yourproject
, your GitLab instance URL ishttps://gitlab.example.com
. - For runners on GitLab.com, the GitLab instance URL is
https://gitlab.com
.
- For runners on GitLab Self-Managed, use the URL for your GitLab instance. For example,
-
Enter the runner authentication token.
-
Enter a description for the runner.
-
Enter the job tags, separated by commas.
-
Enter an optional maintenance note for the runner.
-
Enter the type of executor.
- To register multiple runners on the same host machine, each with a different configuration,
repeat theregister
command. - To register the same configuration on multiple host machines, use the same runner authentication token
for each runner registration. For more information, see Reusing a runner configuration.
You can also use the non-interactive mode to use additional arguments to register the runner:
sudo gitlab-runner register \
--non-interactive \
--url "https://gitlab.com/" \
--token "$RUNNER_TOKEN" \
--executor "docker" \
--docker-image alpine:latest \
--description "docker-runner"
gitlab-runner register \
--non-interactive \
--url "https://gitlab.com/" \
--token "$RUNNER_TOKEN" \
--executor "docker" \
--docker-image alpine:latest \
--description "docker-runner"
.\gitlab-runner.exe register \
--non-interactive \
--url "https://gitlab.com/" \
--token "$RUNNER_TOKEN" \
--executor "docker-windows" \
--docker-image mcr.microsoft.com/windows/servercore:1809_amd64 \
--description "docker-runner"
sudo -u gitlab-runner -H /usr/local/bin/gitlab-runner register
--non-interactive \
--url "https://gitlab.com/" \
--token "$RUNNER_TOKEN" \
--executor "docker" \
--docker-image alpine:latest \
--description "docker-runner"
docker run --rm -v /srv/gitlab-runner/config:/etc/gitlab-runner gitlab/gitlab-runner register \
--non-interactive \
--url "https://gitlab.com/" \
--token "$RUNNER_TOKEN" \
--executor "docker" \
--docker-image alpine:latest \
--description "docker-runner"
Register with a runner registration token (deprecated)
The ability to pass a runner registration token and support for certain configuration arguments was
deprecated in GitLab 15.6. They are scheduled for removal
in GitLab 20.0. Use runner authentication tokens instead. For more information, see
Migrating to the new runner registration workflow.
Prerequisites:
- Runner registration tokens must be enabled in the Admin Area.
- Obtain a runner registration token
at the desired instance,
group, or
project.
After you register the runner, the configuration is saved to the config.toml
.
To register the runner with a runner registration token:
-
Run the register command:
sudo gitlab-runner register
If you are behind a proxy, add an environment variable and then run the
registration command:export HTTP_PROXY=http://yourproxyurl:3128 export HTTPS_PROXY=http://yourproxyurl:3128 sudo -E gitlab-runner register
.\gitlab-runner.exe register
sudo -u gitlab-runner -H /usr/local/bin/gitlab-runner register
To launch a short-lived
gitlab-runner
container to register the container
you created during installation:-
For local system volume mounts:
docker run --rm -it -v /srv/gitlab-runner/config:/etc/gitlab-runner gitlab/gitlab-runner register
If you used a configuration volume other than
/srv/gitlab-runner/config
during installation, update the command with the correct volume. -
For Docker volume mounts:
docker run --rm -it -v gitlab-runner-config:/etc/gitlab-runner gitlab/gitlab-runner:latest register
-
-
Enter your GitLab URL:
- For runners on GitLab Self-Managed, use the URL for your GitLab instance. For example,
if your project is hosted ongitlab.example.com/yourname/yourproject
, your GitLab instance URL ishttps://gitlab.example.com
. - For GitLab.com, the GitLab instance URL is
https://gitlab.com
.
- For runners on GitLab Self-Managed, use the URL for your GitLab instance. For example,
-
Enter the token you obtained to register the runner.
-
Enter a description for the runner.
-
Enter the job tags, separated by commas.
-
Enter an optional maintenance note for the runner.
-
Enter the type of executor.
To register multiple runners on the same host machine, each with a different configuration,
repeat the register
command.
You can also use the non-interactive mode to use additional arguments to register the runner:
sudo gitlab-runner register \
--non-interactive \
--url "https://gitlab.com/" \
--registration-token "$PROJECT_REGISTRATION_TOKEN" \
--executor "docker" \
--docker-image alpine:latest \
--description "docker-runner" \
--maintenance-note "Free-form maintainer notes about this runner" \
--tag-list "docker,aws" \
--run-untagged="true" \
--locked="false" \
--access-level="not_protected"
gitlab-runner register \
--non-interactive \
--url "https://gitlab.com/" \
--registration-token "$PROJECT_REGISTRATION_TOKEN" \
--executor "docker" \
--docker-image alpine:latest \
--description "docker-runner" \
--maintenance-note "Free-form maintainer notes about this runner" \
--tag-list "docker,aws" \
--run-untagged="true" \
--locked="false" \
--access-level="not_protected"
.\gitlab-runner.exe register \
--non-interactive \
--url "https://gitlab.com/" \
--registration-token "$PROJECT_REGISTRATION_TOKEN" \
--executor "docker-windows" \
--docker-image mcr.microsoft.com/windows/servercore:1809_amd64 \
--description "docker-runner" \
--maintenance-note "Free-form maintainer notes about this runner" \
--tag-list "docker,aws" \
--run-untagged="true" \
--locked="false" \
--access-level="not_protected"
sudo -u gitlab-runner -H /usr/local/bin/gitlab-runner register
--non-interactive \
--url "https://gitlab.com/" \
--registration-token "$PROJECT_REGISTRATION_TOKEN" \
--executor "docker" \
--docker-image alpine:latest \
--description "docker-runner" \
--maintenance-note "Free-form maintainer notes about this runner" \
--tag-list "docker,aws" \
--run-untagged="true" \
--locked="false" \
--access-level="not_protected"
docker run --rm -v /srv/gitlab-runner/config:/etc/gitlab-runner gitlab/gitlab-runner register \
--non-interactive \
--url "https://gitlab.com/" \
--registration-token "$PROJECT_REGISTRATION_TOKEN" \
--executor "docker" \
--docker-image alpine:latest \
--description "docker-runner" \
--maintenance-note "Free-form maintainer notes about this runner" \
--tag-list "docker,aws" \
--run-untagged="true" \
--locked="false" \
--access-level="not_protected"
--access-level
creates a protected runner.- For a protected runner, use the
--access-level="ref_protected"
parameter. - For an unprotected runner, use
--access-level="not_protected"
or leave the value undefined.
- For a protected runner, use the
--maintenance-note
allows adding information you might find helpful for runner maintenance. The maximum length is 255 characters.
Legacy-compatible registration process
Runner registration tokens and several runner configuration arguments were deprecated
in GitLab 15.6. They are scheduled for removal in GitLab 20.0.
To ensure minimal disruption to your automation workflow,
the legacy-compatible registration process
triggers if a runner authentication token is specified in the legacy parameter --registration-token
.
The legacy-compatible registration process ignores the following command-line parameters.
These parameters can only be configured when a runner is created in the UI or with the API.
--locked
--access-level
--run-untagged
--maximum-timeout
--paused
--tag-list
--maintenance-note
Register with a configuration template
You can use a configuration template to register a runner with settings that are not supported by the register
command.
Prerequisites:
- The volume for the location of the template file must be mounted on the GitLab Runner container.
- A runner authentication or registration token:
- Obtain a runner authentication token (recommended). You can either:
- Create an instance,
group, or
project runner. - Locate the runner authentication token in the
config.toml
file. Runner authentication tokens have the prefix,glrt-
.
- Create an instance,
- Obtain a runner registration token (deprecated) for an instance,
group, or
project runner.
- Obtain a runner authentication token (recommended). You can either:
The configuration template can be used for automated environments that do not support some arguments
in the register
command due to:
- Size limits on environment variables based on the environment.
- Command-line options that are not available for executor volumes for Kubernetes.
The configuration template supports only a single [[runners]]
section and does not support global options.
To register a runner:
-
Create a configuration template file with the
.toml
format and add your specifications. For example:[[runners]] [runners.kubernetes] [runners.kubernetes.volumes] [[runners.kubernetes.volumes.empty_dir]] name = "empty_dir" mount_path = "/path/to/empty_dir" medium = "Memory"
-
Add the path to the file. You can use either:
-
The non-interactive mode in the command line:
$ sudo gitlab-runner register \ --template-config /tmp/test-config.template.toml \ --non-interactive \ --url "https://gitlab.com" \ --token <TOKEN> \ "# --registration-token if using the deprecated runner registration token" --name test-runner \ --executor kubernetes --host = "http://localhost:9876/"
-
The environment variable in the
.gitlab.yaml
file:variables: TEMPLATE_CONFIG_FILE = <file_path>
If you update the environment variable, you do not need to
add the file path in theregister
command each time you register.
-
After you register the runner, the settings in the configuration template
are merged with the [[runners]]
entry created in the config.toml
:
concurrent = 1
check_interval = 0
[session_server]
session_timeout = 1800
[[runners]]
name = "test-runner"
url = "https://gitlab.com"
token = "glrt-<TOKEN>"
executor = "kubernetes"
[runners.kubernetes]
host = "http://localhost:9876/"
bearer_token_overwrite_allowed = false
image = ""
namespace = ""
namespace_overwrite_allowed = ""
privileged = false
service_account_overwrite_allowed = ""
pod_labels_overwrite_allowed = ""
pod_annotations_overwrite_allowed = ""
[runners.kubernetes.volumes]
[[runners.kubernetes.volumes.empty_dir]]
name = "empty_dir"
mount_path = "/path/to/empty_dir"
medium = "Memory"
Template settings are merged only for options that are:
- Empty strings
- Null or non-existent entries
- Zeroes
Command-line arguments or environment variables take precedence over
settings in the configuration template. For example, if the template
specifies a docker
executor, but the command line specifies shell
,
the configured executor is shell
.
To test GitLab Community Edition integrations, use a configuration template to register a runner
with a confined Docker executor.
-
Create a project runner.
-
Create a template with the
[[runners.docker.services]]
section:$ cat > /tmp/test-config.template.toml << EOF [[runners]] [runners.docker] [[runners.docker.services]] name = "mysql:latest" [[runners.docker.services]] name = "redis:latest" EOF
-
Register the runner:
sudo gitlab-runner register \ --non-interactive \ --url "https://gitlab.com" \ --token "$RUNNER_AUTHENTICATION_TOKEN" \ --template-config /tmp/test-config.template.toml \ --description "gitlab-ce-ruby-3.1" \ --executor "docker" \ --docker-image ruby:3.1
gitlab-runner register \ --non-interactive \ --url "https://gitlab.com" \ --token "$RUNNER_AUTHENTICATION_TOKEN" \ --template-config /tmp/test-config.template.toml \ --description "gitlab-ce-ruby-3.1" \ --executor "docker" \ --docker-image ruby:3.1
.\gitlab-runner.exe register \ --non-interactive \ --url "https://gitlab.com" \ --token "$RUNNER_AUTHENTICATION_TOKEN" \ --template-config /tmp/test-config.template.toml \ --description "gitlab-ce-ruby-3.1" \ --executor "docker" \ --docker-image ruby:3.1
sudo -u gitlab-runner -H /usr/local/bin/gitlab-runner register --non-interactive \ --url "https://gitlab.com" \ --token "$RUNNER_AUTHENTICATION_TOKEN" \ --template-config /tmp/test-config.template.toml \ --description "gitlab-ce-ruby-3.1" \ --executor "docker" \ --docker-image ruby:3.1
docker run --rm -v /srv/gitlab-runner/config:/etc/gitlab-runner gitlab/gitlab-runner register \ --non-interactive \ --url "https://gitlab.com" \ --token "$RUNNER_AUTHENTICATION_TOKEN" \ --template-config /tmp/test-config.template.toml \ --description "gitlab-ce-ruby-3.1" \ --executor "docker" \ --docker-image ruby:3.1
For more configuration options, see Advanced configuration.
Registering runners with Docker
After you register the runner with a Docker container:
- The configuration is written to your configuration volume. For example,
/srv/gitlab-runner/config
. - The container uses the configuration volume to load the runner.
If gitlab-runner restart
runs in a Docker container, GitLab Runner starts a new process instead of restarting the existing process.
To apply configuration changes, restart the Docker container instead.
Troubleshooting
Check registration token
error
The check registration token
error message displays when the GitLab instance does not recognize
the runner registration token entered during registration. This issue can occur when either:
- The instance, group, or project runner registration token was changed in GitLab.
- An incorrect runner registration token was entered.
When this error occurs, you can ask a GitLab administrator to:
- Verify that the runner registration token is valid.
- Confirm that runner registration in the project or group is permitted.
410 Gone - runner registration disallowed
error
The 410 Gone - runner registration disallowed
error message displays when runner registration through
registration tokens has been disabled.
When this error occurs, you can ask a GitLab administrator to:
- Verify that the runner registration token is valid.
- Confirm that runner registration in the instance is permitted.
- In the case of a group or project runner registration token, verify that runner registration in the respective group
and/or project is allowed.
По натуре своей многие разработчики слишком ленивые не любят делать одно и то же действие много раз. Нам проще научить компьютер, чтобы он делал монотонные действия за нас.
Как только кто-либо из нашей команды вносит изменения в код (читай «мерджит feature-ветку в develop»), наш билд-сервер:
- Собирает исходный код и установщик приложения
- проставляет номер сборки, каждый раз увеличивая последнюю цифру. Например, текущая версия нашего ПО 3.3.0.202 – часть 3.3.0 когда-то ввёл разработчик (привет, SemVer), а «202» проставляется в процессе сборки.
- В процессе анализирует качество кода (с использованием SonarQube) – и отправляет отчёт во внутренний SonarQube,
- Сразу после сборки запускает автотесты (xUnit) и анализирует покрытие тестами (OpenCover),
Также, в зависимости от ветки, в которую были внесены изменения, могут быть выполнены:
- отправка сборки (вместе с changelog-ом) в один или несколько телеграм-каналов (иногда удобнее брать сборки оттуда).
- публикация файлов в систему автообновления ПО.
Под катом о том, как мы научили Gitlab CI делать за нас бОльшую часть этой муторной работы.
Оглавление
- Устанавливаем и регистрируем Gitlab Runner.
- Что нужно знать про .gitlab-ci.yml и переменные сборки.
- Активируем режим Developer PowerShell for VS.
- Используем CI для проставления версии во все сборки решения.
- Добавляем отправку данных в SonarQube.
- «Причёсываем» автотесты xUnit + добавляем вычисление покрытия тестами через OpenCover.
- Послесловие.
Перед началом
Чтобы быть уверенными, что написанное ниже работает, мы взяли на github небольшой проект, написанный на WPF и имеющий unit-тесты, и воспроизвели на нём описанные в статье шаги. Самые нетерпеливые могут сразу зайти в созданный на сайте gitlab.com репозиторий и посмотреть, как это выглядит.
Устанавливаем и регистрируем Gitlab Runner
Для того чтобы Gitlab CI мог что-либо собрать, сначала установите и настройте Gitlab Runner на машине, на которой будет осуществляться сборка. В случае проекта на .Net Framework это будет машина с ОС Windows.
Чтобы настроить Gitlab Runner, выполните следующие шаги:
- Установите Git для Windows с сайта git.
- Установите Visual Studio с сайта Microsoft. Мы поставили себе Build Tools для Visual Studio 2019. Чтобы скачать именно его, разверните список Инструменты для Visual Studio 2019.
- Создайте папку C:\GitLab-Runner и сохраните в неё программу gitlab runner. Скачать её можно со страницы [документации Gitlab] (https://docs.gitlab.com/runner/install/windows.html) — ссылки скрыты прямо в тексте: «Download the binary for x86 or amd64».
- Запустите cmd или powershell в режиме администратора, перейдите в папку C:\GitLab-Runner и запустите скачанный файл с параметром install (Gitlab runner установится как системная служба).
.\gitlab-runner.exe install
- Посмотрите токен для регистрации Runner-а. В зависимости от того, где будет доступен ваш Runner:
- только в одном проекте — смотрите токен в меню проекта Settings > CI/CD в разделе Runners,
- в группе проектов — смотрите токен в меню группы Settings > CI/CD в разделе Runners,
- для всех проектов Gitlab-а — смотрите токен в секции администрирования, меню Overview > Runners.
- Выполните регистрацию 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
- Утилита vswhere.exe умеет находить и выдавать список найденных инсталляций Visual Studio. Расположен она всегда по одному и тому же пути (этот путь записан в переменной VSWHERE_PATH). Поскольку в переменной фигурирует подстановка
%programfiles%
, её требуется раскрыть до пути к этой папке. Такое раскрытие проще всего сделать через статический метод .NET System.Environment.ExpandEnvironmentVariables.
Результат: мы имеем путь к vswhere.
- Вызовом 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 не найдено (обработку этой ситуации мы ещё не добавили).
- Команда Import-Module загружает библиотеку Microsoft.VisualStudio.DevShell.dll, в которой прописаны командлеты трансформации консоли Powershell в Developer-консоль. А командлет Join-Path формирует путь к этой библиотеке относительно пути установки Visual Studio.
На этом шаге нам прилетит ошибка, если библиотека Microsoft.VisualStudio.DevShell.dll отсутствует или путь к установке Visual Studio нужной редакции не был найден — Import-Module сообщит, что не может загрузить библиотеку.
Результат: загружен модуль Powershell с командлетом трансформации.
- Запускаем «переделку» консоли в 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'
Как это работает:
- Мы проставляем метки в формате
<major>.<minor>.<revision>
. - Тогда
git describe --long
возвращает нам строку, описывающую версию в формате<major>.<minor>.<revision>-<количество новых коммитов>-g<хэш текущего коммита>
. - Парсим полученную строку через регулярные выражения, выделяя нужные нам части — и записывем части в
$versionGroup
. - Преобразовываем четыре найденные подстроки в 4 числа и пишем их в переменные
$major
,$minor
,$patch
,$commit
, после чего собираем из них строку уже в нужном нам формате. - Передаём указанную строку в msbuild чтобы он сам проставил версию файлов при сборке.
Обратите внимание: если вы, согласно gitflow, будете отмечать (тэгировать) ветку master после вливания в неё release или hofix, будьте внимательны: до простановки метки автосборка будет вестись относительно последней существующей ветки. Например, сейчас опубликована версия 3.4, а вы создаёте release-ветку для выпуска версии 3.5. Так вот: всё время существования этой ветки, а также после её вливания в master, но до простановки тэга, автосборка будет проставлять версию 3.4.
Добавляем отправку данных в SonarQube
SonarQube — это мощный инструмент контроля качества кода.
SonarQube имеет бесплатную Community-версию, которая способна проводить полный анализ. Правда, только одной ветки. Чтобы настроить её на контроль качества ветки разработки (develop), требуется выполнить следующие шаги (разумеется, помимо установки и развёртывания сервера SonarQube):
- Создайте в SonarQube новый проект, после чего запомните его ключ.
- Скачайте SonarScanner for MSBuild (с сайта sonarqube.org)[https://docs.sonarqube.org/latest/analysis/scan/sonarscanner-for-msbuild/] — мы используем версию .NET Framework 4.6+.
- Распакуйте содержимое архива в папку. Например, в
C:\Tools\SonarScanner
.
На заметку: эту утилиту также можно скачать на сборочную машину через NuGet, но тогда надо будет чуть по-иному указывать её путь. - Зайдите в параметры CI/CD в свойствах проекта Gitlab и добавьте следующие параметры:
- SONARQUBE_PROJECT_KEY — ключ проекта,
- SONARQUBE_AUTH_TOKEN — токен авторизации.
Прописывать параметр ключа проекта необходимо для каждого проекта отдельно (ведь у каждого проекта свой уникальный ключ). А параметр токена авторизации желательно скрыть (отметить как Masked) чтобы он не был доступен всем, кто имете доступ к репозиторию или логам сборки.
- Допишите переменные к секции Variables:
variables: SONARSCANNER_MSBUILD_PATH: 'C:\Tools\SonarScanner\SonarScanner.MSBuild.exe' SONARQUBE_HOST_URL: 'url вашего сервера SonarQube'
- Допишите в задачу тестирования ветки разработки (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 мы с тем же успехом можем смотреть результаты через его интерфейс.
Для настройки выполним следующие шаги:
- Скачайте OpenCover в виде zip-файла с сайта github.
- Распакуйте содержимое архива в папку. Например, в
C:\Tools\OpenCover
.
На заметку: эту утилиту также можно скачать на сборочную машину через NuGet, но тогда надо будет чуть по-иному указывать её путь. - Допишите переменные к секции 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'
- Модифицируйте задачу тестирования ветки разработки (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), указываем выражение
\[!\[([^>]+)\]!\]
.
- если хочется видеть значение покрытия тестов по строкам кода (его ешё называют Sequence Coverage или Statement Coverage), указываем выражение
Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.
Какие примеры использования автосборки/автопубликации вам интересны?
10% Публикация артефактов сборки: на сайт, в телеграм-канал1
30% Создание и сборка инсталлера3
20% Оповещение об этапах сборки и ошибках: в телеграм, в слак, по почте2
90% Автосборка и тестирование в .NET 5/.NET Core9
10% Другое, напишу в комментариях1
Проголосовали 10 пользователей. Воздержались 2 пользователя.
GitLab Runner — это веб-приложение (агент), предназначенное для запуска и автоматического выполнения процессов CI/CD в GitLab. GitLab Runner выполняет задачи из файла .gitlab-ci.yml
, который располагается в корневой директории вашего проекта.
Runner можно установить как на одном сервере, где установлен GitLab, так и отдельно. Главное, чтобы между GitLab Runner и сервером GitLab было сетевое взаимодействие. Установить Runner можно на такие ОС, как Linux, Windows, macOS, также поддерживается запуск в контейнере Docker.
В данной статье мы установим GitLab Runner в Docker и запустим тестовый проект.
cloud
Предварительные требования
Для установки GitLab Runner необходимо следующее:
- Сервер или виртуальная машина с предустановленной ОС Linux. Использовать можно любой дистрибутив, на который можно установить Docker.
- Заранее установленный Docker.
- Учетная запись на сайте gitlab.com, а также заранее подготовленный проект.
Установка GitLab Runner с помощью Docker
Переходим на сервер где установлен Docker.
- Для начала создадим том Docker, в котором будет храниться конфигурация.
Том Docker представляет собой файловую систему для постоянного хранения информации. Данные в томе хранятся отдельно от контейнера. При перезапуске, остановке или удалении контейнера том и данные в нем останутся. Команда для создания тома с именем runner1:
docker volume create runner1
- Далее запускаем контейнер с образом
gitlab-runner
:
docker run -d --name gitlab-runner1 --restart always \
-v /var/run/docker.sock:/var/run/docker.sock \
-v runner1:/etc/gitlab-runner \
gitlab/gitlab-runner:latest
- Проверяем статус контейнера и убеждаемся, что он запущен (статус Up):
docker ps
На этом установка GitLab Runner закончена. Следующий этап — регистрация Runner.
После того как Runner был установлен, его необходимо зарегистрировать. Без регистрации Runner не сможет выполнять задачи.
- Регистрация выполняется при помощи запуска контейнера
gitlab-runner
и выполнения в нем командыregister
:
docker run --rm -it -v runner1:/etc/gitlab-runner gitlab/gitlab-runner:latest register
- На первом шаге нас попросят ввести URL, на котором располагается сервер GitLab:
Если вы используете self hosted GitLab (который установлен на отдельном сервере), то необходимо использовать адрес вашего экземпляра GitLab. Например, если ваш проект располагается по адресу https://gitlab.test1.com/projects/testproject
, то URL будет https://gitlab.test1.com
.
Если же ваши проекты хранятся на GitLab.com, то URL — https://gitlab.com
.
- Следующим шагом нас попросят ввести регистрационный токен:
Чтобы его получить, необходимо перейти в веб-интерфейс GitLab, выбрать нужный проект, слева выбрать раздел Settings, далее CI/CD:
Найти меню Runners, раскрыть раздел (Expand). Токен будет доступен в Action menu (кнопка с 3 точками):
- Далее нам предложат ввести описание для данного Runner. Пункт можно пропустить и ничего не писать:
- Далее необходимо задать тег(и). Теги — это метки, предназначенные для определения, какой именно раннер будет использоваться при запуске задач. Можно ввести более одного тега. В этом случае их необходимо разделить запятыми:
- На этапе ввода технической информации — maintenance note — можно задать информацию для других разработчиков, которая будет содержать, например, технические данные сервера. Можно ничего не писать и пропустить.
- Далее необходимо выбрать executor — среду, в которой будут запускаться pipeline. В качестве примера выберем
docker
. В этом случае pipeline будут запускаться в контейнерах Docker, а по завершению контейнеры будут удаляться.
- На последнем шаге необходимо выбрать образ Docker, который будет использоваться в контейнере, где будет запускаться pipeline. В качестве примера выберем образ
python 3.10-slim
:
После того как регистрация Runner завершена, он будет отображен в настройках проекта, в разделе Runners:
Использование GitLab Runner при запуске pipeline
Для того чтобы использовать Runner для запуска pipeline, необходимо создать файл с именем .gitlab-ci.yml
. Можно создать файл сразу в корневой директории проекта или в веб-интерфейсе GitLab — для этого на главной странице проекта необходимо нажать на кнопку Set up CI/CD (данная кнопка будет присутствовать только один раз — при первой настройке CI/CD):
Далее нажимаем на Configure pipeline:
При первой настройке pipeline, GitLab предоставляет базовый синтаксис pipeline. В нашем примере мы используем проект на Python, а именно скрипт для проверки скорости интернет-соединения. При успешном выполнение скрипта в выводе должны отображаться строки с входящим и исходящим соединением:
Your Download speed is 95.8 Mbit/s
Your Upload speed is 110.1 Mbit/s
Синтаксис pipeline будет выглядеть следующим образом:
image: python:3.10-slimdefault:
tags:
- test1
before_script:
- pip3 install -r requirements.txt
run:
script:
- python3 check_internet_speed.py
Для того чтобы назначить ранее созданный Runner для данного проекта, необходимо прописать блок:
default:
tags:
- test1
В котором test1
— это тег нашего созданного Runner. Благодаря этому тегу, pipeline будет выполнен на том Runner, которому присвоен тег test1
. Сохраняем изменения в файле (делаем commit) и запускаем наш pipeline. Если посмотреть процесс выполнения job, то в самом начале вывода можно увидеть, что используется gitlab runner:
Полный вывод всего pipeline изображен на скриншоте ниже:
В итоге мы установили GitLab Runner, настроили его а также назначили его на проект и запустили pipeline на этом Runner.
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.
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.
After downloaded binary File copy it , Go to c drive and create new folder ex: C:\GitLab-Runner
and paste binary in that folder which you created.
Rename downloaded file ex: gitlab-runner
Open command prompt and go to directory where GitLab Runner file saved using below command.
cd c:\GitLab-Runner
To install GitLab Runner run the below command.
.\gitlab-runner.exe install
To verify GitLab Runner version using below command
.\gitlab-runner –v
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/
Enter the registration token:
To get token, you have to go your GitLab project -> setting -> CI/CD -> Runner
Expand runner to access 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.
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.
You can see the GitLab Runner configuration in the config.toml
file under the GitLab-Runner folder as shown below.
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
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]