url
stringlengths 24
122
| repo_url
stringlengths 60
156
| date_extracted
stringdate 2025-08-13 00:00:00
2025-08-13 00:00:00
| root
stringlengths 3
85
| breadcrumbs
listlengths 1
6
| filename
stringlengths 6
60
| stage
stringclasses 33
values | group
stringclasses 81
values | info
stringclasses 22
values | title
stringlengths 3
110
⌀ | description
stringlengths 11
359
⌀ | clean_text
stringlengths 47
3.32M
| rich_text
stringlengths 321
3.32M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://docs.gitlab.com/ci/pipeline_security
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/pipeline_security.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
pipeline_security.md
| null | null | null | null | null |
<!-- markdownlint-disable -->
This document was moved to [another location](../pipeline_security/_index.md).
<!-- This redirect file can be deleted after <2025-09-24>. -->
<!-- Redirects that point to other docs in the same project expire in three months. -->
<!-- Redirects that point to docs in a different project or site (for example, link is not relative and starts with `https:`) expire in one year. -->
<!-- Before deletion, see: https://docs.gitlab.com/development/documentation/redirects -->
|
---
redirect_to: ../pipeline_security/_index.md
remove_date: '2025-09-24'
breadcrumbs:
- doc
- ci
- pipelines
---
<!-- markdownlint-disable -->
This document was moved to [another location](../pipeline_security/_index.md).
<!-- This redirect file can be deleted after <2025-09-24>. -->
<!-- Redirects that point to other docs in the same project expire in three months. -->
<!-- Redirects that point to docs in a different project or site (for example, link is not relative and starts with `https:`) expire in one year. -->
<!-- Before deletion, see: https://docs.gitlab.com/development/documentation/redirects -->
|
https://docs.gitlab.com/ci/merged_results_pipelines
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/merged_results_pipelines.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
merged_results_pipelines.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Merged results pipelines
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
A merged results pipeline runs on the result of the source and target branches merged together.
It is a type of [merge request pipeline](merge_request_pipelines.md).
GitLab creates an internal commit with the merged results, so the pipeline can run
against it. This commit does not exist in either branch,
but you can view it in the pipeline details. The author of the internal commit is
always the user that created the merge request.
The pipeline runs against the target branch as it exists at the moment you run the pipeline.
Over time, while you're working in the source branch, the target branch might change.
Any time you want to be sure the merged results are accurate, you should re-run the pipeline.
Merged results pipelines can't run when the target branch has changes that conflict with the changes in the source branch.
In these cases, the pipeline runs as a [merge request pipeline](merge_request_pipelines.md)
and is labeled as `merge request`.
## Prerequisites
To use merged results pipelines:
- Your project's `.gitlab-ci.yml` file must be configured to
[run jobs in merge request pipelines](merge_request_pipelines.md#prerequisites).
- Your repository must be a GitLab repository, not an
[external repository](../ci_cd_for_external_repos/_index.md).
## Enable merged results pipelines
To enable merged results pipelines in a project, you must have at least the
Maintainer role:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Merge requests**.
1. In the **Merge options** section, select **Enable merged results pipelines**.
1. Select **Save changes**.
{{< alert type="warning" >}}
If you select the checkbox but don't configure your pipeline to use
merge request pipelines, your merge requests may become stuck in an
unresolved state or your pipelines may be dropped.
{{< /alert >}}
## Troubleshooting
### Jobs or pipelines run unexpectedly with `rules:changes:compare_to`
You might have jobs or pipelines that run unexpectedly when using `rules:changes:compare_to` with merge request pipelines.
With merged results pipelines, the internal commit that GitLab creates is used as a base to compare against. This commit likely contains more changes than the tip of the MR branch, which causes unexpected outcomes.
### Successful merged results pipeline overrides a failed branch pipeline
A failed branch pipeline is sometimes ignored when the
[**Pipelines must succeed** setting](../../user/project/merge_requests/auto_merge.md#require-a-successful-pipeline-for-merge)
is activated.
[Issue 385841](https://gitlab.com/gitlab-org/gitlab/-/issues/385841) is open to track this.
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Merged results pipelines
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
A merged results pipeline runs on the result of the source and target branches merged together.
It is a type of [merge request pipeline](merge_request_pipelines.md).
GitLab creates an internal commit with the merged results, so the pipeline can run
against it. This commit does not exist in either branch,
but you can view it in the pipeline details. The author of the internal commit is
always the user that created the merge request.
The pipeline runs against the target branch as it exists at the moment you run the pipeline.
Over time, while you're working in the source branch, the target branch might change.
Any time you want to be sure the merged results are accurate, you should re-run the pipeline.
Merged results pipelines can't run when the target branch has changes that conflict with the changes in the source branch.
In these cases, the pipeline runs as a [merge request pipeline](merge_request_pipelines.md)
and is labeled as `merge request`.
## Prerequisites
To use merged results pipelines:
- Your project's `.gitlab-ci.yml` file must be configured to
[run jobs in merge request pipelines](merge_request_pipelines.md#prerequisites).
- Your repository must be a GitLab repository, not an
[external repository](../ci_cd_for_external_repos/_index.md).
## Enable merged results pipelines
To enable merged results pipelines in a project, you must have at least the
Maintainer role:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Merge requests**.
1. In the **Merge options** section, select **Enable merged results pipelines**.
1. Select **Save changes**.
{{< alert type="warning" >}}
If you select the checkbox but don't configure your pipeline to use
merge request pipelines, your merge requests may become stuck in an
unresolved state or your pipelines may be dropped.
{{< /alert >}}
## Troubleshooting
### Jobs or pipelines run unexpectedly with `rules:changes:compare_to`
You might have jobs or pipelines that run unexpectedly when using `rules:changes:compare_to` with merge request pipelines.
With merged results pipelines, the internal commit that GitLab creates is used as a base to compare against. This commit likely contains more changes than the tip of the MR branch, which causes unexpected outcomes.
### Successful merged results pipeline overrides a failed branch pipeline
A failed branch pipeline is sometimes ignored when the
[**Pipelines must succeed** setting](../../user/project/merge_requests/auto_merge.md#require-a-successful-pipeline-for-merge)
is activated.
[Issue 385841](https://gitlab.com/gitlab-org/gitlab/-/issues/385841) is open to track this.
|
https://docs.gitlab.com/ci/compute_minutes
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/compute_minutes.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
compute_minutes.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Compute minutes
|
Calculations, quotas, purchase information.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Renamed](https://gitlab.com/groups/gitlab-com/-/epics/2150) from "CI/CD minutes" to "compute quota" or "compute minutes" in GitLab 16.1.
{{< /history >}}
The usage of instance runners by projects running CI/CD jobs is measured in compute minutes.
For some installation types, your [namespace](../../user/namespace/_index.md) has a [compute quota](instance_runner_compute_minutes.md#compute-quota-enforcement),
which limits the available compute minutes you can use.
A compute quota can be applied to all [admin-managed instance runners](instance_runner_compute_minutes.md):
- All instance runners on GitLab.com or GitLab Self-Managed
- All self-hosted instance runners on GitLab Dedicated
The compute quota is disabled by default but can be enabled for top-level groups and user namespaces.
On GitLab.com, the quota is enabled by default to limit usage on Free namespaces. The limit is increased if a paid subscription is purchased.
GitLab-hosted instance runners on GitLab Dedicated cannot have the instance runner compute quota applied.
### Instance runners
For instance runners on GitLab.com, GitLab Self-Managed, and self-hosted instance runners on GitLab Dedicated:
- You can view your usage in the [instance runner usage dashboard](instance_runner_compute_minutes.md#view-usage).
- When a quota is enabled:
- You receive notifications when approaching your quota limits.
- Enforcement measures are applied when you exceed your quota.
For GitLab.com:
- The base monthly compute quota is determined by your subscription tier.
- You can [purchase additional compute minutes](../../subscriptions/gitlab_com/compute_minutes.md) if you need more.
## Compute minute usage
### Compute usage calculation
Your compute minute usage for each job is calculated using this formula:
```plaintext
Job duration / 60 * Cost factor
```
- **Job duration**: The time, in seconds, that a job took to run, not including time spent in the `created` or `pending` statuses.
- **Cost factor**: A number based on the [runner type](#cost-factors) and
[project type](#cost-factors).
The value is converted into compute minutes and added to the count of used units
in the job's top-level namespace.
For example, if a user `alice` runs a pipeline:
- In a project in the `gitlab-org` namespace, the compute minutes used by each job in the pipeline are
added to the overall usage for the `gitlab-org` namespace, not the `alice` namespace.
- In a personal project in their `alice` namespace, the compute minutes are added
to the overall usage for their namespace.
The compute used by one pipeline is the total compute minutes used by all the jobs
that ran in the pipeline. Jobs can run concurrently, so the total compute usage
can be higher than the end-to-end duration of a pipeline.
[Trigger jobs](../yaml/_index.md#trigger) do not execute on runners, so they do not
consume compute minutes, even when using [`strategy:depend`](../yaml/_index.md#triggerstrategy)
to wait for the [downstream pipeline](downstream_pipelines.md) status.
The triggered downstream pipeline consumes compute minutes the same as other pipelines.
Usage is tracked on a monthly basis. On the first day of the month the usage is `0` for that month for all namespaces.
### Cost factors
The rate at which compute minutes are consumed varies based on the runner type and project settings.
#### Cost factors of hosted runners for GitLab.com
GitLab-hosted runners have different cost factors depending on the runner type
(Linux, Windows, macOS) and the virtual machine configuration:
| Runner type | Machine size | Cost factor |
|:---------------------------|:-----------------------|:------------------------|
| Linux x86-64 (default) | `small` | `1` |
| Linux x86-64 | `medium` | `2` |
| Linux x86-64 | `large` | `3` |
| Linux x86-64 | `xlarge` | `6` |
| Linux x86-64 | `2xlarge` | `12` |
| Linux x86-64 + GPU-enabled | `medium`, GPU standard | `7` |
| Linux Arm64 | `small` | `1` |
| Linux Arm64 | `medium` | `2` |
| Linux Arm64 | `large` | `3` |
| macOS M1 | `medium` | `6` (**Status**: Beta) |
| macOS M2 Pro | `large` | `12` (**Status**: Beta) |
| Windows | `medium` | `1` (**Status**: Beta) |
These cost factors apply to hosted runners for GitLab.com.
Certain discounts apply based on the project type:
| Project type | Cost factor | Compute minutes used |
|--------------|-------------|---------------------|
| Standard projects | [Based on runner type](#cost-factors-of-hosted-runners-for-gitlabcom) | 1 minute per (job duration / 60 × cost factor) |
| Public projects in [GitLab for Open Source program](../../subscriptions/community_programs.md#gitlab-for-open-source) | `0.5` | 1 minute per 2 minutes of job time |
| Public forks of [GitLab Open Source program projects](../../subscriptions/community_programs.md#gitlab-for-open-source) | `0.008` | 1 minute per 125 minutes of job time |
| [Community contributions to GitLab projects](#community-contributions-to-gitlab-projects) | Dynamic discount | See the following section |
#### Community contributions to GitLab projects
Community contributors can use up to 300,000 minutes on instance runners when contributing to open source projects
maintained by GitLab. The maximum of 300,000 minutes would only be possible if contributing exclusively to projects
part of the GitLab product.
The total number of minutes available on instance runners is reduced by the compute minutes used by pipelines from
other projects. The 300,000 minutes applies to all GitLab.com tiers.
The cost factor calculation is:
- `Monthly compute quota / 300,000 job duration minutes = Cost factor`
For example, with a monthly compute quota of 10,000 in the Premium tier:
- 10,000 / 300,000 = 0.03333333333 cost factor.
For this reduced cost factor:
- The merge request source project must be a fork of a GitLab-maintained project,
such as [`gitlab-com/www-gitlab-com`](https://gitlab.com/gitlab-com/www-gitlab-com),
or [`gitlab-org/gitlab`](https://gitlab.com/gitlab-org/gitlab).
- The merge request target project must be the fork's parent project.
- The pipeline must be a merge request, merged results, or merge train pipeline.
### Reduce compute minute usage
If your project consumes too many compute minutes, try these strategies to reduce your usage:
- If you are using project mirrors, ensure that [pipelines for mirror updates](../../user/project/repository/mirror/pull.md#trigger-pipelines-for-mirror-updates)
is disabled.
- Reduce the frequency of [scheduled pipelines](schedules.md).
- [Skip pipelines](_index.md#skip-a-pipeline) when not needed.
- Use [interruptible](../yaml/_index.md#interruptible) jobs which can be auto-canceled
if a new pipeline starts.
- If a job doesn't have to run in every pipeline, use [`rules`](../jobs/job_control.md)
to make it only run when it's needed.
- [Use private runners](../runners/runners_scope.md#group-runners) for some jobs.
- If you are working from a fork and you submit a merge request to the parent project,
you can ask a maintainer to run a pipeline [in the parent project](merge_request_pipelines.md#run-pipelines-in-the-parent-project).
If you manage an open source project, these improvements can also reduce compute minute
usage for contributor fork projects, enabling more contributions.
See the [pipeline efficiency guide](pipeline_efficiency.md) for more details.
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Calculations, quotas, purchase information.
title: Compute minutes
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Renamed](https://gitlab.com/groups/gitlab-com/-/epics/2150) from "CI/CD minutes" to "compute quota" or "compute minutes" in GitLab 16.1.
{{< /history >}}
The usage of instance runners by projects running CI/CD jobs is measured in compute minutes.
For some installation types, your [namespace](../../user/namespace/_index.md) has a [compute quota](instance_runner_compute_minutes.md#compute-quota-enforcement),
which limits the available compute minutes you can use.
A compute quota can be applied to all [admin-managed instance runners](instance_runner_compute_minutes.md):
- All instance runners on GitLab.com or GitLab Self-Managed
- All self-hosted instance runners on GitLab Dedicated
The compute quota is disabled by default but can be enabled for top-level groups and user namespaces.
On GitLab.com, the quota is enabled by default to limit usage on Free namespaces. The limit is increased if a paid subscription is purchased.
GitLab-hosted instance runners on GitLab Dedicated cannot have the instance runner compute quota applied.
### Instance runners
For instance runners on GitLab.com, GitLab Self-Managed, and self-hosted instance runners on GitLab Dedicated:
- You can view your usage in the [instance runner usage dashboard](instance_runner_compute_minutes.md#view-usage).
- When a quota is enabled:
- You receive notifications when approaching your quota limits.
- Enforcement measures are applied when you exceed your quota.
For GitLab.com:
- The base monthly compute quota is determined by your subscription tier.
- You can [purchase additional compute minutes](../../subscriptions/gitlab_com/compute_minutes.md) if you need more.
## Compute minute usage
### Compute usage calculation
Your compute minute usage for each job is calculated using this formula:
```plaintext
Job duration / 60 * Cost factor
```
- **Job duration**: The time, in seconds, that a job took to run, not including time spent in the `created` or `pending` statuses.
- **Cost factor**: A number based on the [runner type](#cost-factors) and
[project type](#cost-factors).
The value is converted into compute minutes and added to the count of used units
in the job's top-level namespace.
For example, if a user `alice` runs a pipeline:
- In a project in the `gitlab-org` namespace, the compute minutes used by each job in the pipeline are
added to the overall usage for the `gitlab-org` namespace, not the `alice` namespace.
- In a personal project in their `alice` namespace, the compute minutes are added
to the overall usage for their namespace.
The compute used by one pipeline is the total compute minutes used by all the jobs
that ran in the pipeline. Jobs can run concurrently, so the total compute usage
can be higher than the end-to-end duration of a pipeline.
[Trigger jobs](../yaml/_index.md#trigger) do not execute on runners, so they do not
consume compute minutes, even when using [`strategy:depend`](../yaml/_index.md#triggerstrategy)
to wait for the [downstream pipeline](downstream_pipelines.md) status.
The triggered downstream pipeline consumes compute minutes the same as other pipelines.
Usage is tracked on a monthly basis. On the first day of the month the usage is `0` for that month for all namespaces.
### Cost factors
The rate at which compute minutes are consumed varies based on the runner type and project settings.
#### Cost factors of hosted runners for GitLab.com
GitLab-hosted runners have different cost factors depending on the runner type
(Linux, Windows, macOS) and the virtual machine configuration:
| Runner type | Machine size | Cost factor |
|:---------------------------|:-----------------------|:------------------------|
| Linux x86-64 (default) | `small` | `1` |
| Linux x86-64 | `medium` | `2` |
| Linux x86-64 | `large` | `3` |
| Linux x86-64 | `xlarge` | `6` |
| Linux x86-64 | `2xlarge` | `12` |
| Linux x86-64 + GPU-enabled | `medium`, GPU standard | `7` |
| Linux Arm64 | `small` | `1` |
| Linux Arm64 | `medium` | `2` |
| Linux Arm64 | `large` | `3` |
| macOS M1 | `medium` | `6` (**Status**: Beta) |
| macOS M2 Pro | `large` | `12` (**Status**: Beta) |
| Windows | `medium` | `1` (**Status**: Beta) |
These cost factors apply to hosted runners for GitLab.com.
Certain discounts apply based on the project type:
| Project type | Cost factor | Compute minutes used |
|--------------|-------------|---------------------|
| Standard projects | [Based on runner type](#cost-factors-of-hosted-runners-for-gitlabcom) | 1 minute per (job duration / 60 × cost factor) |
| Public projects in [GitLab for Open Source program](../../subscriptions/community_programs.md#gitlab-for-open-source) | `0.5` | 1 minute per 2 minutes of job time |
| Public forks of [GitLab Open Source program projects](../../subscriptions/community_programs.md#gitlab-for-open-source) | `0.008` | 1 minute per 125 minutes of job time |
| [Community contributions to GitLab projects](#community-contributions-to-gitlab-projects) | Dynamic discount | See the following section |
#### Community contributions to GitLab projects
Community contributors can use up to 300,000 minutes on instance runners when contributing to open source projects
maintained by GitLab. The maximum of 300,000 minutes would only be possible if contributing exclusively to projects
part of the GitLab product.
The total number of minutes available on instance runners is reduced by the compute minutes used by pipelines from
other projects. The 300,000 minutes applies to all GitLab.com tiers.
The cost factor calculation is:
- `Monthly compute quota / 300,000 job duration minutes = Cost factor`
For example, with a monthly compute quota of 10,000 in the Premium tier:
- 10,000 / 300,000 = 0.03333333333 cost factor.
For this reduced cost factor:
- The merge request source project must be a fork of a GitLab-maintained project,
such as [`gitlab-com/www-gitlab-com`](https://gitlab.com/gitlab-com/www-gitlab-com),
or [`gitlab-org/gitlab`](https://gitlab.com/gitlab-org/gitlab).
- The merge request target project must be the fork's parent project.
- The pipeline must be a merge request, merged results, or merge train pipeline.
### Reduce compute minute usage
If your project consumes too many compute minutes, try these strategies to reduce your usage:
- If you are using project mirrors, ensure that [pipelines for mirror updates](../../user/project/repository/mirror/pull.md#trigger-pipelines-for-mirror-updates)
is disabled.
- Reduce the frequency of [scheduled pipelines](schedules.md).
- [Skip pipelines](_index.md#skip-a-pipeline) when not needed.
- Use [interruptible](../yaml/_index.md#interruptible) jobs which can be auto-canceled
if a new pipeline starts.
- If a job doesn't have to run in every pipeline, use [`rules`](../jobs/job_control.md)
to make it only run when it's needed.
- [Use private runners](../runners/runners_scope.md#group-runners) for some jobs.
- If you are working from a fork and you submit a merge request to the parent project,
you can ask a maintainer to run a pipeline [in the parent project](merge_request_pipelines.md#run-pipelines-in-the-parent-project).
If you manage an open source project, these improvements can also reduce compute minute
usage for contributor fork projects, enabling more contributions.
See the [pipeline efficiency guide](pipeline_efficiency.md) for more details.
|
https://docs.gitlab.com/ci/downstream_pipelines_troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/downstream_pipelines_troubleshooting.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
downstream_pipelines_troubleshooting.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting downstream pipelines
| null |
## Trigger job fails and does not create multi-project pipeline
With multi-project pipelines, the trigger job fails and does not create the downstream pipeline if:
- The downstream project is not found.
- The user that creates the upstream pipeline does not have [permission](../../user/permissions.md)
to create pipelines in the downstream project.
- The downstream pipeline targets a protected branch and the user does not have permission
to run pipelines against the protected branch. See [pipeline security for protected branches](_index.md#pipeline-security-on-protected-branches)
for more information.
To identify which user is having permission issues in the downstream project, you can check the trigger job using the following command in the [Rails console](../../administration/operations/rails_console.md) and look at the `user_id` attribute.
```ruby
Ci::Bridge.find(<job_id>)
```
## Job in child pipeline is not created when the pipeline runs
If the parent pipeline is a [merge request pipeline](merge_request_pipelines.md),
the child pipeline must [use `workflow:rules` or `rules` to ensure the jobs run](downstream_pipelines.md#run-child-pipelines-with-merge-request-pipelines).
If no jobs in the child pipeline can run due to missing or incorrect `rules` configuration:
- The child pipeline fails to start.
- The parent pipeline's trigger job fails with: `downstream pipeline can not be created, the resulting pipeline would have been empty. Review the`[`rules`](../yaml/_index.md#rules)`configuration for the relevant jobs.`
## Variable with `$` character does not get passed to a downstream pipeline properly
You cannot use [`$$` to escape the `$` character in a CI/CD variable](../variables/job_scripts.md#use-the--character-in-cicd-variables),
when [passing a CI/CD variable to a downstream pipeline](downstream_pipelines.md#pass-cicd-variables-to-a-downstream-pipeline).
The downstream pipeline still treats the `$` as the start of a variable reference.
You can [Prevent CI/CD variable expansion](../variables/_index.md#prevent-cicd-variable-expansion) when configuring
a variable in the UI, or use the [`variables:expand` keyword](../yaml/_index.md#variablesexpand) to
set a variable value to not be expanded. This variable can then be passed to the downstream pipeline
without the `$` being interpreted as a variable reference.
## `Ref is ambiguous`
You cannot trigger a multi-project pipeline with a tag when a branch exists with the same
name. The downstream pipeline fails to create with the error: `downstream pipeline can not be created, Ref is ambiguous`.
Only trigger multi-project pipelines with tag names that do not match branch names.
## `403 Forbidden` error when downloading a job artifact from an upstream pipeline
In GitLab 15.9 and later, CI/CD job tokens are scoped to the project that the pipeline executes under. Therefore, the job token in a downstream pipeline cannot be used to access an upstream project by default.
To resolve this, [add the downstream project to the job token scope allowlist](../jobs/ci_job_token.md#add-a-group-or-project-to-the-job-token-allowlist).
## Error: `needs:need pipeline should be a string`
When using [`needs:pipeline:job`](../yaml/_index.md#needspipelinejob) with dynamic child pipelines,
you might receive this error:
```plaintext
Unable to create pipeline
- jobs:<job_name>:needs:need pipeline should be a string
```
This error occurs when a pipeline ID is parsed as an integer instead of a string.
To fix this, enclose the pipeline ID in quotes:
```yaml
rspec:
needs:
- pipeline: "$UPSTREAM_PIPELINE_ID"
job: dependency-job
artifacts: true
```
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting downstream pipelines
breadcrumbs:
- doc
- ci
- pipelines
---
## Trigger job fails and does not create multi-project pipeline
With multi-project pipelines, the trigger job fails and does not create the downstream pipeline if:
- The downstream project is not found.
- The user that creates the upstream pipeline does not have [permission](../../user/permissions.md)
to create pipelines in the downstream project.
- The downstream pipeline targets a protected branch and the user does not have permission
to run pipelines against the protected branch. See [pipeline security for protected branches](_index.md#pipeline-security-on-protected-branches)
for more information.
To identify which user is having permission issues in the downstream project, you can check the trigger job using the following command in the [Rails console](../../administration/operations/rails_console.md) and look at the `user_id` attribute.
```ruby
Ci::Bridge.find(<job_id>)
```
## Job in child pipeline is not created when the pipeline runs
If the parent pipeline is a [merge request pipeline](merge_request_pipelines.md),
the child pipeline must [use `workflow:rules` or `rules` to ensure the jobs run](downstream_pipelines.md#run-child-pipelines-with-merge-request-pipelines).
If no jobs in the child pipeline can run due to missing or incorrect `rules` configuration:
- The child pipeline fails to start.
- The parent pipeline's trigger job fails with: `downstream pipeline can not be created, the resulting pipeline would have been empty. Review the`[`rules`](../yaml/_index.md#rules)`configuration for the relevant jobs.`
## Variable with `$` character does not get passed to a downstream pipeline properly
You cannot use [`$$` to escape the `$` character in a CI/CD variable](../variables/job_scripts.md#use-the--character-in-cicd-variables),
when [passing a CI/CD variable to a downstream pipeline](downstream_pipelines.md#pass-cicd-variables-to-a-downstream-pipeline).
The downstream pipeline still treats the `$` as the start of a variable reference.
You can [Prevent CI/CD variable expansion](../variables/_index.md#prevent-cicd-variable-expansion) when configuring
a variable in the UI, or use the [`variables:expand` keyword](../yaml/_index.md#variablesexpand) to
set a variable value to not be expanded. This variable can then be passed to the downstream pipeline
without the `$` being interpreted as a variable reference.
## `Ref is ambiguous`
You cannot trigger a multi-project pipeline with a tag when a branch exists with the same
name. The downstream pipeline fails to create with the error: `downstream pipeline can not be created, Ref is ambiguous`.
Only trigger multi-project pipelines with tag names that do not match branch names.
## `403 Forbidden` error when downloading a job artifact from an upstream pipeline
In GitLab 15.9 and later, CI/CD job tokens are scoped to the project that the pipeline executes under. Therefore, the job token in a downstream pipeline cannot be used to access an upstream project by default.
To resolve this, [add the downstream project to the job token scope allowlist](../jobs/ci_job_token.md#add-a-group-or-project-to-the-job-token-allowlist).
## Error: `needs:need pipeline should be a string`
When using [`needs:pipeline:job`](../yaml/_index.md#needspipelinejob) with dynamic child pipelines,
you might receive this error:
```plaintext
Unable to create pipeline
- jobs:<job_name>:needs:need pipeline should be a string
```
This error occurs when a pipeline ID is parsed as an integer instead of a string.
To fix this, enclose the pipeline ID in quotes:
```yaml
rspec:
needs:
- pipeline: "$UPSTREAM_PIPELINE_ID"
job: dependency-job
artifacts: true
```
|
https://docs.gitlab.com/ci/merge_request_pipelines
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/merge_request_pipelines.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
merge_request_pipelines.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Merge request pipelines
|
Learn how to use merge request pipelines in GitLab CI/CD to test changes efficiently, run targeted jobs, and improve code quality before merging.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can configure your pipeline to run every time you make changes to the
source branch in a merge request.
This type of pipeline, called a merge request pipeline, runs when you:
- Create a new merge request from a source branch that has one or more commits.
- Push a new commit to the source branch for a merge request.
- Go to the **Pipelines** tab in a merge request and select **Run pipeline**.
In addition, merge request pipelines:
- Have access to [more predefined variables](merge_request_pipelines.md#available-predefined-variables).
- Can [optionally access protected variables or runners](#control-access-to-protected-variables-and-runners).
These pipelines display a `merge request` label in pipeline lists.
Merge request pipelines run on the contents of the source branch only, ignoring the content
of the target branch. To run a pipeline that tests the result of merging the source
and target branches together, use merged results pipelines.
## Prerequisites
To use merge request pipelines:
- Your project's `.gitlab-ci.yml` file must be
[configured with jobs that run in merge request pipelines](#add-jobs-to-merge-request-pipelines).
- You must have at least the Developer role for the
source project to run a merge request pipeline.
- Your repository must be a GitLab repository, not an [external repository](../ci_cd_for_external_repos/_index.md).
## Add jobs to merge request pipelines
Use the [`rules`](../yaml/_index.md#rules) keyword to configure jobs to run in
merge request pipelines. For example:
```yaml
job1:
script:
- echo "This job runs in merge request pipelines"
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
```
You can also use the [`workflow: rules`](../yaml/_index.md#workflowrules) keyword
to configure the entire pipeline to run in merge request pipelines. For example:
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
job1:
script:
- echo "This job runs in merge request pipelines"
job2:
script:
- echo "This job also runs in merge request pipelines"
```
A common `workflow` configuration is to have pipelines run for merge requests, tags, and the default branch. For example:
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
- if: $CI_COMMIT_TAG
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
## Use with forked projects
External contributors who work in forks can't create pipelines in the parent project.
A merge request from a fork that is submitted to the parent project triggers a
pipeline that:
- Is created and runs in the fork (source) project, not the parent (target) project.
- Uses the fork project's CI/CD configuration, resources, and project CI/CD variables.
Pipelines for forks display with the **fork** badge in the parent project.
### Run pipelines in the parent project
Project members in the parent project can trigger a merge request pipeline
for a merge request submitted from a fork project. This pipeline:
- Is created and runs in the parent (target) project, not the fork (source) project.
- Uses the CI/CD configuration present in the fork project's branch.
- Uses the parent project's CI/CD settings, resources, and project CI/CD variables.
- Uses the permissions of the parent project member that triggers the pipeline.
Run pipelines in fork project MRs to ensure that the post-merge pipeline passes in
the parent project. Additionally, if you do not trust the fork project's runner,
running the pipeline in the parent project uses the parent project's trusted runners.
{{< alert type="warning" >}}
Fork merge requests can contain malicious code that tries to steal secrets in the parent project
when the pipeline runs, even before merge. As a reviewer, carefully check the changes
in the merge request before triggering the pipeline. Unless you trigger the pipeline
through the API or the [`/rebase` quick action](../../user/project/quick_actions.md#issues-merge-requests-and-epics),
GitLab shows a warning that you must accept before the pipeline runs. Otherwise, **no warning displays**.
{{< /alert >}}
Prerequisites:
- The parent project's `.gitlab-ci.yml` file must be configured to
[run jobs in merge request pipelines](#prerequisites).
- You must be a member of the parent project with [permissions to run CI/CD pipelines](../../user/permissions.md#cicd).
You might need additional permissions if the branch is protected.
- The fork project must be [visible](../../user/public_access.md) to the
user running the pipeline. Otherwise, the **Pipelines** tab does not display
in the merge request.
To use the UI to run a pipeline in the parent project for a merge request from a fork project:
1. In the merge request, go to the **Pipelines** tab.
1. Select **Run pipeline**. You must read and accept the warning, or the pipeline does not run.
### Prevent pipelines from fork projects
To prevent users from running new pipelines for fork projects in the parent project
use [the projects API](../../api/projects.md#edit-a-project) to disable the `ci_allow_fork_pipelines_to_run_in_parent_project`
setting.
{{< alert type="warning" >}}
Pipelines created before the setting was disabled are not affected and continue to run.
If you rerun a job in an older pipeline, the job uses the same context as when the
pipeline was originally created.
{{< /alert >}}
## Available predefined variables
When you use merge request pipelines, you can use:
- All the same [predefined variables](../variables/predefined_variables.md) that are
available in branch pipelines.
- [Additional predefined variables](../variables/predefined_variables.md#predefined-variables-for-merge-request-pipelines)
available only to jobs in merge request pipelines.
## Control access to protected variables and runners
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/188008) in GitLab 18.1
{{< /history >}}
You can control access to [protected CI/CD variables](../variables/_index.md#protect-a-cicd-variable)
and [protected runners](../runners/configure_runners.md#prevent-runners-from-revealing-sensitive-information)
from merge request pipelines.
Merge request pipelines can only access these protected resources if both the source and target branches
of the merge request are [protected](../../user/project/repository/branches/protected.md). Also, the user triggering the pipeline should have push/merge access to the target branch of the Merge Request. Merge request pipelines can only access these protected resources if both the source and target branches belong to the same project. Merge request pipelines from a fork of a repository cannot access these protected resources.
Prerequisites:
- You must have the Maintainer role in the project.
To control access to protected variables and runners:
- Go to **Settings > CI/CD**.
- Expand **Variables**
- Under **Access protected resources in merge request pipelines**, select or clear
the **Allow merge request pipelines to access protected variables and runners** option.
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Learn how to use merge request pipelines in GitLab CI/CD to test changes
efficiently, run targeted jobs, and improve code quality before merging.
title: Merge request pipelines
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can configure your pipeline to run every time you make changes to the
source branch in a merge request.
This type of pipeline, called a merge request pipeline, runs when you:
- Create a new merge request from a source branch that has one or more commits.
- Push a new commit to the source branch for a merge request.
- Go to the **Pipelines** tab in a merge request and select **Run pipeline**.
In addition, merge request pipelines:
- Have access to [more predefined variables](merge_request_pipelines.md#available-predefined-variables).
- Can [optionally access protected variables or runners](#control-access-to-protected-variables-and-runners).
These pipelines display a `merge request` label in pipeline lists.
Merge request pipelines run on the contents of the source branch only, ignoring the content
of the target branch. To run a pipeline that tests the result of merging the source
and target branches together, use merged results pipelines.
## Prerequisites
To use merge request pipelines:
- Your project's `.gitlab-ci.yml` file must be
[configured with jobs that run in merge request pipelines](#add-jobs-to-merge-request-pipelines).
- You must have at least the Developer role for the
source project to run a merge request pipeline.
- Your repository must be a GitLab repository, not an [external repository](../ci_cd_for_external_repos/_index.md).
## Add jobs to merge request pipelines
Use the [`rules`](../yaml/_index.md#rules) keyword to configure jobs to run in
merge request pipelines. For example:
```yaml
job1:
script:
- echo "This job runs in merge request pipelines"
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
```
You can also use the [`workflow: rules`](../yaml/_index.md#workflowrules) keyword
to configure the entire pipeline to run in merge request pipelines. For example:
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
job1:
script:
- echo "This job runs in merge request pipelines"
job2:
script:
- echo "This job also runs in merge request pipelines"
```
A common `workflow` configuration is to have pipelines run for merge requests, tags, and the default branch. For example:
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
- if: $CI_COMMIT_TAG
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
## Use with forked projects
External contributors who work in forks can't create pipelines in the parent project.
A merge request from a fork that is submitted to the parent project triggers a
pipeline that:
- Is created and runs in the fork (source) project, not the parent (target) project.
- Uses the fork project's CI/CD configuration, resources, and project CI/CD variables.
Pipelines for forks display with the **fork** badge in the parent project.
### Run pipelines in the parent project
Project members in the parent project can trigger a merge request pipeline
for a merge request submitted from a fork project. This pipeline:
- Is created and runs in the parent (target) project, not the fork (source) project.
- Uses the CI/CD configuration present in the fork project's branch.
- Uses the parent project's CI/CD settings, resources, and project CI/CD variables.
- Uses the permissions of the parent project member that triggers the pipeline.
Run pipelines in fork project MRs to ensure that the post-merge pipeline passes in
the parent project. Additionally, if you do not trust the fork project's runner,
running the pipeline in the parent project uses the parent project's trusted runners.
{{< alert type="warning" >}}
Fork merge requests can contain malicious code that tries to steal secrets in the parent project
when the pipeline runs, even before merge. As a reviewer, carefully check the changes
in the merge request before triggering the pipeline. Unless you trigger the pipeline
through the API or the [`/rebase` quick action](../../user/project/quick_actions.md#issues-merge-requests-and-epics),
GitLab shows a warning that you must accept before the pipeline runs. Otherwise, **no warning displays**.
{{< /alert >}}
Prerequisites:
- The parent project's `.gitlab-ci.yml` file must be configured to
[run jobs in merge request pipelines](#prerequisites).
- You must be a member of the parent project with [permissions to run CI/CD pipelines](../../user/permissions.md#cicd).
You might need additional permissions if the branch is protected.
- The fork project must be [visible](../../user/public_access.md) to the
user running the pipeline. Otherwise, the **Pipelines** tab does not display
in the merge request.
To use the UI to run a pipeline in the parent project for a merge request from a fork project:
1. In the merge request, go to the **Pipelines** tab.
1. Select **Run pipeline**. You must read and accept the warning, or the pipeline does not run.
### Prevent pipelines from fork projects
To prevent users from running new pipelines for fork projects in the parent project
use [the projects API](../../api/projects.md#edit-a-project) to disable the `ci_allow_fork_pipelines_to_run_in_parent_project`
setting.
{{< alert type="warning" >}}
Pipelines created before the setting was disabled are not affected and continue to run.
If you rerun a job in an older pipeline, the job uses the same context as when the
pipeline was originally created.
{{< /alert >}}
## Available predefined variables
When you use merge request pipelines, you can use:
- All the same [predefined variables](../variables/predefined_variables.md) that are
available in branch pipelines.
- [Additional predefined variables](../variables/predefined_variables.md#predefined-variables-for-merge-request-pipelines)
available only to jobs in merge request pipelines.
## Control access to protected variables and runners
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/188008) in GitLab 18.1
{{< /history >}}
You can control access to [protected CI/CD variables](../variables/_index.md#protect-a-cicd-variable)
and [protected runners](../runners/configure_runners.md#prevent-runners-from-revealing-sensitive-information)
from merge request pipelines.
Merge request pipelines can only access these protected resources if both the source and target branches
of the merge request are [protected](../../user/project/repository/branches/protected.md). Also, the user triggering the pipeline should have push/merge access to the target branch of the Merge Request. Merge request pipelines can only access these protected resources if both the source and target branches belong to the same project. Merge request pipelines from a fork of a repository cannot access these protected resources.
Prerequisites:
- You must have the Maintainer role in the project.
To control access to protected variables and runners:
- Go to **Settings > CI/CD**.
- Expand **Variables**
- Under **Access protected resources in merge request pipelines**, select or clear
the **Allow merge request pipelines to access protected variables and runners** option.
|
https://docs.gitlab.com/ci/pipelines
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/_index.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
_index.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
CI/CD pipelines
|
Configuration, automation, stages, schedules, and efficiency.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
CI/CD pipelines are the fundamental component of GitLab CI/CD. Pipelines are configured
in a `.gitlab-ci.yml` file by using [YAML keywords](../yaml/_index.md).
Pipelines can run automatically for specific events, like when pushing to a branch,
creating a merge request, or on a schedule. When needed, you can also run pipelines manually.
Pipelines are composed of:
- [Global YAML keywords](../yaml/_index.md#global-keywords) that control the overall
behavior of the project's pipelines.
- [Jobs](../jobs/_index.md) that execute commands to accomplish a task. For example,
a job could compile, test, or deploy code. Jobs run independently from each other,
and are executed by [runners](../runners/_index.md).
- Stages, which define how to group jobs together. Stages run in sequence, while the jobs
in a stage run in parallel. For example, an early stage could have jobs that lint and compile
code, while later stages could have jobs that test and deploy code. If all jobs in a stage succeed,
the pipeline moves on to the next stage. If any job in a stage fails, the next stage
is not (usually) executed and the pipeline ends early.
A small pipeline could consist of three stages, executed in the following order:
- A `build` stage, with a job called `compile` that compiles the project's code.
- A `test` stage, with two jobs called `test1` and `test2` that run various tests on the code.
These tests would only run if the `compile` job completed successfully.
- A `deploy` stage, with a job called `deploy-to-production`. This job would only run
if both jobs in the `test` stage started and completed successfully.
To get started with your first pipeline, see [Create and run your first GitLab CI/CD pipeline](../quick_start/_index.md).
## Types of pipelines
Pipelines can be configured in many different ways:
- [Basic pipelines](pipeline_architectures.md#basic-pipelines) run everything in each stage concurrently,
followed by the next stage.
- [Pipelines that use the `needs` keyword](../yaml/needs.md) run based on dependencies
between jobs and can run more quickly than basic pipelines.
- [Merge request pipelines](merge_request_pipelines.md) run for merge
requests only (rather than for every commit).
- [Merged results pipelines](merged_results_pipelines.md)
are merge request pipelines that act as though the changes from the source branch have
already been merged into the target branch.
- [Merge trains](merge_trains.md)
use merged results pipelines to queue merges one after the other.
- [Parent-child pipelines](downstream_pipelines.md#parent-child-pipelines) break down complex pipelines
into one parent pipeline that can trigger multiple child sub-pipelines, which all
run in the same project and with the same SHA. This pipeline architecture is commonly used for mono-repos.
- [Multi-project pipelines](downstream_pipelines.md#multi-project-pipelines) combine pipelines for different projects together.
## Configure a pipeline
Pipelines and their component jobs and stages are defined with [YAML keywords](../yaml/_index.md)
in the CI/CD pipeline configuration file for each project. When editing CI/CD configuration
in GitLab, you should use the [pipeline editor](../pipeline_editor/_index.md).
You can also configure specific aspects of your pipelines through the GitLab UI:
- [Pipeline settings](settings.md) for each project.
- [Pipeline schedules](schedules.md).
- [Custom CI/CD variables](../variables/_index.md#for-a-project).
If you use VS Code to edit your GitLab CI/CD configuration, the [GitLab Workflow extension for VS Code](../../editor_extensions/visual_studio_code/_index.md)
helps you [validate your configuration](https://marketplace.visualstudio.com/items?itemName=GitLab.gitlab-workflow#validate-gitlab-ci-configuration)
and [view your pipeline status](https://marketplace.visualstudio.com/items?itemName=GitLab.gitlab-workflow#information-about-your-branch-pipelines-mr-closing-issue).
### Run a pipeline manually
{{< history >}}
- **Run pipeline** name [changed](https://gitlab.com/gitlab-org/gitlab/-/issues/482718) to **New pipeline** in GitLab 17.7.
- **Inputs** option [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/525504) in GitLab 17.11 [with a flag](../../administration/feature_flags/_index.md) named `ci_inputs_for_pipelines`. Enabled by default.
- **Inputs** option [generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/536548) in GitLab 18.1. Feature flag `ci_inputs_for_pipelines` removed.
{{< /history >}}
Pipelines can be manually executed, with predefined or manually-specified [variables](../variables/_index.md).
You might do this if the results of a pipeline (for example, a code build) are required outside the standard
operation of the pipeline.
To execute a pipeline manually:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build** > **Pipelines**.
1. Select **New pipeline**.
1. In the **Run for branch name or tag** field, select the branch or tag to run the pipeline for.
1. (Optional) Enter any:
- [Inputs](../inputs/_index.md) required for the pipeline to run. Default values for inputs are prefilled,
but can be modified. Input values must follow the expected type.
- [CI/CD variables](../variables/_index.md). You can configure variables to have their
[values prefilled in the form](#prefill-variables-in-manual-pipelines). Using inputs to
control pipeline behavior offers improved security and flexibility over CI/CD variables.
1. Select **New pipeline**.
The pipeline now executes the jobs as configured.
#### Prefill variables in manual pipelines
{{< history >}}
- Markdown rendering on the **Run pipeline** page [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/441474) in GitLab 17.11.
{{< /history >}}
You can use the [`description` and `value`](../yaml/_index.md#variablesdescription)
keywords to [define pipeline-level (global) variables](../variables/_index.md#define-a-cicd-variable-in-the-gitlab-ciyml-file)
that are prefilled when running a pipeline manually. Use the description to explain
information such as what the variable is used for, and what the acceptable values are.
You can use Markdown in the description.
Job-level variables cannot be pre-filled.
In manually-triggered pipelines, the **New pipeline** page displays all pipeline-level variables
that have a `description` defined in the `.gitlab-ci.yml` file. The description displays
below the variable.
You can change the prefilled value, which [overrides the value](../variables/_index.md#use-pipeline-variables) for that single pipeline run.
Any variables overridden by using this process are [expanded](../variables/_index.md#prevent-cicd-variable-expansion)
and not [masked](../variables/_index.md#mask-a-cicd-variable).
If you do not define a `value` for the variable in the configuration file, the variable name is still listed,
but the value field is blank.
For example:
```yaml
variables:
DEPLOY_CREDENTIALS:
description: "The deployment credentials."
DEPLOY_ENVIRONMENT:
description: "Select the deployment target. Valid options are: 'canary', 'staging', 'production', or a stable branch of your choice."
value: "canary"
```
In this example:
- `DEPLOY_CREDENTIALS` is listed in the **New pipeline** page, but with no value set.
The user is expected to define the value each time the pipeline is run manually.
- `DEPLOY_ENVIRONMENT` is pre-filled in the **New pipeline** page with `canary` as the default value,
and the message explains the other options.
{{< alert type="note" >}}
Because of a [known issue](https://gitlab.com/gitlab-org/gitlab/-/issues/382857), projects that use [compliance pipelines](../../user/compliance/compliance_pipelines.md) can have prefilled variables not appear
when running a pipeline manually. To workaround this issue,
[change the compliance pipeline configuration](../../user/compliance/compliance_pipelines.md#prefilled-variables-are-not-shown).
{{< /alert >}}
#### Configure a list of selectable prefilled variable values
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/363660) in GitLab 15.5 [with a flag](../../administration/feature_flags/_index.md) named `run_pipeline_graphql`. Disabled by default.
- The `options` keyword was [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/105502) in GitLab 15.7.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/106038) in GitLab 15.7. Feature flag `run_pipeline_graphql` removed.
- The variables list sometimes did not populate correctly due to [a bug](https://gitlab.com/gitlab-org/gitlab/-/issues/386245), which was resolved in GitLab 15.9.
{{< /history >}}
You can define an array of CI/CD variable values the user can select from when running a pipeline manually.
These values are in a dropdown list in the **New pipeline** page. Add the list of
value options to `options` and set the default value with `value`. The string in `value`
must also be included in the `options` list.
For example:
```yaml
variables:
DEPLOY_ENVIRONMENT:
value: "staging"
options:
- "production"
- "staging"
- "canary"
description: "The deployment target. Set to 'staging' by default."
```
### Run a pipeline by using a URL query string
You can use a query string to pre-populate the **New pipeline** page. For example, the query string
`.../pipelines/new?ref=my_branch&var[foo]=bar&file_var[file_foo]=file_bar` pre-populates the
**New pipeline** page with:
- **Run for** field: `my_branch`.
- **Variables** section:
- Variable:
- Key: `foo`
- Value: `bar`
- File:
- Key: `file_foo`
- Value: `file_bar`
The format of the `pipelines/new` URL is:
```plaintext
.../pipelines/new?ref=<branch>&var[<variable_key>]=<value>&file_var[<file_key>]=<value>
```
The following parameters are supported:
- `ref`: specify the branch to populate the **Run for** field with.
- `var`: specify a `Variable` variable.
- `file_var`: specify a `File` variable.
For each `var` or `file_var`, a key and value are required.
### Add manual interaction to your pipeline
[Manual jobs](../jobs/job_control.md#create-a-job-that-must-be-run-manually),
allow you to require manual interaction before moving forward in the pipeline.
You can do this straight from the pipeline graph. Select **Run** ({{< icon name="play" >}}) to execute that particular job.
For example, your pipeline can start automatically, but require a manual action to
[deploy to production](../environments/deployments.md#configure-manual-deployments).
In the following example, the `production` stage has a job with a manual action:

#### Start all manual jobs in a stage
If a stage contains only manual jobs, you can start all the jobs at the same time
by selecting **Run all manual** ({{< icon name="play" >}}) above the stage. If the stage contains
non-manual jobs, the option is not displayed.
### Skip a pipeline
To push a commit without triggering a pipeline, add `[ci skip]` or `[skip ci]`, using any
capitalization, to your commit message.
Alternatively, with Git 2.10 or later, use the `ci.skip` [Git push option](../../topics/git/commit.md#push-options-for-gitlab-cicd).
The `ci.skip` push option does not skip merge request pipelines.
### Delete a pipeline
Users with the Owner role for a project can delete a pipeline:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build** > **Pipelines**.
1. Select either the pipeline ID (for example `#123456789`) or the pipeline status icon
(for example **Passed**) of the pipeline to delete.
1. In the top right of the pipeline details page, select **Delete**.
Deleting a pipeline does not automatically delete its [child pipelines](downstream_pipelines.md#parent-child-pipelines).
See [issue 39503](https://gitlab.com/gitlab-org/gitlab/-/issues/39503) for more details.
{{< alert type="warning" >}}
Deleting a pipeline expires all pipeline caches, and deletes all immediately
related objects, such as jobs, logs, artifacts, and triggers.
**This action cannot be undone**.
{{< /alert >}}
### Pipeline security on protected branches
A strict security model is enforced when pipelines are executed on
[protected branches](../../user/project/repository/branches/protected.md).
The following actions are allowed on protected branches if the user is
[allowed to merge or push](../../user/project/repository/branches/protected.md)
to that specific branch:
- Run manual pipelines (using the [Web UI](#run-a-pipeline-manually) or [pipelines API](#pipelines-api)).
- Run scheduled pipelines.
- Run pipelines using triggers.
- Run on-demand DAST scan.
- Trigger manual actions on existing pipelines.
- Retry or cancel existing jobs (using the Web UI or pipelines API).
**Variables** marked as **protected** are accessible to jobs that run in pipelines for protected branches. Only assign users the right to merge to protected branches if they have permission to access sensitive information like deployment credentials and tokens.
**Runners** marked as **protected** can run jobs only on protected
branches, preventing untrusted code from executing on the protected runner and
preserving deployment keys and other credentials from being unintentionally
accessed. To ensure that jobs intended to be executed on protected
runners do not use regular runners, they must be [tagged](../yaml/_index.md#tags) accordingly.
Review the [documentation](merge_request_pipelines.md#control-access-to-protected-variables-and-runners) to understand how access to
protected variables and runners work in the context of Merge request pipelines.
Review the [deployment safety](../environments/deployment_safety.md)
page for additional security recommendations for securing your pipelines.
<!--- start_remove The following content will be removed on remove_date: '2025-08-15' -->
## Trigger a pipeline when an upstream project is rebuilt (deprecated)
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< alert type="warning" >}}
This feature was [deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/501460) in GitLab 17.6
and is planned for removal in 19.0. Use [CI/CD jobs with pipeline trigger tokens](../triggers/_index.md#use-a-cicd-job) instead.
This is a breaking change.
{{< /alert >}}
You can set up your project to automatically trigger a pipeline based on tags in a different project.
When a new tag pipeline in the subscribed project finishes, it triggers a pipeline on your project's default branch,
regardless of the tag pipeline's success, failure, or cancellation.
Prerequisites:
- The upstream project must be [public](../../user/public_access.md).
- The user must have the Developer role
in the upstream project.
To trigger the pipeline when the upstream project is rebuilt:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Pipeline subscriptions**.
1. Select **Add project**.
1. Enter the project you want to subscribe to, in the format `<namespace>/<project>`.
For example, if the project is `https://gitlab.com/gitlab-org/gitlab`, use `gitlab-org/gitlab`.
1. Select **Subscribe**.
The maximum number of upstream pipeline subscriptions is 2 by default, for both the upstream and
downstream projects. On GitLab Self-Managed, an administrator can change this
[limit](../../administration/instance_limits.md#number-of-cicd-subscriptions-to-a-project).
<!--- end_remove -->
## How pipeline duration is calculated
The total running time for a given pipeline excludes:
- The duration of the initial run for any job that is retried or manually re-run.
- Any pending (queue) time.
That means that if a job is retried or manually re-run, only the duration of the latest run is included in the total running time.
Each job is represented as a `Period`, which consists of:
- `Period#first` (when the job started).
- `Period#last` (when the job finished).
A simple example is:
- A (0, 2)
- A' (2, 4)
- This is retrying A
- B (1, 3)
- C (6, 7)
In the example:
- A begins at 0 and ends at 2.
- A' begins at 2 and ends at 4.
- B begins at 1 and ends at 3.
- C begins at 6 and ends at 7.
Visually, it can be viewed as:
```plaintext
0 1 2 3 4 5 6 7
AAAAAAA
BBBBBBB
A'A'A'A
CCCC
```
Because A is retried, we ignore it and count only job A'.
The union of B, A', and C is (1, 4) and (6, 7). Therefore, the total
running time is:
```plaintext
(4 - 1) + (7 - 6) => 4
```
## View pipelines
To view all the pipelines that ran for your project:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build** > **Pipelines**.
You can filter the **Pipelines** page by:
- Trigger author
- Branch name
- Status
- Tag
- Source
Select **Pipeline ID** in the dropdown list in the top right to display the pipeline IDs
(unique ID across the instance).
Select **pipeline IID** to display the pipeline IIDs (internal ID, unique across the project only).
For example:

To view the pipelines that relate to a specific merge request, go to the **Pipelines** tab
in the merge request.
### Pipeline details
{{< history >}}
- Pipeline detail view [updated](https://gitlab.com/gitlab-org/gitlab/-/issues/424403) in GitLab 16.6 [with a flag](../../administration/feature_flags/_index.md) named `new_pipeline_graph`. Disabled by default.
- Updated pipeline detail view [enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/issues/426902) in GitLab 16.8.
{{< /history >}}
Select a pipeline to open the pipeline details page which shows every job in the pipeline.
From this page you can cancel a running pipeline, retry failed jobs, or [delete a pipeline](#delete-a-pipeline).
The pipeline details page displays a graph of all the jobs in the pipeline:

You can use a standard URL to access the details for specific pipelines:
- `gitlab.example.com/my-group/my-project/-/pipelines/latest`: The details page
for the latest pipeline for the most recent commit on the default branch in the project.
- `gitlab.example.com/my-group/my-project/-/pipelines/<branch>/latest`: The details page
for the latest pipeline for the most recent commit on branch `<branch>` in the project.
#### Group jobs by stage or `needs` configuration
When you configure jobs with the [`needs`](../yaml/_index.md#needs) keyword, you have
two options for how to group the jobs in the pipeline details page. To group the jobs
by stage configuration, select **stage** in the **Group jobs by** section:

To group the jobs by [`needs`](../yaml/_index.md#needs) configuration, select **Job dependencies**.
You can optionally select **Show dependencies** to render lines between dependent jobs.

Jobs in the leftmost column run first, and jobs that depend on them are grouped in the next columns.
In this example:
- `lint-job` is configured with `needs: []` and depends on no jobs, so it displays in the first column,
despite being in the `test` stage.
- `test-job1` depends on `build-job1`, and `test-job2` depends on both `build-job1` and `build-job2`,
so both test jobs display in the second column.
- Both `deploy` jobs depend on jobs in second column (which themselves depend on other earlier jobs),
so the deploy jobs display in the third column.
When you hover over a job in the **Job dependencies** view, every job that must run
before the selected job is highlighted:

### Pipeline mini graphs
Pipeline mini graphs take less space and can tell you at a quick glance if all jobs passed
or something failed. They show all related jobs for a single commit and the net result
of each stage of your pipeline. You can quickly see what failed and fix it.
The pipeline mini graph always group jobs by stage, and display throughout GitLab
when displaying pipeline or commit details.

Stages in pipeline mini graphs are expandable. Hover your mouse over each stage
to see the name and status, and select a stage to expand its jobs list.
### Downstream pipeline graphs
When a pipeline contains a job that triggers a [downstream pipeline](downstream_pipelines.md),
you can see the downstream pipeline in the pipeline details view and mini graphs.
In the pipeline details view, a card displays for every triggered downstream pipeline
on the right of the pipeline graph. Hover over a card to see which job triggered the
downstream pipeline. Select a card to display the downstream pipeline to the right
of the pipeline graph.
In the pipeline mini graph, the status of every triggered downstream pipeline displays
as additional status icons to the right of the mini graph. Select a downstream pipeline
status icon to go to the detail page of that downstream pipeline.
## Pipeline success and duration charts
Pipeline analytics are available on the [**CI/CD Analytics** page](../../user/analytics/ci_cd_analytics.md).
## Pipeline badges
Pipeline status and test coverage report badges are available and configurable for each project.
For information on adding pipeline badges to projects, see [Pipeline badges](settings.md#pipeline-badges).
## Pipelines API
GitLab provides API endpoints to:
- Perform basic functions. For more information, see [Pipelines API](../../api/pipelines.md).
- Maintain pipeline schedules. For more information, see [Pipeline schedules API](../../api/pipeline_schedules.md).
- Trigger pipeline runs. For more information, see:
- [Triggering pipelines through the API](../triggers/_index.md).
- [Pipeline triggers API](../../api/pipeline_triggers.md).
## Ref specs for runners
When a runner picks a pipeline job, GitLab provides that job's metadata. This includes the [Git refspecs](https://git-scm.com/book/en/v2/Git-Internals-The-Refspec),
which indicate which ref (such as branch or tag) and commit (SHA1) are checked out from your
project repository.
This table lists the refspecs injected for each pipeline type:
| Pipeline type | Refspecs |
|-------------------------------------------------------------------|----------|
| pipeline for branches | `+<sha>:refs/pipelines/<id>` and `+refs/heads/<name>:refs/remotes/origin/<name>` |
| pipeline for tags | `+<sha>:refs/pipelines/<id>` and `+refs/tags/<name>:refs/tags/<name>` |
| [merge request pipeline](merge_request_pipelines.md) | `+refs/pipelines/<id>:refs/pipelines/<id>` |
The refs `refs/heads/<name>` and `refs/tags/<name>` exist in your
project repository. GitLab generates the special ref `refs/pipelines/<id>` during a
running pipeline job. This ref can be created even after the associated branch or tag has been
deleted. It's therefore useful in some features such as [automatically stopping an environment](../environments/_index.md#stopping-an-environment),
and [merge trains](merge_trains.md) that might run pipelines after branch deletion.
<!--- start_remove The following content will be removed on remove_date: '2025-08-15' -->
## Troubleshooting
### Pipeline subscriptions continue after user deletion
When a user [deletes their GitLab.com account](../../user/profile/account/delete_account.md#delete-your-own-account),
the deletion does not occur for seven days. During this period, any [pipeline subscriptions created by that user](#trigger-a-pipeline-when-an-upstream-project-is-rebuilt-deprecated)
continue to run with the user's original permissions. To prevent unauthorized pipeline executions,
immediately update pipeline subscription settings for the deleted user.
<!--- end_remove -->
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: CI/CD pipelines
description: Configuration, automation, stages, schedules, and efficiency.
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
CI/CD pipelines are the fundamental component of GitLab CI/CD. Pipelines are configured
in a `.gitlab-ci.yml` file by using [YAML keywords](../yaml/_index.md).
Pipelines can run automatically for specific events, like when pushing to a branch,
creating a merge request, or on a schedule. When needed, you can also run pipelines manually.
Pipelines are composed of:
- [Global YAML keywords](../yaml/_index.md#global-keywords) that control the overall
behavior of the project's pipelines.
- [Jobs](../jobs/_index.md) that execute commands to accomplish a task. For example,
a job could compile, test, or deploy code. Jobs run independently from each other,
and are executed by [runners](../runners/_index.md).
- Stages, which define how to group jobs together. Stages run in sequence, while the jobs
in a stage run in parallel. For example, an early stage could have jobs that lint and compile
code, while later stages could have jobs that test and deploy code. If all jobs in a stage succeed,
the pipeline moves on to the next stage. If any job in a stage fails, the next stage
is not (usually) executed and the pipeline ends early.
A small pipeline could consist of three stages, executed in the following order:
- A `build` stage, with a job called `compile` that compiles the project's code.
- A `test` stage, with two jobs called `test1` and `test2` that run various tests on the code.
These tests would only run if the `compile` job completed successfully.
- A `deploy` stage, with a job called `deploy-to-production`. This job would only run
if both jobs in the `test` stage started and completed successfully.
To get started with your first pipeline, see [Create and run your first GitLab CI/CD pipeline](../quick_start/_index.md).
## Types of pipelines
Pipelines can be configured in many different ways:
- [Basic pipelines](pipeline_architectures.md#basic-pipelines) run everything in each stage concurrently,
followed by the next stage.
- [Pipelines that use the `needs` keyword](../yaml/needs.md) run based on dependencies
between jobs and can run more quickly than basic pipelines.
- [Merge request pipelines](merge_request_pipelines.md) run for merge
requests only (rather than for every commit).
- [Merged results pipelines](merged_results_pipelines.md)
are merge request pipelines that act as though the changes from the source branch have
already been merged into the target branch.
- [Merge trains](merge_trains.md)
use merged results pipelines to queue merges one after the other.
- [Parent-child pipelines](downstream_pipelines.md#parent-child-pipelines) break down complex pipelines
into one parent pipeline that can trigger multiple child sub-pipelines, which all
run in the same project and with the same SHA. This pipeline architecture is commonly used for mono-repos.
- [Multi-project pipelines](downstream_pipelines.md#multi-project-pipelines) combine pipelines for different projects together.
## Configure a pipeline
Pipelines and their component jobs and stages are defined with [YAML keywords](../yaml/_index.md)
in the CI/CD pipeline configuration file for each project. When editing CI/CD configuration
in GitLab, you should use the [pipeline editor](../pipeline_editor/_index.md).
You can also configure specific aspects of your pipelines through the GitLab UI:
- [Pipeline settings](settings.md) for each project.
- [Pipeline schedules](schedules.md).
- [Custom CI/CD variables](../variables/_index.md#for-a-project).
If you use VS Code to edit your GitLab CI/CD configuration, the [GitLab Workflow extension for VS Code](../../editor_extensions/visual_studio_code/_index.md)
helps you [validate your configuration](https://marketplace.visualstudio.com/items?itemName=GitLab.gitlab-workflow#validate-gitlab-ci-configuration)
and [view your pipeline status](https://marketplace.visualstudio.com/items?itemName=GitLab.gitlab-workflow#information-about-your-branch-pipelines-mr-closing-issue).
### Run a pipeline manually
{{< history >}}
- **Run pipeline** name [changed](https://gitlab.com/gitlab-org/gitlab/-/issues/482718) to **New pipeline** in GitLab 17.7.
- **Inputs** option [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/525504) in GitLab 17.11 [with a flag](../../administration/feature_flags/_index.md) named `ci_inputs_for_pipelines`. Enabled by default.
- **Inputs** option [generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/536548) in GitLab 18.1. Feature flag `ci_inputs_for_pipelines` removed.
{{< /history >}}
Pipelines can be manually executed, with predefined or manually-specified [variables](../variables/_index.md).
You might do this if the results of a pipeline (for example, a code build) are required outside the standard
operation of the pipeline.
To execute a pipeline manually:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build** > **Pipelines**.
1. Select **New pipeline**.
1. In the **Run for branch name or tag** field, select the branch or tag to run the pipeline for.
1. (Optional) Enter any:
- [Inputs](../inputs/_index.md) required for the pipeline to run. Default values for inputs are prefilled,
but can be modified. Input values must follow the expected type.
- [CI/CD variables](../variables/_index.md). You can configure variables to have their
[values prefilled in the form](#prefill-variables-in-manual-pipelines). Using inputs to
control pipeline behavior offers improved security and flexibility over CI/CD variables.
1. Select **New pipeline**.
The pipeline now executes the jobs as configured.
#### Prefill variables in manual pipelines
{{< history >}}
- Markdown rendering on the **Run pipeline** page [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/441474) in GitLab 17.11.
{{< /history >}}
You can use the [`description` and `value`](../yaml/_index.md#variablesdescription)
keywords to [define pipeline-level (global) variables](../variables/_index.md#define-a-cicd-variable-in-the-gitlab-ciyml-file)
that are prefilled when running a pipeline manually. Use the description to explain
information such as what the variable is used for, and what the acceptable values are.
You can use Markdown in the description.
Job-level variables cannot be pre-filled.
In manually-triggered pipelines, the **New pipeline** page displays all pipeline-level variables
that have a `description` defined in the `.gitlab-ci.yml` file. The description displays
below the variable.
You can change the prefilled value, which [overrides the value](../variables/_index.md#use-pipeline-variables) for that single pipeline run.
Any variables overridden by using this process are [expanded](../variables/_index.md#prevent-cicd-variable-expansion)
and not [masked](../variables/_index.md#mask-a-cicd-variable).
If you do not define a `value` for the variable in the configuration file, the variable name is still listed,
but the value field is blank.
For example:
```yaml
variables:
DEPLOY_CREDENTIALS:
description: "The deployment credentials."
DEPLOY_ENVIRONMENT:
description: "Select the deployment target. Valid options are: 'canary', 'staging', 'production', or a stable branch of your choice."
value: "canary"
```
In this example:
- `DEPLOY_CREDENTIALS` is listed in the **New pipeline** page, but with no value set.
The user is expected to define the value each time the pipeline is run manually.
- `DEPLOY_ENVIRONMENT` is pre-filled in the **New pipeline** page with `canary` as the default value,
and the message explains the other options.
{{< alert type="note" >}}
Because of a [known issue](https://gitlab.com/gitlab-org/gitlab/-/issues/382857), projects that use [compliance pipelines](../../user/compliance/compliance_pipelines.md) can have prefilled variables not appear
when running a pipeline manually. To workaround this issue,
[change the compliance pipeline configuration](../../user/compliance/compliance_pipelines.md#prefilled-variables-are-not-shown).
{{< /alert >}}
#### Configure a list of selectable prefilled variable values
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/363660) in GitLab 15.5 [with a flag](../../administration/feature_flags/_index.md) named `run_pipeline_graphql`. Disabled by default.
- The `options` keyword was [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/105502) in GitLab 15.7.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/106038) in GitLab 15.7. Feature flag `run_pipeline_graphql` removed.
- The variables list sometimes did not populate correctly due to [a bug](https://gitlab.com/gitlab-org/gitlab/-/issues/386245), which was resolved in GitLab 15.9.
{{< /history >}}
You can define an array of CI/CD variable values the user can select from when running a pipeline manually.
These values are in a dropdown list in the **New pipeline** page. Add the list of
value options to `options` and set the default value with `value`. The string in `value`
must also be included in the `options` list.
For example:
```yaml
variables:
DEPLOY_ENVIRONMENT:
value: "staging"
options:
- "production"
- "staging"
- "canary"
description: "The deployment target. Set to 'staging' by default."
```
### Run a pipeline by using a URL query string
You can use a query string to pre-populate the **New pipeline** page. For example, the query string
`.../pipelines/new?ref=my_branch&var[foo]=bar&file_var[file_foo]=file_bar` pre-populates the
**New pipeline** page with:
- **Run for** field: `my_branch`.
- **Variables** section:
- Variable:
- Key: `foo`
- Value: `bar`
- File:
- Key: `file_foo`
- Value: `file_bar`
The format of the `pipelines/new` URL is:
```plaintext
.../pipelines/new?ref=<branch>&var[<variable_key>]=<value>&file_var[<file_key>]=<value>
```
The following parameters are supported:
- `ref`: specify the branch to populate the **Run for** field with.
- `var`: specify a `Variable` variable.
- `file_var`: specify a `File` variable.
For each `var` or `file_var`, a key and value are required.
### Add manual interaction to your pipeline
[Manual jobs](../jobs/job_control.md#create-a-job-that-must-be-run-manually),
allow you to require manual interaction before moving forward in the pipeline.
You can do this straight from the pipeline graph. Select **Run** ({{< icon name="play" >}}) to execute that particular job.
For example, your pipeline can start automatically, but require a manual action to
[deploy to production](../environments/deployments.md#configure-manual-deployments).
In the following example, the `production` stage has a job with a manual action:

#### Start all manual jobs in a stage
If a stage contains only manual jobs, you can start all the jobs at the same time
by selecting **Run all manual** ({{< icon name="play" >}}) above the stage. If the stage contains
non-manual jobs, the option is not displayed.
### Skip a pipeline
To push a commit without triggering a pipeline, add `[ci skip]` or `[skip ci]`, using any
capitalization, to your commit message.
Alternatively, with Git 2.10 or later, use the `ci.skip` [Git push option](../../topics/git/commit.md#push-options-for-gitlab-cicd).
The `ci.skip` push option does not skip merge request pipelines.
### Delete a pipeline
Users with the Owner role for a project can delete a pipeline:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build** > **Pipelines**.
1. Select either the pipeline ID (for example `#123456789`) or the pipeline status icon
(for example **Passed**) of the pipeline to delete.
1. In the top right of the pipeline details page, select **Delete**.
Deleting a pipeline does not automatically delete its [child pipelines](downstream_pipelines.md#parent-child-pipelines).
See [issue 39503](https://gitlab.com/gitlab-org/gitlab/-/issues/39503) for more details.
{{< alert type="warning" >}}
Deleting a pipeline expires all pipeline caches, and deletes all immediately
related objects, such as jobs, logs, artifacts, and triggers.
**This action cannot be undone**.
{{< /alert >}}
### Pipeline security on protected branches
A strict security model is enforced when pipelines are executed on
[protected branches](../../user/project/repository/branches/protected.md).
The following actions are allowed on protected branches if the user is
[allowed to merge or push](../../user/project/repository/branches/protected.md)
to that specific branch:
- Run manual pipelines (using the [Web UI](#run-a-pipeline-manually) or [pipelines API](#pipelines-api)).
- Run scheduled pipelines.
- Run pipelines using triggers.
- Run on-demand DAST scan.
- Trigger manual actions on existing pipelines.
- Retry or cancel existing jobs (using the Web UI or pipelines API).
**Variables** marked as **protected** are accessible to jobs that run in pipelines for protected branches. Only assign users the right to merge to protected branches if they have permission to access sensitive information like deployment credentials and tokens.
**Runners** marked as **protected** can run jobs only on protected
branches, preventing untrusted code from executing on the protected runner and
preserving deployment keys and other credentials from being unintentionally
accessed. To ensure that jobs intended to be executed on protected
runners do not use regular runners, they must be [tagged](../yaml/_index.md#tags) accordingly.
Review the [documentation](merge_request_pipelines.md#control-access-to-protected-variables-and-runners) to understand how access to
protected variables and runners work in the context of Merge request pipelines.
Review the [deployment safety](../environments/deployment_safety.md)
page for additional security recommendations for securing your pipelines.
<!--- start_remove The following content will be removed on remove_date: '2025-08-15' -->
## Trigger a pipeline when an upstream project is rebuilt (deprecated)
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< alert type="warning" >}}
This feature was [deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/501460) in GitLab 17.6
and is planned for removal in 19.0. Use [CI/CD jobs with pipeline trigger tokens](../triggers/_index.md#use-a-cicd-job) instead.
This is a breaking change.
{{< /alert >}}
You can set up your project to automatically trigger a pipeline based on tags in a different project.
When a new tag pipeline in the subscribed project finishes, it triggers a pipeline on your project's default branch,
regardless of the tag pipeline's success, failure, or cancellation.
Prerequisites:
- The upstream project must be [public](../../user/public_access.md).
- The user must have the Developer role
in the upstream project.
To trigger the pipeline when the upstream project is rebuilt:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Pipeline subscriptions**.
1. Select **Add project**.
1. Enter the project you want to subscribe to, in the format `<namespace>/<project>`.
For example, if the project is `https://gitlab.com/gitlab-org/gitlab`, use `gitlab-org/gitlab`.
1. Select **Subscribe**.
The maximum number of upstream pipeline subscriptions is 2 by default, for both the upstream and
downstream projects. On GitLab Self-Managed, an administrator can change this
[limit](../../administration/instance_limits.md#number-of-cicd-subscriptions-to-a-project).
<!--- end_remove -->
## How pipeline duration is calculated
The total running time for a given pipeline excludes:
- The duration of the initial run for any job that is retried or manually re-run.
- Any pending (queue) time.
That means that if a job is retried or manually re-run, only the duration of the latest run is included in the total running time.
Each job is represented as a `Period`, which consists of:
- `Period#first` (when the job started).
- `Period#last` (when the job finished).
A simple example is:
- A (0, 2)
- A' (2, 4)
- This is retrying A
- B (1, 3)
- C (6, 7)
In the example:
- A begins at 0 and ends at 2.
- A' begins at 2 and ends at 4.
- B begins at 1 and ends at 3.
- C begins at 6 and ends at 7.
Visually, it can be viewed as:
```plaintext
0 1 2 3 4 5 6 7
AAAAAAA
BBBBBBB
A'A'A'A
CCCC
```
Because A is retried, we ignore it and count only job A'.
The union of B, A', and C is (1, 4) and (6, 7). Therefore, the total
running time is:
```plaintext
(4 - 1) + (7 - 6) => 4
```
## View pipelines
To view all the pipelines that ran for your project:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build** > **Pipelines**.
You can filter the **Pipelines** page by:
- Trigger author
- Branch name
- Status
- Tag
- Source
Select **Pipeline ID** in the dropdown list in the top right to display the pipeline IDs
(unique ID across the instance).
Select **pipeline IID** to display the pipeline IIDs (internal ID, unique across the project only).
For example:

To view the pipelines that relate to a specific merge request, go to the **Pipelines** tab
in the merge request.
### Pipeline details
{{< history >}}
- Pipeline detail view [updated](https://gitlab.com/gitlab-org/gitlab/-/issues/424403) in GitLab 16.6 [with a flag](../../administration/feature_flags/_index.md) named `new_pipeline_graph`. Disabled by default.
- Updated pipeline detail view [enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/issues/426902) in GitLab 16.8.
{{< /history >}}
Select a pipeline to open the pipeline details page which shows every job in the pipeline.
From this page you can cancel a running pipeline, retry failed jobs, or [delete a pipeline](#delete-a-pipeline).
The pipeline details page displays a graph of all the jobs in the pipeline:

You can use a standard URL to access the details for specific pipelines:
- `gitlab.example.com/my-group/my-project/-/pipelines/latest`: The details page
for the latest pipeline for the most recent commit on the default branch in the project.
- `gitlab.example.com/my-group/my-project/-/pipelines/<branch>/latest`: The details page
for the latest pipeline for the most recent commit on branch `<branch>` in the project.
#### Group jobs by stage or `needs` configuration
When you configure jobs with the [`needs`](../yaml/_index.md#needs) keyword, you have
two options for how to group the jobs in the pipeline details page. To group the jobs
by stage configuration, select **stage** in the **Group jobs by** section:

To group the jobs by [`needs`](../yaml/_index.md#needs) configuration, select **Job dependencies**.
You can optionally select **Show dependencies** to render lines between dependent jobs.

Jobs in the leftmost column run first, and jobs that depend on them are grouped in the next columns.
In this example:
- `lint-job` is configured with `needs: []` and depends on no jobs, so it displays in the first column,
despite being in the `test` stage.
- `test-job1` depends on `build-job1`, and `test-job2` depends on both `build-job1` and `build-job2`,
so both test jobs display in the second column.
- Both `deploy` jobs depend on jobs in second column (which themselves depend on other earlier jobs),
so the deploy jobs display in the third column.
When you hover over a job in the **Job dependencies** view, every job that must run
before the selected job is highlighted:

### Pipeline mini graphs
Pipeline mini graphs take less space and can tell you at a quick glance if all jobs passed
or something failed. They show all related jobs for a single commit and the net result
of each stage of your pipeline. You can quickly see what failed and fix it.
The pipeline mini graph always group jobs by stage, and display throughout GitLab
when displaying pipeline or commit details.

Stages in pipeline mini graphs are expandable. Hover your mouse over each stage
to see the name and status, and select a stage to expand its jobs list.
### Downstream pipeline graphs
When a pipeline contains a job that triggers a [downstream pipeline](downstream_pipelines.md),
you can see the downstream pipeline in the pipeline details view and mini graphs.
In the pipeline details view, a card displays for every triggered downstream pipeline
on the right of the pipeline graph. Hover over a card to see which job triggered the
downstream pipeline. Select a card to display the downstream pipeline to the right
of the pipeline graph.
In the pipeline mini graph, the status of every triggered downstream pipeline displays
as additional status icons to the right of the mini graph. Select a downstream pipeline
status icon to go to the detail page of that downstream pipeline.
## Pipeline success and duration charts
Pipeline analytics are available on the [**CI/CD Analytics** page](../../user/analytics/ci_cd_analytics.md).
## Pipeline badges
Pipeline status and test coverage report badges are available and configurable for each project.
For information on adding pipeline badges to projects, see [Pipeline badges](settings.md#pipeline-badges).
## Pipelines API
GitLab provides API endpoints to:
- Perform basic functions. For more information, see [Pipelines API](../../api/pipelines.md).
- Maintain pipeline schedules. For more information, see [Pipeline schedules API](../../api/pipeline_schedules.md).
- Trigger pipeline runs. For more information, see:
- [Triggering pipelines through the API](../triggers/_index.md).
- [Pipeline triggers API](../../api/pipeline_triggers.md).
## Ref specs for runners
When a runner picks a pipeline job, GitLab provides that job's metadata. This includes the [Git refspecs](https://git-scm.com/book/en/v2/Git-Internals-The-Refspec),
which indicate which ref (such as branch or tag) and commit (SHA1) are checked out from your
project repository.
This table lists the refspecs injected for each pipeline type:
| Pipeline type | Refspecs |
|-------------------------------------------------------------------|----------|
| pipeline for branches | `+<sha>:refs/pipelines/<id>` and `+refs/heads/<name>:refs/remotes/origin/<name>` |
| pipeline for tags | `+<sha>:refs/pipelines/<id>` and `+refs/tags/<name>:refs/tags/<name>` |
| [merge request pipeline](merge_request_pipelines.md) | `+refs/pipelines/<id>:refs/pipelines/<id>` |
The refs `refs/heads/<name>` and `refs/tags/<name>` exist in your
project repository. GitLab generates the special ref `refs/pipelines/<id>` during a
running pipeline job. This ref can be created even after the associated branch or tag has been
deleted. It's therefore useful in some features such as [automatically stopping an environment](../environments/_index.md#stopping-an-environment),
and [merge trains](merge_trains.md) that might run pipelines after branch deletion.
<!--- start_remove The following content will be removed on remove_date: '2025-08-15' -->
## Troubleshooting
### Pipeline subscriptions continue after user deletion
When a user [deletes their GitLab.com account](../../user/profile/account/delete_account.md#delete-your-own-account),
the deletion does not occur for seven days. During this period, any [pipeline subscriptions created by that user](#trigger-a-pipeline-when-an-upstream-project-is-rebuilt-deprecated)
continue to run with the user's original permissions. To prevent unauthorized pipeline executions,
immediately update pipeline subscription settings for the deleted user.
<!--- end_remove -->
|
https://docs.gitlab.com/ci/schedules
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/schedules.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
schedules.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Scheduled pipelines
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use scheduled pipelines to run GitLab CI/CD [pipelines](_index.md) at regular intervals.
## Prerequisites
For a scheduled pipeline to run:
- The schedule owner must have the Developer role. For pipelines on protected branches,
the schedule owner must be [allowed to merge](../../user/project/repository/branches/protected.md#protect-a-branch)
to the branch.
- The `.gitlab-ci.yml` file must have valid syntax.
Otherwise, the pipeline is not created. No error message is displayed.
## Add a pipeline schedule
{{< history >}}
- **Inputs** option [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/525504) in GitLab 17.11.
{{< /history >}}
To add a pipeline schedule:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline schedules**.
1. Select **New schedule** and fill in the form.
- **Interval Pattern**: Select one of the preconfigured intervals, or enter a custom
interval in [cron notation](../../topics/cron/_index.md). You can use any cron value,
but scheduled pipelines cannot run more frequently than the instance's
[maximum scheduled pipeline frequency](../../administration/cicd/_index.md#change-maximum-scheduled-pipeline-frequency).
- **Target branch or tag**: Select the branch or tag for the pipeline.
- **Inputs**: Set values for any [inputs](../inputs/_index.md) defined in your pipeline's `spec:inputs` section.
These input values are used every time the scheduled pipeline runs. A schedule can have a maximum of 20 inputs.
- **Variables**: Add any number of [CI/CD variables](../variables/_index.md) to the schedule.
These variables are available only when the scheduled pipeline runs,
and not in any other pipeline run. Inputs are recommended for pipeline configuration instead of variables
because they offer improved security and flexibility.
If the project already has the [maximum number of pipeline schedules](../../administration/instance_limits.md#number-of-pipeline-schedules),
you must delete unused schedules before you can add another.
## Edit a pipeline schedule
The owner of a pipeline schedule can edit it:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline schedules**.
1. Next to the schedule, select **Edit** ({{< icon name="pencil" >}}) and fill in the form.
The user must have at least the Developer role for the project. If the user is
not the owner of the schedule, they must first [take ownership](#take-ownership)
of the schedule.
## Run manually
To trigger a pipeline schedule manually, so that it runs immediately instead of
the next scheduled time:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline schedules**.
1. On the right of the list, for
the pipeline you want to run, select **Run** ({{< icon name="play" >}}).
You can manually run scheduled pipelines once per minute.
When you run a scheduled pipeline manually, the pipeline runs with the
permissions of the user who triggered it, not the permissions of the schedule owner.
## Take ownership
Scheduled pipelines execute with the permissions of the user
who owns the schedule. The pipeline has access to the same resources as the pipeline owner,
including [protected environments](../environments/protected_environments.md) and the
[CI/CD job token](../jobs/ci_job_token.md).
To take ownership of a pipeline created by a different user:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline schedules**.
1. On the right of the list, for
the pipeline you want to become owner of, select **Take ownership**.
You need at least the Maintainer role to take ownership of a pipeline created by a different user.
## Related topics
- [Pipeline schedules API](../../api/pipeline_schedules.md)
- [Run jobs for scheduled pipelines](../jobs/job_rules.md#run-jobs-for-scheduled-pipelines)
## Troubleshooting
When working with pipeline schedules, you might encounter the following issues.
### Short refs are expanded to full refs
When you provide a short `ref` to the API, it is automatically expanded to a full `ref`.
This behavior is intended and ensures explicit resource identification.
The API accepts both short refs (such as `main`) and full refs (such as `refs/heads/main` or `refs/tags/main`).
### Ambiguous refs
In some cases, the API can't automatically expand a short `ref` to a full `ref`. This can happen when:
- You provide a short `ref` (such as `main`), but both a branch and a tag exist with that name.
- You provide a short `ref`, but no branch or tag with that name exists.
To resolve this issue, provide the full `ref` to ensure the correct resource is identified.
### View and optimize pipeline schedules
To prevent [excessive load](pipeline_efficiency.md) caused by too many pipelines starting simultaneously,
you can review and optimize your pipeline schedules.
To get an overview of all existing schedules and identify opportunities to distribute them more evenly:
1. Run this command to extract and format schedule data:
```shell
outfile=/tmp/gitlab_ci_schedules.tsv
sudo gitlab-psql --command "
COPY (SELECT
ci_pipeline_schedules.cron,
projects.path AS project,
users.email
FROM ci_pipeline_schedules
JOIN projects ON projects.id = ci_pipeline_schedules.project_id
JOIN users ON users.id = ci_pipeline_schedules.owner_id
) TO '$outfile' CSV HEADER DELIMITER E'\t' ;"
sort "$outfile" | uniq -c | sort -n
```
1. Review the output to identify popular `cron` patterns.
For example, you might see many schedules set to run at the start of each hour (`0 * * * *`).
1. Adjust the schedules to create a staggered [`cron` pattern](../../topics/cron/_index.md#cron-syntax), especially for large repositories.
For example, instead of multiple schedules running at the start of each hour, distribute them throughout the hour (`5 * * * *`, `15 * * * *`, `25 * * * *`).
### Scheduled pipeline suddenly becomes inactive
If a scheduled pipeline status changes to `Inactive` unexpectedly, it might be because
the owner of the schedule was blocked or removed. [Take ownership](#take-ownership)
of the schedule to modify and activate it.
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Scheduled pipelines
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use scheduled pipelines to run GitLab CI/CD [pipelines](_index.md) at regular intervals.
## Prerequisites
For a scheduled pipeline to run:
- The schedule owner must have the Developer role. For pipelines on protected branches,
the schedule owner must be [allowed to merge](../../user/project/repository/branches/protected.md#protect-a-branch)
to the branch.
- The `.gitlab-ci.yml` file must have valid syntax.
Otherwise, the pipeline is not created. No error message is displayed.
## Add a pipeline schedule
{{< history >}}
- **Inputs** option [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/525504) in GitLab 17.11.
{{< /history >}}
To add a pipeline schedule:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline schedules**.
1. Select **New schedule** and fill in the form.
- **Interval Pattern**: Select one of the preconfigured intervals, or enter a custom
interval in [cron notation](../../topics/cron/_index.md). You can use any cron value,
but scheduled pipelines cannot run more frequently than the instance's
[maximum scheduled pipeline frequency](../../administration/cicd/_index.md#change-maximum-scheduled-pipeline-frequency).
- **Target branch or tag**: Select the branch or tag for the pipeline.
- **Inputs**: Set values for any [inputs](../inputs/_index.md) defined in your pipeline's `spec:inputs` section.
These input values are used every time the scheduled pipeline runs. A schedule can have a maximum of 20 inputs.
- **Variables**: Add any number of [CI/CD variables](../variables/_index.md) to the schedule.
These variables are available only when the scheduled pipeline runs,
and not in any other pipeline run. Inputs are recommended for pipeline configuration instead of variables
because they offer improved security and flexibility.
If the project already has the [maximum number of pipeline schedules](../../administration/instance_limits.md#number-of-pipeline-schedules),
you must delete unused schedules before you can add another.
## Edit a pipeline schedule
The owner of a pipeline schedule can edit it:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline schedules**.
1. Next to the schedule, select **Edit** ({{< icon name="pencil" >}}) and fill in the form.
The user must have at least the Developer role for the project. If the user is
not the owner of the schedule, they must first [take ownership](#take-ownership)
of the schedule.
## Run manually
To trigger a pipeline schedule manually, so that it runs immediately instead of
the next scheduled time:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline schedules**.
1. On the right of the list, for
the pipeline you want to run, select **Run** ({{< icon name="play" >}}).
You can manually run scheduled pipelines once per minute.
When you run a scheduled pipeline manually, the pipeline runs with the
permissions of the user who triggered it, not the permissions of the schedule owner.
## Take ownership
Scheduled pipelines execute with the permissions of the user
who owns the schedule. The pipeline has access to the same resources as the pipeline owner,
including [protected environments](../environments/protected_environments.md) and the
[CI/CD job token](../jobs/ci_job_token.md).
To take ownership of a pipeline created by a different user:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline schedules**.
1. On the right of the list, for
the pipeline you want to become owner of, select **Take ownership**.
You need at least the Maintainer role to take ownership of a pipeline created by a different user.
## Related topics
- [Pipeline schedules API](../../api/pipeline_schedules.md)
- [Run jobs for scheduled pipelines](../jobs/job_rules.md#run-jobs-for-scheduled-pipelines)
## Troubleshooting
When working with pipeline schedules, you might encounter the following issues.
### Short refs are expanded to full refs
When you provide a short `ref` to the API, it is automatically expanded to a full `ref`.
This behavior is intended and ensures explicit resource identification.
The API accepts both short refs (such as `main`) and full refs (such as `refs/heads/main` or `refs/tags/main`).
### Ambiguous refs
In some cases, the API can't automatically expand a short `ref` to a full `ref`. This can happen when:
- You provide a short `ref` (such as `main`), but both a branch and a tag exist with that name.
- You provide a short `ref`, but no branch or tag with that name exists.
To resolve this issue, provide the full `ref` to ensure the correct resource is identified.
### View and optimize pipeline schedules
To prevent [excessive load](pipeline_efficiency.md) caused by too many pipelines starting simultaneously,
you can review and optimize your pipeline schedules.
To get an overview of all existing schedules and identify opportunities to distribute them more evenly:
1. Run this command to extract and format schedule data:
```shell
outfile=/tmp/gitlab_ci_schedules.tsv
sudo gitlab-psql --command "
COPY (SELECT
ci_pipeline_schedules.cron,
projects.path AS project,
users.email
FROM ci_pipeline_schedules
JOIN projects ON projects.id = ci_pipeline_schedules.project_id
JOIN users ON users.id = ci_pipeline_schedules.owner_id
) TO '$outfile' CSV HEADER DELIMITER E'\t' ;"
sort "$outfile" | uniq -c | sort -n
```
1. Review the output to identify popular `cron` patterns.
For example, you might see many schedules set to run at the start of each hour (`0 * * * *`).
1. Adjust the schedules to create a staggered [`cron` pattern](../../topics/cron/_index.md#cron-syntax), especially for large repositories.
For example, instead of multiple schedules running at the start of each hour, distribute them throughout the hour (`5 * * * *`, `15 * * * *`, `25 * * * *`).
### Scheduled pipeline suddenly becomes inactive
If a scheduled pipeline status changes to `Inactive` unexpectedly, it might be because
the owner of the schedule was blocked or removed. [Take ownership](#take-ownership)
of the schedule to modify and activate it.
|
https://docs.gitlab.com/ci/settings
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/settings.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
settings.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Customize pipeline configuration
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can customize how pipelines run for your project.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview of pipelines, watch the video [GitLab CI Pipeline, Artifacts, and Environments](https://www.youtube.com/watch?v=PCKDICEe10s).
Watch also [GitLab CI pipeline tutorial for beginners](https://www.youtube.com/watch?v=Jav4vbUrqII).
## Change which users can view your pipelines
For public and internal projects, you can change who can see your:
- Pipelines
- Job output logs
- Job artifacts
- [Pipeline security results](../../user/application_security/detect/security_scanning_results.md)
To change the visibility of your pipelines and related features:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Select or clear the **Project-based pipeline visibility** checkbox.
When it is selected, pipelines and related features are visible:
- For [**Public**](../../user/public_access.md) projects, to everyone.
- For **Internal** projects, to all authenticated users except [external users](../../administration/external_users.md).
- For **Private** projects, to all project members (Guest or higher).
When it is cleared:
- For **Public** projects, job logs, job artifacts, the pipeline security dashboard,
and the **CI/CD** menu items are visible only to project members (Reporter or higher).
Other users, including guest users, can only view the status of pipelines and jobs, and only
when viewing merge requests or commits.
- For **Internal** projects, pipelines are visible to all authenticated users except [external users](../../administration/external_users.md).
Related features are visible only to project members (Reporter or higher).
- For **Private** projects, pipelines and related features are visible to project members (Reporter or higher) only.
### Change pipeline visibility for non-project members in public projects
You can control the visibility of pipelines for non-project members in [public projects](../../user/public_access.md).
This setting has no effect when:
- Project visibility is set to [**Internal** or **Private**](../../user/public_access.md),
because non-project members cannot access internal or private projects.
- The [**Project-based pipeline visibility**](#change-which-users-can-view-your-pipelines) setting is disabled.
To change the pipeline visibility for non-project members:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > General**.
1. Expand **Visibility, project features, permissions**.
1. For **CI/CD**, choose:
- **Only project members**: Only project members can view pipelines.
- **Everyone With Access**: Non-project members can also view pipelines.
1. Select **Save changes**.
The [CI/CD permissions table](../../user/permissions.md#cicd)
lists the pipeline features non-project members can access when **Everyone With Access**
is selected.
## Auto-cancel redundant pipelines
You can set pending or running pipelines to cancel automatically when a pipeline for new changes runs on the same branch. You can enable this in the project settings:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General Pipelines**.
1. Select the **Auto-cancel redundant pipelines** checkbox.
1. Select **Save changes**.
Use the [`interruptible`](../yaml/_index.md#interruptible) keyword to indicate if a
running job can be canceled before it completes. After a job with
`interruptible: false` starts, the entire pipeline is no longer considered interruptible.
## Prevent outdated deployment jobs
Your project may have multiple concurrent deployment jobs that are
scheduled to run in the same time frame.
This can lead to a situation where an older deployment job runs after a
newer one, which may not be what you want.
To avoid this scenario:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Select the **Prevent outdated deployment jobs** checkbox.
1. Optional. Clear the **Allow job retries for rollback deployments** checkbox.
1. Select **Save changes**.
For more information, see [Deployment safety](../environments/deployment_safety.md#prevent-outdated-deployment-jobs).
## Restrict roles that can cancel pipelines or jobs
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/137301) in GitLab 16.7.
{{< /history >}}
You can customize which roles have permission to cancel pipelines or jobs.
By default, users with at least the Developer role can cancel pipelines or jobs.
You can restrict cancellation permission to only users with at least the Maintainer role,
or completely prevent cancellation of any pipelines or jobs.
To change the permissions to cancel pipelines or jobs:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Select an option from **Minimum role required to cancel a pipeline or job**.
1. Select **Save changes**.
## Specify a custom CI/CD configuration file
GitLab expects to find the CI/CD configuration file (`.gitlab-ci.yml`) in the project's root
directory. However, you can specify an alternate filename path, including locations outside the project.
To customize the path:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. In the **CI/CD configuration file** field, enter the filename. If the file:
- Is not in the root directory, include the path.
- Is in a different project, include the group and project name.
- Is on an external site, enter the full URL.
1. Select **Save changes**.
{{< alert type="note" >}}
You cannot use your project's [pipeline editor](../pipeline_editor/_index.md) to
edit CI/CD configuration files in other projects or on an external site.
{{< /alert >}}
### Custom CI/CD configuration file examples
If the CI/CD configuration file is not in the root directory, the path must be relative to it.
For example:
- `my/path/.gitlab-ci.yml`
- `my/path/.my-custom-file.yml`
If the CI/CD configuration file is on an external site, the URL must end with `.yml`:
- `http://example.com/generate/ci/config.yml`
If the CI/CD configuration file is in a different project:
- The file must exist on its default branch, or specify the branch as refname.
- The path must be relative to the root directory in the other project.
- The path must be followed by an `@` symbol and the full group and project path.
For example:
- `.gitlab-ci.yml@namespace/another-project`
- `my/path/.my-custom-file.yml@namespace/subgroup/another-project`
- `my/path/.my-custom-file.yml@namespace/subgroup1/subgroup2/another-project:refname`
If the configuration file is in a separate project, you can set more granular permissions. For example:
- Create a public project to host the configuration file.
- Give write permissions on the project only to users who are allowed to edit the file.
Then other users and projects can access the configuration file without being
able to edit it.
## Choose the default Git strategy
You can choose how your repository is fetched from GitLab when a job runs.
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Under **Git strategy**, select an option:
- `git clone` is slower because it clones the repository from scratch
for every job. However, the local working copy is always pristine.
- `git fetch` is faster because it re-uses the local working copy (and falls
back to clone if it doesn't exist). This is recommended, especially for
[large repositories](../../user/project/repository/monorepos/_index.md#use-git-fetch-in-cicd-operations).
The configured Git strategy can be overridden by the [`GIT_STRATEGY` variable](../runners/configure_runners.md#git-strategy)
in the `.gitlab-ci.yml` file.
## Limit the number of changes fetched during clone
You can limit the number of changes that GitLab CI/CD fetches when it clones
a repository.
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Under **Git strategy**, under **Git shallow clone**, enter a value.
The maximum value is `1000`. To disable shallow clone and make GitLab CI/CD
fetch all branches and tags each time, keep the value empty or set to `0`.
Newly created projects have a default `git depth` value of `20`.
This value can be overridden by the [`GIT_DEPTH` variable](../../user/project/repository/monorepos/_index.md#use-shallow-clones-in-cicd-processes)
in the `.gitlab-ci.yml` file.
## Set a limit for how long jobs can run
You can define how long a job can run before it times out.
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. In the **Timeout** field, enter the number of minutes, or a human-readable value like `2 hours`.
Must be 10 minutes or more, and less than one month. Default is 60 minutes.
Pending jobs are dropped after 24 hours of inactivity.
Jobs that exceed the timeout are marked as failed.
When both a project timeout and a [runner timeout](../runners/configure_runners.md#set-the-maximum-job-timeout)
are set, the lower value takes precedence.
Jobs without an output for one hour are dropped regardless of the timeout. To prevent this from happening, add a script to continuously output progress. For more information, see [issue 25359](https://gitlab.com/gitlab-org/gitlab/-/issues/25359#workaround).
## Pipeline badges
You can use [pipeline badges](../../user/project/badges.md) to indicate the pipeline status and
test coverage of your projects. These badges are determined by the latest successful pipeline.
## Disable GitLab CI/CD pipelines
GitLab CI/CD pipelines are enabled by default on all new projects. If you use an external CI/CD server like
Jenkins or Drone CI, you can disable GitLab CI/CD to avoid conflicts with the commits status API.
You can disable GitLab CI/CD per project or [for all new projects on an instance](../../administration/cicd/_index.md).
When you disable GitLab CI/CD:
- The **CI/CD** item in the left sidebar is removed.
- The `/pipelines` and `/jobs` pages are no longer available.
- Existing jobs and pipelines are hidden, not removed.
To disable GitLab CI/CD in your project:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > General**.
1. Expand **Visibility, project features, permissions**.
1. In the **Repository** section, turn off **CI/CD**.
1. Select **Save changes**.
These changes do not apply to projects in an [external integration](../../user/project/integrations/_index.md#available-integrations).
## Automatic pipeline cleanup
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/498969) in GitLab 17.7 [with a flag](../../administration/feature_flags/_index.md) named `ci_delete_old_pipelines`. Disabled by default.
- [Feature flag `ci_delete_old_pipelines`](https://gitlab.com/gitlab-org/gitlab/-/issues/503153) removed in GitLab 17.9.
{{< /history >}}
Users with the Owner role can set a CI/CD pipeline expiry time to help manage pipeline storage and improve system performance.
The system automatically deletes pipelines that were created before the configured value.
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. In the **Automatic pipeline cleanup** field, enter the number of seconds, or a human-readable value like `2 weeks`.
Must be one day or more, and less than one year. Leave empty to never delete pipelines automatically.
Empty by default.
1. Select **Save changes**.
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Customize pipeline configuration
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can customize how pipelines run for your project.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview of pipelines, watch the video [GitLab CI Pipeline, Artifacts, and Environments](https://www.youtube.com/watch?v=PCKDICEe10s).
Watch also [GitLab CI pipeline tutorial for beginners](https://www.youtube.com/watch?v=Jav4vbUrqII).
## Change which users can view your pipelines
For public and internal projects, you can change who can see your:
- Pipelines
- Job output logs
- Job artifacts
- [Pipeline security results](../../user/application_security/detect/security_scanning_results.md)
To change the visibility of your pipelines and related features:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Select or clear the **Project-based pipeline visibility** checkbox.
When it is selected, pipelines and related features are visible:
- For [**Public**](../../user/public_access.md) projects, to everyone.
- For **Internal** projects, to all authenticated users except [external users](../../administration/external_users.md).
- For **Private** projects, to all project members (Guest or higher).
When it is cleared:
- For **Public** projects, job logs, job artifacts, the pipeline security dashboard,
and the **CI/CD** menu items are visible only to project members (Reporter or higher).
Other users, including guest users, can only view the status of pipelines and jobs, and only
when viewing merge requests or commits.
- For **Internal** projects, pipelines are visible to all authenticated users except [external users](../../administration/external_users.md).
Related features are visible only to project members (Reporter or higher).
- For **Private** projects, pipelines and related features are visible to project members (Reporter or higher) only.
### Change pipeline visibility for non-project members in public projects
You can control the visibility of pipelines for non-project members in [public projects](../../user/public_access.md).
This setting has no effect when:
- Project visibility is set to [**Internal** or **Private**](../../user/public_access.md),
because non-project members cannot access internal or private projects.
- The [**Project-based pipeline visibility**](#change-which-users-can-view-your-pipelines) setting is disabled.
To change the pipeline visibility for non-project members:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > General**.
1. Expand **Visibility, project features, permissions**.
1. For **CI/CD**, choose:
- **Only project members**: Only project members can view pipelines.
- **Everyone With Access**: Non-project members can also view pipelines.
1. Select **Save changes**.
The [CI/CD permissions table](../../user/permissions.md#cicd)
lists the pipeline features non-project members can access when **Everyone With Access**
is selected.
## Auto-cancel redundant pipelines
You can set pending or running pipelines to cancel automatically when a pipeline for new changes runs on the same branch. You can enable this in the project settings:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General Pipelines**.
1. Select the **Auto-cancel redundant pipelines** checkbox.
1. Select **Save changes**.
Use the [`interruptible`](../yaml/_index.md#interruptible) keyword to indicate if a
running job can be canceled before it completes. After a job with
`interruptible: false` starts, the entire pipeline is no longer considered interruptible.
## Prevent outdated deployment jobs
Your project may have multiple concurrent deployment jobs that are
scheduled to run in the same time frame.
This can lead to a situation where an older deployment job runs after a
newer one, which may not be what you want.
To avoid this scenario:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Select the **Prevent outdated deployment jobs** checkbox.
1. Optional. Clear the **Allow job retries for rollback deployments** checkbox.
1. Select **Save changes**.
For more information, see [Deployment safety](../environments/deployment_safety.md#prevent-outdated-deployment-jobs).
## Restrict roles that can cancel pipelines or jobs
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/137301) in GitLab 16.7.
{{< /history >}}
You can customize which roles have permission to cancel pipelines or jobs.
By default, users with at least the Developer role can cancel pipelines or jobs.
You can restrict cancellation permission to only users with at least the Maintainer role,
or completely prevent cancellation of any pipelines or jobs.
To change the permissions to cancel pipelines or jobs:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Select an option from **Minimum role required to cancel a pipeline or job**.
1. Select **Save changes**.
## Specify a custom CI/CD configuration file
GitLab expects to find the CI/CD configuration file (`.gitlab-ci.yml`) in the project's root
directory. However, you can specify an alternate filename path, including locations outside the project.
To customize the path:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. In the **CI/CD configuration file** field, enter the filename. If the file:
- Is not in the root directory, include the path.
- Is in a different project, include the group and project name.
- Is on an external site, enter the full URL.
1. Select **Save changes**.
{{< alert type="note" >}}
You cannot use your project's [pipeline editor](../pipeline_editor/_index.md) to
edit CI/CD configuration files in other projects or on an external site.
{{< /alert >}}
### Custom CI/CD configuration file examples
If the CI/CD configuration file is not in the root directory, the path must be relative to it.
For example:
- `my/path/.gitlab-ci.yml`
- `my/path/.my-custom-file.yml`
If the CI/CD configuration file is on an external site, the URL must end with `.yml`:
- `http://example.com/generate/ci/config.yml`
If the CI/CD configuration file is in a different project:
- The file must exist on its default branch, or specify the branch as refname.
- The path must be relative to the root directory in the other project.
- The path must be followed by an `@` symbol and the full group and project path.
For example:
- `.gitlab-ci.yml@namespace/another-project`
- `my/path/.my-custom-file.yml@namespace/subgroup/another-project`
- `my/path/.my-custom-file.yml@namespace/subgroup1/subgroup2/another-project:refname`
If the configuration file is in a separate project, you can set more granular permissions. For example:
- Create a public project to host the configuration file.
- Give write permissions on the project only to users who are allowed to edit the file.
Then other users and projects can access the configuration file without being
able to edit it.
## Choose the default Git strategy
You can choose how your repository is fetched from GitLab when a job runs.
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Under **Git strategy**, select an option:
- `git clone` is slower because it clones the repository from scratch
for every job. However, the local working copy is always pristine.
- `git fetch` is faster because it re-uses the local working copy (and falls
back to clone if it doesn't exist). This is recommended, especially for
[large repositories](../../user/project/repository/monorepos/_index.md#use-git-fetch-in-cicd-operations).
The configured Git strategy can be overridden by the [`GIT_STRATEGY` variable](../runners/configure_runners.md#git-strategy)
in the `.gitlab-ci.yml` file.
## Limit the number of changes fetched during clone
You can limit the number of changes that GitLab CI/CD fetches when it clones
a repository.
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Under **Git strategy**, under **Git shallow clone**, enter a value.
The maximum value is `1000`. To disable shallow clone and make GitLab CI/CD
fetch all branches and tags each time, keep the value empty or set to `0`.
Newly created projects have a default `git depth` value of `20`.
This value can be overridden by the [`GIT_DEPTH` variable](../../user/project/repository/monorepos/_index.md#use-shallow-clones-in-cicd-processes)
in the `.gitlab-ci.yml` file.
## Set a limit for how long jobs can run
You can define how long a job can run before it times out.
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. In the **Timeout** field, enter the number of minutes, or a human-readable value like `2 hours`.
Must be 10 minutes or more, and less than one month. Default is 60 minutes.
Pending jobs are dropped after 24 hours of inactivity.
Jobs that exceed the timeout are marked as failed.
When both a project timeout and a [runner timeout](../runners/configure_runners.md#set-the-maximum-job-timeout)
are set, the lower value takes precedence.
Jobs without an output for one hour are dropped regardless of the timeout. To prevent this from happening, add a script to continuously output progress. For more information, see [issue 25359](https://gitlab.com/gitlab-org/gitlab/-/issues/25359#workaround).
## Pipeline badges
You can use [pipeline badges](../../user/project/badges.md) to indicate the pipeline status and
test coverage of your projects. These badges are determined by the latest successful pipeline.
## Disable GitLab CI/CD pipelines
GitLab CI/CD pipelines are enabled by default on all new projects. If you use an external CI/CD server like
Jenkins or Drone CI, you can disable GitLab CI/CD to avoid conflicts with the commits status API.
You can disable GitLab CI/CD per project or [for all new projects on an instance](../../administration/cicd/_index.md).
When you disable GitLab CI/CD:
- The **CI/CD** item in the left sidebar is removed.
- The `/pipelines` and `/jobs` pages are no longer available.
- Existing jobs and pipelines are hidden, not removed.
To disable GitLab CI/CD in your project:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > General**.
1. Expand **Visibility, project features, permissions**.
1. In the **Repository** section, turn off **CI/CD**.
1. Select **Save changes**.
These changes do not apply to projects in an [external integration](../../user/project/integrations/_index.md#available-integrations).
## Automatic pipeline cleanup
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/498969) in GitLab 17.7 [with a flag](../../administration/feature_flags/_index.md) named `ci_delete_old_pipelines`. Disabled by default.
- [Feature flag `ci_delete_old_pipelines`](https://gitlab.com/gitlab-org/gitlab/-/issues/503153) removed in GitLab 17.9.
{{< /history >}}
Users with the Owner role can set a CI/CD pipeline expiry time to help manage pipeline storage and improve system performance.
The system automatically deletes pipelines that were created before the configured value.
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. In the **Automatic pipeline cleanup** field, enter the number of seconds, or a human-readable value like `2 weeks`.
Must be one day or more, and less than one year. Leave empty to never delete pipelines automatically.
Empty by default.
1. Select **Save changes**.
|
https://docs.gitlab.com/ci/dedicated_hosted_runner_compute_minutes
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/dedicated_hosted_runner_compute_minutes.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
dedicated_hosted_runner_compute_minutes.md
|
Production Engineering
|
Runners Platform
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Compute usage for GitLab-hosted runners on GitLab Dedicated
|
Compute minutes, usage tracking, quota management for GitLab-hosted runners on GitLab Dedicated.
|
{{< details >}}
- Tier: Ultimate
- Offering: GitLab Dedicated
{{< /details >}}
A GitLab Dedicated instance can have both GitLab Self-Managed instance runners and GitLab-hosted instance runners.
As an administrator of a GitLab Dedicated instance, you can track and monitor compute minutes used by
namespaces running jobs on either type of instance runners.
For GitLab-hosted runners:
- You can view your estimated usage in the [GitLab-hosted runner usage dashboard](#view-compute-usage).
- Quota enforcement and notifications are not available.
For GitLab Self-Managed instance runners registered to your GitLab Dedicated instance, see [view instance runner usage](instance_runner_compute_minutes.md#view-usage).
## View compute usage
{{< history >}}
- Compute usage data for GitLab-hosted runners [introduced](https://gitlab.com/groups/gitlab-com/gl-infra/gitlab-dedicated/-/epics/524) in GitLab 18.0.
{{< /history >}}
Prerequisites:
- You must be an administrator for a GitLab Dedicated instance.
You can see compute usage:
- Total compute usage for the current month.
- By month, which you can filter by year and runner.
- By namespace, which you can filter by month and runner.
To view GitLab-hosted runner compute usage for all namespaces across your entire GitLab instance:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Usage quotas**.
|
---
stage: Production Engineering
group: Runners Platform
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Compute minutes, usage tracking, quota management for GitLab-hosted runners
on GitLab Dedicated.
title: Compute usage for GitLab-hosted runners on GitLab Dedicated
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Ultimate
- Offering: GitLab Dedicated
{{< /details >}}
A GitLab Dedicated instance can have both GitLab Self-Managed instance runners and GitLab-hosted instance runners.
As an administrator of a GitLab Dedicated instance, you can track and monitor compute minutes used by
namespaces running jobs on either type of instance runners.
For GitLab-hosted runners:
- You can view your estimated usage in the [GitLab-hosted runner usage dashboard](#view-compute-usage).
- Quota enforcement and notifications are not available.
For GitLab Self-Managed instance runners registered to your GitLab Dedicated instance, see [view instance runner usage](instance_runner_compute_minutes.md#view-usage).
## View compute usage
{{< history >}}
- Compute usage data for GitLab-hosted runners [introduced](https://gitlab.com/groups/gitlab-com/gl-infra/gitlab-dedicated/-/epics/524) in GitLab 18.0.
{{< /history >}}
Prerequisites:
- You must be an administrator for a GitLab Dedicated instance.
You can see compute usage:
- Total compute usage for the current month.
- By month, which you can filter by year and runner.
- By namespace, which you can filter by month and runner.
To view GitLab-hosted runner compute usage for all namespaces across your entire GitLab instance:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > Usage quotas**.
|
https://docs.gitlab.com/ci/pipeline_types
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/pipeline_types.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
pipeline_types.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Types of pipelines
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Multiple types of pipelines can run in a project, including:
- Branch pipelines
- Tag pipelines
- Merge request pipelines
- Merged results pipelines
- Merge trains
These types of pipelines all appear on the **Pipelines** tab of a merge request.
## Branch pipeline
Your pipeline can run every time you commit changes to a branch.
This type of pipeline is called a *branch pipeline*.
They display a `branch` label in pipeline lists.
This pipeline runs by default. No configuration is required.
Branch pipelines:
- Run when you push a new commit to a branch.
- Have access to [some predefined variables](../variables/predefined_variables.md).
- Have access to [protected variables](../variables/_index.md#protect-a-cicd-variable)
and [protected runners](../runners/configure_runners.md#prevent-runners-from-revealing-sensitive-information)
when the branch is a [protected branch](../../user/project/repository/branches/protected.md).
## Tag pipeline
A pipeline can run every time you create or push a new [tag](../../user/project/repository/tags/_index.md).
This type of pipeline is called a *tag pipeline*.
They display a `tag` label in pipeline lists.
This pipeline runs by default. No configuration is required.
Tag pipelines:
- Run when you create/push a new tag to your repository.
- Have access to [some predefined variables](../variables/predefined_variables.md).
- Have access to [protected variables](../variables/_index.md#protect-a-cicd-variable)
and [protected runners](../runners/configure_runners.md#prevent-runners-from-revealing-sensitive-information)
when the tag is a [protected tag](../../user/project/protected_tags.md).
## Merge request pipeline
Instead of a branch pipeline, you can configure your pipeline to run every time you make changes to the
source branch in a merge request.
This type of pipeline is called a *merge request pipeline*.
They display a `merge request` label in pipeline lists.
Merge request pipelines do not run by default. You must configure
the jobs in the `.gitlab-ci.yml` file to run as merge request pipelines.
For more information, see [merge request pipelines](merge_request_pipelines.md).
## Merged results pipeline
{{< history >}}
- The `merged results` label was [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/132975) in GitLab 16.5.
{{< /history >}}
A *merged results pipeline* runs on the result of the source and target branches merged together.
It's a type of merge request pipeline.
These pipelines do not run by default. You must configure the jobs in the `.gitlab-ci.yml` file
to run as a merge request pipeline, and enable merged results pipelines.
These pipelines display a `merged results` label in pipeline lists.
For more information, see [merged results pipeline](merged_results_pipelines.md).
## Merge trains
In projects with frequent merges to the default branch, changes in different merge requests
might conflict with each other. Use *merge trains* to put merge requests in a queue.
Each merge request is compared to the other, earlier merge requests, to ensure they all work together.
Merge trains differ from merged results pipelines, because merged results pipelines
ensure the changes work with the content in the default branch,
but not content that others are merging at the same time.
These pipelines do not run by default. You must configure the jobs in the `.gitlab-ci.yml` file
to run as a merge request pipeline, enable merged results pipelines, and enable merge trains.
These pipelines display a `merge train` label in pipeline lists.
For more information, see [merge trains](merge_trains.md).
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Types of pipelines
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Multiple types of pipelines can run in a project, including:
- Branch pipelines
- Tag pipelines
- Merge request pipelines
- Merged results pipelines
- Merge trains
These types of pipelines all appear on the **Pipelines** tab of a merge request.
## Branch pipeline
Your pipeline can run every time you commit changes to a branch.
This type of pipeline is called a *branch pipeline*.
They display a `branch` label in pipeline lists.
This pipeline runs by default. No configuration is required.
Branch pipelines:
- Run when you push a new commit to a branch.
- Have access to [some predefined variables](../variables/predefined_variables.md).
- Have access to [protected variables](../variables/_index.md#protect-a-cicd-variable)
and [protected runners](../runners/configure_runners.md#prevent-runners-from-revealing-sensitive-information)
when the branch is a [protected branch](../../user/project/repository/branches/protected.md).
## Tag pipeline
A pipeline can run every time you create or push a new [tag](../../user/project/repository/tags/_index.md).
This type of pipeline is called a *tag pipeline*.
They display a `tag` label in pipeline lists.
This pipeline runs by default. No configuration is required.
Tag pipelines:
- Run when you create/push a new tag to your repository.
- Have access to [some predefined variables](../variables/predefined_variables.md).
- Have access to [protected variables](../variables/_index.md#protect-a-cicd-variable)
and [protected runners](../runners/configure_runners.md#prevent-runners-from-revealing-sensitive-information)
when the tag is a [protected tag](../../user/project/protected_tags.md).
## Merge request pipeline
Instead of a branch pipeline, you can configure your pipeline to run every time you make changes to the
source branch in a merge request.
This type of pipeline is called a *merge request pipeline*.
They display a `merge request` label in pipeline lists.
Merge request pipelines do not run by default. You must configure
the jobs in the `.gitlab-ci.yml` file to run as merge request pipelines.
For more information, see [merge request pipelines](merge_request_pipelines.md).
## Merged results pipeline
{{< history >}}
- The `merged results` label was [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/132975) in GitLab 16.5.
{{< /history >}}
A *merged results pipeline* runs on the result of the source and target branches merged together.
It's a type of merge request pipeline.
These pipelines do not run by default. You must configure the jobs in the `.gitlab-ci.yml` file
to run as a merge request pipeline, and enable merged results pipelines.
These pipelines display a `merged results` label in pipeline lists.
For more information, see [merged results pipeline](merged_results_pipelines.md).
## Merge trains
In projects with frequent merges to the default branch, changes in different merge requests
might conflict with each other. Use *merge trains* to put merge requests in a queue.
Each merge request is compared to the other, earlier merge requests, to ensure they all work together.
Merge trains differ from merged results pipelines, because merged results pipelines
ensure the changes work with the content in the default branch,
but not content that others are merging at the same time.
These pipelines do not run by default. You must configure the jobs in the `.gitlab-ci.yml` file
to run as a merge request pipeline, enable merged results pipelines, and enable merge trains.
These pipelines display a `merge train` label in pipeline lists.
For more information, see [merge trains](merge_trains.md).
|
https://docs.gitlab.com/ci/downstream_pipelines
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/downstream_pipelines.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
downstream_pipelines.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Downstream pipelines
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
A downstream pipeline is any GitLab CI/CD pipeline triggered by another pipeline.
Downstream pipelines run independently and concurrently to the upstream pipeline
that triggered them.
- A [parent-child pipeline](downstream_pipelines.md#parent-child-pipelines) is a downstream pipeline
triggered in the same project as the first pipeline.
- A [multi-project pipeline](#multi-project-pipelines) is a downstream pipeline triggered
in a different project than the first pipeline.
You can sometimes use parent-child pipelines and multi-project pipelines for similar purposes,
but there are [key differences](pipeline_architectures.md).
A pipeline hierarchy can contain up to 1000 downstream pipelines by default.
For more information about this limit and how to change it, see [Limit pipeline hierarchy size](../../administration/instance_limits.md#limit-pipeline-hierarchy-size).
## Parent-child pipelines
A parent pipeline is a pipeline that triggers a downstream pipeline in the same project.
The downstream pipeline is called a child pipeline.
Child pipelines:
- Run under the same project, ref, and commit SHA as the parent pipeline.
- Do not directly affect the overall status of the ref the pipeline runs against. For example,
if a pipeline fails for the main branch, it's common to say that "main is broken".
The status of child pipelines only affects the status of the ref if the child
pipeline is triggered with [`trigger:strategy`](../yaml/_index.md#triggerstrategy).
- Are automatically canceled if the pipeline is configured with [`interruptible`](../yaml/_index.md#interruptible)
when a new pipeline is created for the same ref.
- Are not displayed in the project's pipeline list. You can only view child pipelines on
their parent pipeline's details page.
### Nested child pipelines
Parent and child pipelines have a maximum depth of two levels of child pipelines.
A parent pipeline can trigger many child pipelines, and these child pipelines can trigger
their own child pipelines. You cannot trigger another level of child pipelines.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [Nested Dynamic Pipelines](https://youtu.be/C5j3ju9je2M).
## Multi-project pipelines
A pipeline in one project can trigger downstream pipelines in another project,
called multi-project pipelines. The user triggering the upstream pipeline must be able to
start pipelines in the downstream project, otherwise [the downstream pipeline fails to start](downstream_pipelines_troubleshooting.md#trigger-job-fails-and-does-not-create-multi-project-pipeline).
Multi-project pipelines:
- Are triggered from another project's pipeline, but the upstream (triggering) pipeline does
not have much control over the downstream (triggered) pipeline. However, it can
choose the ref of the downstream pipeline, and pass CI/CD variables to it.
- Affect the overall status of the ref of the project it runs in, but does not
affect the status of the triggering pipeline's ref, unless it was triggered with
[`trigger:strategy`](../yaml/_index.md#triggerstrategy).
- Are not automatically canceled in the downstream project when using [`interruptible`](../yaml/_index.md#interruptible)
if a new pipeline runs for the same ref in the upstream pipeline. They can be
automatically canceled if a new pipeline is triggered for the same ref on the downstream project.
- Are visible in the downstream project's pipeline list.
- Are independent, so there are no nesting limits.
If you use a public project to trigger downstream pipelines in a private project,
make sure there are no confidentiality problems. The upstream project's pipelines page
always displays:
- The name of the downstream project.
- The status of the pipeline.
## Trigger a downstream pipeline from a job in the `.gitlab-ci.yml` file
Use the [`trigger`](../yaml/_index.md#trigger) keyword in your `.gitlab-ci.yml` file
to create a job that triggers a downstream pipeline. This job is called a trigger job.
For example:
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
```yaml
trigger_job:
trigger:
include:
- local: path/to/child-pipeline.yml
```
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
```yaml
trigger_job:
trigger:
project: project-group/my-downstream-project
```
{{< /tab >}}
{{< /tabs >}}
After the trigger job starts, the initial status of the job is `pending` while GitLab
attempts to create the downstream pipeline. The trigger job shows `passed` if the
downstream pipeline is created successfully, otherwise it shows `failed`. Alternatively,
you can [set the trigger job to show the downstream pipeline's status](#mirror-the-status-of-a-downstream-pipeline-in-the-trigger-job)
instead.
### Use `rules` to control downstream pipeline jobs
Use CI/CD variables or the [`rules`](../yaml/_index.md#rulesif) keyword to
[control job behavior](../jobs/job_control.md) in downstream pipelines.
When you trigger a downstream pipeline with the [`trigger`](../yaml/_index.md#trigger) keyword,
the value of the [`$CI_PIPELINE_SOURCE` predefined variable](../variables/predefined_variables.md)
for all jobs is:
- `pipeline` for multi-project pipelines.
- `parent_pipeline` for parent-child pipelines.
For example, to control jobs in multi-project pipelines in a project that also runs
merge request pipelines:
```yaml
job1:
rules:
- if: $CI_PIPELINE_SOURCE == "pipeline"
script: echo "This job runs in multi-project pipelines only"
job2:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
script: echo "This job runs in merge request pipelines only"
job3:
rules:
- if: $CI_PIPELINE_SOURCE == "pipeline"
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
script: echo "This job runs in both multi-project and merge request pipelines"
```
### Use a child pipeline configuration file in a different project
You can use [`include:project`](../yaml/_index.md#includeproject) in a trigger job
to trigger child pipelines with a configuration file in a different project:
```yaml
microservice_a:
trigger:
include:
- project: 'my-group/my-pipeline-library'
ref: 'main'
file: '/path/to/child-pipeline.yml'
```
### Combine multiple child pipeline configuration files
You can include up to three configuration files when defining a child pipeline. The child pipeline's
configuration is composed of all configuration files merged together:
```yaml
microservice_a:
trigger:
include:
- local: path/to/microservice_a.yml
- template: Jobs/SAST.gitlab-ci.yml
- project: 'my-group/my-pipeline-library'
ref: 'main'
file: '/path/to/child-pipeline.yml'
```
### Dynamic child pipelines
You can trigger a child pipeline from a YAML file generated in a job, instead of a
static file saved in your project. This technique can be very powerful for generating pipelines
targeting content that changed or to build a matrix of targets and architectures.
The artifact containing the generated YAML file must be within [instance limits](../../administration/instance_limits.md#maximum-size-of-the-ci-artifacts-archive).
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [Create child pipelines using dynamically generated configurations](https://youtu.be/nMdfus2JWHM).
For an example project that generates a dynamic child pipeline, see
[Dynamic Child Pipelines with Jsonnet](https://gitlab.com/gitlab-org/project-templates/jsonnet).
This project shows how to use a data templating language to generate your `.gitlab-ci.yml` at runtime.
You can use a similar process for other templating languages like
[Dhall](https://dhall-lang.org/) or [ytt](https://get-ytt.io/).
#### Trigger a dynamic child pipeline
To trigger a child pipeline from a dynamically generated configuration file:
1. Generate the configuration file in a job and save it as an [artifact](../yaml/_index.md#artifactspaths):
```yaml
generate-config:
stage: build
script: generate-ci-config > generated-config.yml
artifacts:
paths:
- generated-config.yml
```
1. Configure the trigger job to run after the job that generated the configuration file.
Set `include: artifact` to the generated artifact, and set `include: job` to
the job that created the artifact:
```yaml
child-pipeline:
stage: test
trigger:
include:
- artifact: generated-config.yml
job: generate-config
```
In this example, GitLab retrieves `generated-config.yml` and triggers a child pipeline
with the CI/CD configuration in that file.
The artifact path is parsed by GitLab, not the runner, so the path must match the
syntax for the OS running GitLab. If GitLab is running on Linux but using a Windows
runner for testing, the path separator for the trigger job is `/`. Other CI/CD
configuration for jobs that use the Windows runner, like scripts, use ` \ `.
You cannot use CI/CD variables in an `include` section in a dynamic child pipeline's configuration.
[Issue 378717](https://gitlab.com/gitlab-org/gitlab/-/issues/378717) proposes fixing
this issue.
### Run child pipelines with merge request pipelines
Pipelines, including child pipelines, run as branch pipelines by default when not using
[`rules`](../yaml/_index.md#rules) or [`workflow:rules`](../yaml/_index.md#workflowrules).
To configure child pipelines to run when triggered from a [merge request (parent) pipeline](merge_request_pipelines.md), use `rules` or `workflow:rules`.
For example, using `rules`:
1. Set the parent pipeline's trigger job to run on merge requests:
```yaml
trigger-child-pipeline-job:
trigger:
include: path/to/child-pipeline-configuration.yml
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
```
1. Use `rules` to configure the child pipeline jobs to run when triggered by the parent pipeline:
```yaml
job1:
script: echo "This child pipeline job runs any time the parent pipeline triggers it."
rules:
- if: $CI_PIPELINE_SOURCE == "parent_pipeline"
job2:
script: echo "This child pipeline job runs only when the parent pipeline is a merge request pipeline"
rules:
- if: $CI_MERGE_REQUEST_ID
```
In child pipelines, `$CI_PIPELINE_SOURCE` always has a value of `parent_pipeline`, so:
- You can use `if: $CI_PIPELINE_SOURCE == "parent_pipeline"` to ensure child pipeline jobs always run.
- You can't use `if: $CI_PIPELINE_SOURCE == "merge_request_event"` to configure child pipeline
jobs to run for merge request pipelines. Instead, use `if: $CI_MERGE_REQUEST_ID`
to set child pipeline jobs to run only when the parent pipeline is a merge request pipeline. The parent pipeline's
[`CI_MERGE_REQUEST_*` predefined variables](../variables/predefined_variables.md#predefined-variables-for-merge-request-pipelines)
are passed to the child pipeline jobs.
### Specify a branch for multi-project pipelines
You can specify the branch to use when triggering a multi-project pipeline. GitLab uses
the commit on the head of the branch to create the downstream pipeline. For example:
```yaml
staging:
stage: deploy
trigger:
project: my/deployment
branch: stable-11-2
```
Use:
- The `project` keyword to specify the full path to the downstream project.
In [GitLab 15.3 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/367660),
you can use [variable expansion](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
- The `branch` keyword to specify the name of a branch or [tag](../../user/project/repository/tags/_index.md)
in the project specified by `project`. You can use variable expansion.
## Trigger a multi-project pipeline by using the API
You can use the [CI/CD job token (`CI_JOB_TOKEN`)](../jobs/ci_job_token.md) with the
[pipeline trigger API endpoint](../../api/pipeline_triggers.md#trigger-a-pipeline-with-a-token)
to trigger multi-project pipelines from inside a CI/CD job. GitLab sets pipelines triggered
with a job token as downstream pipelines of the pipeline that contains the job that
made the API call.
For example:
```yaml
trigger_pipeline:
stage: deploy
script:
- curl --request POST --form "token=$CI_JOB_TOKEN" --form ref=main "https://gitlab.example.com/api/v4/projects/9/trigger/pipeline"
rules:
- if: $CI_COMMIT_TAG
environment: production
```
## View a downstream pipeline
In the [pipeline details page](_index.md#pipeline-details), downstream pipelines display
as a list of cards on the right of the graph. From this view, you can:
- Select a trigger job to see the triggered downstream pipeline's jobs.
- Select **Expand jobs** {{< icon name="chevron-lg-right" >}} on a pipeline card to expand the view
with the downstream pipeline's jobs. You can view one downstream pipeline at a time.
- Hover over a pipeline card to have the job that triggered the downstream pipeline highlighted.
### Retry failed and canceled jobs in a downstream pipeline
{{< history >}}
- Retry from graph view [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/354974) in GitLab 15.0 [with a flag](../../administration/feature_flags/_index.md) named `downstream_retry_action`. Disabled by default.
- Retry from graph view [generally available and feature flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/357406) in GitLab 15.1.
{{< /history >}}
To retry failed and canceled jobs, select **Retry** ({{< icon name="retry" >}}):
- From the downstream pipeline's details page.
- On the pipeline's card in the pipeline graph view.
### Recreate a downstream pipeline
{{< history >}}
- Retry trigger job from graph view [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/367547) in GitLab 15.10 [with a flag](../../administration/feature_flags/_index.md) named `ci_recreate_downstream_pipeline`. Disabled by default.
- [Generally available](https://gitlab.com/groups/gitlab-org/-/epics/6947) in GitLab 15.11. Feature flag `ci_recreate_downstream_pipeline` removed.
{{< /history >}}
You can recreate a downstream pipeline by retrying its corresponding trigger job. The newly created downstream pipeline replaces the current downstream pipeline in the pipeline graph.
To recreate a downstream pipeline:
- Select **Run again** ({{< icon name="retry" >}}) on the trigger job's card in the pipeline graph view.
### Cancel a downstream pipeline
{{< history >}}
- Retry from graph view [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/354974) in GitLab 15.0 [with a flag](../../administration/feature_flags/_index.md) named `downstream_retry_action`. Disabled by default.
- Retry from graph view [generally available and feature flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/357406) in GitLab 15.1.
{{< /history >}}
To cancel a downstream pipeline that is still running, select **Cancel** ({{< icon name="cancel" >}}):
- From the downstream pipeline's details page.
- On the pipeline's card in the pipeline graph view.
### Auto-cancel the parent pipeline from a downstream pipeline
You can configure a child pipeline to [auto-cancel](../yaml/_index.md#workflowauto_cancelon_job_failure)
as soon as one of its jobs fail.
The parent pipeline only auto-cancels when a job in the child pipeline fails if:
- The parent pipeline is also set up to auto-cancel on job failure.
- The trigger job is configured with [`strategy: depend`](../yaml/_index.md#triggerstrategy).
For example:
- Content of `.gitlab-ci.yml`:
```yaml
workflow:
auto_cancel:
on_job_failure: all
trigger_job:
trigger:
include: child-pipeline.yml
strategy: depend
job3:
script:
- sleep 120
```
- Content of `child-pipeline.yml`
```yaml
# Contents of child-pipeline.yml
workflow:
auto_cancel:
on_job_failure: all
job1:
script: sleep 60
job2:
script:
- sleep 30
- exit 1
```
In this example:
1. The parent pipeline triggers the child pipeline and `job3` at the same time
1. `job2` from the child pipeline fails and the child pipeline is canceled, stopping `job1` as well
1. The child pipeline has been canceled so the parent pipeline is auto-canceled
### Mirror the status of a downstream pipeline in the trigger job
You can mirror the status of the downstream pipeline in the trigger job
by using [`strategy: mirror`](../yaml/_index.md#triggerstrategy):
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
```yaml
trigger_job:
trigger:
include:
- local: path/to/child-pipeline.yml
strategy: mirror
```
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
```yaml
trigger_job:
trigger:
project: my/project
strategy: mirror
```
{{< /tab >}}
{{< /tabs >}}
### View multi-project pipelines in pipeline graphs
{{< history >}}
- [Moved](https://gitlab.com/gitlab-org/gitlab/-/issues/422282) from GitLab Premium to GitLab Free in 16.8.
{{< /history >}}
After you trigger a multi-project pipeline, the downstream pipeline displays
to the right of the [pipeline graph](_index.md#view-pipelines).
In [pipeline mini graphs](_index.md#pipeline-mini-graphs), the downstream pipeline
displays to the right of the mini graph.
## Fetch artifacts from an upstream pipeline
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
Use [`needs:pipeline:job`](../yaml/_index.md#needspipelinejob) to fetch artifacts from an
upstream pipeline:
1. In the upstream pipeline, save the artifacts in a job with the [`artifacts`](../yaml/_index.md#artifacts)
keyword, then trigger the downstream pipeline with a trigger job:
```yaml
build_artifacts:
stage: build
script:
- echo "This is a test artifact!" >> artifact.txt
artifacts:
paths:
- artifact.txt
deploy:
stage: deploy
trigger:
include:
- local: path/to/child-pipeline.yml
variables:
PARENT_PIPELINE_ID: $CI_PIPELINE_ID
```
1. Use `needs:pipeline:job` in a job in the downstream pipeline to fetch the artifacts.
```yaml
test:
stage: test
script:
- cat artifact.txt
needs:
- pipeline: $PARENT_PIPELINE_ID
job: build_artifacts
```
Set `job` to the job in the upstream pipeline that created the artifacts.
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
Use [`needs:project`](../yaml/_index.md#needsproject) to fetch artifacts from an
upstream pipeline:
1. In GitLab 15.9 and later, [add the downstream project to the job token scope allowlist](../jobs/ci_job_token.md#add-a-group-or-project-to-the-job-token-allowlist) of the upstream project.
1. In the upstream pipeline, save the artifacts in a job with the [`artifacts`](../yaml/_index.md#artifacts)
keyword, then trigger the downstream pipeline with a trigger job:
```yaml
build_artifacts:
stage: build
script:
- echo "This is a test artifact!" >> artifact.txt
artifacts:
paths:
- artifact.txt
deploy:
stage: deploy
trigger: my/downstream_project # Path to the project to trigger a pipeline in
```
1. Use `needs:project` in a job in the downstream pipeline to fetch the artifacts.
```yaml
test:
stage: test
script:
- cat artifact.txt
needs:
- project: my/upstream_project
job: build_artifacts
ref: main
artifacts: true
```
Set:
- `job` to the job in the upstream pipeline that created the artifacts.
- `ref` to the branch.
- `artifacts` to `true`.
{{< /tab >}}
{{< /tabs >}}
### Fetch artifacts from an upstream merge request pipeline
When you use `needs:project` to [pass artifacts to a downstream pipeline](#fetch-artifacts-from-an-upstream-pipeline),
the `ref` value is usually a branch name, like `main` or `development`.
For [merge request pipelines](merge_request_pipelines.md), the `ref` value is in the form of `refs/merge-requests/<id>/head`,
where `id` is the merge request ID. You can retrieve this ref with the [`CI_MERGE_REQUEST_REF_PATH`](../variables/predefined_variables.md#predefined-variables-for-merge-request-pipelines)
CI/CD variable. Do not use a branch name as the `ref` with merge request pipelines,
because the downstream pipeline attempts to fetch artifacts from the latest branch pipeline.
To fetch the artifacts from the upstream `merge request` pipeline instead of the `branch` pipeline,
pass `CI_MERGE_REQUEST_REF_PATH` to the downstream pipeline using [variable inheritance](#pass-yaml-defined-cicd-variables):
1. In GitLab 15.9 and later, [add the downstream project to the job token scope allowlist](../jobs/ci_job_token.md#add-a-group-or-project-to-the-job-token-allowlist) of the upstream project.
1. In a job in the upstream pipeline, save the artifacts using the [`artifacts`](../yaml/_index.md#artifacts) keyword.
1. In the job that triggers the downstream pipeline, pass the `$CI_MERGE_REQUEST_REF_PATH` variable:
```yaml
build_artifacts:
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
stage: build
script:
- echo "This is a test artifact!" >> artifact.txt
artifacts:
paths:
- artifact.txt
upstream_job:
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
variables:
UPSTREAM_REF: $CI_MERGE_REQUEST_REF_PATH
trigger:
project: my/downstream_project
branch: my-branch
```
1. In a job in the downstream pipeline, fetch the artifacts from the upstream pipeline
by using `needs:project` and the passed variable as the `ref`:
```yaml
test:
stage: test
script:
- cat artifact.txt
needs:
- project: my/upstream_project
job: build_artifacts
ref: $UPSTREAM_REF
artifacts: true
```
You can use this method to fetch artifacts from upstream merge request pipelines,
but not from [merged results pipelines](merged_results_pipelines.md).
## Pass inputs to a downstream pipeline
You can use the [`inputs`](../inputs/_index.md) keyword to pass input values to downstream pipelines.
Inputs provide advantages over variables including type checking, validation through options,
descriptions, and default values.
First, define input parameters in the target configuration file using `spec:inputs`:
```yaml
# Target pipeline configuration
spec:
inputs:
environment:
description: "Deployment environment"
options: [staging, production]
version:
type: string
description: "Application version"
```
Then provide values when triggering the pipeline:
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
```yaml
staging:
trigger:
include:
- local: path/to/child-pipeline.yml
inputs:
environment: staging
version: "1.0.0"
```
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
```yaml
staging:
trigger:
project: my-group/my-deployment-project
inputs:
environment: staging
version: "1.0.0"
```
{{< /tab >}}
{{< /tabs >}}
## Pass CI/CD variables to a downstream pipeline
You can pass [CI/CD variables](../variables/_index.md) to a downstream pipeline with
a few different methods, based on where the variable is created or defined.
### Pass YAML-defined CI/CD variables
_Note: Inputs are recommended for pipeline configuration instead of variables as they offer improved security and flexibility._
You can use the `variables` keyword to pass CI/CD variables to a downstream pipeline.
These variables are pipeline variables for [variable precedence](../variables/_index.md#cicd-variable-precedence).
For example:
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
```yaml
variables:
VERSION: "1.0.0"
staging:
variables:
ENVIRONMENT: staging
stage: deploy
trigger:
include:
- local: path/to/child-pipeline.yml
```
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
```yaml
variables:
VERSION: "1.0.0"
staging:
variables:
ENVIRONMENT: staging
stage: deploy
trigger: my-group/my-deployment-project
```
{{< /tab >}}
{{< /tabs >}}
The `ENVIRONMENT` variable is available in every job defined in the downstream pipeline.
The `VERSION` default variable is also available in the downstream pipeline, because
all jobs in a pipeline, including trigger jobs, inherit [default `variables`](../yaml/_index.md#default-variables).
#### Prevent default variables from being passed
You can stop default CI/CD variables from reaching the downstream pipeline with
[`inherit:variables`](../yaml/_index.md#inheritvariables). You can list specific variables to inherit,
or block all default variables.
For example:
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
```yaml
variables:
DEFAULT_VAR: value
trigger-job:
inherit:
variables: false
variables:
JOB_VAR: value
trigger:
include:
- local: path/to/child-pipeline.yml
```
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
```yaml
variables:
DEFAULT_VAR: value
trigger-job:
inherit:
variables: false
variables:
JOB_VAR: value
trigger: my-group/my-project
```
{{< /tab >}}
{{< /tabs >}}
The `DEFAULT_VAR` variable is not available in the triggered pipeline, but `JOB_VAR`
is available.
### Pass a predefined variable
To pass information about the upstream pipeline using [predefined CI/CD variables](../variables/predefined_variables.md)
use interpolation. Save the predefined variable as a new job variable in the trigger
job, which is passed to the downstream pipeline. For example:
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
```yaml
trigger-job:
variables:
PARENT_BRANCH: $CI_COMMIT_REF_NAME
trigger:
include:
- local: path/to/child-pipeline.yml
```
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
```yaml
trigger-job:
variables:
UPSTREAM_BRANCH: $CI_COMMIT_REF_NAME
trigger: my-group/my-project
```
{{< /tab >}}
{{< /tabs >}}
The `UPSTREAM_BRANCH` variable, which contains the value of the upstream pipeline's `$CI_COMMIT_REF_NAME`
predefined CI/CD variable, is available in the downstream pipeline.
Do not use this method to pass [masked variables](../variables/_index.md#mask-a-cicd-variable)
to a multi-project pipeline. The CI/CD masking configuration is not passed to the
downstream pipeline and the variable could be unmasked in job logs in the downstream project.
You cannot use this method to forward [job-only variables](../variables/predefined_variables.md#variable-availability)
to a downstream pipeline, as they are not available in trigger jobs.
Upstream pipelines take precedence over downstream ones. If there are two
variables with the same name defined in both upstream and downstream projects,
the ones defined in the upstream project take precedence.
### Pass dotenv variables created in a job
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can pass variables to a downstream pipeline with [`dotenv` variable inheritance](../variables/job_scripts.md#pass-an-environment-variable-to-another-job).
For example, in a [multi-project pipeline](#multi-project-pipelines):
1. Save the variables in a `.env` file.
1. Save the `.env` file as a `dotenv` report.
1. Trigger the downstream pipeline.
```yaml
build_vars:
stage: build
script:
- echo "BUILD_VERSION=hello" >> build.env
artifacts:
reports:
dotenv: build.env
deploy:
stage: deploy
trigger: my/downstream_project
```
1. Set the `test` job in the downstream pipeline to inherit the variables from the `build_vars`
job in the upstream project with `needs`. The `test` job inherits the variables in the
`dotenv` report and it can access `BUILD_VERSION` in the script:
```yaml
test:
stage: test
script:
- echo $BUILD_VERSION
needs:
- project: my/upstream_project
job: build_vars
ref: master
artifacts: true
```
### Control what type of variables to forward to downstream pipelines
Use the [`trigger:forward` keyword](../yaml/_index.md#triggerforward) to specify
what type of variables to forward to the downstream pipeline. Forwarded variables
are considered trigger variables, which have the [highest precedence](../variables/_index.md#cicd-variable-precedence).
## Downstream pipelines for deployments
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/369061) in GitLab 16.4.
{{< /history >}}
You can use the [`environment`](../yaml/_index.md#environment) keyword with [`trigger`](../yaml/_index.md#trigger).
You might want to use `environment` from a trigger job if your deployment and application projects are separately managed.
```yaml
deploy:
trigger:
project: project-group/my-downstream-project
environment: production
```
A downstream pipeline can provision infrastructure, deploy to a designated environment, and return the deployment status
to the upstream project.
You can [view the environment and deployment](../environments/_index.md#view-environments-and-deployments)
from the upstream project.
### Advanced example
This example configuration has the following behaviors:
- The upstream project dynamically composes an environment name based on a branch name.
- The upstream project passes the context of the deployment to the downstream project with `UPSTREAM_*` variables.
The `.gitlab-ci.yml` in an upstream project:
```yaml
stages:
- deploy
- cleanup
.downstream-deployment-pipeline:
variables:
UPSTREAM_PROJECT_ID: $CI_PROJECT_ID
UPSTREAM_ENVIRONMENT_NAME: $CI_ENVIRONMENT_NAME
UPSTREAM_ENVIRONMENT_ACTION: $CI_ENVIRONMENT_ACTION
trigger:
project: project-group/deployment-project
branch: main
strategy: mirror
deploy-review:
stage: deploy
extends: .downstream-deployment-pipeline
environment:
name: review/$CI_COMMIT_REF_SLUG
on_stop: stop-review
stop-review:
stage: cleanup
extends: .downstream-deployment-pipeline
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
when: manual
```
The `.gitlab-ci.yml` in a downstream project:
```yaml
deploy:
script: echo "Deploy to ${UPSTREAM_ENVIRONMENT_NAME} for ${UPSTREAM_PROJECT_ID}"
rules:
- if: $CI_PIPELINE_SOURCE == "pipeline" && $UPSTREAM_ENVIRONMENT_ACTION == "start"
stop:
script: echo "Stop ${UPSTREAM_ENVIRONMENT_NAME} for ${UPSTREAM_PROJECT_ID}"
rules:
- if: $CI_PIPELINE_SOURCE == "pipeline" && $UPSTREAM_ENVIRONMENT_ACTION == "stop"
```
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Downstream pipelines
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
A downstream pipeline is any GitLab CI/CD pipeline triggered by another pipeline.
Downstream pipelines run independently and concurrently to the upstream pipeline
that triggered them.
- A [parent-child pipeline](downstream_pipelines.md#parent-child-pipelines) is a downstream pipeline
triggered in the same project as the first pipeline.
- A [multi-project pipeline](#multi-project-pipelines) is a downstream pipeline triggered
in a different project than the first pipeline.
You can sometimes use parent-child pipelines and multi-project pipelines for similar purposes,
but there are [key differences](pipeline_architectures.md).
A pipeline hierarchy can contain up to 1000 downstream pipelines by default.
For more information about this limit and how to change it, see [Limit pipeline hierarchy size](../../administration/instance_limits.md#limit-pipeline-hierarchy-size).
## Parent-child pipelines
A parent pipeline is a pipeline that triggers a downstream pipeline in the same project.
The downstream pipeline is called a child pipeline.
Child pipelines:
- Run under the same project, ref, and commit SHA as the parent pipeline.
- Do not directly affect the overall status of the ref the pipeline runs against. For example,
if a pipeline fails for the main branch, it's common to say that "main is broken".
The status of child pipelines only affects the status of the ref if the child
pipeline is triggered with [`trigger:strategy`](../yaml/_index.md#triggerstrategy).
- Are automatically canceled if the pipeline is configured with [`interruptible`](../yaml/_index.md#interruptible)
when a new pipeline is created for the same ref.
- Are not displayed in the project's pipeline list. You can only view child pipelines on
their parent pipeline's details page.
### Nested child pipelines
Parent and child pipelines have a maximum depth of two levels of child pipelines.
A parent pipeline can trigger many child pipelines, and these child pipelines can trigger
their own child pipelines. You cannot trigger another level of child pipelines.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [Nested Dynamic Pipelines](https://youtu.be/C5j3ju9je2M).
## Multi-project pipelines
A pipeline in one project can trigger downstream pipelines in another project,
called multi-project pipelines. The user triggering the upstream pipeline must be able to
start pipelines in the downstream project, otherwise [the downstream pipeline fails to start](downstream_pipelines_troubleshooting.md#trigger-job-fails-and-does-not-create-multi-project-pipeline).
Multi-project pipelines:
- Are triggered from another project's pipeline, but the upstream (triggering) pipeline does
not have much control over the downstream (triggered) pipeline. However, it can
choose the ref of the downstream pipeline, and pass CI/CD variables to it.
- Affect the overall status of the ref of the project it runs in, but does not
affect the status of the triggering pipeline's ref, unless it was triggered with
[`trigger:strategy`](../yaml/_index.md#triggerstrategy).
- Are not automatically canceled in the downstream project when using [`interruptible`](../yaml/_index.md#interruptible)
if a new pipeline runs for the same ref in the upstream pipeline. They can be
automatically canceled if a new pipeline is triggered for the same ref on the downstream project.
- Are visible in the downstream project's pipeline list.
- Are independent, so there are no nesting limits.
If you use a public project to trigger downstream pipelines in a private project,
make sure there are no confidentiality problems. The upstream project's pipelines page
always displays:
- The name of the downstream project.
- The status of the pipeline.
## Trigger a downstream pipeline from a job in the `.gitlab-ci.yml` file
Use the [`trigger`](../yaml/_index.md#trigger) keyword in your `.gitlab-ci.yml` file
to create a job that triggers a downstream pipeline. This job is called a trigger job.
For example:
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
```yaml
trigger_job:
trigger:
include:
- local: path/to/child-pipeline.yml
```
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
```yaml
trigger_job:
trigger:
project: project-group/my-downstream-project
```
{{< /tab >}}
{{< /tabs >}}
After the trigger job starts, the initial status of the job is `pending` while GitLab
attempts to create the downstream pipeline. The trigger job shows `passed` if the
downstream pipeline is created successfully, otherwise it shows `failed`. Alternatively,
you can [set the trigger job to show the downstream pipeline's status](#mirror-the-status-of-a-downstream-pipeline-in-the-trigger-job)
instead.
### Use `rules` to control downstream pipeline jobs
Use CI/CD variables or the [`rules`](../yaml/_index.md#rulesif) keyword to
[control job behavior](../jobs/job_control.md) in downstream pipelines.
When you trigger a downstream pipeline with the [`trigger`](../yaml/_index.md#trigger) keyword,
the value of the [`$CI_PIPELINE_SOURCE` predefined variable](../variables/predefined_variables.md)
for all jobs is:
- `pipeline` for multi-project pipelines.
- `parent_pipeline` for parent-child pipelines.
For example, to control jobs in multi-project pipelines in a project that also runs
merge request pipelines:
```yaml
job1:
rules:
- if: $CI_PIPELINE_SOURCE == "pipeline"
script: echo "This job runs in multi-project pipelines only"
job2:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
script: echo "This job runs in merge request pipelines only"
job3:
rules:
- if: $CI_PIPELINE_SOURCE == "pipeline"
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
script: echo "This job runs in both multi-project and merge request pipelines"
```
### Use a child pipeline configuration file in a different project
You can use [`include:project`](../yaml/_index.md#includeproject) in a trigger job
to trigger child pipelines with a configuration file in a different project:
```yaml
microservice_a:
trigger:
include:
- project: 'my-group/my-pipeline-library'
ref: 'main'
file: '/path/to/child-pipeline.yml'
```
### Combine multiple child pipeline configuration files
You can include up to three configuration files when defining a child pipeline. The child pipeline's
configuration is composed of all configuration files merged together:
```yaml
microservice_a:
trigger:
include:
- local: path/to/microservice_a.yml
- template: Jobs/SAST.gitlab-ci.yml
- project: 'my-group/my-pipeline-library'
ref: 'main'
file: '/path/to/child-pipeline.yml'
```
### Dynamic child pipelines
You can trigger a child pipeline from a YAML file generated in a job, instead of a
static file saved in your project. This technique can be very powerful for generating pipelines
targeting content that changed or to build a matrix of targets and architectures.
The artifact containing the generated YAML file must be within [instance limits](../../administration/instance_limits.md#maximum-size-of-the-ci-artifacts-archive).
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [Create child pipelines using dynamically generated configurations](https://youtu.be/nMdfus2JWHM).
For an example project that generates a dynamic child pipeline, see
[Dynamic Child Pipelines with Jsonnet](https://gitlab.com/gitlab-org/project-templates/jsonnet).
This project shows how to use a data templating language to generate your `.gitlab-ci.yml` at runtime.
You can use a similar process for other templating languages like
[Dhall](https://dhall-lang.org/) or [ytt](https://get-ytt.io/).
#### Trigger a dynamic child pipeline
To trigger a child pipeline from a dynamically generated configuration file:
1. Generate the configuration file in a job and save it as an [artifact](../yaml/_index.md#artifactspaths):
```yaml
generate-config:
stage: build
script: generate-ci-config > generated-config.yml
artifacts:
paths:
- generated-config.yml
```
1. Configure the trigger job to run after the job that generated the configuration file.
Set `include: artifact` to the generated artifact, and set `include: job` to
the job that created the artifact:
```yaml
child-pipeline:
stage: test
trigger:
include:
- artifact: generated-config.yml
job: generate-config
```
In this example, GitLab retrieves `generated-config.yml` and triggers a child pipeline
with the CI/CD configuration in that file.
The artifact path is parsed by GitLab, not the runner, so the path must match the
syntax for the OS running GitLab. If GitLab is running on Linux but using a Windows
runner for testing, the path separator for the trigger job is `/`. Other CI/CD
configuration for jobs that use the Windows runner, like scripts, use ` \ `.
You cannot use CI/CD variables in an `include` section in a dynamic child pipeline's configuration.
[Issue 378717](https://gitlab.com/gitlab-org/gitlab/-/issues/378717) proposes fixing
this issue.
### Run child pipelines with merge request pipelines
Pipelines, including child pipelines, run as branch pipelines by default when not using
[`rules`](../yaml/_index.md#rules) or [`workflow:rules`](../yaml/_index.md#workflowrules).
To configure child pipelines to run when triggered from a [merge request (parent) pipeline](merge_request_pipelines.md), use `rules` or `workflow:rules`.
For example, using `rules`:
1. Set the parent pipeline's trigger job to run on merge requests:
```yaml
trigger-child-pipeline-job:
trigger:
include: path/to/child-pipeline-configuration.yml
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
```
1. Use `rules` to configure the child pipeline jobs to run when triggered by the parent pipeline:
```yaml
job1:
script: echo "This child pipeline job runs any time the parent pipeline triggers it."
rules:
- if: $CI_PIPELINE_SOURCE == "parent_pipeline"
job2:
script: echo "This child pipeline job runs only when the parent pipeline is a merge request pipeline"
rules:
- if: $CI_MERGE_REQUEST_ID
```
In child pipelines, `$CI_PIPELINE_SOURCE` always has a value of `parent_pipeline`, so:
- You can use `if: $CI_PIPELINE_SOURCE == "parent_pipeline"` to ensure child pipeline jobs always run.
- You can't use `if: $CI_PIPELINE_SOURCE == "merge_request_event"` to configure child pipeline
jobs to run for merge request pipelines. Instead, use `if: $CI_MERGE_REQUEST_ID`
to set child pipeline jobs to run only when the parent pipeline is a merge request pipeline. The parent pipeline's
[`CI_MERGE_REQUEST_*` predefined variables](../variables/predefined_variables.md#predefined-variables-for-merge-request-pipelines)
are passed to the child pipeline jobs.
### Specify a branch for multi-project pipelines
You can specify the branch to use when triggering a multi-project pipeline. GitLab uses
the commit on the head of the branch to create the downstream pipeline. For example:
```yaml
staging:
stage: deploy
trigger:
project: my/deployment
branch: stable-11-2
```
Use:
- The `project` keyword to specify the full path to the downstream project.
In [GitLab 15.3 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/367660),
you can use [variable expansion](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
- The `branch` keyword to specify the name of a branch or [tag](../../user/project/repository/tags/_index.md)
in the project specified by `project`. You can use variable expansion.
## Trigger a multi-project pipeline by using the API
You can use the [CI/CD job token (`CI_JOB_TOKEN`)](../jobs/ci_job_token.md) with the
[pipeline trigger API endpoint](../../api/pipeline_triggers.md#trigger-a-pipeline-with-a-token)
to trigger multi-project pipelines from inside a CI/CD job. GitLab sets pipelines triggered
with a job token as downstream pipelines of the pipeline that contains the job that
made the API call.
For example:
```yaml
trigger_pipeline:
stage: deploy
script:
- curl --request POST --form "token=$CI_JOB_TOKEN" --form ref=main "https://gitlab.example.com/api/v4/projects/9/trigger/pipeline"
rules:
- if: $CI_COMMIT_TAG
environment: production
```
## View a downstream pipeline
In the [pipeline details page](_index.md#pipeline-details), downstream pipelines display
as a list of cards on the right of the graph. From this view, you can:
- Select a trigger job to see the triggered downstream pipeline's jobs.
- Select **Expand jobs** {{< icon name="chevron-lg-right" >}} on a pipeline card to expand the view
with the downstream pipeline's jobs. You can view one downstream pipeline at a time.
- Hover over a pipeline card to have the job that triggered the downstream pipeline highlighted.
### Retry failed and canceled jobs in a downstream pipeline
{{< history >}}
- Retry from graph view [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/354974) in GitLab 15.0 [with a flag](../../administration/feature_flags/_index.md) named `downstream_retry_action`. Disabled by default.
- Retry from graph view [generally available and feature flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/357406) in GitLab 15.1.
{{< /history >}}
To retry failed and canceled jobs, select **Retry** ({{< icon name="retry" >}}):
- From the downstream pipeline's details page.
- On the pipeline's card in the pipeline graph view.
### Recreate a downstream pipeline
{{< history >}}
- Retry trigger job from graph view [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/367547) in GitLab 15.10 [with a flag](../../administration/feature_flags/_index.md) named `ci_recreate_downstream_pipeline`. Disabled by default.
- [Generally available](https://gitlab.com/groups/gitlab-org/-/epics/6947) in GitLab 15.11. Feature flag `ci_recreate_downstream_pipeline` removed.
{{< /history >}}
You can recreate a downstream pipeline by retrying its corresponding trigger job. The newly created downstream pipeline replaces the current downstream pipeline in the pipeline graph.
To recreate a downstream pipeline:
- Select **Run again** ({{< icon name="retry" >}}) on the trigger job's card in the pipeline graph view.
### Cancel a downstream pipeline
{{< history >}}
- Retry from graph view [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/354974) in GitLab 15.0 [with a flag](../../administration/feature_flags/_index.md) named `downstream_retry_action`. Disabled by default.
- Retry from graph view [generally available and feature flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/357406) in GitLab 15.1.
{{< /history >}}
To cancel a downstream pipeline that is still running, select **Cancel** ({{< icon name="cancel" >}}):
- From the downstream pipeline's details page.
- On the pipeline's card in the pipeline graph view.
### Auto-cancel the parent pipeline from a downstream pipeline
You can configure a child pipeline to [auto-cancel](../yaml/_index.md#workflowauto_cancelon_job_failure)
as soon as one of its jobs fail.
The parent pipeline only auto-cancels when a job in the child pipeline fails if:
- The parent pipeline is also set up to auto-cancel on job failure.
- The trigger job is configured with [`strategy: depend`](../yaml/_index.md#triggerstrategy).
For example:
- Content of `.gitlab-ci.yml`:
```yaml
workflow:
auto_cancel:
on_job_failure: all
trigger_job:
trigger:
include: child-pipeline.yml
strategy: depend
job3:
script:
- sleep 120
```
- Content of `child-pipeline.yml`
```yaml
# Contents of child-pipeline.yml
workflow:
auto_cancel:
on_job_failure: all
job1:
script: sleep 60
job2:
script:
- sleep 30
- exit 1
```
In this example:
1. The parent pipeline triggers the child pipeline and `job3` at the same time
1. `job2` from the child pipeline fails and the child pipeline is canceled, stopping `job1` as well
1. The child pipeline has been canceled so the parent pipeline is auto-canceled
### Mirror the status of a downstream pipeline in the trigger job
You can mirror the status of the downstream pipeline in the trigger job
by using [`strategy: mirror`](../yaml/_index.md#triggerstrategy):
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
```yaml
trigger_job:
trigger:
include:
- local: path/to/child-pipeline.yml
strategy: mirror
```
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
```yaml
trigger_job:
trigger:
project: my/project
strategy: mirror
```
{{< /tab >}}
{{< /tabs >}}
### View multi-project pipelines in pipeline graphs
{{< history >}}
- [Moved](https://gitlab.com/gitlab-org/gitlab/-/issues/422282) from GitLab Premium to GitLab Free in 16.8.
{{< /history >}}
After you trigger a multi-project pipeline, the downstream pipeline displays
to the right of the [pipeline graph](_index.md#view-pipelines).
In [pipeline mini graphs](_index.md#pipeline-mini-graphs), the downstream pipeline
displays to the right of the mini graph.
## Fetch artifacts from an upstream pipeline
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
Use [`needs:pipeline:job`](../yaml/_index.md#needspipelinejob) to fetch artifacts from an
upstream pipeline:
1. In the upstream pipeline, save the artifacts in a job with the [`artifacts`](../yaml/_index.md#artifacts)
keyword, then trigger the downstream pipeline with a trigger job:
```yaml
build_artifacts:
stage: build
script:
- echo "This is a test artifact!" >> artifact.txt
artifacts:
paths:
- artifact.txt
deploy:
stage: deploy
trigger:
include:
- local: path/to/child-pipeline.yml
variables:
PARENT_PIPELINE_ID: $CI_PIPELINE_ID
```
1. Use `needs:pipeline:job` in a job in the downstream pipeline to fetch the artifacts.
```yaml
test:
stage: test
script:
- cat artifact.txt
needs:
- pipeline: $PARENT_PIPELINE_ID
job: build_artifacts
```
Set `job` to the job in the upstream pipeline that created the artifacts.
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
Use [`needs:project`](../yaml/_index.md#needsproject) to fetch artifacts from an
upstream pipeline:
1. In GitLab 15.9 and later, [add the downstream project to the job token scope allowlist](../jobs/ci_job_token.md#add-a-group-or-project-to-the-job-token-allowlist) of the upstream project.
1. In the upstream pipeline, save the artifacts in a job with the [`artifacts`](../yaml/_index.md#artifacts)
keyword, then trigger the downstream pipeline with a trigger job:
```yaml
build_artifacts:
stage: build
script:
- echo "This is a test artifact!" >> artifact.txt
artifacts:
paths:
- artifact.txt
deploy:
stage: deploy
trigger: my/downstream_project # Path to the project to trigger a pipeline in
```
1. Use `needs:project` in a job in the downstream pipeline to fetch the artifacts.
```yaml
test:
stage: test
script:
- cat artifact.txt
needs:
- project: my/upstream_project
job: build_artifacts
ref: main
artifacts: true
```
Set:
- `job` to the job in the upstream pipeline that created the artifacts.
- `ref` to the branch.
- `artifacts` to `true`.
{{< /tab >}}
{{< /tabs >}}
### Fetch artifacts from an upstream merge request pipeline
When you use `needs:project` to [pass artifacts to a downstream pipeline](#fetch-artifacts-from-an-upstream-pipeline),
the `ref` value is usually a branch name, like `main` or `development`.
For [merge request pipelines](merge_request_pipelines.md), the `ref` value is in the form of `refs/merge-requests/<id>/head`,
where `id` is the merge request ID. You can retrieve this ref with the [`CI_MERGE_REQUEST_REF_PATH`](../variables/predefined_variables.md#predefined-variables-for-merge-request-pipelines)
CI/CD variable. Do not use a branch name as the `ref` with merge request pipelines,
because the downstream pipeline attempts to fetch artifacts from the latest branch pipeline.
To fetch the artifacts from the upstream `merge request` pipeline instead of the `branch` pipeline,
pass `CI_MERGE_REQUEST_REF_PATH` to the downstream pipeline using [variable inheritance](#pass-yaml-defined-cicd-variables):
1. In GitLab 15.9 and later, [add the downstream project to the job token scope allowlist](../jobs/ci_job_token.md#add-a-group-or-project-to-the-job-token-allowlist) of the upstream project.
1. In a job in the upstream pipeline, save the artifacts using the [`artifacts`](../yaml/_index.md#artifacts) keyword.
1. In the job that triggers the downstream pipeline, pass the `$CI_MERGE_REQUEST_REF_PATH` variable:
```yaml
build_artifacts:
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
stage: build
script:
- echo "This is a test artifact!" >> artifact.txt
artifacts:
paths:
- artifact.txt
upstream_job:
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
variables:
UPSTREAM_REF: $CI_MERGE_REQUEST_REF_PATH
trigger:
project: my/downstream_project
branch: my-branch
```
1. In a job in the downstream pipeline, fetch the artifacts from the upstream pipeline
by using `needs:project` and the passed variable as the `ref`:
```yaml
test:
stage: test
script:
- cat artifact.txt
needs:
- project: my/upstream_project
job: build_artifacts
ref: $UPSTREAM_REF
artifacts: true
```
You can use this method to fetch artifacts from upstream merge request pipelines,
but not from [merged results pipelines](merged_results_pipelines.md).
## Pass inputs to a downstream pipeline
You can use the [`inputs`](../inputs/_index.md) keyword to pass input values to downstream pipelines.
Inputs provide advantages over variables including type checking, validation through options,
descriptions, and default values.
First, define input parameters in the target configuration file using `spec:inputs`:
```yaml
# Target pipeline configuration
spec:
inputs:
environment:
description: "Deployment environment"
options: [staging, production]
version:
type: string
description: "Application version"
```
Then provide values when triggering the pipeline:
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
```yaml
staging:
trigger:
include:
- local: path/to/child-pipeline.yml
inputs:
environment: staging
version: "1.0.0"
```
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
```yaml
staging:
trigger:
project: my-group/my-deployment-project
inputs:
environment: staging
version: "1.0.0"
```
{{< /tab >}}
{{< /tabs >}}
## Pass CI/CD variables to a downstream pipeline
You can pass [CI/CD variables](../variables/_index.md) to a downstream pipeline with
a few different methods, based on where the variable is created or defined.
### Pass YAML-defined CI/CD variables
_Note: Inputs are recommended for pipeline configuration instead of variables as they offer improved security and flexibility._
You can use the `variables` keyword to pass CI/CD variables to a downstream pipeline.
These variables are pipeline variables for [variable precedence](../variables/_index.md#cicd-variable-precedence).
For example:
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
```yaml
variables:
VERSION: "1.0.0"
staging:
variables:
ENVIRONMENT: staging
stage: deploy
trigger:
include:
- local: path/to/child-pipeline.yml
```
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
```yaml
variables:
VERSION: "1.0.0"
staging:
variables:
ENVIRONMENT: staging
stage: deploy
trigger: my-group/my-deployment-project
```
{{< /tab >}}
{{< /tabs >}}
The `ENVIRONMENT` variable is available in every job defined in the downstream pipeline.
The `VERSION` default variable is also available in the downstream pipeline, because
all jobs in a pipeline, including trigger jobs, inherit [default `variables`](../yaml/_index.md#default-variables).
#### Prevent default variables from being passed
You can stop default CI/CD variables from reaching the downstream pipeline with
[`inherit:variables`](../yaml/_index.md#inheritvariables). You can list specific variables to inherit,
or block all default variables.
For example:
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
```yaml
variables:
DEFAULT_VAR: value
trigger-job:
inherit:
variables: false
variables:
JOB_VAR: value
trigger:
include:
- local: path/to/child-pipeline.yml
```
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
```yaml
variables:
DEFAULT_VAR: value
trigger-job:
inherit:
variables: false
variables:
JOB_VAR: value
trigger: my-group/my-project
```
{{< /tab >}}
{{< /tabs >}}
The `DEFAULT_VAR` variable is not available in the triggered pipeline, but `JOB_VAR`
is available.
### Pass a predefined variable
To pass information about the upstream pipeline using [predefined CI/CD variables](../variables/predefined_variables.md)
use interpolation. Save the predefined variable as a new job variable in the trigger
job, which is passed to the downstream pipeline. For example:
{{< tabs >}}
{{< tab title="Parent-child pipeline" >}}
```yaml
trigger-job:
variables:
PARENT_BRANCH: $CI_COMMIT_REF_NAME
trigger:
include:
- local: path/to/child-pipeline.yml
```
{{< /tab >}}
{{< tab title="Multi-project pipeline" >}}
```yaml
trigger-job:
variables:
UPSTREAM_BRANCH: $CI_COMMIT_REF_NAME
trigger: my-group/my-project
```
{{< /tab >}}
{{< /tabs >}}
The `UPSTREAM_BRANCH` variable, which contains the value of the upstream pipeline's `$CI_COMMIT_REF_NAME`
predefined CI/CD variable, is available in the downstream pipeline.
Do not use this method to pass [masked variables](../variables/_index.md#mask-a-cicd-variable)
to a multi-project pipeline. The CI/CD masking configuration is not passed to the
downstream pipeline and the variable could be unmasked in job logs in the downstream project.
You cannot use this method to forward [job-only variables](../variables/predefined_variables.md#variable-availability)
to a downstream pipeline, as they are not available in trigger jobs.
Upstream pipelines take precedence over downstream ones. If there are two
variables with the same name defined in both upstream and downstream projects,
the ones defined in the upstream project take precedence.
### Pass dotenv variables created in a job
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can pass variables to a downstream pipeline with [`dotenv` variable inheritance](../variables/job_scripts.md#pass-an-environment-variable-to-another-job).
For example, in a [multi-project pipeline](#multi-project-pipelines):
1. Save the variables in a `.env` file.
1. Save the `.env` file as a `dotenv` report.
1. Trigger the downstream pipeline.
```yaml
build_vars:
stage: build
script:
- echo "BUILD_VERSION=hello" >> build.env
artifacts:
reports:
dotenv: build.env
deploy:
stage: deploy
trigger: my/downstream_project
```
1. Set the `test` job in the downstream pipeline to inherit the variables from the `build_vars`
job in the upstream project with `needs`. The `test` job inherits the variables in the
`dotenv` report and it can access `BUILD_VERSION` in the script:
```yaml
test:
stage: test
script:
- echo $BUILD_VERSION
needs:
- project: my/upstream_project
job: build_vars
ref: master
artifacts: true
```
### Control what type of variables to forward to downstream pipelines
Use the [`trigger:forward` keyword](../yaml/_index.md#triggerforward) to specify
what type of variables to forward to the downstream pipeline. Forwarded variables
are considered trigger variables, which have the [highest precedence](../variables/_index.md#cicd-variable-precedence).
## Downstream pipelines for deployments
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/369061) in GitLab 16.4.
{{< /history >}}
You can use the [`environment`](../yaml/_index.md#environment) keyword with [`trigger`](../yaml/_index.md#trigger).
You might want to use `environment` from a trigger job if your deployment and application projects are separately managed.
```yaml
deploy:
trigger:
project: project-group/my-downstream-project
environment: production
```
A downstream pipeline can provision infrastructure, deploy to a designated environment, and return the deployment status
to the upstream project.
You can [view the environment and deployment](../environments/_index.md#view-environments-and-deployments)
from the upstream project.
### Advanced example
This example configuration has the following behaviors:
- The upstream project dynamically composes an environment name based on a branch name.
- The upstream project passes the context of the deployment to the downstream project with `UPSTREAM_*` variables.
The `.gitlab-ci.yml` in an upstream project:
```yaml
stages:
- deploy
- cleanup
.downstream-deployment-pipeline:
variables:
UPSTREAM_PROJECT_ID: $CI_PROJECT_ID
UPSTREAM_ENVIRONMENT_NAME: $CI_ENVIRONMENT_NAME
UPSTREAM_ENVIRONMENT_ACTION: $CI_ENVIRONMENT_ACTION
trigger:
project: project-group/deployment-project
branch: main
strategy: mirror
deploy-review:
stage: deploy
extends: .downstream-deployment-pipeline
environment:
name: review/$CI_COMMIT_REF_SLUG
on_stop: stop-review
stop-review:
stage: cleanup
extends: .downstream-deployment-pipeline
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
when: manual
```
The `.gitlab-ci.yml` in a downstream project:
```yaml
deploy:
script: echo "Deploy to ${UPSTREAM_ENVIRONMENT_NAME} for ${UPSTREAM_PROJECT_ID}"
rules:
- if: $CI_PIPELINE_SOURCE == "pipeline" && $UPSTREAM_ENVIRONMENT_ACTION == "start"
stop:
script: echo "Stop ${UPSTREAM_ENVIRONMENT_NAME} for ${UPSTREAM_PROJECT_ID}"
rules:
- if: $CI_PIPELINE_SOURCE == "pipeline" && $UPSTREAM_ENVIRONMENT_ACTION == "stop"
```
|
https://docs.gitlab.com/ci/pipeline_architectures
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/pipeline_architectures.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
pipeline_architectures.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Pipeline architecture
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Pipelines are the fundamental building blocks for CI/CD in GitLab. This page documents
some of the important concepts related to them.
You can structure your pipelines with different methods, each with their
own advantages. These methods can be mixed and matched if needed:
- [Basic](#basic-pipelines): Good for straightforward projects where all the configuration is in one place.
- [Pipelines with the `needs` keyword](#pipelines-with-the-needs-keyword): Good for large, complex projects that need efficient execution.
- [Parent-child pipelines](#parent-child-pipelines): Good for monorepos and projects with lots of independently defined components.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see the [Parent-Child Pipelines feature demo](https://youtu.be/n8KpBSqZNbk).
- [Multi-project pipelines](downstream_pipelines.md#multi-project-pipelines): Good for larger products that require cross-project interdependencies,
like those with a [microservices architecture](https://about.gitlab.com/blog/2016/08/16/trends-in-version-control-land-microservices/).
For example, you might deploy your web application from three different GitLab projects.
With multi-project pipelines you can trigger a pipeline in each project, where each
has its own build, test, and deploy process. You can visualize the connected pipelines
in one place, including all cross-project interdependencies.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see the [Multi-project pipelines demo](https://www.youtube.com/watch?v=g_PIwBM1J84).
## Basic pipelines
Basic pipelines are the simplest pipelines in GitLab. It runs everything in the build stage concurrently,
and once all of those finish, it runs everything in the test and subsequent stages the same way.
It's not the most efficient, and if you have lots of steps it can grow quite complex, but it's
easier to maintain:
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
graph LR
accTitle: Basic pipelines
accDescr: Shows a pipeline that runs sequentially through the build, test, and deploy stages.
subgraph deploy stage
deploy --> deploy_a
deploy --> deploy_b
end
subgraph test stage
test --> test_a
test --> test_b
end
subgraph build stage
build --> build_a
build --> build_b
end
build_a -.-> test
build_b -.-> test
test_a -.-> deploy
test_b -.-> deploy
```
Example basic `/.gitlab-ci.yml` pipeline configuration matching the diagram:
```yaml
stages:
- build
- test
- deploy
default:
image: alpine
build_a:
stage: build
script:
- echo "This job builds something."
build_b:
stage: build
script:
- echo "This job builds something else."
test_a:
stage: test
script:
- echo "This job tests something. It will only run when all jobs in the"
- echo "build stage are complete."
test_b:
stage: test
script:
- echo "This job tests something else. It will only run when all jobs in the"
- echo "build stage are complete too. It will start at about the same time as test_a."
deploy_a:
stage: deploy
script:
- echo "This job deploys something. It will only run when all jobs in the"
- echo "test stage complete."
environment: production
deploy_b:
stage: deploy
script:
- echo "This job deploys something else. It will only run when all jobs in the"
- echo "test stage complete. It will start at about the same time as deploy_a."
environment: production
```
## Pipelines with the `needs` keyword
If efficiency is important and you want everything to run as quickly as possible,
you can use the [`needs` keyword](../yaml/needs.md) to define dependencies
between your jobs. When GitLab knows the dependencies between your jobs,
jobs can run as fast as possible, even starting earlier than other jobs in the same stage.
In the following example, if `build_a` and `test_a` are much faster than `build_b` and
`test_b`, GitLab starts `deploy_a` even if `build_b` is still running.
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
graph LR
accTitle: Pipeline using needs
accDescr: Shows how two jobs can start without waiting for earlier stages to complete
subgraph Pipeline using needs
build_a --> test_a --> deploy_a
build_b --> test_b --> deploy_b
end
```
Example `/.gitlab-ci.yml` configuration matching the diagram:
```yaml
stages:
- build
- test
- deploy
default:
image: alpine
build_a:
stage: build
script:
- echo "This job builds something quickly."
build_b:
stage: build
script:
- echo "This job builds something else slowly."
test_a:
stage: test
needs: [build_a]
script:
- echo "This test job will start as soon as build_a finishes."
- echo "It will not wait for build_b, or other jobs in the build stage, to finish."
test_b:
stage: test
needs: [build_b]
script:
- echo "This test job will start as soon as build_b finishes."
- echo "It will not wait for other jobs in the build stage to finish."
deploy_a:
stage: deploy
needs: [test_a]
script:
- echo "Since build_a and test_a run quickly, this deploy job can run much earlier."
- echo "It does not need to wait for build_b or test_b."
environment: production
deploy_b:
stage: deploy
needs: [test_b]
script:
- echo "Since build_b and test_b run slowly, this deploy job will run much later."
environment: production
```
## Parent-child pipelines
As pipelines grow more complex, a few related problems start to emerge:
- The staged structure, where all steps in a stage must complete before the first
job in next stage begins, causes waits that slow things down.
- Configuration for the single global pipeline becomes
hard to manage.
- Imports with [`include`](../yaml/_index.md#include) increase the complexity of the configuration, and can cause
namespace collisions where jobs are unintentionally duplicated.
- Pipeline UX has too many jobs and stages to work with.
Additionally, sometimes the behavior of a pipeline needs to be more dynamic. The ability
to choose to start sub-pipelines (or not) is a powerful ability, especially if the
YAML is dynamically generated.
In the previous [basic pipeline](#basic-pipelines) and [`needs` pipeline](#pipelines-with-the-needs-keyword)
examples, there are two packages that could be built independently.
These cases are ideal for using [parent-child pipelines](downstream_pipelines.md#parent-child-pipelines).
It separates out the configuration into multiple files, keeping things simpler.
You can combine parent-child pipelines with:
- The [`rules` keyword](../yaml/_index.md#rules): For example, have the child pipelines triggered only
when there are changes to that area.
- The [`include` keyword](../yaml/_index.md#include): Bring in common behaviors, ensuring
you are not repeating yourself.
- The [`needs` keyword](#pipelines-with-the-needs-keyword) inside of child pipelines, achieving the benefits of both.
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
graph LR
accTitle: Parent and child pipelines
accDescr: Shows that a parent pipeline can trigger independent child pipelines
subgraph Parent pipeline
trigger_a -.-> build_a
trigger_b -.-> build_b
subgraph child pipeline B
build_b --> test_b --> deploy_b
end
subgraph child pipeline A
build_a --> test_a --> deploy_a
end
end
```
Example `/.gitlab-ci.yml` configuration for the parent pipeline matching the diagram:
```yaml
stages:
- triggers
trigger_a:
stage: triggers
trigger:
include: a/.gitlab-ci.yml
rules:
- changes:
- a/*
trigger_b:
stage: triggers
trigger:
include: b/.gitlab-ci.yml
rules:
- changes:
- b/*
```
Example child `a` pipeline configuration, located in `/a/.gitlab-ci.yml`, making
use of the `needs` keyword:
```yaml
stages:
- build
- test
- deploy
default:
image: alpine
build_a:
stage: build
script:
- echo "This job builds something."
test_a:
stage: test
needs: [build_a]
script:
- echo "This job tests something."
deploy_a:
stage: deploy
needs: [test_a]
script:
- echo "This job deploys something."
environment: production
```
Example child `b` pipeline configuration, located in `/b/.gitlab-ci.yml`, making
use of the `needs` keyword:
```yaml
stages:
- build
- test
- deploy
default:
image: alpine
build_b:
stage: build
script:
- echo "This job builds something else."
test_b:
stage: test
needs: [build_b]
script:
- echo "This job tests something else."
deploy_b:
stage: deploy
needs: [test_b]
script:
- echo "This job deploys something else."
environment: production
```
Jobs can be set to run before or after triggering child pipelines in GitLab, allowing common setup steps or unified deployment.
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Pipeline architecture
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Pipelines are the fundamental building blocks for CI/CD in GitLab. This page documents
some of the important concepts related to them.
You can structure your pipelines with different methods, each with their
own advantages. These methods can be mixed and matched if needed:
- [Basic](#basic-pipelines): Good for straightforward projects where all the configuration is in one place.
- [Pipelines with the `needs` keyword](#pipelines-with-the-needs-keyword): Good for large, complex projects that need efficient execution.
- [Parent-child pipelines](#parent-child-pipelines): Good for monorepos and projects with lots of independently defined components.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see the [Parent-Child Pipelines feature demo](https://youtu.be/n8KpBSqZNbk).
- [Multi-project pipelines](downstream_pipelines.md#multi-project-pipelines): Good for larger products that require cross-project interdependencies,
like those with a [microservices architecture](https://about.gitlab.com/blog/2016/08/16/trends-in-version-control-land-microservices/).
For example, you might deploy your web application from three different GitLab projects.
With multi-project pipelines you can trigger a pipeline in each project, where each
has its own build, test, and deploy process. You can visualize the connected pipelines
in one place, including all cross-project interdependencies.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see the [Multi-project pipelines demo](https://www.youtube.com/watch?v=g_PIwBM1J84).
## Basic pipelines
Basic pipelines are the simplest pipelines in GitLab. It runs everything in the build stage concurrently,
and once all of those finish, it runs everything in the test and subsequent stages the same way.
It's not the most efficient, and if you have lots of steps it can grow quite complex, but it's
easier to maintain:
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
graph LR
accTitle: Basic pipelines
accDescr: Shows a pipeline that runs sequentially through the build, test, and deploy stages.
subgraph deploy stage
deploy --> deploy_a
deploy --> deploy_b
end
subgraph test stage
test --> test_a
test --> test_b
end
subgraph build stage
build --> build_a
build --> build_b
end
build_a -.-> test
build_b -.-> test
test_a -.-> deploy
test_b -.-> deploy
```
Example basic `/.gitlab-ci.yml` pipeline configuration matching the diagram:
```yaml
stages:
- build
- test
- deploy
default:
image: alpine
build_a:
stage: build
script:
- echo "This job builds something."
build_b:
stage: build
script:
- echo "This job builds something else."
test_a:
stage: test
script:
- echo "This job tests something. It will only run when all jobs in the"
- echo "build stage are complete."
test_b:
stage: test
script:
- echo "This job tests something else. It will only run when all jobs in the"
- echo "build stage are complete too. It will start at about the same time as test_a."
deploy_a:
stage: deploy
script:
- echo "This job deploys something. It will only run when all jobs in the"
- echo "test stage complete."
environment: production
deploy_b:
stage: deploy
script:
- echo "This job deploys something else. It will only run when all jobs in the"
- echo "test stage complete. It will start at about the same time as deploy_a."
environment: production
```
## Pipelines with the `needs` keyword
If efficiency is important and you want everything to run as quickly as possible,
you can use the [`needs` keyword](../yaml/needs.md) to define dependencies
between your jobs. When GitLab knows the dependencies between your jobs,
jobs can run as fast as possible, even starting earlier than other jobs in the same stage.
In the following example, if `build_a` and `test_a` are much faster than `build_b` and
`test_b`, GitLab starts `deploy_a` even if `build_b` is still running.
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
graph LR
accTitle: Pipeline using needs
accDescr: Shows how two jobs can start without waiting for earlier stages to complete
subgraph Pipeline using needs
build_a --> test_a --> deploy_a
build_b --> test_b --> deploy_b
end
```
Example `/.gitlab-ci.yml` configuration matching the diagram:
```yaml
stages:
- build
- test
- deploy
default:
image: alpine
build_a:
stage: build
script:
- echo "This job builds something quickly."
build_b:
stage: build
script:
- echo "This job builds something else slowly."
test_a:
stage: test
needs: [build_a]
script:
- echo "This test job will start as soon as build_a finishes."
- echo "It will not wait for build_b, or other jobs in the build stage, to finish."
test_b:
stage: test
needs: [build_b]
script:
- echo "This test job will start as soon as build_b finishes."
- echo "It will not wait for other jobs in the build stage to finish."
deploy_a:
stage: deploy
needs: [test_a]
script:
- echo "Since build_a and test_a run quickly, this deploy job can run much earlier."
- echo "It does not need to wait for build_b or test_b."
environment: production
deploy_b:
stage: deploy
needs: [test_b]
script:
- echo "Since build_b and test_b run slowly, this deploy job will run much later."
environment: production
```
## Parent-child pipelines
As pipelines grow more complex, a few related problems start to emerge:
- The staged structure, where all steps in a stage must complete before the first
job in next stage begins, causes waits that slow things down.
- Configuration for the single global pipeline becomes
hard to manage.
- Imports with [`include`](../yaml/_index.md#include) increase the complexity of the configuration, and can cause
namespace collisions where jobs are unintentionally duplicated.
- Pipeline UX has too many jobs and stages to work with.
Additionally, sometimes the behavior of a pipeline needs to be more dynamic. The ability
to choose to start sub-pipelines (or not) is a powerful ability, especially if the
YAML is dynamically generated.
In the previous [basic pipeline](#basic-pipelines) and [`needs` pipeline](#pipelines-with-the-needs-keyword)
examples, there are two packages that could be built independently.
These cases are ideal for using [parent-child pipelines](downstream_pipelines.md#parent-child-pipelines).
It separates out the configuration into multiple files, keeping things simpler.
You can combine parent-child pipelines with:
- The [`rules` keyword](../yaml/_index.md#rules): For example, have the child pipelines triggered only
when there are changes to that area.
- The [`include` keyword](../yaml/_index.md#include): Bring in common behaviors, ensuring
you are not repeating yourself.
- The [`needs` keyword](#pipelines-with-the-needs-keyword) inside of child pipelines, achieving the benefits of both.
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
graph LR
accTitle: Parent and child pipelines
accDescr: Shows that a parent pipeline can trigger independent child pipelines
subgraph Parent pipeline
trigger_a -.-> build_a
trigger_b -.-> build_b
subgraph child pipeline B
build_b --> test_b --> deploy_b
end
subgraph child pipeline A
build_a --> test_a --> deploy_a
end
end
```
Example `/.gitlab-ci.yml` configuration for the parent pipeline matching the diagram:
```yaml
stages:
- triggers
trigger_a:
stage: triggers
trigger:
include: a/.gitlab-ci.yml
rules:
- changes:
- a/*
trigger_b:
stage: triggers
trigger:
include: b/.gitlab-ci.yml
rules:
- changes:
- b/*
```
Example child `a` pipeline configuration, located in `/a/.gitlab-ci.yml`, making
use of the `needs` keyword:
```yaml
stages:
- build
- test
- deploy
default:
image: alpine
build_a:
stage: build
script:
- echo "This job builds something."
test_a:
stage: test
needs: [build_a]
script:
- echo "This job tests something."
deploy_a:
stage: deploy
needs: [test_a]
script:
- echo "This job deploys something."
environment: production
```
Example child `b` pipeline configuration, located in `/b/.gitlab-ci.yml`, making
use of the `needs` keyword:
```yaml
stages:
- build
- test
- deploy
default:
image: alpine
build_b:
stage: build
script:
- echo "This job builds something else."
test_b:
stage: test
needs: [build_b]
script:
- echo "This job tests something else."
deploy_b:
stage: deploy
needs: [test_b]
script:
- echo "This job deploys something else."
environment: production
```
Jobs can be set to run before or after triggering child pipelines in GitLab, allowing common setup steps or unified deployment.
|
https://docs.gitlab.com/ci/mr_pipeline_troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/mr_pipeline_troubleshooting.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
mr_pipeline_troubleshooting.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting merge request pipelines
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
When working with merge request pipelines, you might encounter the following issues.
## Two pipelines when pushing to a branch
If you get duplicate pipelines in merge requests, your pipeline might be configured
to run for both branches and merge requests at the same time. Adjust your pipeline
configuration to [avoid duplicate pipelines](../jobs/job_rules.md#avoid-duplicate-pipelines).
You can add `workflow:rules` to [switch from branch pipelines to merge request pipelines](../yaml/workflow.md#switch-between-branch-pipelines-and-merge-request-pipelines).
After a merge request is open on the branch, the pipeline switches to a merge request pipeline.
## Two pipelines when pushing an invalid CI/CD configuration file
If you push an invalid CI/CD configuration to a merge request's branch, two failed
pipelines appear in the pipelines tab. One pipeline is a failed branch pipeline,
the other is a failed merge request pipeline.
When the configuration syntax is fixed, no further failed pipelines should appear.
To find and fix the configuration problem, you can use:
- The [pipeline editor](../pipeline_editor/_index.md).
- The [CI lint tool](../yaml/lint.md).
## The merge request's pipeline is marked as failed but the latest pipeline succeeded
It's possible to have both branch pipelines and merge request pipelines in the
**Pipelines** tab of a single merge request. This might be [by configuration](../yaml/workflow.md#switch-between-branch-pipelines-and-merge-request-pipelines),
or [by accident](#two-pipelines-when-pushing-to-a-branch).
When the project has [**Pipelines must succeed**](../../user/project/merge_requests/auto_merge.md#require-a-successful-pipeline-for-merge) enabled
and both pipelines types are present, the merge request pipelines are checked,
not the branch pipelines.
Therefore, the MR pipeline result is marked as unsuccessful if the
**merge request pipeline** fails, independently of the **branch pipeline** result.
However:
- These conditions are not enforced.
- A race condition determines which pipeline's result is used to either block or pass merge requests.
This bug is tracked on [issue 384927](https://gitlab.com/gitlab-org/gitlab/-/issues/384927).
## `An error occurred while trying to run a new pipeline for this merge request.`
This error can happen when you select **Run pipeline** in a merge request, but the
project does not have merge request pipelines enabled anymore.
Some possible reasons for this error message:
- The project does not have merge request pipelines enabled, has no pipelines listed
in the **Pipelines** tab, and you select **Run pipelines**.
- The project used to have merge request pipelines enabled, but the configuration
was removed. For example:
1. The project has merge request pipelines enabled in the `.gitlab-ci.yml` configuration
file when the merge request is created.
1. The **Run pipeline** options is available in the merge request's **Pipelines** tab,
and selecting **Run pipeline** at this point likely does not cause any errors.
1. The project's `.gitlab-ci.yml` file is changed to remove the merge request pipelines configuration.
1. The branch is rebased to bring the updated configuration into the merge request.
1. Now the pipeline configuration no longer supports merge request pipelines,
but you select **Run pipeline** to run a merge request pipeline.
If **Run pipeline** is available, but the project does not have merge request pipelines
enabled, do not use this option. You can push a commit or rebase the branch to trigger
new branch pipelines.
## `Merge blocked: pipeline must succeed. Push a new commit that fixes the failure` message
This message is shown if the merge request pipeline, [merged results pipeline](merged_results_pipelines.md),
or [merge train pipeline](merge_trains.md) has failed or been canceled.
This does not happen when a branch pipeline fails.
If a merge request pipeline or a merged results pipeline was canceled or failed, you can:
- Re-run the entire pipeline by selecting **Run pipeline** in the pipeline tab in the merge request.
- [Retry only the jobs that failed](_index.md#view-pipelines). If you re-run the entire pipeline, this is not necessary.
- Push a new commit to fix the failure.
If the merge train pipeline has failed, you can:
- Check the failure and determine if you can use the [`/merge` quick action](../../user/project/quick_actions.md) to immediately add the merge request to the train again.
- Re-run the entire pipeline by selecting **Run pipeline** in the pipeline tab in the merge request, then add the merge request to the train again.
- Push a commit to fix the failure, then add the merge request to the train again.
If the merge train pipeline was canceled before the merge request was merged, without a failure, you can:
- Add it to the train again.
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting merge request pipelines
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
When working with merge request pipelines, you might encounter the following issues.
## Two pipelines when pushing to a branch
If you get duplicate pipelines in merge requests, your pipeline might be configured
to run for both branches and merge requests at the same time. Adjust your pipeline
configuration to [avoid duplicate pipelines](../jobs/job_rules.md#avoid-duplicate-pipelines).
You can add `workflow:rules` to [switch from branch pipelines to merge request pipelines](../yaml/workflow.md#switch-between-branch-pipelines-and-merge-request-pipelines).
After a merge request is open on the branch, the pipeline switches to a merge request pipeline.
## Two pipelines when pushing an invalid CI/CD configuration file
If you push an invalid CI/CD configuration to a merge request's branch, two failed
pipelines appear in the pipelines tab. One pipeline is a failed branch pipeline,
the other is a failed merge request pipeline.
When the configuration syntax is fixed, no further failed pipelines should appear.
To find and fix the configuration problem, you can use:
- The [pipeline editor](../pipeline_editor/_index.md).
- The [CI lint tool](../yaml/lint.md).
## The merge request's pipeline is marked as failed but the latest pipeline succeeded
It's possible to have both branch pipelines and merge request pipelines in the
**Pipelines** tab of a single merge request. This might be [by configuration](../yaml/workflow.md#switch-between-branch-pipelines-and-merge-request-pipelines),
or [by accident](#two-pipelines-when-pushing-to-a-branch).
When the project has [**Pipelines must succeed**](../../user/project/merge_requests/auto_merge.md#require-a-successful-pipeline-for-merge) enabled
and both pipelines types are present, the merge request pipelines are checked,
not the branch pipelines.
Therefore, the MR pipeline result is marked as unsuccessful if the
**merge request pipeline** fails, independently of the **branch pipeline** result.
However:
- These conditions are not enforced.
- A race condition determines which pipeline's result is used to either block or pass merge requests.
This bug is tracked on [issue 384927](https://gitlab.com/gitlab-org/gitlab/-/issues/384927).
## `An error occurred while trying to run a new pipeline for this merge request.`
This error can happen when you select **Run pipeline** in a merge request, but the
project does not have merge request pipelines enabled anymore.
Some possible reasons for this error message:
- The project does not have merge request pipelines enabled, has no pipelines listed
in the **Pipelines** tab, and you select **Run pipelines**.
- The project used to have merge request pipelines enabled, but the configuration
was removed. For example:
1. The project has merge request pipelines enabled in the `.gitlab-ci.yml` configuration
file when the merge request is created.
1. The **Run pipeline** options is available in the merge request's **Pipelines** tab,
and selecting **Run pipeline** at this point likely does not cause any errors.
1. The project's `.gitlab-ci.yml` file is changed to remove the merge request pipelines configuration.
1. The branch is rebased to bring the updated configuration into the merge request.
1. Now the pipeline configuration no longer supports merge request pipelines,
but you select **Run pipeline** to run a merge request pipeline.
If **Run pipeline** is available, but the project does not have merge request pipelines
enabled, do not use this option. You can push a commit or rebase the branch to trigger
new branch pipelines.
## `Merge blocked: pipeline must succeed. Push a new commit that fixes the failure` message
This message is shown if the merge request pipeline, [merged results pipeline](merged_results_pipelines.md),
or [merge train pipeline](merge_trains.md) has failed or been canceled.
This does not happen when a branch pipeline fails.
If a merge request pipeline or a merged results pipeline was canceled or failed, you can:
- Re-run the entire pipeline by selecting **Run pipeline** in the pipeline tab in the merge request.
- [Retry only the jobs that failed](_index.md#view-pipelines). If you re-run the entire pipeline, this is not necessary.
- Push a new commit to fix the failure.
If the merge train pipeline has failed, you can:
- Check the failure and determine if you can use the [`/merge` quick action](../../user/project/quick_actions.md) to immediately add the merge request to the train again.
- Re-run the entire pipeline by selecting **Run pipeline** in the pipeline tab in the merge request, then add the merge request to the train again.
- Push a commit to fix the failure, then add the merge request to the train again.
If the merge train pipeline was canceled before the merge request was merged, without a failure, you can:
- Add it to the train again.
|
https://docs.gitlab.com/ci/pipeline_efficiency
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/pipeline_efficiency.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
pipeline_efficiency.md
|
Verify
|
Pipeline Execution
|
This page is maintained by Developer Relations, author @dnsmichi, see https://handbook.gitlab.com/handbook/marketing/developer-relations/developer-advocacy/content/#maintained-documentation
|
Pipeline efficiency
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
[CI/CD Pipelines](_index.md) are the fundamental building blocks for [GitLab CI/CD](../_index.md).
Making pipelines more efficient helps you save developer time, which:
- Speeds up your DevOps processes
- Reduces costs
- Shortens the development feedback loop
It's common that new teams or projects start with slow and inefficient pipelines,
and improve their configuration over time through trial and error. A better process is
to use pipeline features that improve efficiency right away, and get a faster software
development lifecycle earlier.
First ensure you are familiar with [GitLab CI/CD fundamentals](../_index.md)
and understand the [quick start guide](../quick_start/_index.md).
## Identify bottlenecks and common failures
The easiest indicators to check for inefficient pipelines are the runtimes of the jobs,
stages, and the total runtime of the pipeline itself. The total pipeline duration is
heavily influenced by the:
- [Size of the repository](../../user/project/repository/monorepos/_index.md)
- Total number of stages and jobs.
- Dependencies between jobs.
- The ["critical path"](#needs-dependency-visualization), which represents
the minimum and maximum pipeline duration.
Additional points to pay attention relate to [GitLab Runners](../runners/_index.md):
- Availability of the runners and the resources they are provisioned with.
- Build dependencies, their installation time, and storage space requirements.
- [Container image size](#docker-images).
- Network latency and slow connections.
Pipelines frequently failing unnecessarily also causes slowdowns in the development
lifecycle. You should look for problematic patterns with failed jobs:
- Flaky unit tests which fail randomly, or produce unreliable test results.
- Test coverage drops and code quality correlated to that behavior.
- Failures that can be safely ignored, but that halt the pipeline instead.
- Tests that fail at the end of a long pipeline, but could be in an earlier stage,
causing delayed feedback.
## Pipeline analysis
Analyze the performance of your pipeline to find ways to improve efficiency. Analysis
can help identify possible blockers in the CI/CD infrastructure. This includes analyzing:
- Job workloads.
- Bottlenecks in the execution times.
- The overall pipeline architecture.
It's important to understand and document the pipeline workflows, and discuss possible
actions and changes. Refactoring pipelines may need careful interaction between teams
in the DevSecOps lifecycle.
Pipeline analysis can help identify issues with cost efficiency. For example, [runners](../runners/_index.md)
hosted with a paid cloud service may be provisioned with:
- More resources than needed for CI/CD pipelines, wasting money.
- Not enough resources, causing slow runtimes and wasting time.
### Pipeline Insights
The [Pipeline success and duration charts](_index.md#pipeline-success-and-duration-charts)
give information about pipeline runtime and failed job counts.
Tests like [unit tests](../testing/unit_test_reports.md), integration tests, end-to-end tests,
[code quality](../testing/code_quality.md) tests, and others
ensure that problems are automatically found by the CI/CD pipeline. There could be many
pipeline stages involved causing long runtimes.
You can improve runtimes by running jobs that test different things in parallel, in
the same stage, reducing overall runtime. The downside is that you need more runners
running simultaneously to support the parallel jobs.
### `needs` dependency visualization
Viewing the `needs` dependencies in the [full pipeline graph](_index.md#group-jobs-by-stage-or-needs-configuration)
can help analyze the critical path in the pipeline and understand possible blockers.
### Pipeline Monitoring
Global pipeline health is a key indicator to monitor along with job and pipeline duration.
[CI/CD analytics](_index.md#pipeline-success-and-duration-charts) give a visual
representation of pipeline health.
Instance administrators have access to additional [performance metrics and self-monitoring](../../administration/monitoring/_index.md).
You can fetch specific pipeline health metrics from the [API](../../api/rest/_index.md).
External monitoring tools can poll the API and verify pipeline health or collect
metrics for long term SLA analytics.
For example, the [GitLab CI Pipelines Exporter](https://github.com/mvisonneau/gitlab-ci-pipelines-exporter)
for Prometheus fetches metrics from the API and pipeline events. It can check branches in projects automatically
and get the pipeline status and duration. In combination with a Grafana dashboard,
this helps build an actionable view for your operations team. Metric graphs can also
be embedded into incidents making problem resolving easier. Additionally, it can also export metrics about jobs and environments.
If you use the GitLab CI Pipelines Exporter, you should start with the [example configuration](https://github.com/mvisonneau/gitlab-ci-pipelines-exporter/blob/main/docs/configuration_syntax.md).

Alternatively, you can use a monitoring tool that can execute scripts, like
[`check_gitlab`](https://gitlab.com/6uellerBpanda/check_gitlab) for example.
#### Runner monitoring
You can also [monitor CI runners](https://docs.gitlab.com/runner/monitoring/) on
their host systems, or in clusters like Kubernetes. This includes checking:
- Disk and disk IO
- CPU usage
- Memory
- Runner process resources
The [Prometheus Node Exporter](https://prometheus.io/docs/guides/node-exporter/)
can monitor runners on Linux hosts, and [`kube-state-metrics`](https://github.com/kubernetes/kube-state-metrics)
runs in a Kubernetes cluster.
You can also test [GitLab Runner auto-scaling](https://docs.gitlab.com/runner/configuration/autoscale.html)
with cloud providers, and define offline times to reduce costs.
#### Dashboards and incident management
Use your existing monitoring tools and dashboards to integrate CI/CD pipeline monitoring,
or build them from scratch. Ensure that the runtime data is actionable and useful
in teams, and operations/SREs are able to identify problems early enough.
[Incident management](../../operations/incident_management/_index.md) can help here too,
with embedded metric charts and all valuable details to analyze the problem.
### Storage usage
Review the storage use of the following to help analyze costs and efficiency:
- [Job artifacts](../jobs/job_artifacts.md) and their [`expire_in`](../yaml/_index.md#artifactsexpire_in)
configuration. If kept for too long, storage usage grows and could slow pipelines down.
- [Container registry](../../user/packages/container_registry/_index.md) usage.
- [Package registry](../../user/packages/package_registry/_index.md) usage.
## Pipeline configuration
Make careful choices when configuring pipelines to speed up pipelines and reduce
resource usage. This includes making use of GitLab CI/CD's built-in features that
make pipelines run faster and more efficiently.
### Reduce how often jobs run
Try to find which jobs don't need to run in all situations, and use pipeline configuration
to stop them from running:
- Use the [`interruptible`](../yaml/_index.md#interruptible) keyword to stop old pipelines
when they are superseded by a newer pipeline.
- Use [`rules`](../yaml/_index.md#rules) to skip tests that aren't needed. For example,
skip backend tests when only the frontend code is changed.
- Run non-essential [scheduled pipelines](schedules.md) less frequently.
- Distribute [`cron` schedules](schedules.md#view-and-optimize-pipeline-schedules) evenly across time.
### Fail fast
Ensure that errors are detected early in the CI/CD pipeline. A job that takes a very long
time to complete keeps a pipeline from returning a failed status until the job completes.
Design pipelines so that jobs that can [fail fast](../testing/fail_fast_testing.md)
run earlier. For example, add an early stage and move the syntax, style linting,
Git commit message verification, and similar jobs in there.
Decide if it's important for long jobs to run early, before fast feedback from
faster jobs. The initial failures may make it clear that the rest of the pipeline
shouldn't run, saving pipeline resources.
### `needs` keyword
In a basic configuration, jobs always wait for all other jobs in earlier stages to complete
before running. This is the simplest configuration, but it's also the slowest in most
cases. [Pipelines with the `needs` keyword](../yaml/needs.md) and
[parent/child pipelines](downstream_pipelines.md#parent-child-pipelines) are more flexible and can
be more efficient, but can also make pipelines harder to understand and analyze.
### Caching
Another optimization method is to [cache](../caching/_index.md) dependencies. If your
dependencies change rarely, like [NodeJS `/node_modules`](../caching/_index.md#cache-nodejs-dependencies),
caching can make pipeline execution much faster.
You can use [`cache:when`](../yaml/_index.md#cachewhen) to cache downloaded dependencies
even when a job fails.
### Docker Images
Downloading and initializing Docker images can be a large part of the overall runtime
of jobs.
If a Docker image is slowing down job execution, analyze the base image size and network
connection to the registry. If GitLab is running in the cloud, look for a cloud container
registry offered by the vendor. In addition to that, you can make use of the
[GitLab container registry](../../user/packages/container_registry/_index.md) which can be accessed
by the GitLab instance faster than other registries.
#### Optimize Docker images
Build optimized Docker images because large Docker images use up a lot of space and
take a long time to download with slower connection speeds. If possible, avoid using
one large image for all jobs. Use multiple smaller images, each for a specific task,
that download and run faster.
Try to use custom Docker images with the software pre-installed. It's usually much
faster to download a larger pre-configured image than to use a common image and install
software on it each time. The Docker [Best practices for writing Dockerfiles article](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
has more information about building efficient Docker images.
Methods to reduce Docker image size:
- Use a small base image, for example `debian-slim`.
- Do not install convenience tools such as vim or curl if they aren't strictly needed.
- Create a dedicated development image.
- Disable man pages and documentation installed by packages to save space.
- Reduce the `RUN` layers and combine software installation steps.
- Use [multi-stage builds](https://blog.alexellis.io/mutli-stage-docker-builds/)
to merge multiple Dockerfiles that use the builder pattern into one Dockerfile, which can reduce image size.
- If using `apt`, add `--no-install-recommends` to avoid unnecessary packages.
- Clean up caches and files that are no longer needed at the end. For example
`rm -rf /var/lib/apt/lists/*` for Debian and Ubuntu, or `yum clean all` for RHEL and CentOS.
- Use tools like [dive](https://github.com/wagoodman/dive) or [DockerSlim](https://github.com/docker-slim/docker-slim)
to analyze and shrink images.
To simplify Docker image management, you can create a dedicated group for managing
[Docker images](../docker/_index.md) and test, build and publish them with CI/CD pipelines.
## Test, document, and learn
Improving pipelines is an iterative process. Make small changes, monitor the effect,
then iterate again. Many small improvements can add up to a large increase in pipeline
efficiency.
It can help to document the pipeline design and architecture. You can do this with
[Mermaid charts in Markdown](../../user/markdown.md#mermaid) directly in the GitLab
repository.
Document CI/CD pipeline problems and incidents in issues, including research done
and solutions found. This helps onboarding new team members, and also helps
identify recurring problems with CI pipeline efficiency.
### Related topics
- [CI Monitoring Webcast Slides](https://docs.google.com/presentation/d/1ONwIIzRB7GWX-WOSziIIv8fz1ngqv77HO1yVfRooOHM/edit?usp=sharing)
- GitLab.com Monitoring Handbook
- [Buildings dashboards for operational visibility](https://aws.amazon.com/builders-library/building-dashboards-for-operational-visibility/)
|
---
stage: Verify
group: Pipeline Execution
info: This page is maintained by Developer Relations, author @dnsmichi, see https://handbook.gitlab.com/handbook/marketing/developer-relations/developer-advocacy/content/#maintained-documentation
title: Pipeline efficiency
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
[CI/CD Pipelines](_index.md) are the fundamental building blocks for [GitLab CI/CD](../_index.md).
Making pipelines more efficient helps you save developer time, which:
- Speeds up your DevOps processes
- Reduces costs
- Shortens the development feedback loop
It's common that new teams or projects start with slow and inefficient pipelines,
and improve their configuration over time through trial and error. A better process is
to use pipeline features that improve efficiency right away, and get a faster software
development lifecycle earlier.
First ensure you are familiar with [GitLab CI/CD fundamentals](../_index.md)
and understand the [quick start guide](../quick_start/_index.md).
## Identify bottlenecks and common failures
The easiest indicators to check for inefficient pipelines are the runtimes of the jobs,
stages, and the total runtime of the pipeline itself. The total pipeline duration is
heavily influenced by the:
- [Size of the repository](../../user/project/repository/monorepos/_index.md)
- Total number of stages and jobs.
- Dependencies between jobs.
- The ["critical path"](#needs-dependency-visualization), which represents
the minimum and maximum pipeline duration.
Additional points to pay attention relate to [GitLab Runners](../runners/_index.md):
- Availability of the runners and the resources they are provisioned with.
- Build dependencies, their installation time, and storage space requirements.
- [Container image size](#docker-images).
- Network latency and slow connections.
Pipelines frequently failing unnecessarily also causes slowdowns in the development
lifecycle. You should look for problematic patterns with failed jobs:
- Flaky unit tests which fail randomly, or produce unreliable test results.
- Test coverage drops and code quality correlated to that behavior.
- Failures that can be safely ignored, but that halt the pipeline instead.
- Tests that fail at the end of a long pipeline, but could be in an earlier stage,
causing delayed feedback.
## Pipeline analysis
Analyze the performance of your pipeline to find ways to improve efficiency. Analysis
can help identify possible blockers in the CI/CD infrastructure. This includes analyzing:
- Job workloads.
- Bottlenecks in the execution times.
- The overall pipeline architecture.
It's important to understand and document the pipeline workflows, and discuss possible
actions and changes. Refactoring pipelines may need careful interaction between teams
in the DevSecOps lifecycle.
Pipeline analysis can help identify issues with cost efficiency. For example, [runners](../runners/_index.md)
hosted with a paid cloud service may be provisioned with:
- More resources than needed for CI/CD pipelines, wasting money.
- Not enough resources, causing slow runtimes and wasting time.
### Pipeline Insights
The [Pipeline success and duration charts](_index.md#pipeline-success-and-duration-charts)
give information about pipeline runtime and failed job counts.
Tests like [unit tests](../testing/unit_test_reports.md), integration tests, end-to-end tests,
[code quality](../testing/code_quality.md) tests, and others
ensure that problems are automatically found by the CI/CD pipeline. There could be many
pipeline stages involved causing long runtimes.
You can improve runtimes by running jobs that test different things in parallel, in
the same stage, reducing overall runtime. The downside is that you need more runners
running simultaneously to support the parallel jobs.
### `needs` dependency visualization
Viewing the `needs` dependencies in the [full pipeline graph](_index.md#group-jobs-by-stage-or-needs-configuration)
can help analyze the critical path in the pipeline and understand possible blockers.
### Pipeline Monitoring
Global pipeline health is a key indicator to monitor along with job and pipeline duration.
[CI/CD analytics](_index.md#pipeline-success-and-duration-charts) give a visual
representation of pipeline health.
Instance administrators have access to additional [performance metrics and self-monitoring](../../administration/monitoring/_index.md).
You can fetch specific pipeline health metrics from the [API](../../api/rest/_index.md).
External monitoring tools can poll the API and verify pipeline health or collect
metrics for long term SLA analytics.
For example, the [GitLab CI Pipelines Exporter](https://github.com/mvisonneau/gitlab-ci-pipelines-exporter)
for Prometheus fetches metrics from the API and pipeline events. It can check branches in projects automatically
and get the pipeline status and duration. In combination with a Grafana dashboard,
this helps build an actionable view for your operations team. Metric graphs can also
be embedded into incidents making problem resolving easier. Additionally, it can also export metrics about jobs and environments.
If you use the GitLab CI Pipelines Exporter, you should start with the [example configuration](https://github.com/mvisonneau/gitlab-ci-pipelines-exporter/blob/main/docs/configuration_syntax.md).

Alternatively, you can use a monitoring tool that can execute scripts, like
[`check_gitlab`](https://gitlab.com/6uellerBpanda/check_gitlab) for example.
#### Runner monitoring
You can also [monitor CI runners](https://docs.gitlab.com/runner/monitoring/) on
their host systems, or in clusters like Kubernetes. This includes checking:
- Disk and disk IO
- CPU usage
- Memory
- Runner process resources
The [Prometheus Node Exporter](https://prometheus.io/docs/guides/node-exporter/)
can monitor runners on Linux hosts, and [`kube-state-metrics`](https://github.com/kubernetes/kube-state-metrics)
runs in a Kubernetes cluster.
You can also test [GitLab Runner auto-scaling](https://docs.gitlab.com/runner/configuration/autoscale.html)
with cloud providers, and define offline times to reduce costs.
#### Dashboards and incident management
Use your existing monitoring tools and dashboards to integrate CI/CD pipeline monitoring,
or build them from scratch. Ensure that the runtime data is actionable and useful
in teams, and operations/SREs are able to identify problems early enough.
[Incident management](../../operations/incident_management/_index.md) can help here too,
with embedded metric charts and all valuable details to analyze the problem.
### Storage usage
Review the storage use of the following to help analyze costs and efficiency:
- [Job artifacts](../jobs/job_artifacts.md) and their [`expire_in`](../yaml/_index.md#artifactsexpire_in)
configuration. If kept for too long, storage usage grows and could slow pipelines down.
- [Container registry](../../user/packages/container_registry/_index.md) usage.
- [Package registry](../../user/packages/package_registry/_index.md) usage.
## Pipeline configuration
Make careful choices when configuring pipelines to speed up pipelines and reduce
resource usage. This includes making use of GitLab CI/CD's built-in features that
make pipelines run faster and more efficiently.
### Reduce how often jobs run
Try to find which jobs don't need to run in all situations, and use pipeline configuration
to stop them from running:
- Use the [`interruptible`](../yaml/_index.md#interruptible) keyword to stop old pipelines
when they are superseded by a newer pipeline.
- Use [`rules`](../yaml/_index.md#rules) to skip tests that aren't needed. For example,
skip backend tests when only the frontend code is changed.
- Run non-essential [scheduled pipelines](schedules.md) less frequently.
- Distribute [`cron` schedules](schedules.md#view-and-optimize-pipeline-schedules) evenly across time.
### Fail fast
Ensure that errors are detected early in the CI/CD pipeline. A job that takes a very long
time to complete keeps a pipeline from returning a failed status until the job completes.
Design pipelines so that jobs that can [fail fast](../testing/fail_fast_testing.md)
run earlier. For example, add an early stage and move the syntax, style linting,
Git commit message verification, and similar jobs in there.
Decide if it's important for long jobs to run early, before fast feedback from
faster jobs. The initial failures may make it clear that the rest of the pipeline
shouldn't run, saving pipeline resources.
### `needs` keyword
In a basic configuration, jobs always wait for all other jobs in earlier stages to complete
before running. This is the simplest configuration, but it's also the slowest in most
cases. [Pipelines with the `needs` keyword](../yaml/needs.md) and
[parent/child pipelines](downstream_pipelines.md#parent-child-pipelines) are more flexible and can
be more efficient, but can also make pipelines harder to understand and analyze.
### Caching
Another optimization method is to [cache](../caching/_index.md) dependencies. If your
dependencies change rarely, like [NodeJS `/node_modules`](../caching/_index.md#cache-nodejs-dependencies),
caching can make pipeline execution much faster.
You can use [`cache:when`](../yaml/_index.md#cachewhen) to cache downloaded dependencies
even when a job fails.
### Docker Images
Downloading and initializing Docker images can be a large part of the overall runtime
of jobs.
If a Docker image is slowing down job execution, analyze the base image size and network
connection to the registry. If GitLab is running in the cloud, look for a cloud container
registry offered by the vendor. In addition to that, you can make use of the
[GitLab container registry](../../user/packages/container_registry/_index.md) which can be accessed
by the GitLab instance faster than other registries.
#### Optimize Docker images
Build optimized Docker images because large Docker images use up a lot of space and
take a long time to download with slower connection speeds. If possible, avoid using
one large image for all jobs. Use multiple smaller images, each for a specific task,
that download and run faster.
Try to use custom Docker images with the software pre-installed. It's usually much
faster to download a larger pre-configured image than to use a common image and install
software on it each time. The Docker [Best practices for writing Dockerfiles article](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
has more information about building efficient Docker images.
Methods to reduce Docker image size:
- Use a small base image, for example `debian-slim`.
- Do not install convenience tools such as vim or curl if they aren't strictly needed.
- Create a dedicated development image.
- Disable man pages and documentation installed by packages to save space.
- Reduce the `RUN` layers and combine software installation steps.
- Use [multi-stage builds](https://blog.alexellis.io/mutli-stage-docker-builds/)
to merge multiple Dockerfiles that use the builder pattern into one Dockerfile, which can reduce image size.
- If using `apt`, add `--no-install-recommends` to avoid unnecessary packages.
- Clean up caches and files that are no longer needed at the end. For example
`rm -rf /var/lib/apt/lists/*` for Debian and Ubuntu, or `yum clean all` for RHEL and CentOS.
- Use tools like [dive](https://github.com/wagoodman/dive) or [DockerSlim](https://github.com/docker-slim/docker-slim)
to analyze and shrink images.
To simplify Docker image management, you can create a dedicated group for managing
[Docker images](../docker/_index.md) and test, build and publish them with CI/CD pipelines.
## Test, document, and learn
Improving pipelines is an iterative process. Make small changes, monitor the effect,
then iterate again. Many small improvements can add up to a large increase in pipeline
efficiency.
It can help to document the pipeline design and architecture. You can do this with
[Mermaid charts in Markdown](../../user/markdown.md#mermaid) directly in the GitLab
repository.
Document CI/CD pipeline problems and incidents in issues, including research done
and solutions found. This helps onboarding new team members, and also helps
identify recurring problems with CI pipeline efficiency.
### Related topics
- [CI Monitoring Webcast Slides](https://docs.google.com/presentation/d/1ONwIIzRB7GWX-WOSziIIv8fz1ngqv77HO1yVfRooOHM/edit?usp=sharing)
- GitLab.com Monitoring Handbook
- [Buildings dashboards for operational visibility](https://aws.amazon.com/builders-library/building-dashboards-for-operational-visibility/)
|
https://docs.gitlab.com/ci/merge_trains
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/merge_trains.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
merge_trains.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Merge trains
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [In GitLab 16.0 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/359057), the **Start merge train** and **Start merge train when pipeline succeeds** buttons became **Set to auto-merge**. **Remove from merge train** became **Cancel auto-merge**.
- Support for [fast-forward](../../user/project/merge_requests/methods/_index.md#fast-forward-merge) and [semi-linear](../../user/project/merge_requests/methods/_index.md#merge-commit-with-semi-linear-history) merge methods [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/282442) in GitLab 16.5 [with a flag](../../administration/feature_flags/_index.md) named `fast_forward_merge_trains_support`. Enabled by default.
- [Feature flag `fast_forward_merge_trains_support` removed](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/148964#note_1855981445) in GitLab 16.11.
{{< /history >}}
In projects with frequent merges to the default branch, changes in different merge requests
might conflict with each other. Use merge trains to put merge requests in a queue.
Each merge request is compared to the other, earlier merge requests, to ensure they all work together.
For more information about:
- How merge trains work, review the [merge train workflow](#merge-train-workflow).
- Why you might want to use merge trains, read [How starting merge trains improve efficiency for DevOps](https://about.gitlab.com/blog/2020/01/30/all-aboard-merge-trains/).
## Merge train workflow
A merge train starts when there are no merge requests waiting to merge and you
select [**Merge** or **Set to auto-merge**](#start-a-merge-train). GitLab starts a merge
train pipeline that verifies that the changes can merge into the default branch.
This first pipeline is the same as a [merged results pipeline](merged_results_pipelines.md),
which runs on the changes of the source and target branches combined together.
The author of the internal merged result commit is the user that initiated the
merge.
To queue a second merge request to merge immediately after the first pipeline
completes, select [**Merge** or **Set to auto-merge**](#add-a-merge-request-to-a-merge-train)
to add it to the train. This second merge train pipeline runs on the changes of
_both_ merge requests combined with the target branch. Similarly, if you add a
third merge request, that pipeline runs on the changes of all three merge
requests merged with the target branch. The pipelines all run in parallel.
Each merge request merges into the target branch only after:
- The merge request's pipeline completes successfully.
- All other merge requests queued before it are merged.
If a merge train pipeline fails, the merge request is not merged. GitLab
removes that merge request from the merge train, and starts new pipelines for all
the merge requests that were queued after it.
For example:
Three merge requests (`A`, `B`, and `C`) are added to a merge train in order, which
creates three merged results pipelines that run in parallel:
1. The first pipeline runs on the changes from `A` combined with the target branch.
1. The second pipeline runs on the changes from `A` and `B` combined with the target branch.
1. The third pipeline runs on the changes from `A`, `B`, and `C` combined with the target branch.
If the pipeline for `B` fails:
- The first pipeline (`A`) continues to run.
- `B` is removed from the train.
- The pipeline for `C` [is canceled](#automatic-pipeline-cancellation), and a new pipeline
starts for the changes from `A` and `C` combined with the target branch (without the `B` changes).
If `A` then completes successfully, it merges into the target branch, and `C` continues
to run. Any new merge requests added to the train include the `A` changes now in
the target branch, and the `C` changes from the merge train.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
Watch this video for a demonstration on [how parallel execution of merge trains can prevent commits from breaking the default branch](https://www.youtube.com/watch?v=D4qCqXgZkHQ).
### Automatic pipeline cancellation
GitLab CI/CD detects redundant pipelines, and cancels them to conserve resources.
Redundant merge train pipelines happen when:
- The pipeline fails for one of the merge requests in the merge train.
- You [skip the merge train and merge immediately](#skip-the-merge-train-and-merge-immediately).
- You [remove a merge request from a merge train](#remove-a-merge-request-from-a-merge-train).
In these cases, GitLab must create new merge train pipelines for some or all of the
merge requests on the train. The old pipelines were comparing against the previous
combined changes in the merge train, which are no longer valid, so these old pipelines
are canceled.
## Enable merge trains
{{< history >}}
- `disable_merge_trains` feature flag [removed](https://gitlab.com/gitlab-org/gitlab/-/issues/282477) in GitLab 16.5.
{{< /history >}}
Prerequisites:
- You must have the Maintainer role.
- Your repository must be a GitLab repository, not an [external repository](../ci_cd_for_external_repos/_index.md).
- Your pipeline must be [configured to use merge request pipelines](merge_request_pipelines.md#prerequisites).
Otherwise your merge requests may become stuck in an unresolved state or your pipelines
might be dropped.
- You must have [merged results pipelines enabled](merged_results_pipelines.md#enable-merged-results-pipelines).
To enable merge trains:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Merge requests**.
1. In GitLab 16.4 and earlier, in the **Merge method** section, verify that **Merge commit** is selected.
In GitLab 16.5 and later, you can use any merge method.
1. In the **Merge options** section, ensure **Enable merged results pipelines** is enabled
and select **Enable merge trains**.
1. Select **Save changes**.
## Start a merge train
Prerequisites:
- You must have [permissions](../../user/permissions.md) to merge or push to the target branch.
To start a merge train:
1. Go to a merge request.
1. Select:
- When no pipeline is running, **Merge**.
- When a pipeline is running, [**Set to auto-merge**](../../user/project/merge_requests/auto_merge.md).
The merge request's merge train status displays under the pipeline widget with a
message similar to `A new merge train has started and this merge request is the first of the queue. View merge train details.`
You can select the link to view the merge train.
Other merge requests can now be added to the train.
## View a merge train
{{< history >}}
- Merge train visualization [introduced](https://gitlab.com/groups/gitlab-org/-/epics/13705) in GitLab 17.3.
{{< /history >}}
You can view the merge train to gain better insight into the order and status of merge requests in the queue.
The merge train details page shows active merge requests in the queue and merged merge requests that were part of the train.
To access the merge train details from the list of merge requests:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Code > Merge requests**.
1. Above the list of merge requests, select **Merge trains**.
1. Optional. Filter the merge trains by target branch.
You also access this view by selecting **View merge train details** from:
- The pipeline widget and system notes on a merge request added to a merge train.
- The pipeline details page for a merge train pipeline.
You can also remove ({{< icon name="close" >}}) a merge request from the merge train details view.
## Add a merge request to a merge train
{{< history >}}
- Auto-merge for merge trains [introduced](https://gitlab.com/groups/gitlab-org/-/epics/10874) in GitLab 17.2 [with a flag](../../administration/feature_flags/_index.md) named `merge_when_checks_pass_merge_train`. Disabled by default.
- Auto-merge for merge trains [enabled](https://gitlab.com/gitlab-org/gitlab/-/issues/470667) on GitLab.com in GitLab 17.2.
- Auto-merge for merge trains [enabled](https://gitlab.com/gitlab-org/gitlab/-/issues/470667) by default in GitLab 17.4.
- Auto-merge for merge trains [generally available](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/174357) in GitLab 17.7. Feature flag `merge_when_checks_pass_merge_train` removed.
{{< /history >}}
Prerequisites:
- You must have [permissions](../../user/permissions.md) to merge or push to the target branch.
To add a merge request to a merge train:
1. Visit a merge request.
1. Select:
- When no pipeline is running, **Merge**.
- When a pipeline is running, [**Set to auto-merge**](../../user/project/merge_requests/auto_merge.md).
The merge request's merge train status displays under the pipeline widget with a
message similar to `This merge request is 2 of 3 in queue.`
Each merge train can run a maximum of twenty pipelines in parallel. If you add more than
twenty merge requests to the merge train, the extra merge requests are queued, waiting
for pipelines to complete. There is no limit to the number of queued merge requests
waiting to join the merge train.
## Remove a merge request from a merge train
When you remove a merge request from a merge train:
- All pipelines for merge requests queued after the removed merge request restart.
- Redundant pipelines [are canceled](#automatic-pipeline-cancellation).
You can add the merge request to a merge train again later.
To remove a merge request from a merge train:
- From a merge request, select **Cancel auto-merge**.
- From the [merge train details](#view-a-merge-train), next to the merge request, select {{< icon name="close" >}}.
## Skip the merge train and merge immediately
If you have a high-priority merge request, like a critical patch that must
be merged urgently, you can select **Merge immediately**.
When you merge a merge request immediately:
- The commits from the merge request are merged, ignoring the status of the merge train.
- The merge train pipelines for all other merge requests on the train [are canceled](#automatic-pipeline-cancellation).
- A new merge train starts and all the merge requests from the original merge train are added to this new merge train,
with a new merge train pipeline for each. These new merge train pipelines now contain
the commits added by the merge request that was merged immediately.
{{< alert type="warning" >}}
Merging immediately can use a lot of CI/CD resources. Use this option
only in critical situations.
{{< /alert >}}
{{< alert type="note" >}}
The **merge immediately** option may not be available if your project uses the [fast-forward](../../user/project/merge_requests/methods/_index.md#fast-forward-merge)
merge method and the source branch is behind the target branch. See [issue 434070](https://gitlab.com/gitlab-org/gitlab/-/issues/434070) for more details.
{{< /alert >}}
### Allow merge trains to be skipped to merge immediately without restarting merge train pipelines
{{< details >}}
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/414505) in GitLab 16.5 [with a flag](../../administration/feature_flags/_index.md) named `merge_trains_skip_train`. Disabled by default.
- [Enabled](https://gitlab.com/gitlab-org/gitlab/-/issues/422111) as an [experiment feature](../../policy/development_stages_support.md) in GitLab 16.10.
{{< /history >}}
{{< alert type="flag" >}}
On GitLab Self-Managed, by default this feature is available. To hide the feature,
an administrator can [disable the feature flag](../../administration/feature_flags/_index.md)
named `merge_trains_skip_train`. On GitLab.com and GitLab Dedicated, this feature is available.
{{< /alert >}}
You can allow merge requests to be merged without completely restarting a running merge train.
Use this feature to quickly merge changes that can safely skip the pipeline, for example
minor documentation updates.
You cannot skip merge trains for fast-forward or semi-linear merge methods. For more information, see [issue 429009](https://gitlab.com/gitlab-org/gitlab/-/issues/429009).
Skipping merge trains is an experimental feature. It may change or be removed completely in future releases.
{{< alert type="warning" >}}
You can use this feature to quickly merge security or bug fixes, but the changes
in the merge request that skipped the train are not verified against
any of the other merge requests in the train. If these other merge train pipelines
complete successfully and merge, there is a risk that the combined changes are incompatible.
The target branch could then require additional work to resolve the new failures.
{{< /alert >}}
Prerequisites:
- You must have the Maintainer role.
- You must have [Merge trains enabled](#enable-merge-trains).
To enable skipping the train without pipeline restarts:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Merge requests**.
1. In the **Merge options** section, ensure the **Enable merged results pipelines**
and **Enable merge trains** options are enabled.
1. Select **Allow skipping the merge train**.
1. Select **Save changes**.
To merge a merge request by skipping the merge train, use the [merge requests merge API endpoint](../../api/merge_requests.md#merge-a-merge-request)
to merge with the attribute `skip_merge_train` set to `true`.
The merge request merges, and the existing merge train pipelines are not canceled
or restarted.
## Troubleshooting
### Merge request dropped from the merge train
If a merge request becomes unmergeable while a merge train pipeline is running,
the merge train drops your merge request automatically. For example, this could be caused by:
- Changing the merge request to a [draft](../../user/project/merge_requests/drafts.md).
- A merge conflict.
- A new conversation thread that is unresolved, when [all threads must be resolved](../../user/project/merge_requests/_index.md#prevent-merge-unless-all-threads-are-resolved)
is enabled.
You can find reason the merge request was dropped from the merge train in the system
notes. Check the **Activity** section in the **Overview** tab for a message similar to:
`User removed this merge request from the merge train because ...`
### Cannot use auto-merge
You cannot use [auto-merge](../../user/project/merge_requests/auto_merge.md)
(formerly **Merge when pipeline succeeds**) to skip the merge train, when merge trains are enabled.
See [issue 12267](https://gitlab.com/gitlab-org/gitlab/-/issues/12267) for more information.
### Cannot retry merge train pipeline
When a merge train pipeline fails, the merge request is dropped from the train and the pipeline can't be retried after it fails.
Merge train pipelines run on the merged result of the changes in the merge request and
changes from other merge requests already on the train. If the merge request is dropped from the train,
the merged result is out of date and the pipeline can't be retried.
You can:
- [Add the merge request to the train](#add-a-merge-request-to-a-merge-train) again,
which triggers a new pipeline.
- Add the [`retry`](../yaml/_index.md#retry) keyword to the job if it fails intermittently.
If it succeeds after a retry, the merge request is not removed from the merge train.
### Cannot add a merge request to the merge train
When [**Pipelines must succeed**](../../user/project/merge_requests/auto_merge.md#require-a-successful-pipeline-for-merge)
is enabled, but the latest pipeline failed:
- The **Set to auto-merge** or **Merge** options are not available.
- The merge request displays `The pipeline for this merge request failed. Please retry the job or push a new commit to fix the failure.`
Before you can re-add a merge request to a merge train, you can try to:
- Retry the failed job. If it passes, and no other jobs failed, the pipeline is marked as successful.
- Rerun the whole pipeline. On the **Pipelines** tab, select **Run pipeline**.
- Push a new commit that fixes the issue, which also triggers a new pipeline.
See [the related issue](https://gitlab.com/gitlab-org/gitlab/-/issues/35135)
for more information.
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Merge trains
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [In GitLab 16.0 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/359057), the **Start merge train** and **Start merge train when pipeline succeeds** buttons became **Set to auto-merge**. **Remove from merge train** became **Cancel auto-merge**.
- Support for [fast-forward](../../user/project/merge_requests/methods/_index.md#fast-forward-merge) and [semi-linear](../../user/project/merge_requests/methods/_index.md#merge-commit-with-semi-linear-history) merge methods [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/282442) in GitLab 16.5 [with a flag](../../administration/feature_flags/_index.md) named `fast_forward_merge_trains_support`. Enabled by default.
- [Feature flag `fast_forward_merge_trains_support` removed](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/148964#note_1855981445) in GitLab 16.11.
{{< /history >}}
In projects with frequent merges to the default branch, changes in different merge requests
might conflict with each other. Use merge trains to put merge requests in a queue.
Each merge request is compared to the other, earlier merge requests, to ensure they all work together.
For more information about:
- How merge trains work, review the [merge train workflow](#merge-train-workflow).
- Why you might want to use merge trains, read [How starting merge trains improve efficiency for DevOps](https://about.gitlab.com/blog/2020/01/30/all-aboard-merge-trains/).
## Merge train workflow
A merge train starts when there are no merge requests waiting to merge and you
select [**Merge** or **Set to auto-merge**](#start-a-merge-train). GitLab starts a merge
train pipeline that verifies that the changes can merge into the default branch.
This first pipeline is the same as a [merged results pipeline](merged_results_pipelines.md),
which runs on the changes of the source and target branches combined together.
The author of the internal merged result commit is the user that initiated the
merge.
To queue a second merge request to merge immediately after the first pipeline
completes, select [**Merge** or **Set to auto-merge**](#add-a-merge-request-to-a-merge-train)
to add it to the train. This second merge train pipeline runs on the changes of
_both_ merge requests combined with the target branch. Similarly, if you add a
third merge request, that pipeline runs on the changes of all three merge
requests merged with the target branch. The pipelines all run in parallel.
Each merge request merges into the target branch only after:
- The merge request's pipeline completes successfully.
- All other merge requests queued before it are merged.
If a merge train pipeline fails, the merge request is not merged. GitLab
removes that merge request from the merge train, and starts new pipelines for all
the merge requests that were queued after it.
For example:
Three merge requests (`A`, `B`, and `C`) are added to a merge train in order, which
creates three merged results pipelines that run in parallel:
1. The first pipeline runs on the changes from `A` combined with the target branch.
1. The second pipeline runs on the changes from `A` and `B` combined with the target branch.
1. The third pipeline runs on the changes from `A`, `B`, and `C` combined with the target branch.
If the pipeline for `B` fails:
- The first pipeline (`A`) continues to run.
- `B` is removed from the train.
- The pipeline for `C` [is canceled](#automatic-pipeline-cancellation), and a new pipeline
starts for the changes from `A` and `C` combined with the target branch (without the `B` changes).
If `A` then completes successfully, it merges into the target branch, and `C` continues
to run. Any new merge requests added to the train include the `A` changes now in
the target branch, and the `C` changes from the merge train.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
Watch this video for a demonstration on [how parallel execution of merge trains can prevent commits from breaking the default branch](https://www.youtube.com/watch?v=D4qCqXgZkHQ).
### Automatic pipeline cancellation
GitLab CI/CD detects redundant pipelines, and cancels them to conserve resources.
Redundant merge train pipelines happen when:
- The pipeline fails for one of the merge requests in the merge train.
- You [skip the merge train and merge immediately](#skip-the-merge-train-and-merge-immediately).
- You [remove a merge request from a merge train](#remove-a-merge-request-from-a-merge-train).
In these cases, GitLab must create new merge train pipelines for some or all of the
merge requests on the train. The old pipelines were comparing against the previous
combined changes in the merge train, which are no longer valid, so these old pipelines
are canceled.
## Enable merge trains
{{< history >}}
- `disable_merge_trains` feature flag [removed](https://gitlab.com/gitlab-org/gitlab/-/issues/282477) in GitLab 16.5.
{{< /history >}}
Prerequisites:
- You must have the Maintainer role.
- Your repository must be a GitLab repository, not an [external repository](../ci_cd_for_external_repos/_index.md).
- Your pipeline must be [configured to use merge request pipelines](merge_request_pipelines.md#prerequisites).
Otherwise your merge requests may become stuck in an unresolved state or your pipelines
might be dropped.
- You must have [merged results pipelines enabled](merged_results_pipelines.md#enable-merged-results-pipelines).
To enable merge trains:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Merge requests**.
1. In GitLab 16.4 and earlier, in the **Merge method** section, verify that **Merge commit** is selected.
In GitLab 16.5 and later, you can use any merge method.
1. In the **Merge options** section, ensure **Enable merged results pipelines** is enabled
and select **Enable merge trains**.
1. Select **Save changes**.
## Start a merge train
Prerequisites:
- You must have [permissions](../../user/permissions.md) to merge or push to the target branch.
To start a merge train:
1. Go to a merge request.
1. Select:
- When no pipeline is running, **Merge**.
- When a pipeline is running, [**Set to auto-merge**](../../user/project/merge_requests/auto_merge.md).
The merge request's merge train status displays under the pipeline widget with a
message similar to `A new merge train has started and this merge request is the first of the queue. View merge train details.`
You can select the link to view the merge train.
Other merge requests can now be added to the train.
## View a merge train
{{< history >}}
- Merge train visualization [introduced](https://gitlab.com/groups/gitlab-org/-/epics/13705) in GitLab 17.3.
{{< /history >}}
You can view the merge train to gain better insight into the order and status of merge requests in the queue.
The merge train details page shows active merge requests in the queue and merged merge requests that were part of the train.
To access the merge train details from the list of merge requests:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Code > Merge requests**.
1. Above the list of merge requests, select **Merge trains**.
1. Optional. Filter the merge trains by target branch.
You also access this view by selecting **View merge train details** from:
- The pipeline widget and system notes on a merge request added to a merge train.
- The pipeline details page for a merge train pipeline.
You can also remove ({{< icon name="close" >}}) a merge request from the merge train details view.
## Add a merge request to a merge train
{{< history >}}
- Auto-merge for merge trains [introduced](https://gitlab.com/groups/gitlab-org/-/epics/10874) in GitLab 17.2 [with a flag](../../administration/feature_flags/_index.md) named `merge_when_checks_pass_merge_train`. Disabled by default.
- Auto-merge for merge trains [enabled](https://gitlab.com/gitlab-org/gitlab/-/issues/470667) on GitLab.com in GitLab 17.2.
- Auto-merge for merge trains [enabled](https://gitlab.com/gitlab-org/gitlab/-/issues/470667) by default in GitLab 17.4.
- Auto-merge for merge trains [generally available](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/174357) in GitLab 17.7. Feature flag `merge_when_checks_pass_merge_train` removed.
{{< /history >}}
Prerequisites:
- You must have [permissions](../../user/permissions.md) to merge or push to the target branch.
To add a merge request to a merge train:
1. Visit a merge request.
1. Select:
- When no pipeline is running, **Merge**.
- When a pipeline is running, [**Set to auto-merge**](../../user/project/merge_requests/auto_merge.md).
The merge request's merge train status displays under the pipeline widget with a
message similar to `This merge request is 2 of 3 in queue.`
Each merge train can run a maximum of twenty pipelines in parallel. If you add more than
twenty merge requests to the merge train, the extra merge requests are queued, waiting
for pipelines to complete. There is no limit to the number of queued merge requests
waiting to join the merge train.
## Remove a merge request from a merge train
When you remove a merge request from a merge train:
- All pipelines for merge requests queued after the removed merge request restart.
- Redundant pipelines [are canceled](#automatic-pipeline-cancellation).
You can add the merge request to a merge train again later.
To remove a merge request from a merge train:
- From a merge request, select **Cancel auto-merge**.
- From the [merge train details](#view-a-merge-train), next to the merge request, select {{< icon name="close" >}}.
## Skip the merge train and merge immediately
If you have a high-priority merge request, like a critical patch that must
be merged urgently, you can select **Merge immediately**.
When you merge a merge request immediately:
- The commits from the merge request are merged, ignoring the status of the merge train.
- The merge train pipelines for all other merge requests on the train [are canceled](#automatic-pipeline-cancellation).
- A new merge train starts and all the merge requests from the original merge train are added to this new merge train,
with a new merge train pipeline for each. These new merge train pipelines now contain
the commits added by the merge request that was merged immediately.
{{< alert type="warning" >}}
Merging immediately can use a lot of CI/CD resources. Use this option
only in critical situations.
{{< /alert >}}
{{< alert type="note" >}}
The **merge immediately** option may not be available if your project uses the [fast-forward](../../user/project/merge_requests/methods/_index.md#fast-forward-merge)
merge method and the source branch is behind the target branch. See [issue 434070](https://gitlab.com/gitlab-org/gitlab/-/issues/434070) for more details.
{{< /alert >}}
### Allow merge trains to be skipped to merge immediately without restarting merge train pipelines
{{< details >}}
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/414505) in GitLab 16.5 [with a flag](../../administration/feature_flags/_index.md) named `merge_trains_skip_train`. Disabled by default.
- [Enabled](https://gitlab.com/gitlab-org/gitlab/-/issues/422111) as an [experiment feature](../../policy/development_stages_support.md) in GitLab 16.10.
{{< /history >}}
{{< alert type="flag" >}}
On GitLab Self-Managed, by default this feature is available. To hide the feature,
an administrator can [disable the feature flag](../../administration/feature_flags/_index.md)
named `merge_trains_skip_train`. On GitLab.com and GitLab Dedicated, this feature is available.
{{< /alert >}}
You can allow merge requests to be merged without completely restarting a running merge train.
Use this feature to quickly merge changes that can safely skip the pipeline, for example
minor documentation updates.
You cannot skip merge trains for fast-forward or semi-linear merge methods. For more information, see [issue 429009](https://gitlab.com/gitlab-org/gitlab/-/issues/429009).
Skipping merge trains is an experimental feature. It may change or be removed completely in future releases.
{{< alert type="warning" >}}
You can use this feature to quickly merge security or bug fixes, but the changes
in the merge request that skipped the train are not verified against
any of the other merge requests in the train. If these other merge train pipelines
complete successfully and merge, there is a risk that the combined changes are incompatible.
The target branch could then require additional work to resolve the new failures.
{{< /alert >}}
Prerequisites:
- You must have the Maintainer role.
- You must have [Merge trains enabled](#enable-merge-trains).
To enable skipping the train without pipeline restarts:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > Merge requests**.
1. In the **Merge options** section, ensure the **Enable merged results pipelines**
and **Enable merge trains** options are enabled.
1. Select **Allow skipping the merge train**.
1. Select **Save changes**.
To merge a merge request by skipping the merge train, use the [merge requests merge API endpoint](../../api/merge_requests.md#merge-a-merge-request)
to merge with the attribute `skip_merge_train` set to `true`.
The merge request merges, and the existing merge train pipelines are not canceled
or restarted.
## Troubleshooting
### Merge request dropped from the merge train
If a merge request becomes unmergeable while a merge train pipeline is running,
the merge train drops your merge request automatically. For example, this could be caused by:
- Changing the merge request to a [draft](../../user/project/merge_requests/drafts.md).
- A merge conflict.
- A new conversation thread that is unresolved, when [all threads must be resolved](../../user/project/merge_requests/_index.md#prevent-merge-unless-all-threads-are-resolved)
is enabled.
You can find reason the merge request was dropped from the merge train in the system
notes. Check the **Activity** section in the **Overview** tab for a message similar to:
`User removed this merge request from the merge train because ...`
### Cannot use auto-merge
You cannot use [auto-merge](../../user/project/merge_requests/auto_merge.md)
(formerly **Merge when pipeline succeeds**) to skip the merge train, when merge trains are enabled.
See [issue 12267](https://gitlab.com/gitlab-org/gitlab/-/issues/12267) for more information.
### Cannot retry merge train pipeline
When a merge train pipeline fails, the merge request is dropped from the train and the pipeline can't be retried after it fails.
Merge train pipelines run on the merged result of the changes in the merge request and
changes from other merge requests already on the train. If the merge request is dropped from the train,
the merged result is out of date and the pipeline can't be retried.
You can:
- [Add the merge request to the train](#add-a-merge-request-to-a-merge-train) again,
which triggers a new pipeline.
- Add the [`retry`](../yaml/_index.md#retry) keyword to the job if it fails intermittently.
If it succeeds after a retry, the merge request is not removed from the merge train.
### Cannot add a merge request to the merge train
When [**Pipelines must succeed**](../../user/project/merge_requests/auto_merge.md#require-a-successful-pipeline-for-merge)
is enabled, but the latest pipeline failed:
- The **Set to auto-merge** or **Merge** options are not available.
- The merge request displays `The pipeline for this merge request failed. Please retry the job or push a new commit to fix the failure.`
Before you can re-add a merge request to a merge train, you can try to:
- Retry the failed job. If it passes, and no other jobs failed, the pipeline is marked as successful.
- Rerun the whole pipeline. On the **Pipelines** tab, select **Run pipeline**.
- Push a new commit that fixes the issue, which also triggers a new pipeline.
See [the related issue](https://gitlab.com/gitlab-org/gitlab/-/issues/35135)
for more information.
|
https://docs.gitlab.com/ci/instance_runner_compute_minutes
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/instance_runner_compute_minutes.md
|
2025-08-13
|
doc/ci/pipelines
|
[
"doc",
"ci",
"pipelines"
] |
instance_runner_compute_minutes.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Compute usage for instance runners
|
Compute minutes, purchasing, usage tracking, quota management for instance runners on GitLab.com and GitLab Self-Managed.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
The amount of compute minute usage that projects can consume to run jobs on admin-managed [instance runners](../runners/runners_scope.md#instance-runners)
is limited. This limit is tracked with an instance runner compute quota on the GitLab server. When a namespace exceeds quota, the [quota is enforced](#enforcement).
Admin-managed instance runners are those [managed by the GitLab instance administrator](../../administration/cicd/compute_minutes.md).
{{< alert type="note" >}}
On GitLab.com instance runners are both admin-managed and GitLab-hosted because the instance is managed by GitLab.
{{< /alert >}}
## Compute quota enforcement
### Monthly reset
Compute minutes usage is reset to `0` monthly.
The compute quota is [reset to the monthly allocation](https://about.gitlab.com/pricing/).
For example, if you have a monthly quota of 10,000 compute minutes:
1. On April 1 you have 10,000 compute minutes available.
1. During April, you use 6,000 of the 10,000 compute minutes available in the quota.
1. On May 1, the accumulated compute usage resets to 0, and you have 10,000
compute minutes available for May.
Usage data for the previous month is kept to show a historical view of the consumption over time.
### Notifications
An in-app banner is displayed and an email notification sent to the
namespace owners when the remaining compute minutes is:
- Less than 25% of the quota.
- Less than 5% of the quota.
- Completely used (zero minutes remaining).
### Enforcement
When the compute quota is used for the current month, instance runners stop processing new jobs.
In pipelines that have already started:
- Any pending job (not yet started) or retried job that must be processed by instance runners is dropped.
- Jobs running on instance runners can continue to run until the overall namespace usage goes over-quota
by 1,000 compute minutes. After the 1,000 compute minute grace period, any remaining running jobs
are also dropped.
Project and group runners are not affected by the compute quota and continue processing jobs.
## View usage
You can view the compute usage for a group or personal namespace to understand
compute usage trends and how many compute minutes remain.
In some cases, the quota limit is replaced by one of the following labels:
- **Unlimited**: For namespaces with unlimited compute quota.
- **Not supported**: For namespaces where instance runners are not enabled.
### View usage for a group
Prerequisites:
- You must have the Owner role for the group.
To view compute usage for your group:
1. On the left sidebar, select **Search or go to** and
find your group. The group must not be a subgroup.
1. Select **Settings > Usage quotas**.
1. Select the **Pipelines** tab.
The projects list shows projects with compute usage or instance runners usage
in the current month only. The list includes all projects in the namespace and its
subgroups, sorted in descending order of compute usage.
### View usage for a personal namespace
You can view the compute usage for your personal namespace:
1. On the left sidebar, select your avatar.
1. Select **Edit profile**.
1. On the left sidebar, select **Usage quotas**.
The projects list shows [personal projects](../../user/project/working_with_projects.md)
with compute usage or instance runners usage in the current month only.
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Compute minutes, purchasing, usage tracking, quota management for instance
runners on GitLab.com and GitLab Self-Managed.
title: Compute usage for instance runners
breadcrumbs:
- doc
- ci
- pipelines
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
The amount of compute minute usage that projects can consume to run jobs on admin-managed [instance runners](../runners/runners_scope.md#instance-runners)
is limited. This limit is tracked with an instance runner compute quota on the GitLab server. When a namespace exceeds quota, the [quota is enforced](#enforcement).
Admin-managed instance runners are those [managed by the GitLab instance administrator](../../administration/cicd/compute_minutes.md).
{{< alert type="note" >}}
On GitLab.com instance runners are both admin-managed and GitLab-hosted because the instance is managed by GitLab.
{{< /alert >}}
## Compute quota enforcement
### Monthly reset
Compute minutes usage is reset to `0` monthly.
The compute quota is [reset to the monthly allocation](https://about.gitlab.com/pricing/).
For example, if you have a monthly quota of 10,000 compute minutes:
1. On April 1 you have 10,000 compute minutes available.
1. During April, you use 6,000 of the 10,000 compute minutes available in the quota.
1. On May 1, the accumulated compute usage resets to 0, and you have 10,000
compute minutes available for May.
Usage data for the previous month is kept to show a historical view of the consumption over time.
### Notifications
An in-app banner is displayed and an email notification sent to the
namespace owners when the remaining compute minutes is:
- Less than 25% of the quota.
- Less than 5% of the quota.
- Completely used (zero minutes remaining).
### Enforcement
When the compute quota is used for the current month, instance runners stop processing new jobs.
In pipelines that have already started:
- Any pending job (not yet started) or retried job that must be processed by instance runners is dropped.
- Jobs running on instance runners can continue to run until the overall namespace usage goes over-quota
by 1,000 compute minutes. After the 1,000 compute minute grace period, any remaining running jobs
are also dropped.
Project and group runners are not affected by the compute quota and continue processing jobs.
## View usage
You can view the compute usage for a group or personal namespace to understand
compute usage trends and how many compute minutes remain.
In some cases, the quota limit is replaced by one of the following labels:
- **Unlimited**: For namespaces with unlimited compute quota.
- **Not supported**: For namespaces where instance runners are not enabled.
### View usage for a group
Prerequisites:
- You must have the Owner role for the group.
To view compute usage for your group:
1. On the left sidebar, select **Search or go to** and
find your group. The group must not be a subgroup.
1. Select **Settings > Usage quotas**.
1. Select the **Pipelines** tab.
The projects list shows projects with compute usage or instance runners usage
in the current month only. The list includes all projects in the namespace and its
subgroups, sorted in descending order of compute usage.
### View usage for a personal namespace
You can view the compute usage for your personal namespace:
1. On the left sidebar, select your avatar.
1. Select **Edit profile**.
1. On the left sidebar, select **Usage quotas**.
The projects list shows [personal projects](../../user/project/working_with_projects.md)
with compute usage or instance runners usage in the current month only.
|
https://docs.gitlab.com/ci/quick_start
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/_index.md
|
2025-08-13
|
doc/ci/quick_start
|
[
"doc",
"ci",
"quick_start"
] |
_index.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Tutorial: Create and run your first GitLab CI/CD pipeline
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
This tutorial shows you how to configure and run your first CI/CD pipeline in GitLab.
If you are already familiar with [basic CI/CD concepts](../_index.md), you can learn about
common keywords in [Tutorial: Create a complex pipeline](tutorial.md).
## Prerequisites
Before you start, make sure you have:
- A project in GitLab that you would like to use CI/CD for.
- The Maintainer or Owner role for the project.
If you don't have a project, you can create a public project for free on <https://gitlab.com>.
## Steps
To create and run your first pipeline:
1. [Ensure you have runners available](#ensure-you-have-runners-available) to run your jobs.
If you're using GitLab.com, you can skip this step. GitLab.com provides instance runners for you.
1. [Create a `.gitlab-ci.yml` file](#create-a-gitlab-ciyml-file)
at the root of your repository. This file is where you define the CI/CD jobs.
When you commit the file to your repository, the runner runs your jobs.
The job results [are displayed in a pipeline](#view-the-status-of-your-pipeline-and-jobs).
## Ensure you have runners available
In GitLab, runners are agents that run your CI/CD jobs.
If you're using GitLab.com, you can skip this step. GitLab.com provides instance runners for you.
To view available runners:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
As long as you have at least one runner that's active, with a green circle next to it,
you have a runner available to process your jobs.
If you don't have access to these settings, contact your GitLab administrator.
### If you don't have a runner
If you don't have a runner:
1. [Install GitLab Runner](https://docs.gitlab.com/runner/install/) on your local machine.
1. [Register the runner](https://docs.gitlab.com/runner/register/) for your project.
Choose the `shell` executor.
When your CI/CD jobs run, in a later step, they will run on your local machine.
## Create a `.gitlab-ci.yml` file
Now create a `.gitlab-ci.yml` file. It is a [YAML](https://en.wikipedia.org/wiki/YAML) file where
you specify instructions for GitLab CI/CD.
In this file, you define:
- The structure and order of jobs that the runner should execute.
- The decisions the runner should make when specific conditions are encountered.
To create a `.gitlab-ci.yml` file in your project:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Code > Repository**.
1. Above the file list, select the branch you want to commit to.
If you're not sure, leave `master` or `main`.
Then select the plus icon ({{< icon name="plus" >}}) and **New file**:

1. For the **Filename**, type `.gitlab-ci.yml` and in the larger window,
paste this sample code:
```yaml
build-job:
stage: build
script:
- echo "Hello, $GITLAB_USER_LOGIN!"
test-job1:
stage: test
script:
- echo "This job tests something"
test-job2:
stage: test
script:
- echo "This job tests something, but takes more time than test-job1."
- echo "After the echo commands complete, it runs the sleep command for 20 seconds"
- echo "which simulates a test that runs 20 seconds longer than test-job1"
- sleep 20
deploy-prod:
stage: deploy
script:
- echo "This job deploys something from the $CI_COMMIT_BRANCH branch."
environment: production
```
This example shows four jobs: `build-job`, `test-job1`, `test-job2`, and `deploy-prod`.
The comments listed in the `echo` commands are displayed in the UI when you view the jobs.
The values for the [predefined variables](../variables/predefined_variables.md)
`$GITLAB_USER_LOGIN` and `$CI_COMMIT_BRANCH` are populated when the jobs run.
1. Select **Commit changes**.
The pipeline starts and runs the jobs you defined in the `.gitlab-ci.yml` file.
## View the status of your pipeline and jobs
Now take a look at your pipeline and the jobs within.
1. Go to **Build > Pipelines**. A pipeline with three stages should be displayed:

1. View a visual representation of your pipeline by selecting the pipeline ID:

1. View details of a job by selecting the job name. For example, `deploy-prod`:

You have successfully created your first CI/CD pipeline in GitLab. Congratulations!
Now you can get started customizing your `.gitlab-ci.yml` and defining more advanced jobs.
## `.gitlab-ci.yml` tips
Here are some tips to get started working with the `.gitlab-ci.yml` file.
For the complete `.gitlab-ci.yml` syntax, see the full [CI/CD YAML syntax reference](../yaml/_index.md).
- Use the [pipeline editor](../pipeline_editor/_index.md) to edit your `.gitlab-ci.yml` file.
- Each job contains a script section and belongs to a stage:
- [`stage`](../yaml/_index.md#stage) describes the sequential execution of jobs.
If there are runners available, jobs in a single stage run in parallel.
- Use the [`needs` keyword](../yaml/_index.md#needs) to [run jobs out of stage order](../yaml/needs.md),
to increase pipeline speed and efficiency.
- You can set additional configuration to customize how your jobs and stages perform:
- Use the [`rules`](../yaml/_index.md#rules) keyword to specify when to run or skip jobs.
The `only` and `except` legacy keywords are still supported, but can't be used
with `rules` in the same job.
- Keep information across jobs and stages persistent in a pipeline with [`cache`](../yaml/_index.md#cache)
and [`artifacts`](../yaml/_index.md#artifacts). These keywords are ways to store
dependencies and job output, even when using ephemeral runners for each job.
- Use the [`default`](../yaml/_index.md#default) keyword to specify additional
configurations that are applied to all jobs. This keyword is often used to define
[`before_script`](../yaml/_index.md#before_script) and [`after_script`](../yaml/_index.md#after_script)
sections that should run on every job.
## Related topics
Migrate from:
- [Bamboo](../migration/bamboo.md)
- [CircleCI](../migration/circleci.md)
- [GitHub Actions](../migration/github_actions.md)
- [Jenkins](../migration/jenkins.md)
- [TeamCity](../migration/teamcity.md)
Watch:
- <i class="fa fa-youtube-play youtube" aria-hidden="true"></i> [First time GitLab & CI/CD](https://www.youtube.com/watch?v=kTNfi5z6Uvk&t=553s).
This includes a quick introduction to GitLab, the first steps with CI/CD, building a Go project,
running tests, using the CI/CD pipeline editor, detecting secrets and security vulnerabilities
and offers more exercises for asynchronous practice.
- <i class="fa fa-youtube-play youtube" aria-hidden="true"></i> [Intro to GitLab CI](https://www.youtube.com/watch?v=l5705U8s_nQ&t=358s).
This workshop uses the Web IDE to quickly get going with building source code using CI/CD,
and run unit tests.
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: 'Tutorial: Create and run your first GitLab CI/CD pipeline'
breadcrumbs:
- doc
- ci
- quick_start
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
This tutorial shows you how to configure and run your first CI/CD pipeline in GitLab.
If you are already familiar with [basic CI/CD concepts](../_index.md), you can learn about
common keywords in [Tutorial: Create a complex pipeline](tutorial.md).
## Prerequisites
Before you start, make sure you have:
- A project in GitLab that you would like to use CI/CD for.
- The Maintainer or Owner role for the project.
If you don't have a project, you can create a public project for free on <https://gitlab.com>.
## Steps
To create and run your first pipeline:
1. [Ensure you have runners available](#ensure-you-have-runners-available) to run your jobs.
If you're using GitLab.com, you can skip this step. GitLab.com provides instance runners for you.
1. [Create a `.gitlab-ci.yml` file](#create-a-gitlab-ciyml-file)
at the root of your repository. This file is where you define the CI/CD jobs.
When you commit the file to your repository, the runner runs your jobs.
The job results [are displayed in a pipeline](#view-the-status-of-your-pipeline-and-jobs).
## Ensure you have runners available
In GitLab, runners are agents that run your CI/CD jobs.
If you're using GitLab.com, you can skip this step. GitLab.com provides instance runners for you.
To view available runners:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
As long as you have at least one runner that's active, with a green circle next to it,
you have a runner available to process your jobs.
If you don't have access to these settings, contact your GitLab administrator.
### If you don't have a runner
If you don't have a runner:
1. [Install GitLab Runner](https://docs.gitlab.com/runner/install/) on your local machine.
1. [Register the runner](https://docs.gitlab.com/runner/register/) for your project.
Choose the `shell` executor.
When your CI/CD jobs run, in a later step, they will run on your local machine.
## Create a `.gitlab-ci.yml` file
Now create a `.gitlab-ci.yml` file. It is a [YAML](https://en.wikipedia.org/wiki/YAML) file where
you specify instructions for GitLab CI/CD.
In this file, you define:
- The structure and order of jobs that the runner should execute.
- The decisions the runner should make when specific conditions are encountered.
To create a `.gitlab-ci.yml` file in your project:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Code > Repository**.
1. Above the file list, select the branch you want to commit to.
If you're not sure, leave `master` or `main`.
Then select the plus icon ({{< icon name="plus" >}}) and **New file**:

1. For the **Filename**, type `.gitlab-ci.yml` and in the larger window,
paste this sample code:
```yaml
build-job:
stage: build
script:
- echo "Hello, $GITLAB_USER_LOGIN!"
test-job1:
stage: test
script:
- echo "This job tests something"
test-job2:
stage: test
script:
- echo "This job tests something, but takes more time than test-job1."
- echo "After the echo commands complete, it runs the sleep command for 20 seconds"
- echo "which simulates a test that runs 20 seconds longer than test-job1"
- sleep 20
deploy-prod:
stage: deploy
script:
- echo "This job deploys something from the $CI_COMMIT_BRANCH branch."
environment: production
```
This example shows four jobs: `build-job`, `test-job1`, `test-job2`, and `deploy-prod`.
The comments listed in the `echo` commands are displayed in the UI when you view the jobs.
The values for the [predefined variables](../variables/predefined_variables.md)
`$GITLAB_USER_LOGIN` and `$CI_COMMIT_BRANCH` are populated when the jobs run.
1. Select **Commit changes**.
The pipeline starts and runs the jobs you defined in the `.gitlab-ci.yml` file.
## View the status of your pipeline and jobs
Now take a look at your pipeline and the jobs within.
1. Go to **Build > Pipelines**. A pipeline with three stages should be displayed:

1. View a visual representation of your pipeline by selecting the pipeline ID:

1. View details of a job by selecting the job name. For example, `deploy-prod`:

You have successfully created your first CI/CD pipeline in GitLab. Congratulations!
Now you can get started customizing your `.gitlab-ci.yml` and defining more advanced jobs.
## `.gitlab-ci.yml` tips
Here are some tips to get started working with the `.gitlab-ci.yml` file.
For the complete `.gitlab-ci.yml` syntax, see the full [CI/CD YAML syntax reference](../yaml/_index.md).
- Use the [pipeline editor](../pipeline_editor/_index.md) to edit your `.gitlab-ci.yml` file.
- Each job contains a script section and belongs to a stage:
- [`stage`](../yaml/_index.md#stage) describes the sequential execution of jobs.
If there are runners available, jobs in a single stage run in parallel.
- Use the [`needs` keyword](../yaml/_index.md#needs) to [run jobs out of stage order](../yaml/needs.md),
to increase pipeline speed and efficiency.
- You can set additional configuration to customize how your jobs and stages perform:
- Use the [`rules`](../yaml/_index.md#rules) keyword to specify when to run or skip jobs.
The `only` and `except` legacy keywords are still supported, but can't be used
with `rules` in the same job.
- Keep information across jobs and stages persistent in a pipeline with [`cache`](../yaml/_index.md#cache)
and [`artifacts`](../yaml/_index.md#artifacts). These keywords are ways to store
dependencies and job output, even when using ephemeral runners for each job.
- Use the [`default`](../yaml/_index.md#default) keyword to specify additional
configurations that are applied to all jobs. This keyword is often used to define
[`before_script`](../yaml/_index.md#before_script) and [`after_script`](../yaml/_index.md#after_script)
sections that should run on every job.
## Related topics
Migrate from:
- [Bamboo](../migration/bamboo.md)
- [CircleCI](../migration/circleci.md)
- [GitHub Actions](../migration/github_actions.md)
- [Jenkins](../migration/jenkins.md)
- [TeamCity](../migration/teamcity.md)
Watch:
- <i class="fa fa-youtube-play youtube" aria-hidden="true"></i> [First time GitLab & CI/CD](https://www.youtube.com/watch?v=kTNfi5z6Uvk&t=553s).
This includes a quick introduction to GitLab, the first steps with CI/CD, building a Go project,
running tests, using the CI/CD pipeline editor, detecting secrets and security vulnerabilities
and offers more exercises for asynchronous practice.
- <i class="fa fa-youtube-play youtube" aria-hidden="true"></i> [Intro to GitLab CI](https://www.youtube.com/watch?v=l5705U8s_nQ&t=358s).
This workshop uses the Web IDE to quickly get going with building source code using CI/CD,
and run unit tests.
|
https://docs.gitlab.com/ci/tutorial
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/tutorial.md
|
2025-08-13
|
doc/ci/quick_start
|
[
"doc",
"ci",
"quick_start"
] |
tutorial.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Tutorial: Create a complex pipeline
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
This tutorial walks you through configuring a progressively more complex CI/CD pipeline
through small, iterative steps. The pipeline is always fully functional,
but it gains more functionality with each step. The goal is to build, test, and deploy
a documentation site.
When you finish this tutorial, you will have a new project on GitLab.com and a working documentation site
using [Docusaurus](https://docusaurus.io/).
To complete this tutorial, you will:
1. Create a project to hold the Docusaurus files
1. Create the initial pipeline configuration file
1. Add a job to build the site
1. Add a job to deploy the site
1. Add test jobs
1. Start using merge request pipelines
1. Reduce duplicated configuration
## Prerequisites
- You need an account on GitLab.com.
- You should be familiar with Git.
- Node.js must be installed on your local machine. For example, on macOS you can
[install node](https://formulae.brew.sh/formula/node) with `brew install node`.
## Create a project to hold the Docusaurus files
Before adding the pipeline configuration, you must first set up a Docusaurus project
on GitLab.com:
1. Create a new project under your username (not a group):
1. On the left sidebar, at the top, select **Create new** ({{< icon name="plus" >}}) and **New project/repository**.
1. Select **Create blank project**.
1. Enter the project details:
- In the **Project name** field, enter the name of your project, for example `My Pipeline Tutorial Project`.
- Select **Initialize repository with a README**.
1. Select **Create project**.
1. On the project's overview page, in the upper-right corner, select **Code**
to find the clone paths for your project. Copy the SSH or HTTP path and use the path
to clone the project locally.
For example, to clone with SSH into a `pipeline-tutorial` directory on your computer:
```shell
git clone git@gitlab.com:my-username/my-pipeline-tutorial-project.git pipeline-tutorial
```
1. Change to the project's directory, then generate a new Docusaurus site:
```shell
cd pipeline-tutorial
npm init docusaurus
```
The Docusaurus initialization wizard prompts you with questions about the site.
Use all the default options.
1. The initialization wizard sets up the site in `website/`, but the site should be in
the root of the project. Move the files up to the root and delete the old directory:
```shell
mv website/* .
rm -r website
```
1. Update the Docusaurus configuration file with the details of your GitLab project.
In `docusaurus.config.js`:
- Set `url:` to a path with this format: `https://<my-username>.gitlab.io/`.
- Set `baseUrl:` to your project name, like `/my-pipeline-tutorial-project/`.
1. Commit the changes, and push them to GitLab:
```shell
git add .
git commit -m "Add simple generated Docusaurus site"
git push origin
```
## Create the initial CI/CD configuration file
Start with the simplest possible pipeline configuration file to ensure CI/CD is enabled
in the project and runners are available to run jobs.
This step introduces:
- [Jobs](../jobs/_index.md): These are self-contained parts of a pipeline that run your commands.
Jobs run on [runners](../runners/_index.md), separate from the GitLab instance.
- [`script`](../yaml/_index.md#script): This section of a job's configuration is
where you define the commands for jobs. If there are multiple commands (in an array),
they run in order. Each command executes as if it was run as a CLI command.
By default, if a command fails or returns an error, the job is flagged as failed
and no more commands run.
In this step, create a `.gitlab-ci.yml` file in the root of the project with this configuration:
```yaml
test-job:
script:
- echo "This is my first job!"
- date
```
Commit and push this change to GitLab, then:
1. Go to **Build > Pipelines** and make sure a pipeline runs in GitLab with this single job.
1. Select the pipeline, then select the job to view the job's log and see the `This is my first job!` message
followed by the date.
Now that you have a `.gitlab-ci.yml` file in your project, you can make all future changes
to pipeline configuration with the [pipeline editor](../pipeline_editor/_index.md).
## Add a job to build the site
A common task for a CI/CD pipeline is to build the code in the project then deploy it.
Start by adding a job that builds the site.
This step introduces:
- [`image`](../yaml/_index.md#image): Tell the runner which Docker
container to use to run the job in. The runner:
1. Downloads the container image and starts it.
1. Clones your GitLab project into the running container.
1. Runs the `script` commands, one at a time.
- [`artifacts`](../yaml/_index.md#artifacts): Jobs are self-contained and do not share
resources with each other. If you want files generated in one job to be used in
another job, you must save them as artifacts first. Then later jobs can retrieve the
artifacts and use the generated files.
In this step, replace `test-job` with `build-job`:
- Use `image` to configure the job to run with the latest `node` image. Docusaurus
is a Node.js project and the `node` image has the needed `npm` commands built in.
- Run `npm install` to install Docusaurus into the running `node` container, then run
`npm run build` to build the site.
- Docusaurus saves the built site in `build/`, so save these files with `artifacts`.
```yaml
build-job:
image: node
script:
- npm install
- npm run build
artifacts:
paths:
- "build/"
```
Use the pipeline editor to commit this pipeline configuration to the default branch,
and check the job log. You can:
- See the `npm` commands run and build the site.
- Verify that the artifacts are saved at the end.
- Browse the contents of the artifacts file by selecting **Browse** to the right of the job log
after the job completes.
## Add a job to deploy the site
After verifying the Docusaurus site builds in `build-job`, you can add a job that deploys it.
This step introduces:
- [`stage`](../yaml/_index.md#stage) and [`stages`](../yaml/_index.md#stage): The most common
pipeline configurations group jobs into stages. Jobs in the same stage can run in parallel,
while jobs in later stages wait for jobs in earlier stages to complete. If a job fails,
the whole stage is considered failed and jobs in later stages do not start running.
- [GitLab Pages](../../user/project/pages/_index.md): To host your static site, you
will use GitLab Pages.
In this step:
- Add a job that fetches the built site and deploys it. When using GitLab Pages,
the job is always named `pages`. The artifacts from the `build-job` are fetched automatically
and extracted into the job. Pages looks for the site in the `public/` directory though,
so add a `script` command to move the site to that directory.
- Add a `stages` section, and define the stages for each job. `build-job` runs first
in the `build` stage, and `pages` runs after in the `deploy` stage.
```yaml
stages: # List of stages for jobs and their order of execution
- build
- deploy
build-job:
stage: build # Set this job to run in the `build` stage
image: node
script:
- npm install
- npm run build
artifacts:
paths:
- "build/"
pages:
stage: deploy # Set this new job to run in the `deploy` stage
script:
- mv build/ public/
artifacts:
paths:
- "public/"
```
Use the pipeline editor to commit this pipeline configuration to the default branch,
and view the pipeline details from the **Pipelines** list. Verify that:
- The two jobs run in different stages, `build` and `deploy`.
- After the `pages` job completes a `pages:deploy` job appears, which is the GitLab process
that deploys the Pages site. When that job completes, you can visit your new Docusaurus
site.
To view your site:
- On the left sidebar, select **Deploy > Pages**.
- Make sure **Use unique domain** is off.
- Under **Access pages**, select the link. The URL format should be similar to: `https://<my-username>.gitlab.io/<project-name>`. For more information, see [GitLab Pages default domain names](../../user/project/pages/getting_started_part_one.md#gitlab-pages-default-domain-names).
{{< alert type="note" >}}
If you need to [use unique domains](../../user/project/pages/_index.md#unique-domains), in `docusaurus.config.js`, set `baseUrl`: to `/`.
{{< /alert >}}
## Add test jobs
Now that the site builds and deploys as expected, you can add tests and linting.
For example, a Ruby project might run RSpec test jobs. Docusaurus is a static site
that uses Markdown and generated HTML, so this tutorial adds jobs to test the Markdown and HTML.
This step introduces:
- [`allow_failure`](../yaml/_index.md#allow_failure): Jobs that fail intermittently,
or are expected to fail, can slow down productivity or be difficult to troubleshoot.
Use `allow_failure` to let jobs fail without halting pipeline execution.
- [`dependencies`](../yaml/_index.md#dependencies): Use `dependencies` to control
artifact downloads in individual jobs by listing which jobs to fetch artifacts from.
In this step:
- Add a new `test` stage that runs between `build` and `deploy`. These three stages
are the default stages when `stages` is undefined in the configuration.
- Add a `lint-markdown` job to run [markdownlint](https://github.com/DavidAnson/markdownlint)
and check the Markdown in your project. markdownlint is a static analysis tool that
checks that your Markdown files follow formatting standards.
- The sample Markdown files Docusaurus generates are in `blog/` and `docs/`.
- This tool scans the original Markdown files only, and does not need the generated HTML
saved in the `build-job` artifacts. Speed up the job with `dependencies: []`
so that it fetches no artifacts.
- A few of the sample Markdown files violate default markdownlint rules, so add
`allow_failure: true` to let the pipeline continue despite the rule violations.
- Add a `test-html` job to run [HTMLHint](https://htmlhint.com/) and check the generated HTML.
HTMLHint is a static analysis tool that scans generated HTML for known issues.
- Both `test-html` and `pages` need the generated HTML found in the `build-job` artifacts.
Jobs fetch artifacts from all jobs in earlier stages by default, but add `dependencies:`
to make sure the jobs don't accidentally download other artifacts after future pipeline changes.
```yaml
stages:
- build
- test # Add a `test` stage for the test jobs
- deploy
build-job:
stage: build
image: node
script:
- npm install
- npm run build
artifacts:
paths:
- "build/"
lint-markdown:
stage: test
image: node
dependencies: [] # Don't fetch any artifacts
script:
- npm install markdownlint-cli2 --global # Install markdownlint into the container
- markdownlint-cli2 -v # Verify the version, useful for troubleshooting
- markdownlint-cli2 "blog/**/*.md" "docs/**/*.md" # Lint all markdown files in blog/ and docs/
allow_failure: true # This job fails right now, but don't let it stop the pipeline.
test-html:
stage: test
image: node
dependencies:
- build-job # Only fetch artifacts from `build-job`
script:
- npm install --save-dev htmlhint # Install HTMLHint into the container
- npx htmlhint --version # Verify the version, useful for troubleshooting
- npx htmlhint build/ # Lint all markdown files in blog/ and docs/
pages:
stage: deploy
dependencies:
- build-job # Only fetch artifacts from `build-job`
script:
- mv build/ public/
artifacts:
paths:
- "public/"
```
Commit this pipeline configuration to the default branch, and view the pipeline details.
- The `lint-markdown` job fails because the sample Markdown violates the default
markdownlint rules, but is allowed to fail. You can:
- Ignore the violations for now. They do not need to be fixed as part of the tutorial.
- Fix the Markdown file violations. Then you can change `allow_failure` to `false`,
or remove `allow_failure` completely because `allow_failure: false` is the default behavior
when not defined.
- Add a markdownlint configuration file to limit which rule violations to alert on.
- You can also make changes to the Markdown file content and see the changes on the site
after the next deployment.
## Start using merge request pipelines
With the previous pipeline configurations, the site deploys every time a pipeline completes
successfully, but this is not an ideal development workflow. It's better to work from
feature branches and merge requests, and only deploy the site when changes merge
to the default branch.
This step introduces:
- [`rules`](../yaml/_index.md#rules): Add rules to each job to configure in which
pipelines they run. You can configure jobs to run in [merge request pipelines](../pipelines/merge_request_pipelines.md),
[scheduled pipelines](../pipelines/schedules.md), or other specific situations.
Rules are evaluated from top to bottom, and if a rule matches, the job is
added to the pipeline.
- [CI/CD variables](../variables/_index.md): use these environment variables
to configure job behavior in the configuration file and in script commands.
[Predefined CI/CD variables](../variables/predefined_variables.md) are variables
that you do not need to manually define. They are automatically injected into pipelines
so you can use them to configure your pipeline. Variables are usually formatted as `$VARIABLE_NAME`.
and predefined variables are usually prefixed with `$CI_`.
In this step:
- Create a new feature branch and make the changes in the branch instead of the default branch.
- Add `rules` to each job:
- The site should only deploy for changes to the default branch.
- The other jobs should run for all changes in merge requests or the default branch.
- With this pipeline configuration, you can work from a feature branch without running any jobs,
which saves resources. When you are ready to validate your changes, create a merge request
and a pipeline runs with the jobs configured to run in merge requests.
- When your merge request is accepted and the changes merge to the default branch,
a new pipeline runs which also contains the `pages` deployment job. The site deploys
if no jobs fail.
```yaml
stages:
- build
- test
- deploy
build-job:
stage: build
image: node
script:
- npm install
- npm run build
artifacts:
paths:
- "build/"
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' # Run for all changes to a merge request's source branch
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run for all changes to the default branch
lint-markdown:
stage: test
image: node
dependencies: []
script:
- npm install markdownlint-cli2 --global
- markdownlint-cli2 -v
- markdownlint-cli2 "blog/**/*.md" "docs/**/*.md"
allow_failure: true
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' # Run for all changes to a merge request's source branch
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run for all changes to the default branch
test-html:
stage: test
image: node
dependencies:
- build-job
script:
- npm install --save-dev htmlhint
- npx htmlhint --version
- npx htmlhint build/
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' # Run for all changes to a merge request's source branch
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run for all changes to the default branch
pages:
stage: deploy
dependencies:
- build-job
script:
- mv build/ public/
artifacts:
paths:
- "public/"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run for all changes to the default branch only
```
Merge the changes in your merge request. This action updates the default branch. Verify that
the new pipeline contains the `pages` job that deploys the site.
Be sure to use feature branches and merge requests for all future changes to pipeline configuration.
Other project changes, like creating a Git tag or adding a pipeline schedule, do not
trigger pipelines unless you add rules for those cases too.
## Reduce duplicated configuration
The pipeline now contains three jobs that all have identical `rules` and `image`
configuration. Instead of repeating these rules, use `extends` and `default` to create
single sources of truth.
This step introduces:
- [Hidden jobs](../jobs/_index.md#hide-a-job): Jobs that start with `.` are never
added to a pipeline. Use them to hold configuration you want to reuse.
- [`extends`](../yaml/_index.md#extends): Use extends to repeat configuration in
multiple places, often from hidden jobs. If you update the hidden job's configuration,
all jobs extending the hidden job use the updated configuration.
- [`default`](../yaml/_index.md#default): Set keyword defaults that apply to all jobs
when not defined.
- YAML overriding: When reusing configuration with `extends` or `default`, you can explicitly
define a keyword in the job to override the `extends` or `default` configuration.
In this step:
- Add a `.standard-rules` hidden job to hold the rules that are repeated in `build-job`,
`lint-markdown`, and `test-html`.
- Use `extends` to reuse the `.standard-rules` configuration in the three jobs.
- Add a `default` section to define the `image` default as `node`.
- The `pages` deployment job does not need the default `node` image, so explicitly use
[`busybox`](https://hub.docker.com/_/busybox), an extremely tiny and fast image.
```yaml
stages:
- build
- test
- deploy
default: # Add a default section to define the `image` keyword's default value
image: node
.standard-rules: # Make a hidden job to hold the common rules
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
build-job:
extends:
- .standard-rules # Reuse the configuration in `.standard-rules` here
stage: build
script:
- npm install
- npm run build
artifacts:
paths:
- "build/"
lint-markdown:
stage: test
extends:
- .standard-rules # Reuse the configuration in `.standard-rules` here
dependencies: []
script:
- npm install markdownlint-cli2 --global
- markdownlint-cli2 -v
- markdownlint-cli2 "blog/**/*.md" "docs/**/*.md"
allow_failure: true
test-html:
stage: test
extends:
- .standard-rules # Reuse the configuration in `.standard-rules` here
dependencies:
- build-job
script:
- npm install --save-dev htmlhint
- npx htmlhint --version
- npx htmlhint build/
pages:
stage: deploy
image: busybox # Override the default `image` value with `busybox`
dependencies:
- build-job
script:
- mv build/ public/
artifacts:
paths:
- "public/"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
Use a merge request to commit this pipeline configuration to the default branch.
The file is simpler, but it should have the same behavior as the previous step.
You've just created a full pipeline and streamlined it to be more efficient. Nice work!
Now you can take this knowledge, learn about the rest of the `.gitlab-ci.yml` keywords
in the [CI/CD YAML syntax reference](../yaml/_index.md), and build your own pipelines.
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: 'Tutorial: Create a complex pipeline'
breadcrumbs:
- doc
- ci
- quick_start
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
This tutorial walks you through configuring a progressively more complex CI/CD pipeline
through small, iterative steps. The pipeline is always fully functional,
but it gains more functionality with each step. The goal is to build, test, and deploy
a documentation site.
When you finish this tutorial, you will have a new project on GitLab.com and a working documentation site
using [Docusaurus](https://docusaurus.io/).
To complete this tutorial, you will:
1. Create a project to hold the Docusaurus files
1. Create the initial pipeline configuration file
1. Add a job to build the site
1. Add a job to deploy the site
1. Add test jobs
1. Start using merge request pipelines
1. Reduce duplicated configuration
## Prerequisites
- You need an account on GitLab.com.
- You should be familiar with Git.
- Node.js must be installed on your local machine. For example, on macOS you can
[install node](https://formulae.brew.sh/formula/node) with `brew install node`.
## Create a project to hold the Docusaurus files
Before adding the pipeline configuration, you must first set up a Docusaurus project
on GitLab.com:
1. Create a new project under your username (not a group):
1. On the left sidebar, at the top, select **Create new** ({{< icon name="plus" >}}) and **New project/repository**.
1. Select **Create blank project**.
1. Enter the project details:
- In the **Project name** field, enter the name of your project, for example `My Pipeline Tutorial Project`.
- Select **Initialize repository with a README**.
1. Select **Create project**.
1. On the project's overview page, in the upper-right corner, select **Code**
to find the clone paths for your project. Copy the SSH or HTTP path and use the path
to clone the project locally.
For example, to clone with SSH into a `pipeline-tutorial` directory on your computer:
```shell
git clone git@gitlab.com:my-username/my-pipeline-tutorial-project.git pipeline-tutorial
```
1. Change to the project's directory, then generate a new Docusaurus site:
```shell
cd pipeline-tutorial
npm init docusaurus
```
The Docusaurus initialization wizard prompts you with questions about the site.
Use all the default options.
1. The initialization wizard sets up the site in `website/`, but the site should be in
the root of the project. Move the files up to the root and delete the old directory:
```shell
mv website/* .
rm -r website
```
1. Update the Docusaurus configuration file with the details of your GitLab project.
In `docusaurus.config.js`:
- Set `url:` to a path with this format: `https://<my-username>.gitlab.io/`.
- Set `baseUrl:` to your project name, like `/my-pipeline-tutorial-project/`.
1. Commit the changes, and push them to GitLab:
```shell
git add .
git commit -m "Add simple generated Docusaurus site"
git push origin
```
## Create the initial CI/CD configuration file
Start with the simplest possible pipeline configuration file to ensure CI/CD is enabled
in the project and runners are available to run jobs.
This step introduces:
- [Jobs](../jobs/_index.md): These are self-contained parts of a pipeline that run your commands.
Jobs run on [runners](../runners/_index.md), separate from the GitLab instance.
- [`script`](../yaml/_index.md#script): This section of a job's configuration is
where you define the commands for jobs. If there are multiple commands (in an array),
they run in order. Each command executes as if it was run as a CLI command.
By default, if a command fails or returns an error, the job is flagged as failed
and no more commands run.
In this step, create a `.gitlab-ci.yml` file in the root of the project with this configuration:
```yaml
test-job:
script:
- echo "This is my first job!"
- date
```
Commit and push this change to GitLab, then:
1. Go to **Build > Pipelines** and make sure a pipeline runs in GitLab with this single job.
1. Select the pipeline, then select the job to view the job's log and see the `This is my first job!` message
followed by the date.
Now that you have a `.gitlab-ci.yml` file in your project, you can make all future changes
to pipeline configuration with the [pipeline editor](../pipeline_editor/_index.md).
## Add a job to build the site
A common task for a CI/CD pipeline is to build the code in the project then deploy it.
Start by adding a job that builds the site.
This step introduces:
- [`image`](../yaml/_index.md#image): Tell the runner which Docker
container to use to run the job in. The runner:
1. Downloads the container image and starts it.
1. Clones your GitLab project into the running container.
1. Runs the `script` commands, one at a time.
- [`artifacts`](../yaml/_index.md#artifacts): Jobs are self-contained and do not share
resources with each other. If you want files generated in one job to be used in
another job, you must save them as artifacts first. Then later jobs can retrieve the
artifacts and use the generated files.
In this step, replace `test-job` with `build-job`:
- Use `image` to configure the job to run with the latest `node` image. Docusaurus
is a Node.js project and the `node` image has the needed `npm` commands built in.
- Run `npm install` to install Docusaurus into the running `node` container, then run
`npm run build` to build the site.
- Docusaurus saves the built site in `build/`, so save these files with `artifacts`.
```yaml
build-job:
image: node
script:
- npm install
- npm run build
artifacts:
paths:
- "build/"
```
Use the pipeline editor to commit this pipeline configuration to the default branch,
and check the job log. You can:
- See the `npm` commands run and build the site.
- Verify that the artifacts are saved at the end.
- Browse the contents of the artifacts file by selecting **Browse** to the right of the job log
after the job completes.
## Add a job to deploy the site
After verifying the Docusaurus site builds in `build-job`, you can add a job that deploys it.
This step introduces:
- [`stage`](../yaml/_index.md#stage) and [`stages`](../yaml/_index.md#stage): The most common
pipeline configurations group jobs into stages. Jobs in the same stage can run in parallel,
while jobs in later stages wait for jobs in earlier stages to complete. If a job fails,
the whole stage is considered failed and jobs in later stages do not start running.
- [GitLab Pages](../../user/project/pages/_index.md): To host your static site, you
will use GitLab Pages.
In this step:
- Add a job that fetches the built site and deploys it. When using GitLab Pages,
the job is always named `pages`. The artifacts from the `build-job` are fetched automatically
and extracted into the job. Pages looks for the site in the `public/` directory though,
so add a `script` command to move the site to that directory.
- Add a `stages` section, and define the stages for each job. `build-job` runs first
in the `build` stage, and `pages` runs after in the `deploy` stage.
```yaml
stages: # List of stages for jobs and their order of execution
- build
- deploy
build-job:
stage: build # Set this job to run in the `build` stage
image: node
script:
- npm install
- npm run build
artifacts:
paths:
- "build/"
pages:
stage: deploy # Set this new job to run in the `deploy` stage
script:
- mv build/ public/
artifacts:
paths:
- "public/"
```
Use the pipeline editor to commit this pipeline configuration to the default branch,
and view the pipeline details from the **Pipelines** list. Verify that:
- The two jobs run in different stages, `build` and `deploy`.
- After the `pages` job completes a `pages:deploy` job appears, which is the GitLab process
that deploys the Pages site. When that job completes, you can visit your new Docusaurus
site.
To view your site:
- On the left sidebar, select **Deploy > Pages**.
- Make sure **Use unique domain** is off.
- Under **Access pages**, select the link. The URL format should be similar to: `https://<my-username>.gitlab.io/<project-name>`. For more information, see [GitLab Pages default domain names](../../user/project/pages/getting_started_part_one.md#gitlab-pages-default-domain-names).
{{< alert type="note" >}}
If you need to [use unique domains](../../user/project/pages/_index.md#unique-domains), in `docusaurus.config.js`, set `baseUrl`: to `/`.
{{< /alert >}}
## Add test jobs
Now that the site builds and deploys as expected, you can add tests and linting.
For example, a Ruby project might run RSpec test jobs. Docusaurus is a static site
that uses Markdown and generated HTML, so this tutorial adds jobs to test the Markdown and HTML.
This step introduces:
- [`allow_failure`](../yaml/_index.md#allow_failure): Jobs that fail intermittently,
or are expected to fail, can slow down productivity or be difficult to troubleshoot.
Use `allow_failure` to let jobs fail without halting pipeline execution.
- [`dependencies`](../yaml/_index.md#dependencies): Use `dependencies` to control
artifact downloads in individual jobs by listing which jobs to fetch artifacts from.
In this step:
- Add a new `test` stage that runs between `build` and `deploy`. These three stages
are the default stages when `stages` is undefined in the configuration.
- Add a `lint-markdown` job to run [markdownlint](https://github.com/DavidAnson/markdownlint)
and check the Markdown in your project. markdownlint is a static analysis tool that
checks that your Markdown files follow formatting standards.
- The sample Markdown files Docusaurus generates are in `blog/` and `docs/`.
- This tool scans the original Markdown files only, and does not need the generated HTML
saved in the `build-job` artifacts. Speed up the job with `dependencies: []`
so that it fetches no artifacts.
- A few of the sample Markdown files violate default markdownlint rules, so add
`allow_failure: true` to let the pipeline continue despite the rule violations.
- Add a `test-html` job to run [HTMLHint](https://htmlhint.com/) and check the generated HTML.
HTMLHint is a static analysis tool that scans generated HTML for known issues.
- Both `test-html` and `pages` need the generated HTML found in the `build-job` artifacts.
Jobs fetch artifacts from all jobs in earlier stages by default, but add `dependencies:`
to make sure the jobs don't accidentally download other artifacts after future pipeline changes.
```yaml
stages:
- build
- test # Add a `test` stage for the test jobs
- deploy
build-job:
stage: build
image: node
script:
- npm install
- npm run build
artifacts:
paths:
- "build/"
lint-markdown:
stage: test
image: node
dependencies: [] # Don't fetch any artifacts
script:
- npm install markdownlint-cli2 --global # Install markdownlint into the container
- markdownlint-cli2 -v # Verify the version, useful for troubleshooting
- markdownlint-cli2 "blog/**/*.md" "docs/**/*.md" # Lint all markdown files in blog/ and docs/
allow_failure: true # This job fails right now, but don't let it stop the pipeline.
test-html:
stage: test
image: node
dependencies:
- build-job # Only fetch artifacts from `build-job`
script:
- npm install --save-dev htmlhint # Install HTMLHint into the container
- npx htmlhint --version # Verify the version, useful for troubleshooting
- npx htmlhint build/ # Lint all markdown files in blog/ and docs/
pages:
stage: deploy
dependencies:
- build-job # Only fetch artifacts from `build-job`
script:
- mv build/ public/
artifacts:
paths:
- "public/"
```
Commit this pipeline configuration to the default branch, and view the pipeline details.
- The `lint-markdown` job fails because the sample Markdown violates the default
markdownlint rules, but is allowed to fail. You can:
- Ignore the violations for now. They do not need to be fixed as part of the tutorial.
- Fix the Markdown file violations. Then you can change `allow_failure` to `false`,
or remove `allow_failure` completely because `allow_failure: false` is the default behavior
when not defined.
- Add a markdownlint configuration file to limit which rule violations to alert on.
- You can also make changes to the Markdown file content and see the changes on the site
after the next deployment.
## Start using merge request pipelines
With the previous pipeline configurations, the site deploys every time a pipeline completes
successfully, but this is not an ideal development workflow. It's better to work from
feature branches and merge requests, and only deploy the site when changes merge
to the default branch.
This step introduces:
- [`rules`](../yaml/_index.md#rules): Add rules to each job to configure in which
pipelines they run. You can configure jobs to run in [merge request pipelines](../pipelines/merge_request_pipelines.md),
[scheduled pipelines](../pipelines/schedules.md), or other specific situations.
Rules are evaluated from top to bottom, and if a rule matches, the job is
added to the pipeline.
- [CI/CD variables](../variables/_index.md): use these environment variables
to configure job behavior in the configuration file and in script commands.
[Predefined CI/CD variables](../variables/predefined_variables.md) are variables
that you do not need to manually define. They are automatically injected into pipelines
so you can use them to configure your pipeline. Variables are usually formatted as `$VARIABLE_NAME`.
and predefined variables are usually prefixed with `$CI_`.
In this step:
- Create a new feature branch and make the changes in the branch instead of the default branch.
- Add `rules` to each job:
- The site should only deploy for changes to the default branch.
- The other jobs should run for all changes in merge requests or the default branch.
- With this pipeline configuration, you can work from a feature branch without running any jobs,
which saves resources. When you are ready to validate your changes, create a merge request
and a pipeline runs with the jobs configured to run in merge requests.
- When your merge request is accepted and the changes merge to the default branch,
a new pipeline runs which also contains the `pages` deployment job. The site deploys
if no jobs fail.
```yaml
stages:
- build
- test
- deploy
build-job:
stage: build
image: node
script:
- npm install
- npm run build
artifacts:
paths:
- "build/"
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' # Run for all changes to a merge request's source branch
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run for all changes to the default branch
lint-markdown:
stage: test
image: node
dependencies: []
script:
- npm install markdownlint-cli2 --global
- markdownlint-cli2 -v
- markdownlint-cli2 "blog/**/*.md" "docs/**/*.md"
allow_failure: true
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' # Run for all changes to a merge request's source branch
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run for all changes to the default branch
test-html:
stage: test
image: node
dependencies:
- build-job
script:
- npm install --save-dev htmlhint
- npx htmlhint --version
- npx htmlhint build/
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event' # Run for all changes to a merge request's source branch
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run for all changes to the default branch
pages:
stage: deploy
dependencies:
- build-job
script:
- mv build/ public/
artifacts:
paths:
- "public/"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run for all changes to the default branch only
```
Merge the changes in your merge request. This action updates the default branch. Verify that
the new pipeline contains the `pages` job that deploys the site.
Be sure to use feature branches and merge requests for all future changes to pipeline configuration.
Other project changes, like creating a Git tag or adding a pipeline schedule, do not
trigger pipelines unless you add rules for those cases too.
## Reduce duplicated configuration
The pipeline now contains three jobs that all have identical `rules` and `image`
configuration. Instead of repeating these rules, use `extends` and `default` to create
single sources of truth.
This step introduces:
- [Hidden jobs](../jobs/_index.md#hide-a-job): Jobs that start with `.` are never
added to a pipeline. Use them to hold configuration you want to reuse.
- [`extends`](../yaml/_index.md#extends): Use extends to repeat configuration in
multiple places, often from hidden jobs. If you update the hidden job's configuration,
all jobs extending the hidden job use the updated configuration.
- [`default`](../yaml/_index.md#default): Set keyword defaults that apply to all jobs
when not defined.
- YAML overriding: When reusing configuration with `extends` or `default`, you can explicitly
define a keyword in the job to override the `extends` or `default` configuration.
In this step:
- Add a `.standard-rules` hidden job to hold the rules that are repeated in `build-job`,
`lint-markdown`, and `test-html`.
- Use `extends` to reuse the `.standard-rules` configuration in the three jobs.
- Add a `default` section to define the `image` default as `node`.
- The `pages` deployment job does not need the default `node` image, so explicitly use
[`busybox`](https://hub.docker.com/_/busybox), an extremely tiny and fast image.
```yaml
stages:
- build
- test
- deploy
default: # Add a default section to define the `image` keyword's default value
image: node
.standard-rules: # Make a hidden job to hold the common rules
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
build-job:
extends:
- .standard-rules # Reuse the configuration in `.standard-rules` here
stage: build
script:
- npm install
- npm run build
artifacts:
paths:
- "build/"
lint-markdown:
stage: test
extends:
- .standard-rules # Reuse the configuration in `.standard-rules` here
dependencies: []
script:
- npm install markdownlint-cli2 --global
- markdownlint-cli2 -v
- markdownlint-cli2 "blog/**/*.md" "docs/**/*.md"
allow_failure: true
test-html:
stage: test
extends:
- .standard-rules # Reuse the configuration in `.standard-rules` here
dependencies:
- build-job
script:
- npm install --save-dev htmlhint
- npx htmlhint --version
- npx htmlhint build/
pages:
stage: deploy
image: busybox # Override the default `image` value with `busybox`
dependencies:
- build-job
script:
- mv build/ public/
artifacts:
paths:
- "public/"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
Use a merge request to commit this pipeline configuration to the default branch.
The file is simpler, but it should have the same behavior as the previous step.
You've just created a full pipeline and streamlined it to be more efficient. Nice work!
Now you can take this knowledge, learn about the rest of the `.gitlab-ci.yml` keywords
in the [CI/CD YAML syntax reference](../yaml/_index.md), and build your own pipelines.
|
https://docs.gitlab.com/ci/runner_fleet_dashboard_groups
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/runner_fleet_dashboard_groups.md
|
2025-08-13
|
doc/ci/runners
|
[
"doc",
"ci",
"runners"
] |
runner_fleet_dashboard_groups.md
|
Verify
|
Runner
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Runner fleet dashboard for groups
| null |
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed
- Status: Beta
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/151640) as a [beta](../../policy/development_stages_support.md#beta) in GitLab 17.0 [with a flag](../../administration/feature_flags/_index.md) named `runners_dashboard_for_groups`. Disabled by default.
- Feature flag `runners_dashboard_for_groups` [removed](https://gitlab.com/gitlab-org/gitlab/-/issues/459052) in GitLab 17.2.
{{< /history >}}
Users with at least the Maintainer role for a group can use the runner fleet dashboard to assess the health of group runners.

## Dashboard metrics
The following metrics are available in the runner fleet dashboard:
| Metric | Description |
|-------------------------------|-------------|
| Online | Number of online runners. In the **Admin** area, this metric displays the number of runners for the entire instance. In a group, this metric displays the number of runners for the group and its subgroups. |
| Offline | Number of offline runners. |
| Active runners | Number of active runners. |
| Runner usage (previous month) | Number of compute minutes used by each project on group runners. Includes the option to export as CSV for cost analysis. |
| Wait time to pick a job | Displays the mean wait time for runners. This metric provides insights into whether the runners are capable of servicing the CI/CD job queue in your organization's target service-level objectives. The data that creates this metric widget is updated every 24 hours. |
## View the runner fleet dashboard for groups
Prerequisites:
- You must have the Maintainer role for the group.
To view the runner fleet dashboard for groups:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. Select **Fleet dashboard**.
For GitLab Self-Managed, most of the dashboard metrics work without any additional configuration.
To use the **Runner usage** and **Wait time to pick a job** metrics,
you must [configure the ClickHouse analytics database](runner_fleet_dashboard.md#enable-more-ci-analytics-features-with-clickhouse).
|
---
stage: Verify
group: Runner
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Runner fleet dashboard for groups
breadcrumbs:
- doc
- ci
- runners
---
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed
- Status: Beta
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/151640) as a [beta](../../policy/development_stages_support.md#beta) in GitLab 17.0 [with a flag](../../administration/feature_flags/_index.md) named `runners_dashboard_for_groups`. Disabled by default.
- Feature flag `runners_dashboard_for_groups` [removed](https://gitlab.com/gitlab-org/gitlab/-/issues/459052) in GitLab 17.2.
{{< /history >}}
Users with at least the Maintainer role for a group can use the runner fleet dashboard to assess the health of group runners.

## Dashboard metrics
The following metrics are available in the runner fleet dashboard:
| Metric | Description |
|-------------------------------|-------------|
| Online | Number of online runners. In the **Admin** area, this metric displays the number of runners for the entire instance. In a group, this metric displays the number of runners for the group and its subgroups. |
| Offline | Number of offline runners. |
| Active runners | Number of active runners. |
| Runner usage (previous month) | Number of compute minutes used by each project on group runners. Includes the option to export as CSV for cost analysis. |
| Wait time to pick a job | Displays the mean wait time for runners. This metric provides insights into whether the runners are capable of servicing the CI/CD job queue in your organization's target service-level objectives. The data that creates this metric widget is updated every 24 hours. |
## View the runner fleet dashboard for groups
Prerequisites:
- You must have the Maintainer role for the group.
To view the runner fleet dashboard for groups:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. Select **Fleet dashboard**.
For GitLab Self-Managed, most of the dashboard metrics work without any additional configuration.
To use the **Runner usage** and **Wait time to pick a job** metrics,
you must [configure the ClickHouse analytics database](runner_fleet_dashboard.md#enable-more-ci-analytics-features-with-clickhouse).
|
https://docs.gitlab.com/ci/new_creation_workflow
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/new_creation_workflow.md
|
2025-08-13
|
doc/ci/runners
|
[
"doc",
"ci",
"runners"
] |
new_creation_workflow.md
|
Verify
|
Runner
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Migrating to the new runner registration workflow
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< alert type="disclaimer" />}}
In GitLab 16.0, we introduced a new runner creation workflow that uses runner authentication tokens to register
runners. The legacy workflow that uses registration tokens is deprecated and is planned for removal in GitLab 20.0.
Use the [runner creation workflow](https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token) instead.
For information about the current development status of the new workflow, see [epic 7663](https://gitlab.com/groups/gitlab-org/-/epics/7663).
For information about the technical design and reasons for the new architecture, see Next GitLab Runner Token Architecture.
If you experience problems or have concerns about the new runner registration workflow,
or need more information, let us know in the [feedback issue](https://gitlab.com/gitlab-org/gitlab/-/issues/387993).
## The new runner registration workflow
For the new runner registration workflow, you:
1. [Create a runner](runners_scope.md) directly in the GitLab UI or [programmatically](#creating-runners-programmatically).
1. Receive a runner authentication token.
1. Use the runner authentication token instead of the registration token when you register
a runner with this configuration. Runner managers registered in multiple hosts appear
under the same runner in the GitLab UI, but with an identifying system ID.
The new runner registration workflow has the following benefits:
- Preserved ownership records for runners, and minimized impact on users.
- The addition of a unique system ID ensures that you can reuse the same authentication token across
multiple runners. For more information, see [Reusing a GitLab Runner configuration](https://docs.gitlab.com/runner/fleet_scaling/#reusing-a-gitlab-runner-configuration).
## Estimated time frame for planned changes
- In GitLab 15.10 and later, you can use the new runner registration workflow.
- In GitLab 20.0, we plan to disable runner registration tokens.
## Prevent your runner registration workflow from breaking
In GitLab 16.11 and earlier, you can use the legacy runner registration workflow.
In GitLab 17.0, the legacy runner registration workflow is disabled by default. You can temporarily re-enable the legacy runner registration workflow. For more information, see [Using registration tokens after GitLab 17.0](#using-registration-tokens-after-gitlab-170).
If you don't migrate to the new workflow when you upgrade to GitLab 17.0, the runner registration breaks and the `gitlab-runner register` command returns a `410 Gone - runner registration disallowed` error.
To avoid a broken workflow, you must:
1. [Create a runner](runners_scope.md) and obtain the authentication token.
1. Replace the registration token in your runner registration workflow with the
authentication token.
{{< alert type="warning" >}}
In GitLab 17.0 and later, runner registration tokens are disabled.
To use stored runner registration tokens to register new runners,
you must [enable the tokens](../../administration/settings/continuous_integration.md#control-runner-registration).
{{< /alert >}}
## Using registration tokens after GitLab 17.0
To continue using registration tokens after GitLab 17.0:
- On GitLab.com, you can manually [enable the legacy runner registration process](runners_scope.md#enable-use-of-runner-registration-tokens-in-projects-and-groups)
in the top-level group settings.
- On GitLab Self-Managed, you can manually [enable the legacy runner registration process](../../administration/settings/continuous_integration.md#control-runner-registration)
in the **Admin** area settings.
## Impact on existing runners
Existing runners will continue to work as usual after upgrading to GitLab 17.0. This change only affects registration of new runners.
The [GitLab Runner Helm chart](https://docs.gitlab.com/runner/install/kubernetes.html) generates new runner pods every time a job is executed.
For these runners, [enable legacy runner registration](#using-registration-tokens-after-gitlab-170) to use registration tokens.
In GitLab 20.0 and later, you must migrate to the [new runner registration workflow](#the-new-runner-registration-workflow).
## Changes to the `gitlab-runner register` command syntax
The `gitlab-runner register` command accepts runner authentication tokens instead of registration tokens.
You can generate tokens from the **Runners** page in the **Admin** area.
The runner authentication tokens are recognizable by their `glrt-` prefix.
When you create a runner in the GitLab UI, you specify configuration values that were previously command-line options
prompted by the `gitlab-runner register` command.
These command-line options will be deprecated in the future.
If you specify a runner authentication token with:
- the `--token` command-line option, the `gitlab-runner register` command does not accept the configuration values.
- the `--registration-token` command-line option, the `gitlab-runner register` command ignores the configuration values.
| Token | Registration command |
|----------------------------------------|----------------------|
| Runner authentication token | `gitlab-runner register --token $RUNNER_AUTHENTICATION_TOKEN` |
| Runner registration token (deprecated) | `gitlab-runner register --registration-token $RUNNER_REGISTRATION_TOKEN <runner configuration arguments>` |
Authentication tokens have the prefix, `glrt-`.
To ensure minimal disruption to your automation workflow,
[legacy-compatible registration processing](https://docs.gitlab.com/runner/register/#legacy-compatible-registration-process)
triggers if a runner authentication token is specified in the legacy parameter `--registration-token`.
Example command for GitLab 15.9:
```shell
gitlab-runner register \
--non-interactive \
--executor "shell" \
--url "https://gitlab.com/" \
--tag-list "shell,mac,gdk,test" \
--run-untagged "false" \
--locked "false" \
--access-level "not_protected" \
--registration-token "REDACTED"
```
In GitLab 15.10 and later, you can create the runner and set attributes in the UI, like
tag list, locked status, and access level.
In GitLab 15.11 and later, these attributes are no longer accepted as arguments to `register` when a runner authentication token with the `glrt-` prefix is specified.
The following example shows the new command:
```shell
gitlab-runner register \
--non-interactive \
--executor "shell" \
--url "https://gitlab.com/" \
--token "REDACTED"
```
## Impact on autoscaling
In autoscaling scenarios such as GitLab Runner Operator or GitLab Runner Helm Chart, the
runner authentication token generated from the UI replaces the registration token.
This means that the same runner configuration is reused across jobs, instead of creating a runner
for each job.
The specific runner can be identified by the unique system ID that is generated when the runner
process is started.
## Creating runners programmatically
In GitLab 15.11 and later, you can use the [POST /user/runners REST API](../../api/users.md#create-a-runner-linked-to-a-user)
to create a runner as an authenticated user. This should only be used if the runner configuration is dynamic
or not reusable. If the runner configuration is static, you should reuse the runner authentication token of
an existing runner.
For instructions about how to automate runner creation and registration, see the tutorial,
[Automate runner creation and registration](../../tutorials/automate_runner_creation/_index.md).
## Installing GitLab Runner with Helm chart
Several runner configuration options cannot be set during runner registration. These options can only be configured:
- When you create a runner in the UI.
- With the `user/runners` REST API endpoint.
The following configuration options are no longer supported in [`values.yaml`](https://gitlab.com/gitlab-org/charts/gitlab-runner/-/blob/main/values.yaml):
```yaml
## All these fields are DEPRECATED and the runner WILL FAIL TO START with GitLab Runner 20.0 and later if you specify them.
## If a runner authentication token is specified in runnerRegistrationToken, the registration will succeed, however the
## other values will be ignored.
runnerRegistrationToken: ""
locked: true
tags: ""
maximumTimeout: ""
runUntagged: true
protected: true
```
For GitLab Runner on Kubernetes, Helm deploy passes the runner authentication token to the runner worker pod and creates the runner configuration.
In GitLab 17.0 and later, if you use the `runnerRegistrationToken` token field on Kubernetes hosted runners attached to GitLab.com, the runner worker pod tries to use the unsupported Registration API method during creation.
Replace the invalid `runnerRegistrationToken` field with the `runnerToken` field. You must also modify the runner authentication token stored in `secrets`.
In the legacy runner registration workflow, fields were specified with:
```yaml
apiVersion: v1
kind: Secret
metadata:
name: gitlab-runner-secret
type: Opaque
data:
runner-registration-token: "REDACTED" # DEPRECATED, set to ""
runner-token: ""
```
In the new runner registration workflow, you must use `runner-token` instead:
```yaml
apiVersion: v1
kind: Secret
metadata:
name: gitlab-runner-secret
type: Opaque
data:
runner-registration-token: "" # need to leave as an empty string for compatibility reasons
runner-token: "REDACTED"
```
{{< alert type="note" >}}
If your secret management solution doesn't allow you to set an empty string for `runner-registration-token`,
you can set it to any string. This value is ignored when `runner-token` is present.
{{< /alert >}}
## Known issues
### Pod name is not visible in runner details page
When you use the new registration workflow to register your runners with Helm chart, the pod name doesn't appear
on the runner details page.
For more information, see [issue 423523](https://gitlab.com/gitlab-org/gitlab/-/issues/423523).
### Runner authentication token does not update when rotated
#### Token rotation with the same runner registered in multiple runner managers
When you register runners on multiple host machines through the new workflow with
automatic token rotation, only the first runner manager receives the new token.
The remaining runner managers continue to use the invalid token and become disconnected.
You must update these managers manually to use the new token.
#### Token rotation in GitLab Operator
During runner registration with GitLab Operator through the new workflow,
the runner authentication token in the Custom Resource Definition doesn't update
during token rotation.
This occurs when:
- You're using a runner authentication token (prefixed with `glrt-`) in a secret
[referenced by a Custom Resource Definition](https://docs.gitlab.com/runner/install/operator.html#install-gitlab-runner).
- The runner authentication token is due to expire.
For more information about runner authentication token expiration,
see [Authentication token security](configure_runners.md#authentication-token-security).
For more information, see [issue 186](https://gitlab.com/gitlab-org/gl-openshift/gitlab-runner-operator/-/issues/186).
|
---
stage: Verify
group: Runner
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Migrating to the new runner registration workflow
breadcrumbs:
- doc
- ci
- runners
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< alert type="disclaimer" />}}
In GitLab 16.0, we introduced a new runner creation workflow that uses runner authentication tokens to register
runners. The legacy workflow that uses registration tokens is deprecated and is planned for removal in GitLab 20.0.
Use the [runner creation workflow](https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token) instead.
For information about the current development status of the new workflow, see [epic 7663](https://gitlab.com/groups/gitlab-org/-/epics/7663).
For information about the technical design and reasons for the new architecture, see Next GitLab Runner Token Architecture.
If you experience problems or have concerns about the new runner registration workflow,
or need more information, let us know in the [feedback issue](https://gitlab.com/gitlab-org/gitlab/-/issues/387993).
## The new runner registration workflow
For the new runner registration workflow, you:
1. [Create a runner](runners_scope.md) directly in the GitLab UI or [programmatically](#creating-runners-programmatically).
1. Receive a runner authentication token.
1. Use the runner authentication token instead of the registration token when you register
a runner with this configuration. Runner managers registered in multiple hosts appear
under the same runner in the GitLab UI, but with an identifying system ID.
The new runner registration workflow has the following benefits:
- Preserved ownership records for runners, and minimized impact on users.
- The addition of a unique system ID ensures that you can reuse the same authentication token across
multiple runners. For more information, see [Reusing a GitLab Runner configuration](https://docs.gitlab.com/runner/fleet_scaling/#reusing-a-gitlab-runner-configuration).
## Estimated time frame for planned changes
- In GitLab 15.10 and later, you can use the new runner registration workflow.
- In GitLab 20.0, we plan to disable runner registration tokens.
## Prevent your runner registration workflow from breaking
In GitLab 16.11 and earlier, you can use the legacy runner registration workflow.
In GitLab 17.0, the legacy runner registration workflow is disabled by default. You can temporarily re-enable the legacy runner registration workflow. For more information, see [Using registration tokens after GitLab 17.0](#using-registration-tokens-after-gitlab-170).
If you don't migrate to the new workflow when you upgrade to GitLab 17.0, the runner registration breaks and the `gitlab-runner register` command returns a `410 Gone - runner registration disallowed` error.
To avoid a broken workflow, you must:
1. [Create a runner](runners_scope.md) and obtain the authentication token.
1. Replace the registration token in your runner registration workflow with the
authentication token.
{{< alert type="warning" >}}
In GitLab 17.0 and later, runner registration tokens are disabled.
To use stored runner registration tokens to register new runners,
you must [enable the tokens](../../administration/settings/continuous_integration.md#control-runner-registration).
{{< /alert >}}
## Using registration tokens after GitLab 17.0
To continue using registration tokens after GitLab 17.0:
- On GitLab.com, you can manually [enable the legacy runner registration process](runners_scope.md#enable-use-of-runner-registration-tokens-in-projects-and-groups)
in the top-level group settings.
- On GitLab Self-Managed, you can manually [enable the legacy runner registration process](../../administration/settings/continuous_integration.md#control-runner-registration)
in the **Admin** area settings.
## Impact on existing runners
Existing runners will continue to work as usual after upgrading to GitLab 17.0. This change only affects registration of new runners.
The [GitLab Runner Helm chart](https://docs.gitlab.com/runner/install/kubernetes.html) generates new runner pods every time a job is executed.
For these runners, [enable legacy runner registration](#using-registration-tokens-after-gitlab-170) to use registration tokens.
In GitLab 20.0 and later, you must migrate to the [new runner registration workflow](#the-new-runner-registration-workflow).
## Changes to the `gitlab-runner register` command syntax
The `gitlab-runner register` command accepts runner authentication tokens instead of registration tokens.
You can generate tokens from the **Runners** page in the **Admin** area.
The runner authentication tokens are recognizable by their `glrt-` prefix.
When you create a runner in the GitLab UI, you specify configuration values that were previously command-line options
prompted by the `gitlab-runner register` command.
These command-line options will be deprecated in the future.
If you specify a runner authentication token with:
- the `--token` command-line option, the `gitlab-runner register` command does not accept the configuration values.
- the `--registration-token` command-line option, the `gitlab-runner register` command ignores the configuration values.
| Token | Registration command |
|----------------------------------------|----------------------|
| Runner authentication token | `gitlab-runner register --token $RUNNER_AUTHENTICATION_TOKEN` |
| Runner registration token (deprecated) | `gitlab-runner register --registration-token $RUNNER_REGISTRATION_TOKEN <runner configuration arguments>` |
Authentication tokens have the prefix, `glrt-`.
To ensure minimal disruption to your automation workflow,
[legacy-compatible registration processing](https://docs.gitlab.com/runner/register/#legacy-compatible-registration-process)
triggers if a runner authentication token is specified in the legacy parameter `--registration-token`.
Example command for GitLab 15.9:
```shell
gitlab-runner register \
--non-interactive \
--executor "shell" \
--url "https://gitlab.com/" \
--tag-list "shell,mac,gdk,test" \
--run-untagged "false" \
--locked "false" \
--access-level "not_protected" \
--registration-token "REDACTED"
```
In GitLab 15.10 and later, you can create the runner and set attributes in the UI, like
tag list, locked status, and access level.
In GitLab 15.11 and later, these attributes are no longer accepted as arguments to `register` when a runner authentication token with the `glrt-` prefix is specified.
The following example shows the new command:
```shell
gitlab-runner register \
--non-interactive \
--executor "shell" \
--url "https://gitlab.com/" \
--token "REDACTED"
```
## Impact on autoscaling
In autoscaling scenarios such as GitLab Runner Operator or GitLab Runner Helm Chart, the
runner authentication token generated from the UI replaces the registration token.
This means that the same runner configuration is reused across jobs, instead of creating a runner
for each job.
The specific runner can be identified by the unique system ID that is generated when the runner
process is started.
## Creating runners programmatically
In GitLab 15.11 and later, you can use the [POST /user/runners REST API](../../api/users.md#create-a-runner-linked-to-a-user)
to create a runner as an authenticated user. This should only be used if the runner configuration is dynamic
or not reusable. If the runner configuration is static, you should reuse the runner authentication token of
an existing runner.
For instructions about how to automate runner creation and registration, see the tutorial,
[Automate runner creation and registration](../../tutorials/automate_runner_creation/_index.md).
## Installing GitLab Runner with Helm chart
Several runner configuration options cannot be set during runner registration. These options can only be configured:
- When you create a runner in the UI.
- With the `user/runners` REST API endpoint.
The following configuration options are no longer supported in [`values.yaml`](https://gitlab.com/gitlab-org/charts/gitlab-runner/-/blob/main/values.yaml):
```yaml
## All these fields are DEPRECATED and the runner WILL FAIL TO START with GitLab Runner 20.0 and later if you specify them.
## If a runner authentication token is specified in runnerRegistrationToken, the registration will succeed, however the
## other values will be ignored.
runnerRegistrationToken: ""
locked: true
tags: ""
maximumTimeout: ""
runUntagged: true
protected: true
```
For GitLab Runner on Kubernetes, Helm deploy passes the runner authentication token to the runner worker pod and creates the runner configuration.
In GitLab 17.0 and later, if you use the `runnerRegistrationToken` token field on Kubernetes hosted runners attached to GitLab.com, the runner worker pod tries to use the unsupported Registration API method during creation.
Replace the invalid `runnerRegistrationToken` field with the `runnerToken` field. You must also modify the runner authentication token stored in `secrets`.
In the legacy runner registration workflow, fields were specified with:
```yaml
apiVersion: v1
kind: Secret
metadata:
name: gitlab-runner-secret
type: Opaque
data:
runner-registration-token: "REDACTED" # DEPRECATED, set to ""
runner-token: ""
```
In the new runner registration workflow, you must use `runner-token` instead:
```yaml
apiVersion: v1
kind: Secret
metadata:
name: gitlab-runner-secret
type: Opaque
data:
runner-registration-token: "" # need to leave as an empty string for compatibility reasons
runner-token: "REDACTED"
```
{{< alert type="note" >}}
If your secret management solution doesn't allow you to set an empty string for `runner-registration-token`,
you can set it to any string. This value is ignored when `runner-token` is present.
{{< /alert >}}
## Known issues
### Pod name is not visible in runner details page
When you use the new registration workflow to register your runners with Helm chart, the pod name doesn't appear
on the runner details page.
For more information, see [issue 423523](https://gitlab.com/gitlab-org/gitlab/-/issues/423523).
### Runner authentication token does not update when rotated
#### Token rotation with the same runner registered in multiple runner managers
When you register runners on multiple host machines through the new workflow with
automatic token rotation, only the first runner manager receives the new token.
The remaining runner managers continue to use the invalid token and become disconnected.
You must update these managers manually to use the new token.
#### Token rotation in GitLab Operator
During runner registration with GitLab Operator through the new workflow,
the runner authentication token in the Custom Resource Definition doesn't update
during token rotation.
This occurs when:
- You're using a runner authentication token (prefixed with `glrt-`) in a secret
[referenced by a Custom Resource Definition](https://docs.gitlab.com/runner/install/operator.html#install-gitlab-runner).
- The runner authentication token is due to expire.
For more information about runner authentication token expiration,
see [Authentication token security](configure_runners.md#authentication-token-security).
For more information, see [issue 186](https://gitlab.com/gitlab-org/gl-openshift/gitlab-runner-operator/-/issues/186).
|
https://docs.gitlab.com/ci/configure_runners
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/configure_runners.md
|
2025-08-13
|
doc/ci/runners
|
[
"doc",
"ci",
"runners"
] |
configure_runners.md
|
Verify
|
Runner
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Configuring runners
|
Set timeouts, protect sensitive information, control behavior with tags and variables, and configure artifact and cache settings of your GitLab Runner.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
This document describes how to configure runners in the GitLab UI.
If you need to configure runners on the machine where you installed GitLab Runner, see
[the GitLab Runner documentation](https://docs.gitlab.com/runner/configuration/).
## Set the maximum job timeout
You can specify a maximum job timeout for each runner to prevent projects
with longer job timeouts from using the runner. The maximum job timeout is
used if it is shorter than the job timeout defined in the project.
To set a runner's maximum timeout, set the `maximum_timeout` parameter in the REST API endpoint [`PUT /runners/:id`](../../api/runners.md#update-runners-details).
### For an instance runner
Prerequisites:
- You must be an administrator.
You can override the job timeout for instance runners on GitLab Self-Managed.
On GitLab.com, you cannot override the job timeout for GitLab hosted instance runners and must use the [project defined timeout](../pipelines/settings.md#set-a-limit-for-how-long-jobs-can-run) instead.
To set the maximum job timeout:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. To the right of the runner, you want to edit, select **Edit** ({{< icon name="pencil" >}}).
1. In the **Maximum job timeout** field, enter a value in seconds. The minimum value is 600 seconds (10 minutes).
1. Select **Save changes**.
### For a group runner
Prerequisites:
- You must have the Owner role for the group.
To set the maximum job timeout:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. To the right of the runner you want to edit, select **Edit** ({{< icon name="pencil" >}}).
1. In the **Maximum job timeout** field, enter a value in seconds. The minimum value is 600 seconds (10 minutes).
1. Select **Save changes**.
### For a project runner
Prerequisites:
- You must have the Owner role for the project.
To set the maximum job timeout:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. To the right of the runner you want to edit, select **Edit** ({{< icon name="pencil" >}}).
1. In the **Maximum job timeout** field, enter a value in seconds. The minimum value is 600 seconds (10 minutes). If not defined, the [job timeout for the project](../pipelines/settings.md#set-a-limit-for-how-long-jobs-can-run) is used instead.
1. Select **Save changes**.
## How maximum job timeout works
**Example 1 - Runner timeout bigger than project timeout**
1. You set the `maximum_timeout` parameter for a runner to 24 hours.
1. You set the **Maximum job timeout** for a project to **2 hours**.
1. You start a job.
1. The job, if running longer, times out after **2 hours**.
**Example 2 - Runner timeout not configured**
1. You remove the `maximum_timeout` parameter configuration from a runner.
1. You set the **Maximum job timeout** for a project to **2 hours**.
1. You start a job.
1. The job, if running longer, times out after **2 hours**.
**Example 3 - Runner timeout smaller than project timeout**
1. You set the `maximum_timeout` parameter for a runner to **30 minutes**.
1. You set the **Maximum job timeout** for a project to 2 hours.
1. You start a job.
1. The job, if running longer, times out after **30 minutes**.
## Set `script` and `after_script` timeouts
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/4335) in GitLab Runner 16.4.
{{< /history >}}
To control the amount of time `script` and `after_script` runs before it terminates, specify a timeout value in the `.gitlab-ci.yml` file.
For example, you can specify a timeout to terminate a long-running `script` early. This ensures artifacts and caches can still be uploaded
before the [job timeout](../pipelines/settings.md#set-a-limit-for-how-long-jobs-can-run) is exceeded.
The timeout values for `script` and `after_script` must be less than the job timeout.
- To set a timeout for `script`, use the job variable `RUNNER_SCRIPT_TIMEOUT`.
- To set a timeout for `after_script`, and override the default of 5 minutes, use the job variable `RUNNER_AFTER_SCRIPT_TIMEOUT`.
Both of these variables accept [Go's duration format](https://pkg.go.dev/time#ParseDuration) (for example, `40s`, `1h20m`, `2h` `4h30m30s`).
For example:
```yaml
job-with-script-timeouts:
variables:
RUNNER_SCRIPT_TIMEOUT: 15m
RUNNER_AFTER_SCRIPT_TIMEOUT: 10m
script:
- "I am allowed to run for min(15m, remaining job timeout)."
after_script:
- "I am allowed to run for min(10m, remaining job timeout)."
job-artifact-upload-on-timeout:
timeout: 1h # set job timeout to 1 hour
variables:
RUNNER_SCRIPT_TIMEOUT: 50m # only allow script to run for 50 minutes
script:
- long-running-process > output.txt # will be terminated after 50m
artifacts: # artifacts will have roughly ~10m to upload
paths:
- output.txt
when: on_failure # on_failure because script termination after a timeout is treated as a failure
```
### Ensuring `after_script` execution
For `after_script` to run successfully, the total of `RUNNER_SCRIPT_TIMEOUT` +
`RUNNER_AFTER_SCRIPT_TIMEOUT` must not exceed the job's configured timeout.
The following example shows how to configure timeouts to ensure `after_script` runs even when the main script times out:
```yaml
job-with-script-timeouts:
timeout: 5m
variables:
RUNNER_SCRIPT_TIMEOUT: 1m
RUNNER_AFTER_SCRIPT_TIMEOUT: 1m
script:
- echo "Starting build..."
- sleep 120 # Wait 2 minutes to trigger timeout. Script aborts after 1 minute due to RUNNER_SCRIPT_TIMEOUT.
- echo "Build finished."
after_script:
- echo "Starting Clean-up..."
- sleep 15 # Wait just a few seconds. Runs successfully because it's within RUNNER_AFTER_SCRIPT_TIMEOUT.
- echo "Clean-up finished."
```
The `script` is canceled by `RUNNER_SCRIPT_TIMEOUT`, but the `after_script` runs successfully because it takes 15 seconds,
which is less than both `RUNNER_AFTER_SCRIPT_TIMEOUT` and the job's `timeout` value.
## Protecting sensitive information
The security risks are greater when using instance runners as they are available by default to all groups and projects in a GitLab instance.
The runner executor and file system configuration affects security. Users with access to the runner host environment can view the code that runner executed and the runner authentication.
For example, users with access to the runner authentication token can clone
a runner and submit false jobs in a vector attack. For more information, see [Security Considerations](https://docs.gitlab.com/runner/security/).
## Configuring long polling
To reduce job queueing times and load on your GitLab server, configure [long polling](long_polling.md).
## Using instance runners in forked projects
When a project is forked, the job settings related to jobs are copied. If you have instance runners
configured for a project and a user forks that project, the instance runners serve jobs of this project.
Due to a [known issue](https://gitlab.com/gitlab-org/gitlab/-/issues/364303), if the runner settings
of the forked project does not match the new project namespace, the following message displays:
`An error occurred while forking the project. Please try again.`.
To work around this issue, ensure that the instance runner settings are consistent in the forked project and the new namespace.
- If instance runners are **enabled** on the forked project, then this should also be **enabled** on the new namespace.
- If instance runners are **disabled** on the forked project, then this should also be **disabled** on the new namespace.
## Reset the runner registration token for a project (deprecated)
{{< alert type="warning" >}}
The option to pass runner registration tokens and support for certain configuration arguments are
[deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/380872) in GitLab 15.6 and is planned for removal in GitLab 20.0.
Use the [runner creation workflow](https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token)
to generate an authentication token to register runners. This process provides full
traceability of runner ownership and enhances your runner fleet's security.
For more information, see
[Migrating to the new runner registration workflow](new_creation_workflow.md).
{{< /alert >}}
If you think that a registration token for a project was revealed, you should
reset it. A registration token can be used to register another runner for the project.
That new runner may then be used to obtain the values of secret variables or to clone project code.
To reset the registration token:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. To the right of **New project runner**, select the vertical ellipsis ({{< icon name="ellipsis_v" >}}).
1. Select **Reset registration token**.
1. Select **Reset token**.
After you reset the registration token, it is no longer valid and does not register
any new runners to the project. You should also update the registration token in tools
you use to provision and register new values.
## Authentication token security
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/30942) in GitLab 15.3 [with a flag](../../administration/feature_flags/_index.md) named `enforce_runner_token_expires_at`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/377902) in GitLab 15.5. Feature flag `enforce_runner_token_expires_at` removed.
{{< /history >}}
Each runner uses a [runner authentication token](../../api/runners.md#registration-and-authentication-tokens)
to connect to and authenticate with a GitLab instance.
To help prevent the token from being compromised, you can have the
token rotate automatically at specified intervals. When the tokens are rotated,
they are updated for each runner, regardless of the runner's status (`online` or `offline`).
No manual intervention should be required, and no running jobs should be affected.
For more information about token rotation, see
[Runner authentication token does not update when rotated](new_creation_workflow.md#runner-authentication-token-does-not-update-when-rotated).
If you need to manually update the runner authentication token, you can run a
command to [reset the token](https://docs.gitlab.com/runner/commands/#gitlab-runner-reset-token).
### Reset the runner configuration authentication token
If a runner's authentication token is exposed, an attacker could use it to [clone the runner](https://docs.gitlab.com/runner/security/#cloning-a-runner).
To reset the runner configuration authentication token:
1. Delete the runner:
- [Delete an instance runner](runners_scope.md#delete-instance-runners).
- [Delete a group runner](runners_scope.md#delete-a-group-runner).
- [Delete a project runner](runners_scope.md#delete-a-project-runner).
1. Create a new runner so that it is assigned a new runner authentication token:
- [Create an instance runner](runners_scope.md#create-an-instance-runner-with-a-runner-authentication-token).
- [Create a group runner](runners_scope.md#create-a-group-runner-with-a-runner-authentication-token).
- [Create a project runner](runners_scope.md#create-a-project-runner-with-a-runner-authentication-token).
1. Optional. To verify that the previous runner authentication token has been revoked, use the [Runners API](../../api/runners.md#verify-authentication-for-a-registered-runner).
To reset runner configuration authentication tokens, you can also use the [Runners API](../../api/runners.md).
### Automatically rotate runner authentication tokens
You can specify an interval to rotate runner authentication tokens.
Regularly rotating runner authentication tokens helps minimize the risk of unauthorized access to your GitLab instance through compromised tokens.
Prerequisites:
- Runners must use [GitLab Runner 15.3 or later](https://docs.gitlab.com/runner/#gitlab-runner-versions).
- You must be an administrator.
To automatically rotate runner authentication tokens:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > CI/CD**.
1. Expand **Continuous Integration and Deployment**.
1. Set a **Runners expiration** time for runners, leave empty for no expiration.
1. Select **Save changes**.
Before the interval expires, runners automatically request a new runner authentication token.
For more information about token rotation, see
[Runner authentication token does not update when rotated](new_creation_workflow.md#runner-authentication-token-does-not-update-when-rotated).
## Prevent runners from revealing sensitive information
To ensure runners don't reveal sensitive information, you can configure them to only run jobs
on [protected branches](../../user/project/repository/branches/protected.md), or jobs that have [protected tags](../../user/project/protected_tags.md).
Runners configured to run jobs on protected branches can
[optionally run jobs in merge request pipelines](../pipelines/merge_request_pipelines.md#control-access-to-protected-variables-and-runners).
### For an instance runner
Prerequisites:
- You must be an administrator.
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. To the right of the runner you want to protect, select **Edit** ({{< icon name="pencil" >}}).
1. Select the **Protected** checkbox.
1. Select **Save changes**.
### For a group runner
Prerequisites:
- You must have the Owner role for the group.
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. To the right of the runner you want to protect, select **Edit** ({{< icon name="pencil" >}}).
1. Select the **Protected** checkbox.
1. Select **Save changes**.
### For a project runner
Prerequisites:
- You must have the Owner role for the project.
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. To the right of the runner you want to protect, select **Edit** ({{< icon name="pencil" >}}).
1. Select the **Protected** checkbox.
1. Select **Save changes**.
## Control jobs that a runner can run
You can use [tags](../yaml/_index.md#tags) to control the jobs a runner can run.
For example, you can specify the `rails` tag for runners that have the dependencies to run
Rails test suites.
GitLab CI/CD tags are different to Git tags. GitLab CI/CD tags are associated with runners.
Git tags are associated with commits.
### For an instance runner
Prerequisites:
- You must be an administrator.
To control the jobs that an instance runner can run:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. To the right of the runner you want to edit, select **Edit** ({{< icon name="pencil" >}}).
1. Set the runner to run tagged or untagged jobs:
- To run tagged jobs, in the **Tags** field, enter the job tags separated with a comma. For example, `macos`, `rails`.
- To run untagged jobs, select the **Run untagged jobs** checkbox.
1. Select **Save changes**.
### For a group runner
Prerequisites:
- You must have the Owner role for the group.
To control the jobs that a group runner can run:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. To the right of the runner you want to edit, select **Edit** ({{< icon name="pencil" >}}).
1. Set the runner to run tagged or untagged jobs:
- To run tagged jobs, in the **Tags** field, enter the job tags separated with a comma. For example, `macos`, `ruby`.
- To run untagged jobs, select the **Run untagged jobs** checkbox.
1. Select **Save changes**.
### For a project runner
Prerequisites:
- You must have the Owner role for the project.
To control the jobs that a project runner can run:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. To the right of the runner you want to edit, select **Edit** ({{< icon name="pencil" >}}).
1. Set the runner to run tagged or untagged jobs:
- To run tagged jobs, in the **Tags** field, enter the job tags separated with a comma. For example, `macos`, `ruby`.
- To run untagged jobs, select the **Run untagged jobs** checkbox.
1. Select **Save changes**.
### How the runner uses tags
#### Runner runs only tagged jobs
The following examples illustrate the potential impact of the runner being set
to run only tagged jobs.
Example 1:
1. The runner is configured to run only tagged jobs and has the `docker` tag.
1. A job that has a `hello` tag is executed and stuck.
Example 2:
1. The runner is configured to run only tagged jobs and has the `docker` tag.
1. A job that has a `docker` tag is executed and run.
Example 3:
1. The runner is configured to run only tagged jobs and has the `docker` tag.
1. A job that has no tags defined is executed and stuck.
#### Runner is allowed to run untagged jobs
The following examples illustrate the potential impact of the runner being set
to run tagged and untagged jobs.
Example 1:
1. The runner is configured to run untagged jobs and has the `docker` tag.
1. A job that has no tags defined is executed and run.
1. A second job that has a `docker` tag defined is executed and run.
Example 2:
1. The runner is configured to run untagged jobs and has no tags defined.
1. A job that has no tags defined is executed and run.
1. A second job that has a `docker` tag defined is stuck.
#### A runner and a job have multiple tags
The selection logic that matches the job and runner is based on the list of `tags`
defined in the job.
The following examples illustrate the impact of a runner and a job having multiple tags. For a runner to be
selected to run a job, it must have all of the tags defined in the job script block.
Example 1:
1. The runner is configured with the tags `[docker, shell, gpu]`.
1. The job has the tags `[docker, shell, gpu]` and is executed and run.
Example 2:
1. The runner is configured with the tags `[docker, shell, gpu]`.
1. The job has the tags `[docker, shell,]` and is executed and run.
Example 3:
1. The runner is configured with the tags `[docker, shell]`.
1. The job has the tags `[docker, shell, gpu]` and is not executed.
### Use tags to run jobs on different platforms
You can use tags to run different jobs on different platforms. For
example, if you have an OS X runner with tag `osx` and a Windows runner with tag
`windows`, you can run a job on each platform.
Update the `tags` field in the `.gitlab-ci.yml`:
```yaml
windows job:
stage: build
tags:
- windows
script:
- echo Hello, %USERNAME%!
osx job:
stage: build
tags:
- osx
script:
- echo "Hello, $USER!"
```
### Use CI/CD variables in tags
In the `.gitlab-ci.yml` file, use [CI/CD variables](../variables/_index.md) with `tags` for dynamic runner selection:
```yaml
variables:
KUBERNETES_RUNNER: kubernetes
job:
tags:
- docker
- $KUBERNETES_RUNNER
script:
- echo "Hello runner selector feature"
```
## Configure runner behavior with variables
You can use [CI/CD variables](../variables/_index.md) to configure runner Git behavior
globally or for individual jobs:
- [`GIT_STRATEGY`](#git-strategy)
- [`GIT_SUBMODULE_STRATEGY`](#git-submodule-strategy)
- [`GIT_CHECKOUT`](#git-checkout)
- [`GIT_CLEAN_FLAGS`](#git-clean-flags)
- [`GIT_FETCH_EXTRA_FLAGS`](#git-fetch-extra-flags)
- [`GIT_SUBMODULE_UPDATE_FLAGS`](#git-submodule-update-flags)
- [`GIT_SUBMODULE_FORCE_HTTPS`](#rewrite-submodule-urls-to-https)
- [`GIT_DEPTH`](#shallow-cloning) (shallow cloning)
- [`GIT_SUBMODULE_DEPTH`](#git-submodule-depth)
- [`GIT_CLONE_PATH`](#custom-build-directories) (custom build directories)
- [`TRANSFER_METER_FREQUENCY`](#artifact-and-cache-settings) (artifact/cache meter update frequency)
- [`ARTIFACT_COMPRESSION_LEVEL`](#artifact-and-cache-settings) (artifact archiver compression level)
- [`CACHE_COMPRESSION_LEVEL`](#artifact-and-cache-settings) (cache archiver compression level)
- [`CACHE_REQUEST_TIMEOUT`](#artifact-and-cache-settings) (cache request timeout)
- [`RUNNER_SCRIPT_TIMEOUT`](#set-script-and-after_script-timeouts)
- [`RUNNER_AFTER_SCRIPT_TIMEOUT`](#set-script-and-after_script-timeouts)
- [`AFTER_SCRIPT_IGNORE_ERRORS`](#ignore-errors-in-after_script)
You can also use variables to configure how many times a runner
[attempts certain stages of job execution](#job-stages-attempts).
When using the Kubernetes executor, you can use variables to
[override Kubernetes CPU and memory allocations for requests and limits](https://docs.gitlab.com/runner/executors/kubernetes/#overwrite-container-resources).
### Git strategy
The `GIT_STRATEGY` variable configures how the build directory is prepared and
repository content is fetched. You can set this variable globally or per job
in the [`variables`](../yaml/_index.md#variables) section.
```yaml
variables:
GIT_STRATEGY: clone
```
Possible values are `clone`, `fetch`, `none`, and `empty`. If you do not specify a value,
jobs use the [project's pipeline setting](../pipelines/settings.md#choose-the-default-git-strategy).
`clone` is the slowest option. It clones the repository from scratch for every
job, ensuring that the local working copy is always pristine.
If an existing worktree is found, it is removed before cloning.
`fetch` is faster as it re-uses the local working copy (falling back to `clone`
if it does not exist). `git clean` is used to undo any changes made by the last
job, and `git fetch` is used to retrieve commits made after the last job ran.
However, `fetch` does require access to the previous worktree. This works
well when using the `shell` or `docker` executor because these
try to preserve worktrees and try to re-use them by default.
This has limitations when using the [Docker Machine executor](https://docs.gitlab.com/runner/executors/docker_machine.html).
A Git strategy of `none` also re-uses the local working copy, but skips all Git
operations usually done by GitLab. GitLab Runner pre-clone scripts are also skipped,
if present. This strategy could mean you need to add `fetch` and `checkout` commands
to [your `.gitlab-ci.yml` script](../yaml/_index.md#script).
It can be used for jobs that operate exclusively on artifacts, like a deployment job.
Git repository data may be present, but it's likely out of date. You should only
rely on files brought into the local working copy from cache or artifacts. Be
aware that cache and artifact files from previous pipelines might still be present.
Unlike `none`, the `empty` Git strategy deletes and then re-creates
a dedicated build directory before downloading cache or artifact files.
With this strategy, the GitLab Runner hook scripts are still run
(if provided) to allow for further behavior customization.
Use the `empty` Git strategy when:
- You do not need the repository data to be present.
- You want a clean, controlled, or customized starting state every time a job runs.
### Git submodule strategy
The `GIT_SUBMODULE_STRATEGY` variable is used to control if / how
[Git submodules](https://git-scm.com/book/en/v2/Git-Tools-Submodules) are included when fetching the code before a build. You can set them
globally or per-job in the [`variables`](../yaml/_index.md#variables) section.
The three possible values are `none`, `normal`, and `recursive`:
- `none` means that submodules are not included when fetching the project
code. This setting matches the default behavior in versions before 1.10.
- `normal` means that only the top-level submodules are included. It's
equivalent to:
```shell
git submodule sync
git submodule update --init
```
- `recursive` means that all submodules (including submodules of submodules)
are included. This feature needs Git v1.8.1 and later. When using a
GitLab Runner with an executor not based on Docker, make sure the Git version
meets that requirement. It's equivalent to:
```shell
git submodule sync --recursive
git submodule update --init --recursive
```
For this feature to work correctly, the submodules must be configured
(in `.gitmodules`) with either:
- the HTTP(S) URL of a publicly-accessible repository, or
- a relative path to another repository on the same GitLab server. See the
[Git submodules](git_submodules.md) documentation.
You can provide additional flags to control advanced behavior using [`GIT_SUBMODULE_UPDATE_FLAGS`](#git-submodule-update-flags).
### Git checkout
The `GIT_CHECKOUT` variable can be used when the `GIT_STRATEGY` is set to either
`clone` or `fetch` to specify whether a `git checkout` should be run. If not
specified, it defaults to true. You can set them globally or per-job in the
[`variables`](../yaml/_index.md#variables) section.
If set to `false`, the runner:
- when doing `fetch` - updates the repository and leaves the working copy on
the current revision,
- when doing `clone` - clones the repository and leaves the working copy on the
default branch.
If `GIT_CHECKOUT` is set to `true`, both `clone` and `fetch` work the same way.
The runner checks out the working copy of a revision related
to the CI pipeline:
```yaml
variables:
GIT_STRATEGY: clone
GIT_CHECKOUT: "false"
script:
- git checkout -B master origin/master
- git merge $CI_COMMIT_SHA
```
### Git clean flags
The `GIT_CLEAN_FLAGS` variable is used to control the default behavior of
`git clean` after checking out the sources. You can set it globally or per-job in the
[`variables`](../yaml/_index.md#variables) section.
`GIT_CLEAN_FLAGS` accepts all possible options of the [`git clean`](https://git-scm.com/docs/git-clean)
command.
`git clean` is disabled if `GIT_CHECKOUT: "false"` is specified.
If `GIT_CLEAN_FLAGS` is:
- Not specified, `git clean` flags default to `-ffdx`.
- Given the value `none`, `git clean` is not executed.
For example:
```yaml
variables:
GIT_CLEAN_FLAGS: -ffdx -e cache/
script:
- ls -al cache/
```
### Git fetch extra flags
Use the `GIT_FETCH_EXTRA_FLAGS` variable to control the behavior of
`git fetch`. You can set it globally or per-job in the [`variables`](../yaml/_index.md#variables) section.
`GIT_FETCH_EXTRA_FLAGS` accepts all options of the [`git fetch`](https://git-scm.com/docs/git-fetch) command. However, `GIT_FETCH_EXTRA_FLAGS` flags are appended after the default flags that can't be modified.
The default flags are:
- [`GIT_DEPTH`](#shallow-cloning).
- The list of [refspecs](https://git-scm.com/book/en/v2/Git-Internals-The-Refspec).
- A remote called `origin`.
If `GIT_FETCH_EXTRA_FLAGS` is:
- Not specified, `git fetch` flags default to `--prune --quiet` along with the default flags.
- Given the value `none`, `git fetch` is executed only with the default flags.
For example, the default flags are `--prune --quiet`, so you can make `git fetch` more verbose by overriding this with just `--prune`:
```yaml
variables:
GIT_FETCH_EXTRA_FLAGS: --prune
script:
- ls -al cache/
```
The previous configuration results in `git fetch` being called this way:
```shell
git fetch origin $REFSPECS --depth 20 --prune
```
Where `$REFSPECS` is a value provided to the runner internally by GitLab.
### Sync or exclude specific submodules from CI jobs
Use the `GIT_SUBMODULE_PATHS` variable to control which submodules have to be synced or updated.
You can set it globally or per-job in the [`variables`](../yaml/_index.md#variables) section.
The path syntax is the same as [`git submodule`](https://git-scm.com/docs/git-submodule#Documentation/git-submodule.txt-ltpathgt82308203):
- To sync and update specific paths:
```yaml
variables:
GIT_SUBMODULE_PATHS: submoduleA submoduleB
```
- To exclude specific paths:
```yaml
variables:
GIT_SUBMODULE_PATHS: ":(exclude)submoduleA :(exclude)submoduleB"
```
{{< alert type="warning" >}}
Git ignores nested paths. To ignore a nested submodule, exclude
the parent submodule and then manually clone it in the job's scripts. For example,
`git clone <repo> --recurse-submodules=':(exclude)nested-submodule'`. Make sure
to wrap the string in single quotes so the YAML can be parsed successfully.
{{< /alert >}}
### Git submodule update flags
Use the `GIT_SUBMODULE_UPDATE_FLAGS` variable to control the behavior of `git submodule update`
when [`GIT_SUBMODULE_STRATEGY`](#git-submodule-strategy) is set to either `normal` or `recursive`.
You can set it globally or per-job in the [`variables`](../yaml/_index.md#variables) section.
`GIT_SUBMODULE_UPDATE_FLAGS` accepts all options of the
[`git submodule update`](https://git-scm.com/docs/git-submodule#Documentation/git-submodule.txt-update--init--remote-N--no-fetch--no-recommend-shallow-f--force--checkout--rebase--merge--referenceltrepositorygt--depthltdepthgt--recursive--jobsltngt--no-single-branch--ltpathgt82308203)
subcommand. However, `GIT_SUBMODULE_UPDATE_FLAGS` flags are appended after a few default flags:
- `--init`, if [`GIT_SUBMODULE_STRATEGY`](#git-submodule-strategy) was set to `normal` or `recursive`.
- `--recursive`, if [`GIT_SUBMODULE_STRATEGY`](#git-submodule-strategy) was set to `recursive`.
- `GIT_DEPTH`. See the default value in the [shallow cloning](#shallow-cloning) section.
Git honors the last occurrence of a flag in the list of arguments, so manually
providing them in `GIT_SUBMODULE_UPDATE_FLAGS` overrides these default flags.
For example, you can use this variable to:
- Fetch the latest remote `HEAD` instead of the tracked commit in the
repository (default) to automatically update all submodules with the
`--remote` flag.
- Speed up the checkout by fetching submodules in multiple parallel jobs with
the `--jobs 4` flag.
```yaml
variables:
GIT_SUBMODULE_STRATEGY: recursive
GIT_SUBMODULE_UPDATE_FLAGS: --remote --jobs 4
script:
- ls -al .git/modules/
```
The previous configuration results in `git submodule update` being called this way:
```shell
git submodule update --init --depth 20 --recursive --remote --jobs 4
```
{{< alert type="warning" >}}
You should be aware of the implications for the security, stability, and
reproducibility of your builds when using the `--remote` flag. In most cases,
it is better to explicitly track submodule commits as designed, and update them
using an auto-remediation/dependency bot.
The `--remote` flag is not required to check out submodules at their committed
revisions. Use this flag only when you want to automatically update submodules
to their latest remote versions.
{{< /alert >}}
The behavior of `--remote` depends on your Git version.
If the branch specified in your superproject's `.gitmodules` file is different from the
default branch of the submodule repository, some Git versions will fail with this error:
`fatal: Unable to find refs/remotes/origin/<branch> revision in submodule path '<submodule-path>'`
The runner implements a "best effort" fallback that attempts to
pull remote refs when the submodule update fails.
If this fallback does not work with your Git version, try one of the following
workarounds:
- Update the submodule repository's default branch to match the branch set in
`.gitmodules` in the superproject.
- Set `GIT_SUBMODULE_DEPTH` to `0`.
- Update the submodules separately and remove the `--remote` flag from
`GIT_SUBMODULE_UPDATE_FLAGS`.
### Rewrite submodule URLs to HTTPS
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3198) in GitLab Runner 15.11.
{{< /history >}}
Use the `GIT_SUBMODULE_FORCE_HTTPS` variable to force a rewrite of all Git and SSH submodule URLs to HTTPS.
You can clone submodules that use absolute URLs on the same GitLab instance, even if they were
configured with a Git or SSH protocol.
```yaml
variables:
GIT_SUBMODULE_STRATEGY: recursive
GIT_SUBMODULE_FORCE_HTTPS: "true"
```
When enabled, GitLab Runner uses a [CI/CD job token](../jobs/ci_job_token.md) to clone the submodules.
The token uses the permissions of the user executing the job and does not require SSH credentials.
### Shallow cloning
You can specify the depth of fetching and cloning using `GIT_DEPTH`.
`GIT_DEPTH` does a shallow clone of the repository and can significantly speed up cloning.
It can be helpful for repositories with a large number of commits or old, large binaries. The value is
passed to `git fetch` and `git clone`.
Newly-created projects automatically have a
[default `git depth` value of `20`](../pipelines/settings.md#limit-the-number-of-changes-fetched-during-clone).
If you use a depth of `1` and have a queue of jobs or retry
jobs, jobs may fail.
Git fetching and cloning is based on a ref, such as a branch name, so runners
can't clone a specific commit SHA. If multiple jobs are in the queue, or
you retry an old job, the commit to be tested must be in the cloned
Git history. Setting too small a value for `GIT_DEPTH` can make
it impossible to run these old commits and `unresolved reference` is displayed in
job logs. You should then reconsider changing `GIT_DEPTH` to a higher value.
Jobs that rely on `git describe` may not work correctly when `GIT_DEPTH` is
set because only part of the Git history is present.
To fetch or clone only the last 3 commits:
```yaml
variables:
GIT_DEPTH: "3"
```
You can set it globally or per-job in the [`variables`](../yaml/_index.md#variables) section.
### Git submodule depth
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3651) in GitLab Runner 15.5.
{{< /history >}}
Use the `GIT_SUBMODULE_DEPTH` variable to specify the depth of fetching and cloning submodules
when [`GIT_SUBMODULE_STRATEGY`](#git-submodule-strategy) is set to either `normal` or `recursive`.
You can set it globally or for a specific job in the [`variables`](../yaml/_index.md#variables) section.
When you set the `GIT_SUBMODULE_DEPTH` variable, it overwrites the [`GIT_DEPTH`](#shallow-cloning) setting
for the submodules only.
To fetch or clone only the last 3 commits:
```yaml
variables:
GIT_SUBMODULE_DEPTH: 3
```
### Custom build directories
By default, GitLab Runner clones the repository in a unique subpath of the
`$CI_BUILDS_DIR` directory. However, your project might require the code in a
specific directory (Go projects, for example). In that case, you can specify
the `GIT_CLONE_PATH` variable to tell the runner the directory to clone the
repository in:
```yaml
variables:
GIT_CLONE_PATH: $CI_BUILDS_DIR/project-name
test:
script:
- pwd
```
The `GIT_CLONE_PATH` must always be inside `$CI_BUILDS_DIR`. The directory set in `$CI_BUILDS_DIR`
is dependent on executor and configuration of [runners.builds_dir](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runners-section)
setting.
This can only be used when `custom_build_dir` is enabled in the
[runner's configuration](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runnerscustom_build_dir-section).
#### Handling concurrency
An executor that uses a concurrency greater than `1` might lead
to failures. Multiple jobs might be working on the same directory if the `builds_dir`
is shared between jobs.
The runner does not try to prevent this situation. It's up to the administrator
and developers to comply with the requirements of runner configuration.
To avoid this scenario, you can use a unique path in `$CI_BUILDS_DIR`, because runner
exposes two additional variables that provide a unique `ID` of concurrency:
- `$CI_CONCURRENT_ID`: Unique ID for all jobs running in the given executor.
- `$CI_CONCURRENT_PROJECT_ID`: Unique ID for all jobs running in the given executor and project.
The most stable configuration that should work well in any scenario and on any executor
is to use `$CI_CONCURRENT_ID` in the `GIT_CLONE_PATH`. For example:
```yaml
variables:
GIT_CLONE_PATH: $CI_BUILDS_DIR/$CI_CONCURRENT_ID/project-name
test:
script:
- pwd -P
```
The `$CI_CONCURRENT_PROJECT_ID` should be used in conjunction with `$CI_PROJECT_PATH`.
`$CI_PROJECT_PATH` provides a path of a repository in the `group/subgroup/project` format.
For example:
```yaml
variables:
GIT_CLONE_PATH: $CI_BUILDS_DIR/$CI_CONCURRENT_ID/$CI_PROJECT_PATH
test:
script:
- pwd -P
```
#### Nested paths
The value of `GIT_CLONE_PATH` expands once. You cannot nest variables
in this value.
For example, you define the following variables in your
`.gitlab-ci.yml` file:
```yaml
variables:
GOPATH: $CI_BUILDS_DIR/go
GIT_CLONE_PATH: $GOPATH/src/namespace/project
```
The value of `GIT_CLONE_PATH` is expanded once into
`$CI_BUILDS_DIR/go/src/namespace/project`, and results in failure
because `$CI_BUILDS_DIR` is not expanded.
### Ignore errors in `after_script`
You can use [`after_script`](../yaml/_index.md#after_script) in a job to define an array of commands
that should run after the job's `before_script` and `script` sections. The `after_script` commands
run regardless of the script termination status (failure or success).
By default, GitLab Runner ignores any errors that happen when `after_script` runs.
To set the job to fail immediately on errors when `after_script` runs, set the
`AFTER_SCRIPT_IGNORE_ERRORS` CI/CD variable to `false`. For example:
```yaml
variables:
AFTER_SCRIPT_IGNORE_ERRORS: false
```
### Job stages attempts
You can set the number of attempts that the running job tries to execute
the following stages:
| Variable | Description |
|---------------------------------|-------------|
| `ARTIFACT_DOWNLOAD_ATTEMPTS` | Number of attempts to download artifacts running a job |
| `EXECUTOR_JOB_SECTION_ATTEMPTS` | The number of attempts to run a section in a job after a [`No Such Container`](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/4450) error ([Docker executor](https://docs.gitlab.com/runner/executors/docker.html) only). |
| `GET_SOURCES_ATTEMPTS` | Number of attempts to fetch sources running a job |
| `RESTORE_CACHE_ATTEMPTS` | Number of attempts to restore the cache running a job |
The default is one single attempt.
Example:
```yaml
variables:
GET_SOURCES_ATTEMPTS: 3
```
You can set them globally or per-job in the [`variables`](../yaml/_index.md#variables) section.
## System calls not available on GitLab.com instance runners
GitLab.com instance runners run on CoreOS. This means that you cannot use some system calls, like `getlogin`, from the C standard library.
## Artifact and cache settings
Artifact and cache settings control the compression ratio of artifacts and caches.
Use these settings to specify the size of the archive produced by a job.
- On a slow network, uploads might be faster for smaller archives.
- On a fast network where bandwidth and storage are not a concern, uploads might be faster using the fastest compression ratio, despite the archive produced being larger.
For [GitLab Pages](../../user/project/pages/_index.md) to serve
[HTTP Range requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests), artifacts
should use the `ARTIFACT_COMPRESSION_LEVEL: fastest` setting, as only uncompressed zip archives
support this feature.
A meter can be enabled to provide the rate of transfer for uploads and downloads.
You can set a maximum time for cache upload and download with the `CACHE_REQUEST_TIMEOUT` setting.
Use this setting when slow cache uploads substantially increase the duration of your job.
```yaml
variables:
# output upload and download progress every 2 seconds
TRANSFER_METER_FREQUENCY: "2s"
# Use fast compression for artifacts, resulting in larger archives
ARTIFACT_COMPRESSION_LEVEL: "fast"
# Use no compression for caches
CACHE_COMPRESSION_LEVEL: "fastest"
# Set maximum duration of cache upload and download
CACHE_REQUEST_TIMEOUT: 5
```
| Variable | Description |
|------------------------------|-------------|
| `TRANSFER_METER_FREQUENCY` | Specify how often to print the meter's transfer rate. It can be set to a duration (for example, `1s` or `1m30s`). A duration of `0` disables the meter (default). When a value is set, the pipeline shows a progress meter for artifact and cache uploads and downloads. |
| `ARTIFACT_COMPRESSION_LEVEL` | To adjust compression ratio, set to `fastest`, `fast`, `default`, `slow`, or `slowest`. This setting works with the Fastzip archiver only, so the GitLab Runner feature flag [`FF_USE_FASTZIP`](https://docs.gitlab.com/runner/configuration/feature-flags.html#available-feature-flags) must also be enabled. |
| `CACHE_COMPRESSION_LEVEL` | To adjust compression ratio, set to `fastest`, `fast`, `default`, `slow`, or `slowest`. This setting works with the Fastzip archiver only, so the GitLab Runner feature flag [`FF_USE_FASTZIP`](https://docs.gitlab.com/runner/configuration/feature-flags.html#available-feature-flags) must also be enabled. |
| `CACHE_REQUEST_TIMEOUT` | Configure the maximum duration of cache upload and download operations for a single job in minutes. Default is `10` minutes. |
## Artifact provenance metadata
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/28940) in GitLab Runner 15.1.
{{< /history >}}
Runners can generate an [SLSA Provenance](https://slsa.dev/spec/v1.0/provenance)
and produce an [SLSA Statement](https://slsa.dev/spec/v1.0/attestation-model#model-and-terminology)
that binds the provenance to all build artifacts.
The statement is called artifact provenance metadata.
To enable artifact provenance metadata, set the `RUNNER_GENERATE_ARTIFACTS_METADATA` environment
variable to `true`. You can set the variable globally or for individual jobs:
```yaml
variables:
RUNNER_GENERATE_ARTIFACTS_METADATA: "true"
job1:
variables:
RUNNER_GENERATE_ARTIFACTS_METADATA: "true"
```
The metadata renders in a plain text `.json` file stored with the artifact. The
filename is `{ARTIFACT_NAME}-metadata.json`. `ARTIFACT_NAME` is the
[name for the artifact](../jobs/job_artifacts.md#with-an-explicitly-defined-artifact-name)
defined in the `.gitlab-ci.yml` file. If the name is not defined, the default filename is
`artifacts-metadata.json`.
### Provenance metadata format
The artifact provenance metadata is generated in the
[in-toto v0.1 Statement](https://github.com/in-toto/attestation/tree/v0.1.0/spec#statement) format.
It contains a provenance predicate generated in the [SLSA 1.0 Provenance](https://slsa.dev/spec/v1.0/provenance) format.
These fields are populated by default:
| Field | Value |
|-------------------------------------------------------------------|-------|
| `_type` | `https://in-toto.io/Statement/v0.1` |
| `subject` | Set of software artifacts the metadata applies to |
| `subject[].name` | The filename of the artifact. |
| `subject[].sha256` | The artifact's `sha256` checksum. |
| `predicateType` | `https://slsa.dev/provenance/v1` |
| `predicate.buildDefinition.buildType` | `https://gitlab.com/gitlab-org/gitlab-runner/-/blob/{GITLAB_RUNNER_VERSION}/PROVENANCE.md`. For example, v15.0.0 |
| `predicate.runDetails.builder.id` | A URI pointing to the runner details page, for example, `https://gitlab.com/gitlab-com/www-gitlab-com/-/runners/3785264`. |
| `predicate.buildDefinition.externalParameters` | The names of any CI/CD or environment variables available during the build command execution. The value is always represented as an empty string to protect secrets. |
| `predicate.buildDefinition.externalParameters.source` | The URL of the project. |
| `predicate.buildDefinition.externalParameters.entryPoint` | The name of the CI/CD job that triggered the build. |
| `predicate.buildDefinition.internalParameters.name` | The name of the runner. |
| `predicate.buildDefinition.internalParameters.executor` | The runner executor. |
| `predicate.buildDefinition.internalParameters.architecture` | The architecture on which the CI/CD job is run. |
| `predicate.buildDefinition.internalParameters.job` | The ID of the CI/CD job that triggered the build. |
| `predicate.buildDefinition.resolvedDependencies[0].uri` | The URL of the project. |
| `predicate.buildDefinition.resolvedDependencies[0].digest.sha256` | The commit revision of the project. |
| `predicate.runDetails.metadata.invocationID` | The ID of the CI/CD job that triggered the build. |
| `predicate.runDetails.metadata.startedOn` | The time when the build was started. This field is `RFC3339` formatted. |
| `predicate.runDetails.metadata.finishedOn` | The time when the build ended. Because metadata generation happens during the build, this time is slightly earlier than the one reported in GitLab. This field is `RFC3339` formatted. |
A provenance statement should look similar to this example:
```json
{
"_type": "https://in-toto.io/Statement/v0.1",
"predicateType": "https://slsa.dev/provenance/v1",
"subject": [
{
"name": "x.txt",
"digest": {
"sha256": "ac097997b6ec7de591d4f11315e4aa112e515bb5d3c52160d0c571298196ea8b"
}
},
{
"name": "y.txt",
"digest": {
"sha256": "9eb634f80da849d828fcf42740d823568c49e8d7b532886134f9086246b1fdf3"
}
}
],
"predicate": {
"buildDefinition": {
"buildType": "https://gitlab.com/gitlab-org/gitlab-runner/-/blob/2147fb44/PROVENANCE.md",
"externalParameters": {
"CI": "",
"CI_API_GRAPHQL_URL": "",
"CI_API_V4_URL": "",
"CI_COMMIT_AUTHOR": "",
"CI_COMMIT_BEFORE_SHA": "",
"CI_COMMIT_BRANCH": "",
"CI_COMMIT_DESCRIPTION": "",
"CI_COMMIT_MESSAGE": "",
[... additional environmental variables ...]
"entryPoint": "build-job",
"source": "https://gitlab.com/my-group/my-project/test-runner-generated-slsa-statement"
},
"internalParameters": {
"architecture": "amd64",
"executor": "docker+machine",
"job": "10340684631",
"name": "green-4.saas-linux-small-amd64.runners-manager.gitlab.com/default"
},
"resolvedDependencies": [
{
"uri": "https://gitlab.com/my-group/my-project/test-runner-generated-slsa-statement",
"digest": {
"sha256": "bdd2ecda9ef57b129c88617a0215afc9fb223521"
}
}
]
},
"runDetails": {
"builder": {
"id": "https://gitlab.com/my-group/my-project/test-runner-generated-slsa-statement/-/runners/12270857",
"version": {
"gitlab-runner": "2147fb44"
}
},
"metadata": {
"invocationID": "10340684631",
"startedOn": "2025-06-13T07:25:13Z",
"finishedOn": "2025-06-13T07:25:40Z"
}
}
}
}
```
## Staging directory
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3403) in GitLab Runner 15.0.
{{< /history >}}
If you do not want to archive cache and artifacts in the system's default temporary directory, you can specify a different directory.
You might need to change the directory if your system's default temporary path has constraints.
If you use a fast disk for the directory location, it can also improve performance.
To change the directory, set `ARCHIVER_STAGING_DIR` as a variable in your CI job, or use a runner variable when you register the runner (`gitlab register --env ARCHIVER_STAGING_DIR=<dir>`).
The directory you specify is used as the location for downloading artifacts prior to extraction. If the `fastzip` archiver is
used, this location is also used as scratch space when archiving.
## Configure `fastzip` to improve performance
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3130) in GitLab Runner 15.0.
{{< /history >}}
To tune `fastzip`, ensure the [`FF_USE_FASTZIP`](https://docs.gitlab.com/runner/configuration/feature-flags.html#available-feature-flags) flag is enabled.
Then use any of the following environment variables.
| Variable | Description |
|---------------------------------|-------------|
| `FASTZIP_ARCHIVER_CONCURRENCY` | The number of files to be concurrently compressed. Default is the number of CPUs available. |
| `FASTZIP_ARCHIVER_BUFFER_SIZE` | The buffer size allocated per concurrency for each file. Data exceeding this number moves to scratch space. Default is 2 MiB. |
| `FASTZIP_EXTRACTOR_CONCURRENCY` | The number of files to be concurrency decompressed. Default is the number of CPUs available. |
Files in a zip archive are appended sequentially. This makes concurrent compression challenging. `fastzip` works around
this limitation by compressing files concurrently to disk first, and then copying the result back to zip archive
sequentially.
To avoid writing to disk and reading the contents back for smaller files, a small buffer per concurrency is used. This setting
can be controlled with `FASTZIP_ARCHIVER_BUFFER_SIZE`. The default size for this buffer is 2 MiB, therefore, a
concurrency of 16 allocates 32 MiB. Data that exceeds the buffer size is written to and read back from disk.
Therefore, using no buffer, `FASTZIP_ARCHIVER_BUFFER_SIZE: 0`, and only scratch space is a valid option.
`FASTZIP_ARCHIVER_CONCURRENCY` controls how many files are compressed concurrency. As previously mentioned, this setting
therefore can increase how much memory is being used. It can also increase the temporary data written to the scratch space.
The default is the number of CPUs available, but given the memory ramifications, this may not always be the best
setting.
`FASTZIP_EXTRACTOR_CONCURRENCY` controls how many files are decompressed at once. Files from a zip archive can natively
be read from concurrency, so no additional memory is allocated in addition to what the extractor requires. This
defaults to the number of CPUs available.
|
---
stage: Verify
group: Runner
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Set timeouts, protect sensitive information, control behavior with tags
and variables, and configure artifact and cache settings of your GitLab Runner.
title: Configuring runners
breadcrumbs:
- doc
- ci
- runners
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
This document describes how to configure runners in the GitLab UI.
If you need to configure runners on the machine where you installed GitLab Runner, see
[the GitLab Runner documentation](https://docs.gitlab.com/runner/configuration/).
## Set the maximum job timeout
You can specify a maximum job timeout for each runner to prevent projects
with longer job timeouts from using the runner. The maximum job timeout is
used if it is shorter than the job timeout defined in the project.
To set a runner's maximum timeout, set the `maximum_timeout` parameter in the REST API endpoint [`PUT /runners/:id`](../../api/runners.md#update-runners-details).
### For an instance runner
Prerequisites:
- You must be an administrator.
You can override the job timeout for instance runners on GitLab Self-Managed.
On GitLab.com, you cannot override the job timeout for GitLab hosted instance runners and must use the [project defined timeout](../pipelines/settings.md#set-a-limit-for-how-long-jobs-can-run) instead.
To set the maximum job timeout:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. To the right of the runner, you want to edit, select **Edit** ({{< icon name="pencil" >}}).
1. In the **Maximum job timeout** field, enter a value in seconds. The minimum value is 600 seconds (10 minutes).
1. Select **Save changes**.
### For a group runner
Prerequisites:
- You must have the Owner role for the group.
To set the maximum job timeout:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. To the right of the runner you want to edit, select **Edit** ({{< icon name="pencil" >}}).
1. In the **Maximum job timeout** field, enter a value in seconds. The minimum value is 600 seconds (10 minutes).
1. Select **Save changes**.
### For a project runner
Prerequisites:
- You must have the Owner role for the project.
To set the maximum job timeout:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. To the right of the runner you want to edit, select **Edit** ({{< icon name="pencil" >}}).
1. In the **Maximum job timeout** field, enter a value in seconds. The minimum value is 600 seconds (10 minutes). If not defined, the [job timeout for the project](../pipelines/settings.md#set-a-limit-for-how-long-jobs-can-run) is used instead.
1. Select **Save changes**.
## How maximum job timeout works
**Example 1 - Runner timeout bigger than project timeout**
1. You set the `maximum_timeout` parameter for a runner to 24 hours.
1. You set the **Maximum job timeout** for a project to **2 hours**.
1. You start a job.
1. The job, if running longer, times out after **2 hours**.
**Example 2 - Runner timeout not configured**
1. You remove the `maximum_timeout` parameter configuration from a runner.
1. You set the **Maximum job timeout** for a project to **2 hours**.
1. You start a job.
1. The job, if running longer, times out after **2 hours**.
**Example 3 - Runner timeout smaller than project timeout**
1. You set the `maximum_timeout` parameter for a runner to **30 minutes**.
1. You set the **Maximum job timeout** for a project to 2 hours.
1. You start a job.
1. The job, if running longer, times out after **30 minutes**.
## Set `script` and `after_script` timeouts
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/4335) in GitLab Runner 16.4.
{{< /history >}}
To control the amount of time `script` and `after_script` runs before it terminates, specify a timeout value in the `.gitlab-ci.yml` file.
For example, you can specify a timeout to terminate a long-running `script` early. This ensures artifacts and caches can still be uploaded
before the [job timeout](../pipelines/settings.md#set-a-limit-for-how-long-jobs-can-run) is exceeded.
The timeout values for `script` and `after_script` must be less than the job timeout.
- To set a timeout for `script`, use the job variable `RUNNER_SCRIPT_TIMEOUT`.
- To set a timeout for `after_script`, and override the default of 5 minutes, use the job variable `RUNNER_AFTER_SCRIPT_TIMEOUT`.
Both of these variables accept [Go's duration format](https://pkg.go.dev/time#ParseDuration) (for example, `40s`, `1h20m`, `2h` `4h30m30s`).
For example:
```yaml
job-with-script-timeouts:
variables:
RUNNER_SCRIPT_TIMEOUT: 15m
RUNNER_AFTER_SCRIPT_TIMEOUT: 10m
script:
- "I am allowed to run for min(15m, remaining job timeout)."
after_script:
- "I am allowed to run for min(10m, remaining job timeout)."
job-artifact-upload-on-timeout:
timeout: 1h # set job timeout to 1 hour
variables:
RUNNER_SCRIPT_TIMEOUT: 50m # only allow script to run for 50 minutes
script:
- long-running-process > output.txt # will be terminated after 50m
artifacts: # artifacts will have roughly ~10m to upload
paths:
- output.txt
when: on_failure # on_failure because script termination after a timeout is treated as a failure
```
### Ensuring `after_script` execution
For `after_script` to run successfully, the total of `RUNNER_SCRIPT_TIMEOUT` +
`RUNNER_AFTER_SCRIPT_TIMEOUT` must not exceed the job's configured timeout.
The following example shows how to configure timeouts to ensure `after_script` runs even when the main script times out:
```yaml
job-with-script-timeouts:
timeout: 5m
variables:
RUNNER_SCRIPT_TIMEOUT: 1m
RUNNER_AFTER_SCRIPT_TIMEOUT: 1m
script:
- echo "Starting build..."
- sleep 120 # Wait 2 minutes to trigger timeout. Script aborts after 1 minute due to RUNNER_SCRIPT_TIMEOUT.
- echo "Build finished."
after_script:
- echo "Starting Clean-up..."
- sleep 15 # Wait just a few seconds. Runs successfully because it's within RUNNER_AFTER_SCRIPT_TIMEOUT.
- echo "Clean-up finished."
```
The `script` is canceled by `RUNNER_SCRIPT_TIMEOUT`, but the `after_script` runs successfully because it takes 15 seconds,
which is less than both `RUNNER_AFTER_SCRIPT_TIMEOUT` and the job's `timeout` value.
## Protecting sensitive information
The security risks are greater when using instance runners as they are available by default to all groups and projects in a GitLab instance.
The runner executor and file system configuration affects security. Users with access to the runner host environment can view the code that runner executed and the runner authentication.
For example, users with access to the runner authentication token can clone
a runner and submit false jobs in a vector attack. For more information, see [Security Considerations](https://docs.gitlab.com/runner/security/).
## Configuring long polling
To reduce job queueing times and load on your GitLab server, configure [long polling](long_polling.md).
## Using instance runners in forked projects
When a project is forked, the job settings related to jobs are copied. If you have instance runners
configured for a project and a user forks that project, the instance runners serve jobs of this project.
Due to a [known issue](https://gitlab.com/gitlab-org/gitlab/-/issues/364303), if the runner settings
of the forked project does not match the new project namespace, the following message displays:
`An error occurred while forking the project. Please try again.`.
To work around this issue, ensure that the instance runner settings are consistent in the forked project and the new namespace.
- If instance runners are **enabled** on the forked project, then this should also be **enabled** on the new namespace.
- If instance runners are **disabled** on the forked project, then this should also be **disabled** on the new namespace.
## Reset the runner registration token for a project (deprecated)
{{< alert type="warning" >}}
The option to pass runner registration tokens and support for certain configuration arguments are
[deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/380872) in GitLab 15.6 and is planned for removal in GitLab 20.0.
Use the [runner creation workflow](https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token)
to generate an authentication token to register runners. This process provides full
traceability of runner ownership and enhances your runner fleet's security.
For more information, see
[Migrating to the new runner registration workflow](new_creation_workflow.md).
{{< /alert >}}
If you think that a registration token for a project was revealed, you should
reset it. A registration token can be used to register another runner for the project.
That new runner may then be used to obtain the values of secret variables or to clone project code.
To reset the registration token:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. To the right of **New project runner**, select the vertical ellipsis ({{< icon name="ellipsis_v" >}}).
1. Select **Reset registration token**.
1. Select **Reset token**.
After you reset the registration token, it is no longer valid and does not register
any new runners to the project. You should also update the registration token in tools
you use to provision and register new values.
## Authentication token security
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/30942) in GitLab 15.3 [with a flag](../../administration/feature_flags/_index.md) named `enforce_runner_token_expires_at`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/377902) in GitLab 15.5. Feature flag `enforce_runner_token_expires_at` removed.
{{< /history >}}
Each runner uses a [runner authentication token](../../api/runners.md#registration-and-authentication-tokens)
to connect to and authenticate with a GitLab instance.
To help prevent the token from being compromised, you can have the
token rotate automatically at specified intervals. When the tokens are rotated,
they are updated for each runner, regardless of the runner's status (`online` or `offline`).
No manual intervention should be required, and no running jobs should be affected.
For more information about token rotation, see
[Runner authentication token does not update when rotated](new_creation_workflow.md#runner-authentication-token-does-not-update-when-rotated).
If you need to manually update the runner authentication token, you can run a
command to [reset the token](https://docs.gitlab.com/runner/commands/#gitlab-runner-reset-token).
### Reset the runner configuration authentication token
If a runner's authentication token is exposed, an attacker could use it to [clone the runner](https://docs.gitlab.com/runner/security/#cloning-a-runner).
To reset the runner configuration authentication token:
1. Delete the runner:
- [Delete an instance runner](runners_scope.md#delete-instance-runners).
- [Delete a group runner](runners_scope.md#delete-a-group-runner).
- [Delete a project runner](runners_scope.md#delete-a-project-runner).
1. Create a new runner so that it is assigned a new runner authentication token:
- [Create an instance runner](runners_scope.md#create-an-instance-runner-with-a-runner-authentication-token).
- [Create a group runner](runners_scope.md#create-a-group-runner-with-a-runner-authentication-token).
- [Create a project runner](runners_scope.md#create-a-project-runner-with-a-runner-authentication-token).
1. Optional. To verify that the previous runner authentication token has been revoked, use the [Runners API](../../api/runners.md#verify-authentication-for-a-registered-runner).
To reset runner configuration authentication tokens, you can also use the [Runners API](../../api/runners.md).
### Automatically rotate runner authentication tokens
You can specify an interval to rotate runner authentication tokens.
Regularly rotating runner authentication tokens helps minimize the risk of unauthorized access to your GitLab instance through compromised tokens.
Prerequisites:
- Runners must use [GitLab Runner 15.3 or later](https://docs.gitlab.com/runner/#gitlab-runner-versions).
- You must be an administrator.
To automatically rotate runner authentication tokens:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Settings > CI/CD**.
1. Expand **Continuous Integration and Deployment**.
1. Set a **Runners expiration** time for runners, leave empty for no expiration.
1. Select **Save changes**.
Before the interval expires, runners automatically request a new runner authentication token.
For more information about token rotation, see
[Runner authentication token does not update when rotated](new_creation_workflow.md#runner-authentication-token-does-not-update-when-rotated).
## Prevent runners from revealing sensitive information
To ensure runners don't reveal sensitive information, you can configure them to only run jobs
on [protected branches](../../user/project/repository/branches/protected.md), or jobs that have [protected tags](../../user/project/protected_tags.md).
Runners configured to run jobs on protected branches can
[optionally run jobs in merge request pipelines](../pipelines/merge_request_pipelines.md#control-access-to-protected-variables-and-runners).
### For an instance runner
Prerequisites:
- You must be an administrator.
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. To the right of the runner you want to protect, select **Edit** ({{< icon name="pencil" >}}).
1. Select the **Protected** checkbox.
1. Select **Save changes**.
### For a group runner
Prerequisites:
- You must have the Owner role for the group.
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. To the right of the runner you want to protect, select **Edit** ({{< icon name="pencil" >}}).
1. Select the **Protected** checkbox.
1. Select **Save changes**.
### For a project runner
Prerequisites:
- You must have the Owner role for the project.
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. To the right of the runner you want to protect, select **Edit** ({{< icon name="pencil" >}}).
1. Select the **Protected** checkbox.
1. Select **Save changes**.
## Control jobs that a runner can run
You can use [tags](../yaml/_index.md#tags) to control the jobs a runner can run.
For example, you can specify the `rails` tag for runners that have the dependencies to run
Rails test suites.
GitLab CI/CD tags are different to Git tags. GitLab CI/CD tags are associated with runners.
Git tags are associated with commits.
### For an instance runner
Prerequisites:
- You must be an administrator.
To control the jobs that an instance runner can run:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. To the right of the runner you want to edit, select **Edit** ({{< icon name="pencil" >}}).
1. Set the runner to run tagged or untagged jobs:
- To run tagged jobs, in the **Tags** field, enter the job tags separated with a comma. For example, `macos`, `rails`.
- To run untagged jobs, select the **Run untagged jobs** checkbox.
1. Select **Save changes**.
### For a group runner
Prerequisites:
- You must have the Owner role for the group.
To control the jobs that a group runner can run:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. To the right of the runner you want to edit, select **Edit** ({{< icon name="pencil" >}}).
1. Set the runner to run tagged or untagged jobs:
- To run tagged jobs, in the **Tags** field, enter the job tags separated with a comma. For example, `macos`, `ruby`.
- To run untagged jobs, select the **Run untagged jobs** checkbox.
1. Select **Save changes**.
### For a project runner
Prerequisites:
- You must have the Owner role for the project.
To control the jobs that a project runner can run:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. To the right of the runner you want to edit, select **Edit** ({{< icon name="pencil" >}}).
1. Set the runner to run tagged or untagged jobs:
- To run tagged jobs, in the **Tags** field, enter the job tags separated with a comma. For example, `macos`, `ruby`.
- To run untagged jobs, select the **Run untagged jobs** checkbox.
1. Select **Save changes**.
### How the runner uses tags
#### Runner runs only tagged jobs
The following examples illustrate the potential impact of the runner being set
to run only tagged jobs.
Example 1:
1. The runner is configured to run only tagged jobs and has the `docker` tag.
1. A job that has a `hello` tag is executed and stuck.
Example 2:
1. The runner is configured to run only tagged jobs and has the `docker` tag.
1. A job that has a `docker` tag is executed and run.
Example 3:
1. The runner is configured to run only tagged jobs and has the `docker` tag.
1. A job that has no tags defined is executed and stuck.
#### Runner is allowed to run untagged jobs
The following examples illustrate the potential impact of the runner being set
to run tagged and untagged jobs.
Example 1:
1. The runner is configured to run untagged jobs and has the `docker` tag.
1. A job that has no tags defined is executed and run.
1. A second job that has a `docker` tag defined is executed and run.
Example 2:
1. The runner is configured to run untagged jobs and has no tags defined.
1. A job that has no tags defined is executed and run.
1. A second job that has a `docker` tag defined is stuck.
#### A runner and a job have multiple tags
The selection logic that matches the job and runner is based on the list of `tags`
defined in the job.
The following examples illustrate the impact of a runner and a job having multiple tags. For a runner to be
selected to run a job, it must have all of the tags defined in the job script block.
Example 1:
1. The runner is configured with the tags `[docker, shell, gpu]`.
1. The job has the tags `[docker, shell, gpu]` and is executed and run.
Example 2:
1. The runner is configured with the tags `[docker, shell, gpu]`.
1. The job has the tags `[docker, shell,]` and is executed and run.
Example 3:
1. The runner is configured with the tags `[docker, shell]`.
1. The job has the tags `[docker, shell, gpu]` and is not executed.
### Use tags to run jobs on different platforms
You can use tags to run different jobs on different platforms. For
example, if you have an OS X runner with tag `osx` and a Windows runner with tag
`windows`, you can run a job on each platform.
Update the `tags` field in the `.gitlab-ci.yml`:
```yaml
windows job:
stage: build
tags:
- windows
script:
- echo Hello, %USERNAME%!
osx job:
stage: build
tags:
- osx
script:
- echo "Hello, $USER!"
```
### Use CI/CD variables in tags
In the `.gitlab-ci.yml` file, use [CI/CD variables](../variables/_index.md) with `tags` for dynamic runner selection:
```yaml
variables:
KUBERNETES_RUNNER: kubernetes
job:
tags:
- docker
- $KUBERNETES_RUNNER
script:
- echo "Hello runner selector feature"
```
## Configure runner behavior with variables
You can use [CI/CD variables](../variables/_index.md) to configure runner Git behavior
globally or for individual jobs:
- [`GIT_STRATEGY`](#git-strategy)
- [`GIT_SUBMODULE_STRATEGY`](#git-submodule-strategy)
- [`GIT_CHECKOUT`](#git-checkout)
- [`GIT_CLEAN_FLAGS`](#git-clean-flags)
- [`GIT_FETCH_EXTRA_FLAGS`](#git-fetch-extra-flags)
- [`GIT_SUBMODULE_UPDATE_FLAGS`](#git-submodule-update-flags)
- [`GIT_SUBMODULE_FORCE_HTTPS`](#rewrite-submodule-urls-to-https)
- [`GIT_DEPTH`](#shallow-cloning) (shallow cloning)
- [`GIT_SUBMODULE_DEPTH`](#git-submodule-depth)
- [`GIT_CLONE_PATH`](#custom-build-directories) (custom build directories)
- [`TRANSFER_METER_FREQUENCY`](#artifact-and-cache-settings) (artifact/cache meter update frequency)
- [`ARTIFACT_COMPRESSION_LEVEL`](#artifact-and-cache-settings) (artifact archiver compression level)
- [`CACHE_COMPRESSION_LEVEL`](#artifact-and-cache-settings) (cache archiver compression level)
- [`CACHE_REQUEST_TIMEOUT`](#artifact-and-cache-settings) (cache request timeout)
- [`RUNNER_SCRIPT_TIMEOUT`](#set-script-and-after_script-timeouts)
- [`RUNNER_AFTER_SCRIPT_TIMEOUT`](#set-script-and-after_script-timeouts)
- [`AFTER_SCRIPT_IGNORE_ERRORS`](#ignore-errors-in-after_script)
You can also use variables to configure how many times a runner
[attempts certain stages of job execution](#job-stages-attempts).
When using the Kubernetes executor, you can use variables to
[override Kubernetes CPU and memory allocations for requests and limits](https://docs.gitlab.com/runner/executors/kubernetes/#overwrite-container-resources).
### Git strategy
The `GIT_STRATEGY` variable configures how the build directory is prepared and
repository content is fetched. You can set this variable globally or per job
in the [`variables`](../yaml/_index.md#variables) section.
```yaml
variables:
GIT_STRATEGY: clone
```
Possible values are `clone`, `fetch`, `none`, and `empty`. If you do not specify a value,
jobs use the [project's pipeline setting](../pipelines/settings.md#choose-the-default-git-strategy).
`clone` is the slowest option. It clones the repository from scratch for every
job, ensuring that the local working copy is always pristine.
If an existing worktree is found, it is removed before cloning.
`fetch` is faster as it re-uses the local working copy (falling back to `clone`
if it does not exist). `git clean` is used to undo any changes made by the last
job, and `git fetch` is used to retrieve commits made after the last job ran.
However, `fetch` does require access to the previous worktree. This works
well when using the `shell` or `docker` executor because these
try to preserve worktrees and try to re-use them by default.
This has limitations when using the [Docker Machine executor](https://docs.gitlab.com/runner/executors/docker_machine.html).
A Git strategy of `none` also re-uses the local working copy, but skips all Git
operations usually done by GitLab. GitLab Runner pre-clone scripts are also skipped,
if present. This strategy could mean you need to add `fetch` and `checkout` commands
to [your `.gitlab-ci.yml` script](../yaml/_index.md#script).
It can be used for jobs that operate exclusively on artifacts, like a deployment job.
Git repository data may be present, but it's likely out of date. You should only
rely on files brought into the local working copy from cache or artifacts. Be
aware that cache and artifact files from previous pipelines might still be present.
Unlike `none`, the `empty` Git strategy deletes and then re-creates
a dedicated build directory before downloading cache or artifact files.
With this strategy, the GitLab Runner hook scripts are still run
(if provided) to allow for further behavior customization.
Use the `empty` Git strategy when:
- You do not need the repository data to be present.
- You want a clean, controlled, or customized starting state every time a job runs.
### Git submodule strategy
The `GIT_SUBMODULE_STRATEGY` variable is used to control if / how
[Git submodules](https://git-scm.com/book/en/v2/Git-Tools-Submodules) are included when fetching the code before a build. You can set them
globally or per-job in the [`variables`](../yaml/_index.md#variables) section.
The three possible values are `none`, `normal`, and `recursive`:
- `none` means that submodules are not included when fetching the project
code. This setting matches the default behavior in versions before 1.10.
- `normal` means that only the top-level submodules are included. It's
equivalent to:
```shell
git submodule sync
git submodule update --init
```
- `recursive` means that all submodules (including submodules of submodules)
are included. This feature needs Git v1.8.1 and later. When using a
GitLab Runner with an executor not based on Docker, make sure the Git version
meets that requirement. It's equivalent to:
```shell
git submodule sync --recursive
git submodule update --init --recursive
```
For this feature to work correctly, the submodules must be configured
(in `.gitmodules`) with either:
- the HTTP(S) URL of a publicly-accessible repository, or
- a relative path to another repository on the same GitLab server. See the
[Git submodules](git_submodules.md) documentation.
You can provide additional flags to control advanced behavior using [`GIT_SUBMODULE_UPDATE_FLAGS`](#git-submodule-update-flags).
### Git checkout
The `GIT_CHECKOUT` variable can be used when the `GIT_STRATEGY` is set to either
`clone` or `fetch` to specify whether a `git checkout` should be run. If not
specified, it defaults to true. You can set them globally or per-job in the
[`variables`](../yaml/_index.md#variables) section.
If set to `false`, the runner:
- when doing `fetch` - updates the repository and leaves the working copy on
the current revision,
- when doing `clone` - clones the repository and leaves the working copy on the
default branch.
If `GIT_CHECKOUT` is set to `true`, both `clone` and `fetch` work the same way.
The runner checks out the working copy of a revision related
to the CI pipeline:
```yaml
variables:
GIT_STRATEGY: clone
GIT_CHECKOUT: "false"
script:
- git checkout -B master origin/master
- git merge $CI_COMMIT_SHA
```
### Git clean flags
The `GIT_CLEAN_FLAGS` variable is used to control the default behavior of
`git clean` after checking out the sources. You can set it globally or per-job in the
[`variables`](../yaml/_index.md#variables) section.
`GIT_CLEAN_FLAGS` accepts all possible options of the [`git clean`](https://git-scm.com/docs/git-clean)
command.
`git clean` is disabled if `GIT_CHECKOUT: "false"` is specified.
If `GIT_CLEAN_FLAGS` is:
- Not specified, `git clean` flags default to `-ffdx`.
- Given the value `none`, `git clean` is not executed.
For example:
```yaml
variables:
GIT_CLEAN_FLAGS: -ffdx -e cache/
script:
- ls -al cache/
```
### Git fetch extra flags
Use the `GIT_FETCH_EXTRA_FLAGS` variable to control the behavior of
`git fetch`. You can set it globally or per-job in the [`variables`](../yaml/_index.md#variables) section.
`GIT_FETCH_EXTRA_FLAGS` accepts all options of the [`git fetch`](https://git-scm.com/docs/git-fetch) command. However, `GIT_FETCH_EXTRA_FLAGS` flags are appended after the default flags that can't be modified.
The default flags are:
- [`GIT_DEPTH`](#shallow-cloning).
- The list of [refspecs](https://git-scm.com/book/en/v2/Git-Internals-The-Refspec).
- A remote called `origin`.
If `GIT_FETCH_EXTRA_FLAGS` is:
- Not specified, `git fetch` flags default to `--prune --quiet` along with the default flags.
- Given the value `none`, `git fetch` is executed only with the default flags.
For example, the default flags are `--prune --quiet`, so you can make `git fetch` more verbose by overriding this with just `--prune`:
```yaml
variables:
GIT_FETCH_EXTRA_FLAGS: --prune
script:
- ls -al cache/
```
The previous configuration results in `git fetch` being called this way:
```shell
git fetch origin $REFSPECS --depth 20 --prune
```
Where `$REFSPECS` is a value provided to the runner internally by GitLab.
### Sync or exclude specific submodules from CI jobs
Use the `GIT_SUBMODULE_PATHS` variable to control which submodules have to be synced or updated.
You can set it globally or per-job in the [`variables`](../yaml/_index.md#variables) section.
The path syntax is the same as [`git submodule`](https://git-scm.com/docs/git-submodule#Documentation/git-submodule.txt-ltpathgt82308203):
- To sync and update specific paths:
```yaml
variables:
GIT_SUBMODULE_PATHS: submoduleA submoduleB
```
- To exclude specific paths:
```yaml
variables:
GIT_SUBMODULE_PATHS: ":(exclude)submoduleA :(exclude)submoduleB"
```
{{< alert type="warning" >}}
Git ignores nested paths. To ignore a nested submodule, exclude
the parent submodule and then manually clone it in the job's scripts. For example,
`git clone <repo> --recurse-submodules=':(exclude)nested-submodule'`. Make sure
to wrap the string in single quotes so the YAML can be parsed successfully.
{{< /alert >}}
### Git submodule update flags
Use the `GIT_SUBMODULE_UPDATE_FLAGS` variable to control the behavior of `git submodule update`
when [`GIT_SUBMODULE_STRATEGY`](#git-submodule-strategy) is set to either `normal` or `recursive`.
You can set it globally or per-job in the [`variables`](../yaml/_index.md#variables) section.
`GIT_SUBMODULE_UPDATE_FLAGS` accepts all options of the
[`git submodule update`](https://git-scm.com/docs/git-submodule#Documentation/git-submodule.txt-update--init--remote-N--no-fetch--no-recommend-shallow-f--force--checkout--rebase--merge--referenceltrepositorygt--depthltdepthgt--recursive--jobsltngt--no-single-branch--ltpathgt82308203)
subcommand. However, `GIT_SUBMODULE_UPDATE_FLAGS` flags are appended after a few default flags:
- `--init`, if [`GIT_SUBMODULE_STRATEGY`](#git-submodule-strategy) was set to `normal` or `recursive`.
- `--recursive`, if [`GIT_SUBMODULE_STRATEGY`](#git-submodule-strategy) was set to `recursive`.
- `GIT_DEPTH`. See the default value in the [shallow cloning](#shallow-cloning) section.
Git honors the last occurrence of a flag in the list of arguments, so manually
providing them in `GIT_SUBMODULE_UPDATE_FLAGS` overrides these default flags.
For example, you can use this variable to:
- Fetch the latest remote `HEAD` instead of the tracked commit in the
repository (default) to automatically update all submodules with the
`--remote` flag.
- Speed up the checkout by fetching submodules in multiple parallel jobs with
the `--jobs 4` flag.
```yaml
variables:
GIT_SUBMODULE_STRATEGY: recursive
GIT_SUBMODULE_UPDATE_FLAGS: --remote --jobs 4
script:
- ls -al .git/modules/
```
The previous configuration results in `git submodule update` being called this way:
```shell
git submodule update --init --depth 20 --recursive --remote --jobs 4
```
{{< alert type="warning" >}}
You should be aware of the implications for the security, stability, and
reproducibility of your builds when using the `--remote` flag. In most cases,
it is better to explicitly track submodule commits as designed, and update them
using an auto-remediation/dependency bot.
The `--remote` flag is not required to check out submodules at their committed
revisions. Use this flag only when you want to automatically update submodules
to their latest remote versions.
{{< /alert >}}
The behavior of `--remote` depends on your Git version.
If the branch specified in your superproject's `.gitmodules` file is different from the
default branch of the submodule repository, some Git versions will fail with this error:
`fatal: Unable to find refs/remotes/origin/<branch> revision in submodule path '<submodule-path>'`
The runner implements a "best effort" fallback that attempts to
pull remote refs when the submodule update fails.
If this fallback does not work with your Git version, try one of the following
workarounds:
- Update the submodule repository's default branch to match the branch set in
`.gitmodules` in the superproject.
- Set `GIT_SUBMODULE_DEPTH` to `0`.
- Update the submodules separately and remove the `--remote` flag from
`GIT_SUBMODULE_UPDATE_FLAGS`.
### Rewrite submodule URLs to HTTPS
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3198) in GitLab Runner 15.11.
{{< /history >}}
Use the `GIT_SUBMODULE_FORCE_HTTPS` variable to force a rewrite of all Git and SSH submodule URLs to HTTPS.
You can clone submodules that use absolute URLs on the same GitLab instance, even if they were
configured with a Git or SSH protocol.
```yaml
variables:
GIT_SUBMODULE_STRATEGY: recursive
GIT_SUBMODULE_FORCE_HTTPS: "true"
```
When enabled, GitLab Runner uses a [CI/CD job token](../jobs/ci_job_token.md) to clone the submodules.
The token uses the permissions of the user executing the job and does not require SSH credentials.
### Shallow cloning
You can specify the depth of fetching and cloning using `GIT_DEPTH`.
`GIT_DEPTH` does a shallow clone of the repository and can significantly speed up cloning.
It can be helpful for repositories with a large number of commits or old, large binaries. The value is
passed to `git fetch` and `git clone`.
Newly-created projects automatically have a
[default `git depth` value of `20`](../pipelines/settings.md#limit-the-number-of-changes-fetched-during-clone).
If you use a depth of `1` and have a queue of jobs or retry
jobs, jobs may fail.
Git fetching and cloning is based on a ref, such as a branch name, so runners
can't clone a specific commit SHA. If multiple jobs are in the queue, or
you retry an old job, the commit to be tested must be in the cloned
Git history. Setting too small a value for `GIT_DEPTH` can make
it impossible to run these old commits and `unresolved reference` is displayed in
job logs. You should then reconsider changing `GIT_DEPTH` to a higher value.
Jobs that rely on `git describe` may not work correctly when `GIT_DEPTH` is
set because only part of the Git history is present.
To fetch or clone only the last 3 commits:
```yaml
variables:
GIT_DEPTH: "3"
```
You can set it globally or per-job in the [`variables`](../yaml/_index.md#variables) section.
### Git submodule depth
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3651) in GitLab Runner 15.5.
{{< /history >}}
Use the `GIT_SUBMODULE_DEPTH` variable to specify the depth of fetching and cloning submodules
when [`GIT_SUBMODULE_STRATEGY`](#git-submodule-strategy) is set to either `normal` or `recursive`.
You can set it globally or for a specific job in the [`variables`](../yaml/_index.md#variables) section.
When you set the `GIT_SUBMODULE_DEPTH` variable, it overwrites the [`GIT_DEPTH`](#shallow-cloning) setting
for the submodules only.
To fetch or clone only the last 3 commits:
```yaml
variables:
GIT_SUBMODULE_DEPTH: 3
```
### Custom build directories
By default, GitLab Runner clones the repository in a unique subpath of the
`$CI_BUILDS_DIR` directory. However, your project might require the code in a
specific directory (Go projects, for example). In that case, you can specify
the `GIT_CLONE_PATH` variable to tell the runner the directory to clone the
repository in:
```yaml
variables:
GIT_CLONE_PATH: $CI_BUILDS_DIR/project-name
test:
script:
- pwd
```
The `GIT_CLONE_PATH` must always be inside `$CI_BUILDS_DIR`. The directory set in `$CI_BUILDS_DIR`
is dependent on executor and configuration of [runners.builds_dir](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runners-section)
setting.
This can only be used when `custom_build_dir` is enabled in the
[runner's configuration](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runnerscustom_build_dir-section).
#### Handling concurrency
An executor that uses a concurrency greater than `1` might lead
to failures. Multiple jobs might be working on the same directory if the `builds_dir`
is shared between jobs.
The runner does not try to prevent this situation. It's up to the administrator
and developers to comply with the requirements of runner configuration.
To avoid this scenario, you can use a unique path in `$CI_BUILDS_DIR`, because runner
exposes two additional variables that provide a unique `ID` of concurrency:
- `$CI_CONCURRENT_ID`: Unique ID for all jobs running in the given executor.
- `$CI_CONCURRENT_PROJECT_ID`: Unique ID for all jobs running in the given executor and project.
The most stable configuration that should work well in any scenario and on any executor
is to use `$CI_CONCURRENT_ID` in the `GIT_CLONE_PATH`. For example:
```yaml
variables:
GIT_CLONE_PATH: $CI_BUILDS_DIR/$CI_CONCURRENT_ID/project-name
test:
script:
- pwd -P
```
The `$CI_CONCURRENT_PROJECT_ID` should be used in conjunction with `$CI_PROJECT_PATH`.
`$CI_PROJECT_PATH` provides a path of a repository in the `group/subgroup/project` format.
For example:
```yaml
variables:
GIT_CLONE_PATH: $CI_BUILDS_DIR/$CI_CONCURRENT_ID/$CI_PROJECT_PATH
test:
script:
- pwd -P
```
#### Nested paths
The value of `GIT_CLONE_PATH` expands once. You cannot nest variables
in this value.
For example, you define the following variables in your
`.gitlab-ci.yml` file:
```yaml
variables:
GOPATH: $CI_BUILDS_DIR/go
GIT_CLONE_PATH: $GOPATH/src/namespace/project
```
The value of `GIT_CLONE_PATH` is expanded once into
`$CI_BUILDS_DIR/go/src/namespace/project`, and results in failure
because `$CI_BUILDS_DIR` is not expanded.
### Ignore errors in `after_script`
You can use [`after_script`](../yaml/_index.md#after_script) in a job to define an array of commands
that should run after the job's `before_script` and `script` sections. The `after_script` commands
run regardless of the script termination status (failure or success).
By default, GitLab Runner ignores any errors that happen when `after_script` runs.
To set the job to fail immediately on errors when `after_script` runs, set the
`AFTER_SCRIPT_IGNORE_ERRORS` CI/CD variable to `false`. For example:
```yaml
variables:
AFTER_SCRIPT_IGNORE_ERRORS: false
```
### Job stages attempts
You can set the number of attempts that the running job tries to execute
the following stages:
| Variable | Description |
|---------------------------------|-------------|
| `ARTIFACT_DOWNLOAD_ATTEMPTS` | Number of attempts to download artifacts running a job |
| `EXECUTOR_JOB_SECTION_ATTEMPTS` | The number of attempts to run a section in a job after a [`No Such Container`](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/4450) error ([Docker executor](https://docs.gitlab.com/runner/executors/docker.html) only). |
| `GET_SOURCES_ATTEMPTS` | Number of attempts to fetch sources running a job |
| `RESTORE_CACHE_ATTEMPTS` | Number of attempts to restore the cache running a job |
The default is one single attempt.
Example:
```yaml
variables:
GET_SOURCES_ATTEMPTS: 3
```
You can set them globally or per-job in the [`variables`](../yaml/_index.md#variables) section.
## System calls not available on GitLab.com instance runners
GitLab.com instance runners run on CoreOS. This means that you cannot use some system calls, like `getlogin`, from the C standard library.
## Artifact and cache settings
Artifact and cache settings control the compression ratio of artifacts and caches.
Use these settings to specify the size of the archive produced by a job.
- On a slow network, uploads might be faster for smaller archives.
- On a fast network where bandwidth and storage are not a concern, uploads might be faster using the fastest compression ratio, despite the archive produced being larger.
For [GitLab Pages](../../user/project/pages/_index.md) to serve
[HTTP Range requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests), artifacts
should use the `ARTIFACT_COMPRESSION_LEVEL: fastest` setting, as only uncompressed zip archives
support this feature.
A meter can be enabled to provide the rate of transfer for uploads and downloads.
You can set a maximum time for cache upload and download with the `CACHE_REQUEST_TIMEOUT` setting.
Use this setting when slow cache uploads substantially increase the duration of your job.
```yaml
variables:
# output upload and download progress every 2 seconds
TRANSFER_METER_FREQUENCY: "2s"
# Use fast compression for artifacts, resulting in larger archives
ARTIFACT_COMPRESSION_LEVEL: "fast"
# Use no compression for caches
CACHE_COMPRESSION_LEVEL: "fastest"
# Set maximum duration of cache upload and download
CACHE_REQUEST_TIMEOUT: 5
```
| Variable | Description |
|------------------------------|-------------|
| `TRANSFER_METER_FREQUENCY` | Specify how often to print the meter's transfer rate. It can be set to a duration (for example, `1s` or `1m30s`). A duration of `0` disables the meter (default). When a value is set, the pipeline shows a progress meter for artifact and cache uploads and downloads. |
| `ARTIFACT_COMPRESSION_LEVEL` | To adjust compression ratio, set to `fastest`, `fast`, `default`, `slow`, or `slowest`. This setting works with the Fastzip archiver only, so the GitLab Runner feature flag [`FF_USE_FASTZIP`](https://docs.gitlab.com/runner/configuration/feature-flags.html#available-feature-flags) must also be enabled. |
| `CACHE_COMPRESSION_LEVEL` | To adjust compression ratio, set to `fastest`, `fast`, `default`, `slow`, or `slowest`. This setting works with the Fastzip archiver only, so the GitLab Runner feature flag [`FF_USE_FASTZIP`](https://docs.gitlab.com/runner/configuration/feature-flags.html#available-feature-flags) must also be enabled. |
| `CACHE_REQUEST_TIMEOUT` | Configure the maximum duration of cache upload and download operations for a single job in minutes. Default is `10` minutes. |
## Artifact provenance metadata
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/28940) in GitLab Runner 15.1.
{{< /history >}}
Runners can generate an [SLSA Provenance](https://slsa.dev/spec/v1.0/provenance)
and produce an [SLSA Statement](https://slsa.dev/spec/v1.0/attestation-model#model-and-terminology)
that binds the provenance to all build artifacts.
The statement is called artifact provenance metadata.
To enable artifact provenance metadata, set the `RUNNER_GENERATE_ARTIFACTS_METADATA` environment
variable to `true`. You can set the variable globally or for individual jobs:
```yaml
variables:
RUNNER_GENERATE_ARTIFACTS_METADATA: "true"
job1:
variables:
RUNNER_GENERATE_ARTIFACTS_METADATA: "true"
```
The metadata renders in a plain text `.json` file stored with the artifact. The
filename is `{ARTIFACT_NAME}-metadata.json`. `ARTIFACT_NAME` is the
[name for the artifact](../jobs/job_artifacts.md#with-an-explicitly-defined-artifact-name)
defined in the `.gitlab-ci.yml` file. If the name is not defined, the default filename is
`artifacts-metadata.json`.
### Provenance metadata format
The artifact provenance metadata is generated in the
[in-toto v0.1 Statement](https://github.com/in-toto/attestation/tree/v0.1.0/spec#statement) format.
It contains a provenance predicate generated in the [SLSA 1.0 Provenance](https://slsa.dev/spec/v1.0/provenance) format.
These fields are populated by default:
| Field | Value |
|-------------------------------------------------------------------|-------|
| `_type` | `https://in-toto.io/Statement/v0.1` |
| `subject` | Set of software artifacts the metadata applies to |
| `subject[].name` | The filename of the artifact. |
| `subject[].sha256` | The artifact's `sha256` checksum. |
| `predicateType` | `https://slsa.dev/provenance/v1` |
| `predicate.buildDefinition.buildType` | `https://gitlab.com/gitlab-org/gitlab-runner/-/blob/{GITLAB_RUNNER_VERSION}/PROVENANCE.md`. For example, v15.0.0 |
| `predicate.runDetails.builder.id` | A URI pointing to the runner details page, for example, `https://gitlab.com/gitlab-com/www-gitlab-com/-/runners/3785264`. |
| `predicate.buildDefinition.externalParameters` | The names of any CI/CD or environment variables available during the build command execution. The value is always represented as an empty string to protect secrets. |
| `predicate.buildDefinition.externalParameters.source` | The URL of the project. |
| `predicate.buildDefinition.externalParameters.entryPoint` | The name of the CI/CD job that triggered the build. |
| `predicate.buildDefinition.internalParameters.name` | The name of the runner. |
| `predicate.buildDefinition.internalParameters.executor` | The runner executor. |
| `predicate.buildDefinition.internalParameters.architecture` | The architecture on which the CI/CD job is run. |
| `predicate.buildDefinition.internalParameters.job` | The ID of the CI/CD job that triggered the build. |
| `predicate.buildDefinition.resolvedDependencies[0].uri` | The URL of the project. |
| `predicate.buildDefinition.resolvedDependencies[0].digest.sha256` | The commit revision of the project. |
| `predicate.runDetails.metadata.invocationID` | The ID of the CI/CD job that triggered the build. |
| `predicate.runDetails.metadata.startedOn` | The time when the build was started. This field is `RFC3339` formatted. |
| `predicate.runDetails.metadata.finishedOn` | The time when the build ended. Because metadata generation happens during the build, this time is slightly earlier than the one reported in GitLab. This field is `RFC3339` formatted. |
A provenance statement should look similar to this example:
```json
{
"_type": "https://in-toto.io/Statement/v0.1",
"predicateType": "https://slsa.dev/provenance/v1",
"subject": [
{
"name": "x.txt",
"digest": {
"sha256": "ac097997b6ec7de591d4f11315e4aa112e515bb5d3c52160d0c571298196ea8b"
}
},
{
"name": "y.txt",
"digest": {
"sha256": "9eb634f80da849d828fcf42740d823568c49e8d7b532886134f9086246b1fdf3"
}
}
],
"predicate": {
"buildDefinition": {
"buildType": "https://gitlab.com/gitlab-org/gitlab-runner/-/blob/2147fb44/PROVENANCE.md",
"externalParameters": {
"CI": "",
"CI_API_GRAPHQL_URL": "",
"CI_API_V4_URL": "",
"CI_COMMIT_AUTHOR": "",
"CI_COMMIT_BEFORE_SHA": "",
"CI_COMMIT_BRANCH": "",
"CI_COMMIT_DESCRIPTION": "",
"CI_COMMIT_MESSAGE": "",
[... additional environmental variables ...]
"entryPoint": "build-job",
"source": "https://gitlab.com/my-group/my-project/test-runner-generated-slsa-statement"
},
"internalParameters": {
"architecture": "amd64",
"executor": "docker+machine",
"job": "10340684631",
"name": "green-4.saas-linux-small-amd64.runners-manager.gitlab.com/default"
},
"resolvedDependencies": [
{
"uri": "https://gitlab.com/my-group/my-project/test-runner-generated-slsa-statement",
"digest": {
"sha256": "bdd2ecda9ef57b129c88617a0215afc9fb223521"
}
}
]
},
"runDetails": {
"builder": {
"id": "https://gitlab.com/my-group/my-project/test-runner-generated-slsa-statement/-/runners/12270857",
"version": {
"gitlab-runner": "2147fb44"
}
},
"metadata": {
"invocationID": "10340684631",
"startedOn": "2025-06-13T07:25:13Z",
"finishedOn": "2025-06-13T07:25:40Z"
}
}
}
}
```
## Staging directory
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3403) in GitLab Runner 15.0.
{{< /history >}}
If you do not want to archive cache and artifacts in the system's default temporary directory, you can specify a different directory.
You might need to change the directory if your system's default temporary path has constraints.
If you use a fast disk for the directory location, it can also improve performance.
To change the directory, set `ARCHIVER_STAGING_DIR` as a variable in your CI job, or use a runner variable when you register the runner (`gitlab register --env ARCHIVER_STAGING_DIR=<dir>`).
The directory you specify is used as the location for downloading artifacts prior to extraction. If the `fastzip` archiver is
used, this location is also used as scratch space when archiving.
## Configure `fastzip` to improve performance
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3130) in GitLab Runner 15.0.
{{< /history >}}
To tune `fastzip`, ensure the [`FF_USE_FASTZIP`](https://docs.gitlab.com/runner/configuration/feature-flags.html#available-feature-flags) flag is enabled.
Then use any of the following environment variables.
| Variable | Description |
|---------------------------------|-------------|
| `FASTZIP_ARCHIVER_CONCURRENCY` | The number of files to be concurrently compressed. Default is the number of CPUs available. |
| `FASTZIP_ARCHIVER_BUFFER_SIZE` | The buffer size allocated per concurrency for each file. Data exceeding this number moves to scratch space. Default is 2 MiB. |
| `FASTZIP_EXTRACTOR_CONCURRENCY` | The number of files to be concurrency decompressed. Default is the number of CPUs available. |
Files in a zip archive are appended sequentially. This makes concurrent compression challenging. `fastzip` works around
this limitation by compressing files concurrently to disk first, and then copying the result back to zip archive
sequentially.
To avoid writing to disk and reading the contents back for smaller files, a small buffer per concurrency is used. This setting
can be controlled with `FASTZIP_ARCHIVER_BUFFER_SIZE`. The default size for this buffer is 2 MiB, therefore, a
concurrency of 16 allocates 32 MiB. Data that exceeds the buffer size is written to and read back from disk.
Therefore, using no buffer, `FASTZIP_ARCHIVER_BUFFER_SIZE: 0`, and only scratch space is a valid option.
`FASTZIP_ARCHIVER_CONCURRENCY` controls how many files are compressed concurrency. As previously mentioned, this setting
therefore can increase how much memory is being used. It can also increase the temporary data written to the scratch space.
The default is the number of CPUs available, but given the memory ramifications, this may not always be the best
setting.
`FASTZIP_EXTRACTOR_CONCURRENCY` controls how many files are decompressed at once. Files from a zip archive can natively
be read from concurrency, so no additional memory is allocated in addition to what the extractor requires. This
defaults to the number of CPUs available.
|
https://docs.gitlab.com/ci/runners_scope
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/runners_scope.md
|
2025-08-13
|
doc/ci/runners
|
[
"doc",
"ci",
"runners"
] |
runners_scope.md
|
Verify
|
Runner
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Manage runners
|
Learn about the types of runners, their availability, and how to manage them.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
GitLab Runner has the following types of runners, which are available based on who you want to have access:
- [Instance runners](#instance-runners) are available to all groups and projects in a GitLab instance.
- [Group runners](#group-runners) are available to all projects and subgroups in a group.
- [Project runners](#project-runners) are associated with specific projects.
Typically, project runners are used by one project at a time.
## Instance runners
*Instance runners* are available to every project in a GitLab instance.
Use instance runners when you have multiple jobs with similar requirements. Rather than
having multiple runners idling for many projects, you can have a few runners that handle
multiple projects.
If you are using GitLab Self-Managed, administrators can:
- [Install GitLab Runner](https://docs.gitlab.com/runner/install/) and register an instance runner.
- Configure a maximum number of instance runner [compute minutes for each group](../../administration/cicd/compute_minutes.md#set-the-compute-quota-for-a-group).
If you are using GitLab.com:
- You can select from a list of [instance runners that GitLab maintains](_index.md).
- The instance runners consume the [compute minutes](../pipelines/compute_minutes.md)
included with your account.
### Create an instance runner with a runner authentication token
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/383139) in GitLab 15.10. Deployed behind the `create_runner_workflow_for_admin` [flag](../../administration/feature_flags/_index.md)
- [Enabled by default](https://gitlab.com/gitlab-org/gitlab/-/issues/389269) in GitLab 16.0.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/415447) in GitLab 16.2. Feature flag `create_runner_workflow_for_admin` removed.
{{< /history >}}
Prerequisites:
- You must be an administrator.
When you create a runner, it is assigned a runner authentication token that you use to register it. The runner uses the token to authenticate with GitLab when picking up jobs from the job queue.
To create an instance runner:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. Select **New instance runner**.
1. Select the operating system where GitLab Runner is installed.
1. In the **Tags** section, in the **Tags** field, enter the job tags to specify jobs the runner can run.
If there are no job tags for this runner, select **Run untagged**.
1. Optional. In the **Runner description** field, to add a runner description
that displays in GitLab, enter a runner description.
1. Optional. In the **Configuration** section, add additional configurations.
1. Select **Create runner**.
1. Follow the on-screen instructions to register the runner from the command line. When prompted by the command line:
- For the `GitLab instance URL`, use the URL for your GitLab instance. For example, if your project
is hosted on `gitlab.example.com/yourname/yourproject`, your GitLab instance URL is `https://gitlab.example.com`.
- For the `executor`, enter the type of [executor](https://docs.gitlab.com/runner/executors/). The executor is the
environment where the runner executes the job.
You can also [use the API](../../api/users.md#create-a-runner-linked-to-a-user) to create a runner.
{{< alert type="note" >}}
The runner authentication token displays in the UI for a limited period of time during registration. After you register the runner,
the authentication token is stored in the `config.toml`.
{{< /alert >}}
### Create an instance runner with a registration token (deprecated)
{{< alert type="warning" >}}
The option to use runner registration tokens and support for certain configuration arguments are
[deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/380872) in GitLab 15.6 and is planned for removal in GitLab 20.0.
Use the [runner creation workflow](https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token)
to generate an authentication token to register runners. This process provides full
traceability of runner ownership and enhances your runner fleet's security.
For more information, see
[Migrating to the new runner registration workflow](new_creation_workflow.md).
{{< /alert >}}
Prerequisites:
- Runner registration tokens must be [enabled](../../administration/settings/continuous_integration.md#control-runner-registration) in the **Admin** area.
- You must be an administrator.
To create an instance runner:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. Select **Register an instance runner**.
1. Copy the registration token.
1. [Register the runner](https://docs.gitlab.com/runner/register/#register-with-a-runner-registration-token-deprecated).
### Pause or resume an instance runner
Prerequisites:
- You must be an administrator.
You can pause a runner so that it does not accept jobs from groups and projects in the GitLab instance.
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. In the search box, enter the runner description or filter the runner list.
1. In the runner list, to the right of the runner:
- To pause the runner, select **Pause** ({{< icon name="pause" >}}).
- To resume the runner, select **Resume** ({{< icon name="play" >}}).
### Delete instance runners
Prerequisites:
- You must be an administrator.
When you delete an instance runner, it is permanently deleted from the GitLab instance and can
no longer be used by groups and projects. If you want to temporarily stop the runner from accepting
jobs, you can [pause](#pause-or-resume-an-instance-runner) the runner instead.
To delete a single or multiple instance runners:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. In the search box, enter the runner description or filter the list of runners.
1. Delete the instance runner:
- To delete a single runner, next to the runner, select **Delete runner** ({{< icon name="remove" >}}).
- To delete multiple instance runners, select the checkbox for each runner and select **Delete selected**.
- To delete all runners, select the checkbox at the top of the runner list and select **Delete selected**.
1. Select **Permanently delete runner**.
### Enable instance runners for a project
On GitLab.com, [instance runners](_index.md) are enabled in all projects by
default.
On GitLab Self-Managed, an administrator can
[enable them for all new projects](../../administration/settings/continuous_integration.md#enable-instance-runners-for-new-projects).
For existing projects, an administrator must
[install](https://docs.gitlab.com/runner/install/) and
[register](https://docs.gitlab.com/runner/register/) them.
To enable instance runners for a project:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. Enable the **Turn on instance runners for this project** toggle.
### Enable instance runners for a group
To enable instance runners for a group:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. Enable the **Turn on instance runners for this group** toggle.
### Disable instance runners for a project
You can disable instance runners for individual projects or for groups.
You must have the Owner role for the project
or group.
To disable instance runners for a project:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. In the **Instance runners** area, turn off the **Turn on runners for this project** toggle.
Instance runners are automatically disabled for a project:
- If the instance runners setting for the parent group is disabled, and
- If overriding this setting is not permitted for projects.
### Disable instance runners for a group
To disable instance runners for a group:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. Turn off the **Enable instance runners for this group** toggle.
1. Optional. To allow instance runners to be enabled for individual projects or subgroups,
select **Allow projects and subgroups to override the group setting**.
### How instance runners pick jobs
Instance runners process jobs by using a fair usage queue. This queue prevents
projects from creating hundreds of jobs and using all available
instance runner resources.
The fair usage queue algorithm assigns jobs based on the projects that have the
fewest number of jobs already running on instance runners.
For example, if these jobs are in the queue:
- Job 1 for Project 1
- Job 2 for Project 1
- Job 3 for Project 1
- Job 4 for Project 2
- Job 5 for Project 2
- Job 6 for Project 3
When several CI/CD jobs run concurrently, the fair usage algorithm assigns jobs in this order:
1. Job 1 is first, because it has the lowest job number from projects with no running jobs (that is, all projects).
1. Job 4 is next, because 4 is now the lowest job number from projects with no running jobs (Project 1 has a job running).
1. Job 6 is next, because 6 is now the lowest job number from projects with no running jobs (Projects 1 and 2 have jobs running).
1. Job 2 is next, because, of projects with the lowest number of jobs running (each has 1), it is the lowest job number.
1. Job 5 is next, because Project 1 now has 2 jobs running and Job 5 is the lowest remaining job number between Projects 2 and 3.
1. Finally is Job 3 because it's the only job left.
When only one job runs at a time, the fair usage algorithm assigns jobs in this order:
1. Job 1 is chosen first, because it has the lowest job number from projects with no running jobs (that is, all projects).
1. We finish Job 1.
1. Job 2 is next, because, having finished Job 1, all projects have 0 jobs running again, and 2 is the lowest available job number.
1. Job 4 is next, because with Project 1 running a Job, 4 is the lowest number from projects running no jobs (Projects 2 and 3).
1. We finish Job 4.
1. Job 5 is next, because having finished Job 4, Project 2 has no jobs running again.
1. Job 6 is next, because Project 3 is the only project left with no running jobs.
1. Lastly we choose Job 3, because, again, it's the only job left.
## Group runners
Use group runners when you want all projects in a group
to have access to a set of runners.
Group runners process jobs by using a first in, first out queue.
### Create a group runner with a runner authentication token
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/383143) in GitLab 15.10. Deployed behind the `create_runner_workflow_for_namespace` [flag](../../administration/feature_flags/_index.md). Disabled by default.
- [Enabled by default](https://gitlab.com/gitlab-org/gitlab/-/issues/393919) in GitLab 16.0.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/415447) in GitLab 16.2. Feature flag `create_runner_workflow_for_admin` removed.
{{< /history >}}
Prerequisites:
- You must have the Owner role for the group.
You can create a group runner for GitLab Self-Managed or for GitLab.com.
When you create a runner, it is assigned a runner authentication token that you use to register it.
The runner uses the token to authenticate with GitLab when it picks up jobs from the job queue.
To create a group runner:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. Select **New group runner**.
1. In the **Tags** section, in the **Tags** field, enter the job tags to specify jobs the runner can run.
If there are no job tags for this runner, select **Run untagged**.
1. Optional. In the **Runner description** field, add a runner description
that displays in GitLab.
1. Optional. In the **Configuration** section, add additional configurations.
1. Select **Create runner**.
1. Select the platform where GitLab Runner is installed.
1. Complete the onscreen instructions:
- For Linux, macOS, and Windows, when prompted by the command line:
- For the `GitLab instance URL`, use the URL for your GitLab instance. For example, if your project
is hosted on `gitlab.example.com/yourname/yourproject`, your GitLab instance URL is `https://gitlab.example.com`.
- For the `executor`, enter the type of [executor](https://docs.gitlab.com/runner/executors/). The executor is the
environment where the runner executes the job.
- For Google Cloud, see [Provisioning runners in Google Cloud](provision_runners_google_cloud.md).
You can also [use the API](../../api/users.md#create-a-runner-linked-to-a-user) to create a runner.
{{< alert type="note" >}}
The runner authentication token displays in the UI for only a short period of time during registration.
{{< /alert >}}
### Create a group runner with a registration token (deprecated)
{{< history >}}
- Path changed from **Settings > CI/CD > Runners**.
{{< /history >}}
{{< alert type="warning" >}}
The option to use runner registration tokens and support for certain configuration arguments are
[deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/380872) in GitLab 15.6 and is planned for removal in GitLab 20.0.
Use the [runner creation workflow](https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token)
to generate an authentication token to register runners. This process provides full
traceability of runner ownership and enhances your runner fleet's security.
For more information, see
[Migrating to the new runner registration workflow](new_creation_workflow.md).
{{< /alert >}}
Prerequisites:
- Runner registration tokens must be [enabled](#enable-use-of-runner-registration-tokens-in-projects-and-groups) in the top-level group.
- You must have the Owner role for the group.
To create a group runner:
1. [Install GitLab Runner](https://docs.gitlab.com/runner/install/).
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. In the upper-right corner, select **Register a group runner**.
1. Select **Show runner installation and registration instructions**.
These instructions include the token, URL, and a command to register a runner.
Alternately, you can copy the registration token and follow the documentation for
how to [register a runner](https://docs.gitlab.com/runner/register/#register-with-a-runner-registration-token-deprecated).
### View group runners
{{< history >}}
- Ability for users with the Maintainer role to view group runners [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/384179) in GitLab 16.4.
{{< /history >}}
Prerequisites:
- You must have the Maintainer or Owner role for the group.
You can view all runners for a group and its subgroups and projects.
You can do this for GitLab Self-Managed or for GitLab.com.
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
#### Filter group runners to show only inherited
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/337838/) in GitLab 15.5.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/101099) in GitLab 15.5. Feature flag `runners_finder_all_available` removed.
{{< /history >}}
You can choose to show all runners in the list, or show only
those that are inherited from the instance or other groups.
By default, only those that are inherited are shown.
To show all runners available in the instance, including instance runners and
those in other groups:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. Above the list, turn off the **Show only inherited** toggle.
### Pause or resume a group runner
Prerequisites:
- You must be an administrator or have the Owner role for the group.
You can pause a runner so that it does not accept jobs from subgroups and projects in the GitLab
instance. If you pause a group runner that is used by multiple projects, the runner pauses for all projects.
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. In the search box, enter the runner description or filter the runner list.
1. In the runner list, to the right of the runner:
- To pause the runner, select **Pause** ({{< icon name="pause" >}}).
- To resume the runner, select **Resume** ({{< icon name="play" >}}).
### Delete a group runner
{{< history >}}
- Multiple runner deletion [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/361721/) in GitLab 15.6.
{{< /history >}}
Prerequisites:
- You must be an administrator or have the Owner role for the group.
When you delete a group runner, it is permanently deleted from the GitLab instance and can
no longer be used by subgroups and projects. If you want to temporarily stop the runner from accepting
jobs, you can [pause](#pause-or-resume-a-group-runner) the runner instead.
To delete a single or multiple group runners:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. In the search box, enter the runner description or filter the list of runners.
1. Delete the group runner:
- To delete a single runner, next to the runner, select **Delete runner** ({{< icon name="remove" >}}).
- To delete multiple instance runners, select the checkbox for each runner and select **Delete selected**.
- To delete all runners, select the checkbox at the top of the runner list and select **Delete selected**.
1. Select **Permanently delete runner**.
### Clean up stale group runners
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/363012) in GitLab 15.1.
{{< /history >}}
Prerequisites:
- You must have the Owner role for the group.
You can clean up group runners that have been inactive for more than three months.
Group runners are those that were created in a specific group.
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. Turn on the **Enable stale runner cleanup** toggle.
#### View stale runner cleanup logs
You can check the [Sidekiq logs](../../administration/logs/_index.md#sidekiq-logs) to see the cleanup result. In Kibana you can use the following query:
```json
{
"query": {
"match_phrase": {
"json.class.keyword": "Ci::Runners::StaleGroupRunnersPruneCronWorker"
}
}
}
```
Filter entries where stale runners were removed:
```json
{
"query": {
"range": {
"json.extra.ci_runners_stale_group_runners_prune_cron_worker.total_pruned": {
"gte": 1,
"lt": null
}
}
}
}
```
## Project runners
Use project runners when you want to use runners for specific projects. For example,
when you have:
- Jobs with specific requirements, like a deploy job that requires credentials.
- Projects with a lot of CI activity that can benefit from being separate from other runners.
You can set up a project runner to be used by multiple projects. Project runners
must be enabled for each project explicitly.
Project runners process jobs by using a first in, first out ([FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics))) queue.
{{< alert type="note" >}}
Project runners do not get instance with forked projects automatically.
A fork does copy the CI/CD settings of the cloned repository.
{{< /alert >}}
### Project runner ownership
When a runner first connects to a project, that project becomes the runner's owner.
If you delete the owner project:
1. GitLab finds all other projects that share the runner.
1. GitLab assigns ownership to the project with the oldest association.
1. If no other projects share the runner, GitLab deletes the runner automatically.
You cannot unassign a runner from the owner project. Delete the runner instead.
### Create a project runner with a runner authentication token
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/383143) in GitLab 15.10. Deployed behind the `create_runner_workflow_for_namespace` [flag](../../administration/feature_flags/_index.md). Disabled by default.
- [Enabled by default](https://gitlab.com/gitlab-org/gitlab/-/issues/393919) in GitLab 16.0.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/415447) in GitLab 16.2. Feature flag `create_runner_workflow_for_admin` removed.
{{< /history >}}
Prerequisites:
- You must have the Maintainer role for the project.
You can create a project runner for GitLab Self-Managed or for GitLab.com. When you create a runner,
it is assigned a runner authentication token that you use to register to the runner. The runner uses the token to
authenticate with GitLab when it picks up jobs from the job queue.
To create a project runner:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand the **Runners** section.
1. Select **New project runner**.
1. Select the operating system where GitLab Runner is installed.
1. In the **Tags** section, in the **Tags** field, enter the job tags to specify jobs the runner can run.
If there are no job tags for this runner, select **Run untagged**.
1. Optional. In the **Runner description** field, add a description for the runner
that displays in GitLab.
1. Optional. In the **Configuration** section, add additional configurations.
1. Select **Create runner**.
1. Select the platform where GitLab Runner is installed.
1. Complete the onscreen instructions:
- For Linux, macOS, and Windows, when prompted by the command line:
- For the `GitLab instance URL`, use the URL for your GitLab instance. For example, if your project
is hosted on `gitlab.example.com/yourname/yourproject`, your GitLab instance URL is `https://gitlab.example.com`.
- For the `executor`, enter the type of [executor](https://docs.gitlab.com/runner/executors/). The executor is the
environment where the runner executes the job.
- For Google Cloud, see [Provisioning runners in Google Cloud](provision_runners_google_cloud.md).
You can also [use the API](../../api/users.md#create-a-runner-linked-to-a-user) to create a runner.
{{< alert type="note" >}}
The runner authentication token displays in the UI for only a short period of time during registration.
{{< /alert >}}
### Create a project runner with a registration token (deprecated)
{{< alert type="warning" >}}
The option to use runner registration tokens and support for certain configuration arguments are
[deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/380872) in GitLab 15.6 and is planned for removal in GitLab 20.0.
Use the [runner creation workflow](https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token)
to generate an authentication token to register runners. This process provides full
traceability of runner ownership and enhances your runner fleet's security.
For more information, see
[Migrating to the new runner registration workflow](new_creation_workflow.md).
{{< /alert >}}
Prerequisites:
- Runner registration tokens must be [enabled](#enable-use-of-runner-registration-tokens-in-projects-and-groups) in the top-level group.
- You must have at least the Maintainer role for the project.
To create a project runner:
1. [Install GitLab Runner](https://docs.gitlab.com/runner/install/).
1. On the left sidebar, select **Search or go to** and
find the project where you want to use the runner.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. In the **Project runners** section, note the URL and token.
1. [Register the runner](https://docs.gitlab.com/runner/register/#register-with-a-runner-registration-token-deprecated).
The runner is now enabled for the project.
### Pause or resume a project runner
Prerequisites:
- You must be an administrator, or have the Maintainer role for the project.
You can pause a project runner so that it does not accept jobs from projects it's assigned to
in the GitLab instance.
1. On the left sidebar, select **Search or go to** and
find the project where you want to enable the runner.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. In the **Assigned project runners** section, find the runner.
1. To the right of the runner:
- To pause the runner, select **Pause** ({{< icon name="pause" >}}), then select **Pause**.
- To resume the runner, select **Resume** ({{< icon name="play" >}}).
### Delete a project runner
Prerequisites:
- You must be an administrator, or have the Maintainer role for the project.
- You cannot delete a project runner that is assigned to more than one project. Before you can delete the runner, you must [disable](#enable-a-project-runner-for-a-different-project) it in all projects where it is enabled.
When you delete a project runner, it is permanently deleted from the GitLab instance and can
no longer be used by projects. If you want to temporarily stop the runner from accepting
jobs, you can [pause](#pause-or-resume-a-project-runner) the runner instead.
When you delete a runner, its configuration still exists in the runner host's `config.toml` file.
If the deleted runner's configuration is still present in this file, the runner host continues to contact GitLab.
To prevent unnecessary API traffic, you must also
[unregister the deleted runner](https://docs.gitlab.com/runner/commands/#gitlab-runner-unregister).
1. On the left sidebar, select **Search or go to** and
find the project where you want to enable the runner.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. In the **Assigned project runners** section, find the runner.
1. To the right of the runner, select **Remove runner**.
1. To delete the runner, select **Remove**.
### Enable a project runner for a different project
After a project runner is created, you can enable it for other projects.
Prerequisites:
You must have at least the Maintainer role for:
- The project where the runner is already enabled.
- The project where you want to enable the runner.
- The project runner must not be [locked](#prevent-a-project-runner-from-being-enabled-for-other-projects).
To enable a project runner for a project:
1. On the left sidebar, select **Search or go to** and
find the project where you want to enable the runner.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. In the **Project runners** area, by the runner you want, select **Enable for this project**.
You can edit a project runner from any of the projects it's enabled for.
The modifications, which include unlocking and editing tags and the description,
affect all projects that use the runner.
An administrator can [enable the runner for multiple projects](../../administration/settings/continuous_integration.md#share-project-runners-with-multiple-projects).
### Prevent a project runner from being enabled for other projects
You can configure a project runner so it is "locked" and cannot be enabled for other projects.
This setting can be enabled when you first [register a runner](https://docs.gitlab.com/runner/register/),
but can also be changed later.
To lock or unlock a project runner:
1. On the left sidebar, select **Search or go to** and
find the project where you want to enable the runner.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. Find the project runner you want to lock or unlock. Make sure it's enabled. You cannot lock instance or group runners.
1. Select **Edit** ({{< icon name="pencil" >}}).
1. Select the **Lock to current projects** checkbox.
1. Select **Save changes**.
## Runner statuses
A runner can have one of the following statuses.
| Status | Description |
|---------|-------------|
| `online` | The runner has contacted GitLab in the last 2 hours and is available to run jobs. |
| `offline` | The runner has not contacted GitLab in more than 2 hours and is not available to run jobs. Check the runner to see if you can bring it online. |
| `stale` | The runner has not contacted GitLab in more than 7 days. If the runner was created more than 7 days ago, but it never contacted the instance, it is also considered **stale**. |
| `never_contacted` | The runner has never contacted GitLab. To make the runner contact GitLab, run `gitlab-runner run`. |
## Stale runner manager cleanup
GitLab periodically deletes stale runner managers to maintain a lean database.
If a runner contacts the GitLab instance, the connection is recreated.
## View statistics for runner performance
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/377963) in GitLab 15.8.
{{< /history >}}
As an administrator, you can view runner statistics to learn about the performance of your runner fleet.
The **Median job queued time** value is calculated by sampling the queue duration of the
most recent 100 jobs that were run by Instance runners. Jobs from only the latest 5000
runners are considered.
The median is a value that falls into the 50th percentile. Half of the jobs
queue longer than the median value, and half queue for less time than the
median value.
To view runner statistics:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. Select **View metrics**.
## Determine which runners need to be upgraded
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/365078) in GitLab 15.3.
{{< /history >}}
The version of GitLab Runner used by your runners should be
[kept up-to-date](https://docs.gitlab.com/runner/#gitlab-runner-versions).
To determine which runners need to be upgraded:
1. View the list of runners:
- For a group:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
- For the instance:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. Above the list of runners, view the status:
- **Outdated - recommended**: The runner does not have the latest `PATCH` version, which may make it vulnerable
to security or high severity bugs. Or, the runner is one or more `MAJOR` versions behind your GitLab instance, so some features may not be available or work properly.
- **Outdated - available**: Newer versions are available but upgrading is not critical.
1. Filter the list by status to view which individual runners need to be upgraded.
## Determine the IP address of a runner
To troubleshoot runner issues, you might need to know the runner's IP address.
GitLab stores and displays the IP address by viewing the source of the
HTTP requests when the runner polls for jobs.
GitLab automatically updates the runner's IP address whenever it is updated.
The IP address for instance runners and project runners can be found in
different places.
### Determine the IP address of an instance runner
Prerequisites:
- You must have administrator access to the instance.
To determine the IP address of an instance runner:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. Find the runner in the table and view the **IP Address** column.

### Determine the IP address of a project runner
To can find the IP address of a runner for a project,
you must have the Owner role for the
project.
1. Go to the project's **Settings > CI/CD** and expand the **Runners** section.
1. Select the runner name and find the **IP Address** row.

## Add maintenance notes to runner configuration
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced for administrators](https://gitlab.com/gitlab-org/gitlab/-/issues/348299) in GitLab 15.1.
- [Made available for groups and projects](https://gitlab.com/gitlab-org/gitlab/-/issues/422621) in GitLab 18.2.
{{< /history >}}
You can add a maintenance note to document the runner. Users who can edit the runner
see the note when they view the runner details.
Use this feature to inform others about consequences or problems related to changing the runner configuration.
## Enable use of runner registration tokens in projects and groups
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/148557) in GitLab 16.11
{{< /history >}}
{{< alert type="warning" >}}
The option to use runner registration tokens and support for certain configuration arguments are
[deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/380872) in GitLab 15.6 and is planned for removal in GitLab 20.0.
Use the [runner creation workflow](https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token)
to generate an authentication token to register runners. This process provides full
traceability of runner ownership and enhances your runner fleet's security.
For more information, see
[Migrating to the new runner registration workflow](new_creation_workflow.md).
{{< /alert >}}
In GitLab 17.0, the use of runner registration tokens is disabled in all GitLab instances.
Prerequisites:
- Runner registration tokens must be [enabled](../../administration/settings/continuous_integration.md#control-runner-registration) in the **Admin** area.
To enable the use of runner registration token in project and groups:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. Turn on the **Allow members of projects and groups to create runners with runner registration tokens** toggle.
|
---
stage: Verify
group: Runner
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Learn about the types of runners, their availability, and how to manage
them.
title: Manage runners
breadcrumbs:
- doc
- ci
- runners
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
GitLab Runner has the following types of runners, which are available based on who you want to have access:
- [Instance runners](#instance-runners) are available to all groups and projects in a GitLab instance.
- [Group runners](#group-runners) are available to all projects and subgroups in a group.
- [Project runners](#project-runners) are associated with specific projects.
Typically, project runners are used by one project at a time.
## Instance runners
*Instance runners* are available to every project in a GitLab instance.
Use instance runners when you have multiple jobs with similar requirements. Rather than
having multiple runners idling for many projects, you can have a few runners that handle
multiple projects.
If you are using GitLab Self-Managed, administrators can:
- [Install GitLab Runner](https://docs.gitlab.com/runner/install/) and register an instance runner.
- Configure a maximum number of instance runner [compute minutes for each group](../../administration/cicd/compute_minutes.md#set-the-compute-quota-for-a-group).
If you are using GitLab.com:
- You can select from a list of [instance runners that GitLab maintains](_index.md).
- The instance runners consume the [compute minutes](../pipelines/compute_minutes.md)
included with your account.
### Create an instance runner with a runner authentication token
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/383139) in GitLab 15.10. Deployed behind the `create_runner_workflow_for_admin` [flag](../../administration/feature_flags/_index.md)
- [Enabled by default](https://gitlab.com/gitlab-org/gitlab/-/issues/389269) in GitLab 16.0.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/415447) in GitLab 16.2. Feature flag `create_runner_workflow_for_admin` removed.
{{< /history >}}
Prerequisites:
- You must be an administrator.
When you create a runner, it is assigned a runner authentication token that you use to register it. The runner uses the token to authenticate with GitLab when picking up jobs from the job queue.
To create an instance runner:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. Select **New instance runner**.
1. Select the operating system where GitLab Runner is installed.
1. In the **Tags** section, in the **Tags** field, enter the job tags to specify jobs the runner can run.
If there are no job tags for this runner, select **Run untagged**.
1. Optional. In the **Runner description** field, to add a runner description
that displays in GitLab, enter a runner description.
1. Optional. In the **Configuration** section, add additional configurations.
1. Select **Create runner**.
1. Follow the on-screen instructions to register the runner from the command line. When prompted by the command line:
- For the `GitLab instance URL`, use the URL for your GitLab instance. For example, if your project
is hosted on `gitlab.example.com/yourname/yourproject`, your GitLab instance URL is `https://gitlab.example.com`.
- For the `executor`, enter the type of [executor](https://docs.gitlab.com/runner/executors/). The executor is the
environment where the runner executes the job.
You can also [use the API](../../api/users.md#create-a-runner-linked-to-a-user) to create a runner.
{{< alert type="note" >}}
The runner authentication token displays in the UI for a limited period of time during registration. After you register the runner,
the authentication token is stored in the `config.toml`.
{{< /alert >}}
### Create an instance runner with a registration token (deprecated)
{{< alert type="warning" >}}
The option to use runner registration tokens and support for certain configuration arguments are
[deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/380872) in GitLab 15.6 and is planned for removal in GitLab 20.0.
Use the [runner creation workflow](https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token)
to generate an authentication token to register runners. This process provides full
traceability of runner ownership and enhances your runner fleet's security.
For more information, see
[Migrating to the new runner registration workflow](new_creation_workflow.md).
{{< /alert >}}
Prerequisites:
- Runner registration tokens must be [enabled](../../administration/settings/continuous_integration.md#control-runner-registration) in the **Admin** area.
- You must be an administrator.
To create an instance runner:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. Select **Register an instance runner**.
1. Copy the registration token.
1. [Register the runner](https://docs.gitlab.com/runner/register/#register-with-a-runner-registration-token-deprecated).
### Pause or resume an instance runner
Prerequisites:
- You must be an administrator.
You can pause a runner so that it does not accept jobs from groups and projects in the GitLab instance.
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. In the search box, enter the runner description or filter the runner list.
1. In the runner list, to the right of the runner:
- To pause the runner, select **Pause** ({{< icon name="pause" >}}).
- To resume the runner, select **Resume** ({{< icon name="play" >}}).
### Delete instance runners
Prerequisites:
- You must be an administrator.
When you delete an instance runner, it is permanently deleted from the GitLab instance and can
no longer be used by groups and projects. If you want to temporarily stop the runner from accepting
jobs, you can [pause](#pause-or-resume-an-instance-runner) the runner instead.
To delete a single or multiple instance runners:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. In the search box, enter the runner description or filter the list of runners.
1. Delete the instance runner:
- To delete a single runner, next to the runner, select **Delete runner** ({{< icon name="remove" >}}).
- To delete multiple instance runners, select the checkbox for each runner and select **Delete selected**.
- To delete all runners, select the checkbox at the top of the runner list and select **Delete selected**.
1. Select **Permanently delete runner**.
### Enable instance runners for a project
On GitLab.com, [instance runners](_index.md) are enabled in all projects by
default.
On GitLab Self-Managed, an administrator can
[enable them for all new projects](../../administration/settings/continuous_integration.md#enable-instance-runners-for-new-projects).
For existing projects, an administrator must
[install](https://docs.gitlab.com/runner/install/) and
[register](https://docs.gitlab.com/runner/register/) them.
To enable instance runners for a project:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. Enable the **Turn on instance runners for this project** toggle.
### Enable instance runners for a group
To enable instance runners for a group:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. Enable the **Turn on instance runners for this group** toggle.
### Disable instance runners for a project
You can disable instance runners for individual projects or for groups.
You must have the Owner role for the project
or group.
To disable instance runners for a project:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. In the **Instance runners** area, turn off the **Turn on runners for this project** toggle.
Instance runners are automatically disabled for a project:
- If the instance runners setting for the parent group is disabled, and
- If overriding this setting is not permitted for projects.
### Disable instance runners for a group
To disable instance runners for a group:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. Turn off the **Enable instance runners for this group** toggle.
1. Optional. To allow instance runners to be enabled for individual projects or subgroups,
select **Allow projects and subgroups to override the group setting**.
### How instance runners pick jobs
Instance runners process jobs by using a fair usage queue. This queue prevents
projects from creating hundreds of jobs and using all available
instance runner resources.
The fair usage queue algorithm assigns jobs based on the projects that have the
fewest number of jobs already running on instance runners.
For example, if these jobs are in the queue:
- Job 1 for Project 1
- Job 2 for Project 1
- Job 3 for Project 1
- Job 4 for Project 2
- Job 5 for Project 2
- Job 6 for Project 3
When several CI/CD jobs run concurrently, the fair usage algorithm assigns jobs in this order:
1. Job 1 is first, because it has the lowest job number from projects with no running jobs (that is, all projects).
1. Job 4 is next, because 4 is now the lowest job number from projects with no running jobs (Project 1 has a job running).
1. Job 6 is next, because 6 is now the lowest job number from projects with no running jobs (Projects 1 and 2 have jobs running).
1. Job 2 is next, because, of projects with the lowest number of jobs running (each has 1), it is the lowest job number.
1. Job 5 is next, because Project 1 now has 2 jobs running and Job 5 is the lowest remaining job number between Projects 2 and 3.
1. Finally is Job 3 because it's the only job left.
When only one job runs at a time, the fair usage algorithm assigns jobs in this order:
1. Job 1 is chosen first, because it has the lowest job number from projects with no running jobs (that is, all projects).
1. We finish Job 1.
1. Job 2 is next, because, having finished Job 1, all projects have 0 jobs running again, and 2 is the lowest available job number.
1. Job 4 is next, because with Project 1 running a Job, 4 is the lowest number from projects running no jobs (Projects 2 and 3).
1. We finish Job 4.
1. Job 5 is next, because having finished Job 4, Project 2 has no jobs running again.
1. Job 6 is next, because Project 3 is the only project left with no running jobs.
1. Lastly we choose Job 3, because, again, it's the only job left.
## Group runners
Use group runners when you want all projects in a group
to have access to a set of runners.
Group runners process jobs by using a first in, first out queue.
### Create a group runner with a runner authentication token
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/383143) in GitLab 15.10. Deployed behind the `create_runner_workflow_for_namespace` [flag](../../administration/feature_flags/_index.md). Disabled by default.
- [Enabled by default](https://gitlab.com/gitlab-org/gitlab/-/issues/393919) in GitLab 16.0.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/415447) in GitLab 16.2. Feature flag `create_runner_workflow_for_admin` removed.
{{< /history >}}
Prerequisites:
- You must have the Owner role for the group.
You can create a group runner for GitLab Self-Managed or for GitLab.com.
When you create a runner, it is assigned a runner authentication token that you use to register it.
The runner uses the token to authenticate with GitLab when it picks up jobs from the job queue.
To create a group runner:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. Select **New group runner**.
1. In the **Tags** section, in the **Tags** field, enter the job tags to specify jobs the runner can run.
If there are no job tags for this runner, select **Run untagged**.
1. Optional. In the **Runner description** field, add a runner description
that displays in GitLab.
1. Optional. In the **Configuration** section, add additional configurations.
1. Select **Create runner**.
1. Select the platform where GitLab Runner is installed.
1. Complete the onscreen instructions:
- For Linux, macOS, and Windows, when prompted by the command line:
- For the `GitLab instance URL`, use the URL for your GitLab instance. For example, if your project
is hosted on `gitlab.example.com/yourname/yourproject`, your GitLab instance URL is `https://gitlab.example.com`.
- For the `executor`, enter the type of [executor](https://docs.gitlab.com/runner/executors/). The executor is the
environment where the runner executes the job.
- For Google Cloud, see [Provisioning runners in Google Cloud](provision_runners_google_cloud.md).
You can also [use the API](../../api/users.md#create-a-runner-linked-to-a-user) to create a runner.
{{< alert type="note" >}}
The runner authentication token displays in the UI for only a short period of time during registration.
{{< /alert >}}
### Create a group runner with a registration token (deprecated)
{{< history >}}
- Path changed from **Settings > CI/CD > Runners**.
{{< /history >}}
{{< alert type="warning" >}}
The option to use runner registration tokens and support for certain configuration arguments are
[deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/380872) in GitLab 15.6 and is planned for removal in GitLab 20.0.
Use the [runner creation workflow](https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token)
to generate an authentication token to register runners. This process provides full
traceability of runner ownership and enhances your runner fleet's security.
For more information, see
[Migrating to the new runner registration workflow](new_creation_workflow.md).
{{< /alert >}}
Prerequisites:
- Runner registration tokens must be [enabled](#enable-use-of-runner-registration-tokens-in-projects-and-groups) in the top-level group.
- You must have the Owner role for the group.
To create a group runner:
1. [Install GitLab Runner](https://docs.gitlab.com/runner/install/).
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. In the upper-right corner, select **Register a group runner**.
1. Select **Show runner installation and registration instructions**.
These instructions include the token, URL, and a command to register a runner.
Alternately, you can copy the registration token and follow the documentation for
how to [register a runner](https://docs.gitlab.com/runner/register/#register-with-a-runner-registration-token-deprecated).
### View group runners
{{< history >}}
- Ability for users with the Maintainer role to view group runners [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/384179) in GitLab 16.4.
{{< /history >}}
Prerequisites:
- You must have the Maintainer or Owner role for the group.
You can view all runners for a group and its subgroups and projects.
You can do this for GitLab Self-Managed or for GitLab.com.
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
#### Filter group runners to show only inherited
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/337838/) in GitLab 15.5.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/101099) in GitLab 15.5. Feature flag `runners_finder_all_available` removed.
{{< /history >}}
You can choose to show all runners in the list, or show only
those that are inherited from the instance or other groups.
By default, only those that are inherited are shown.
To show all runners available in the instance, including instance runners and
those in other groups:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. Above the list, turn off the **Show only inherited** toggle.
### Pause or resume a group runner
Prerequisites:
- You must be an administrator or have the Owner role for the group.
You can pause a runner so that it does not accept jobs from subgroups and projects in the GitLab
instance. If you pause a group runner that is used by multiple projects, the runner pauses for all projects.
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. In the search box, enter the runner description or filter the runner list.
1. In the runner list, to the right of the runner:
- To pause the runner, select **Pause** ({{< icon name="pause" >}}).
- To resume the runner, select **Resume** ({{< icon name="play" >}}).
### Delete a group runner
{{< history >}}
- Multiple runner deletion [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/361721/) in GitLab 15.6.
{{< /history >}}
Prerequisites:
- You must be an administrator or have the Owner role for the group.
When you delete a group runner, it is permanently deleted from the GitLab instance and can
no longer be used by subgroups and projects. If you want to temporarily stop the runner from accepting
jobs, you can [pause](#pause-or-resume-a-group-runner) the runner instead.
To delete a single or multiple group runners:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
1. In the search box, enter the runner description or filter the list of runners.
1. Delete the group runner:
- To delete a single runner, next to the runner, select **Delete runner** ({{< icon name="remove" >}}).
- To delete multiple instance runners, select the checkbox for each runner and select **Delete selected**.
- To delete all runners, select the checkbox at the top of the runner list and select **Delete selected**.
1. Select **Permanently delete runner**.
### Clean up stale group runners
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/363012) in GitLab 15.1.
{{< /history >}}
Prerequisites:
- You must have the Owner role for the group.
You can clean up group runners that have been inactive for more than three months.
Group runners are those that were created in a specific group.
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. Turn on the **Enable stale runner cleanup** toggle.
#### View stale runner cleanup logs
You can check the [Sidekiq logs](../../administration/logs/_index.md#sidekiq-logs) to see the cleanup result. In Kibana you can use the following query:
```json
{
"query": {
"match_phrase": {
"json.class.keyword": "Ci::Runners::StaleGroupRunnersPruneCronWorker"
}
}
}
```
Filter entries where stale runners were removed:
```json
{
"query": {
"range": {
"json.extra.ci_runners_stale_group_runners_prune_cron_worker.total_pruned": {
"gte": 1,
"lt": null
}
}
}
}
```
## Project runners
Use project runners when you want to use runners for specific projects. For example,
when you have:
- Jobs with specific requirements, like a deploy job that requires credentials.
- Projects with a lot of CI activity that can benefit from being separate from other runners.
You can set up a project runner to be used by multiple projects. Project runners
must be enabled for each project explicitly.
Project runners process jobs by using a first in, first out ([FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics))) queue.
{{< alert type="note" >}}
Project runners do not get instance with forked projects automatically.
A fork does copy the CI/CD settings of the cloned repository.
{{< /alert >}}
### Project runner ownership
When a runner first connects to a project, that project becomes the runner's owner.
If you delete the owner project:
1. GitLab finds all other projects that share the runner.
1. GitLab assigns ownership to the project with the oldest association.
1. If no other projects share the runner, GitLab deletes the runner automatically.
You cannot unassign a runner from the owner project. Delete the runner instead.
### Create a project runner with a runner authentication token
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/383143) in GitLab 15.10. Deployed behind the `create_runner_workflow_for_namespace` [flag](../../administration/feature_flags/_index.md). Disabled by default.
- [Enabled by default](https://gitlab.com/gitlab-org/gitlab/-/issues/393919) in GitLab 16.0.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/415447) in GitLab 16.2. Feature flag `create_runner_workflow_for_admin` removed.
{{< /history >}}
Prerequisites:
- You must have the Maintainer role for the project.
You can create a project runner for GitLab Self-Managed or for GitLab.com. When you create a runner,
it is assigned a runner authentication token that you use to register to the runner. The runner uses the token to
authenticate with GitLab when it picks up jobs from the job queue.
To create a project runner:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand the **Runners** section.
1. Select **New project runner**.
1. Select the operating system where GitLab Runner is installed.
1. In the **Tags** section, in the **Tags** field, enter the job tags to specify jobs the runner can run.
If there are no job tags for this runner, select **Run untagged**.
1. Optional. In the **Runner description** field, add a description for the runner
that displays in GitLab.
1. Optional. In the **Configuration** section, add additional configurations.
1. Select **Create runner**.
1. Select the platform where GitLab Runner is installed.
1. Complete the onscreen instructions:
- For Linux, macOS, and Windows, when prompted by the command line:
- For the `GitLab instance URL`, use the URL for your GitLab instance. For example, if your project
is hosted on `gitlab.example.com/yourname/yourproject`, your GitLab instance URL is `https://gitlab.example.com`.
- For the `executor`, enter the type of [executor](https://docs.gitlab.com/runner/executors/). The executor is the
environment where the runner executes the job.
- For Google Cloud, see [Provisioning runners in Google Cloud](provision_runners_google_cloud.md).
You can also [use the API](../../api/users.md#create-a-runner-linked-to-a-user) to create a runner.
{{< alert type="note" >}}
The runner authentication token displays in the UI for only a short period of time during registration.
{{< /alert >}}
### Create a project runner with a registration token (deprecated)
{{< alert type="warning" >}}
The option to use runner registration tokens and support for certain configuration arguments are
[deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/380872) in GitLab 15.6 and is planned for removal in GitLab 20.0.
Use the [runner creation workflow](https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token)
to generate an authentication token to register runners. This process provides full
traceability of runner ownership and enhances your runner fleet's security.
For more information, see
[Migrating to the new runner registration workflow](new_creation_workflow.md).
{{< /alert >}}
Prerequisites:
- Runner registration tokens must be [enabled](#enable-use-of-runner-registration-tokens-in-projects-and-groups) in the top-level group.
- You must have at least the Maintainer role for the project.
To create a project runner:
1. [Install GitLab Runner](https://docs.gitlab.com/runner/install/).
1. On the left sidebar, select **Search or go to** and
find the project where you want to use the runner.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. In the **Project runners** section, note the URL and token.
1. [Register the runner](https://docs.gitlab.com/runner/register/#register-with-a-runner-registration-token-deprecated).
The runner is now enabled for the project.
### Pause or resume a project runner
Prerequisites:
- You must be an administrator, or have the Maintainer role for the project.
You can pause a project runner so that it does not accept jobs from projects it's assigned to
in the GitLab instance.
1. On the left sidebar, select **Search or go to** and
find the project where you want to enable the runner.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. In the **Assigned project runners** section, find the runner.
1. To the right of the runner:
- To pause the runner, select **Pause** ({{< icon name="pause" >}}), then select **Pause**.
- To resume the runner, select **Resume** ({{< icon name="play" >}}).
### Delete a project runner
Prerequisites:
- You must be an administrator, or have the Maintainer role for the project.
- You cannot delete a project runner that is assigned to more than one project. Before you can delete the runner, you must [disable](#enable-a-project-runner-for-a-different-project) it in all projects where it is enabled.
When you delete a project runner, it is permanently deleted from the GitLab instance and can
no longer be used by projects. If you want to temporarily stop the runner from accepting
jobs, you can [pause](#pause-or-resume-a-project-runner) the runner instead.
When you delete a runner, its configuration still exists in the runner host's `config.toml` file.
If the deleted runner's configuration is still present in this file, the runner host continues to contact GitLab.
To prevent unnecessary API traffic, you must also
[unregister the deleted runner](https://docs.gitlab.com/runner/commands/#gitlab-runner-unregister).
1. On the left sidebar, select **Search or go to** and
find the project where you want to enable the runner.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. In the **Assigned project runners** section, find the runner.
1. To the right of the runner, select **Remove runner**.
1. To delete the runner, select **Remove**.
### Enable a project runner for a different project
After a project runner is created, you can enable it for other projects.
Prerequisites:
You must have at least the Maintainer role for:
- The project where the runner is already enabled.
- The project where you want to enable the runner.
- The project runner must not be [locked](#prevent-a-project-runner-from-being-enabled-for-other-projects).
To enable a project runner for a project:
1. On the left sidebar, select **Search or go to** and
find the project where you want to enable the runner.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. In the **Project runners** area, by the runner you want, select **Enable for this project**.
You can edit a project runner from any of the projects it's enabled for.
The modifications, which include unlocking and editing tags and the description,
affect all projects that use the runner.
An administrator can [enable the runner for multiple projects](../../administration/settings/continuous_integration.md#share-project-runners-with-multiple-projects).
### Prevent a project runner from being enabled for other projects
You can configure a project runner so it is "locked" and cannot be enabled for other projects.
This setting can be enabled when you first [register a runner](https://docs.gitlab.com/runner/register/),
but can also be changed later.
To lock or unlock a project runner:
1. On the left sidebar, select **Search or go to** and
find the project where you want to enable the runner.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. Find the project runner you want to lock or unlock. Make sure it's enabled. You cannot lock instance or group runners.
1. Select **Edit** ({{< icon name="pencil" >}}).
1. Select the **Lock to current projects** checkbox.
1. Select **Save changes**.
## Runner statuses
A runner can have one of the following statuses.
| Status | Description |
|---------|-------------|
| `online` | The runner has contacted GitLab in the last 2 hours and is available to run jobs. |
| `offline` | The runner has not contacted GitLab in more than 2 hours and is not available to run jobs. Check the runner to see if you can bring it online. |
| `stale` | The runner has not contacted GitLab in more than 7 days. If the runner was created more than 7 days ago, but it never contacted the instance, it is also considered **stale**. |
| `never_contacted` | The runner has never contacted GitLab. To make the runner contact GitLab, run `gitlab-runner run`. |
## Stale runner manager cleanup
GitLab periodically deletes stale runner managers to maintain a lean database.
If a runner contacts the GitLab instance, the connection is recreated.
## View statistics for runner performance
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/377963) in GitLab 15.8.
{{< /history >}}
As an administrator, you can view runner statistics to learn about the performance of your runner fleet.
The **Median job queued time** value is calculated by sampling the queue duration of the
most recent 100 jobs that were run by Instance runners. Jobs from only the latest 5000
runners are considered.
The median is a value that falls into the 50th percentile. Half of the jobs
queue longer than the median value, and half queue for less time than the
median value.
To view runner statistics:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. Select **View metrics**.
## Determine which runners need to be upgraded
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/365078) in GitLab 15.3.
{{< /history >}}
The version of GitLab Runner used by your runners should be
[kept up-to-date](https://docs.gitlab.com/runner/#gitlab-runner-versions).
To determine which runners need to be upgraded:
1. View the list of runners:
- For a group:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Build > Runners**.
- For the instance:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. Above the list of runners, view the status:
- **Outdated - recommended**: The runner does not have the latest `PATCH` version, which may make it vulnerable
to security or high severity bugs. Or, the runner is one or more `MAJOR` versions behind your GitLab instance, so some features may not be available or work properly.
- **Outdated - available**: Newer versions are available but upgrading is not critical.
1. Filter the list by status to view which individual runners need to be upgraded.
## Determine the IP address of a runner
To troubleshoot runner issues, you might need to know the runner's IP address.
GitLab stores and displays the IP address by viewing the source of the
HTTP requests when the runner polls for jobs.
GitLab automatically updates the runner's IP address whenever it is updated.
The IP address for instance runners and project runners can be found in
different places.
### Determine the IP address of an instance runner
Prerequisites:
- You must have administrator access to the instance.
To determine the IP address of an instance runner:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **CI/CD > Runners**.
1. Find the runner in the table and view the **IP Address** column.

### Determine the IP address of a project runner
To can find the IP address of a runner for a project,
you must have the Owner role for the
project.
1. Go to the project's **Settings > CI/CD** and expand the **Runners** section.
1. Select the runner name and find the **IP Address** row.

## Add maintenance notes to runner configuration
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced for administrators](https://gitlab.com/gitlab-org/gitlab/-/issues/348299) in GitLab 15.1.
- [Made available for groups and projects](https://gitlab.com/gitlab-org/gitlab/-/issues/422621) in GitLab 18.2.
{{< /history >}}
You can add a maintenance note to document the runner. Users who can edit the runner
see the note when they view the runner details.
Use this feature to inform others about consequences or problems related to changing the runner configuration.
## Enable use of runner registration tokens in projects and groups
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/148557) in GitLab 16.11
{{< /history >}}
{{< alert type="warning" >}}
The option to use runner registration tokens and support for certain configuration arguments are
[deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/380872) in GitLab 15.6 and is planned for removal in GitLab 20.0.
Use the [runner creation workflow](https://docs.gitlab.com/runner/register/#register-with-a-runner-authentication-token)
to generate an authentication token to register runners. This process provides full
traceability of runner ownership and enhances your runner fleet's security.
For more information, see
[Migrating to the new runner registration workflow](new_creation_workflow.md).
{{< /alert >}}
In GitLab 17.0, the use of runner registration tokens is disabled in all GitLab instances.
Prerequisites:
- Runner registration tokens must be [enabled](../../administration/settings/continuous_integration.md#control-runner-registration) in the **Admin** area.
To enable the use of runner registration token in project and groups:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings > CI/CD**.
1. Expand **Runners**.
1. Turn on the **Allow members of projects and groups to create runners with runner registration tokens** toggle.
|
https://docs.gitlab.com/ci/runner_fleet_dashboard
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/runner_fleet_dashboard.md
|
2025-08-13
|
doc/ci/runners
|
[
"doc",
"ci",
"runners"
] |
runner_fleet_dashboard.md
|
Verify
|
Runner
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Runner fleet dashboard for administrators
| null |
{{< details >}}
- Tier: Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/424495) in GitLab 16.6
{{< /history >}}
As a GitLab administrator, you can use the runner fleet dashboard to assess the health of your instance runners.
The runner fleet dashboard shows:
- Recent CI errors caused by runner infrastructure
- Number of concurrent jobs executed on most busy runners
- Compute minutes used by instance runners
- Job queue times (available only with [ClickHouse](#enable-more-ci-analytics-features-with-clickhouse))

## Dashboard metrics
The following metrics are available in the runner fleet dashboard:
| Metric | Description |
|-------------------------------|-------------|
| Online | Number of runners that are online for the entire instance. |
| Offline | Number of runners that are currently offline. Runners that were registered but never connected to GitLab are not included in this count. |
| Active runners | The total number of runners that are currently active. |
| Runner usage (previous month) | **Requires ClickHouse**: The total compute minutes used by each project or group runner in the previous month. You can export this data as a CSV file for cost analysis. |
| Wait time to pick a job | **Requires ClickHouse**: The average time a job waits in the queue before a runner picks it up. This metric provides insights into whether your runners are capable of servicing the CI/CD job queue in your organization's target service-level objectives (SLOs). This data is updated every 24 hours. |
{{< alert type="note" >}}
If you do not configure ClickHouse, the Fleet Dashboard page does not populate the widgets that rely on the ClickHouse backend.
{{< /alert >}}
## View the runner fleet dashboard
Prerequisites:
- You must be an administrator.
To view the runner fleet dashboard:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Runners**.
1. Select **Fleet dashboard**.
Most of the dashboard works without any additional actions, with the
exception of **Wait time to pick a job** chart and features proposed in [epic 11183](https://gitlab.com/groups/gitlab-org/-/epics/11183).
These features require [setting up an additional infrastructure](#enable-more-ci-analytics-features-with-clickhouse).
## Export compute minutes used by instance runners
Prerequisites:
- You must have administrator access to the instance.
- You must enable the [ClickHouse integration](../../integration/clickhouse.md).
To analyze runner usage, you can export a CSV file that contains the number of jobs and executed runner minutes. The
CSV file shows the runner type and job status for each project. The CSV is sent to your email when the export is completed.
To export compute minutes used by instance runners:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Runners**.
1. Select **Fleet dashboard**.
1. Select **Export CSV**.
## Enable more CI analytics features with ClickHouse
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed
- Status: Beta
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/11180) as an [experiment](../../policy/development_stages_support.md#experiment) in GitLab 16.7 with [flags](../../administration/feature_flags/_index.md) named `ci_data_ingestion_to_click_house` and `clickhouse_ci_analytics`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/424866) in GitLab 16.10. Feature flags `ci_data_ingestion_to_click_house` and `clickhouse_ci_analytics` removed.
- [Changed](https://gitlab.com/gitlab-org/gitlab/-/issues/424789) to [beta](../../policy/development_stages_support.md#beta) in GitLab 17.1.
{{< /history >}}
{{< alert type="warning" >}}
This feature is in [beta](../../policy/development_stages_support.md#beta) and subject to change without notice.
For more information, see [epic 11180](https://gitlab.com/groups/gitlab-org/-/epics/11180).
{{< /alert >}}
To enable additional CI analytics features, [configure the ClickHouse integration](../../integration/clickhouse.md).
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [Setting up runner fleet dashboard with ClickHouse](https://www.youtube.com/watch?v=YpGV95Ctbpk).
<!-- Video published on 2023-12-19 -->
## Feedback
To help us improve the runner fleet dashboard, you can provide feedback in
[issue 421737](https://gitlab.com/gitlab-org/gitlab/-/issues/421737).
In particular:
- How easy or difficult it was to set up GitLab to make the dashboard work.
- How useful you found the dashboard.
- What other information you would like to see on that dashboard.
- Any other related thoughts and ideas.
|
---
stage: Verify
group: Runner
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Runner fleet dashboard for administrators
breadcrumbs:
- doc
- ci
- runners
---
{{< details >}}
- Tier: Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/424495) in GitLab 16.6
{{< /history >}}
As a GitLab administrator, you can use the runner fleet dashboard to assess the health of your instance runners.
The runner fleet dashboard shows:
- Recent CI errors caused by runner infrastructure
- Number of concurrent jobs executed on most busy runners
- Compute minutes used by instance runners
- Job queue times (available only with [ClickHouse](#enable-more-ci-analytics-features-with-clickhouse))

## Dashboard metrics
The following metrics are available in the runner fleet dashboard:
| Metric | Description |
|-------------------------------|-------------|
| Online | Number of runners that are online for the entire instance. |
| Offline | Number of runners that are currently offline. Runners that were registered but never connected to GitLab are not included in this count. |
| Active runners | The total number of runners that are currently active. |
| Runner usage (previous month) | **Requires ClickHouse**: The total compute minutes used by each project or group runner in the previous month. You can export this data as a CSV file for cost analysis. |
| Wait time to pick a job | **Requires ClickHouse**: The average time a job waits in the queue before a runner picks it up. This metric provides insights into whether your runners are capable of servicing the CI/CD job queue in your organization's target service-level objectives (SLOs). This data is updated every 24 hours. |
{{< alert type="note" >}}
If you do not configure ClickHouse, the Fleet Dashboard page does not populate the widgets that rely on the ClickHouse backend.
{{< /alert >}}
## View the runner fleet dashboard
Prerequisites:
- You must be an administrator.
To view the runner fleet dashboard:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Runners**.
1. Select **Fleet dashboard**.
Most of the dashboard works without any additional actions, with the
exception of **Wait time to pick a job** chart and features proposed in [epic 11183](https://gitlab.com/groups/gitlab-org/-/epics/11183).
These features require [setting up an additional infrastructure](#enable-more-ci-analytics-features-with-clickhouse).
## Export compute minutes used by instance runners
Prerequisites:
- You must have administrator access to the instance.
- You must enable the [ClickHouse integration](../../integration/clickhouse.md).
To analyze runner usage, you can export a CSV file that contains the number of jobs and executed runner minutes. The
CSV file shows the runner type and job status for each project. The CSV is sent to your email when the export is completed.
To export compute minutes used by instance runners:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Runners**.
1. Select **Fleet dashboard**.
1. Select **Export CSV**.
## Enable more CI analytics features with ClickHouse
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed
- Status: Beta
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/11180) as an [experiment](../../policy/development_stages_support.md#experiment) in GitLab 16.7 with [flags](../../administration/feature_flags/_index.md) named `ci_data_ingestion_to_click_house` and `clickhouse_ci_analytics`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/424866) in GitLab 16.10. Feature flags `ci_data_ingestion_to_click_house` and `clickhouse_ci_analytics` removed.
- [Changed](https://gitlab.com/gitlab-org/gitlab/-/issues/424789) to [beta](../../policy/development_stages_support.md#beta) in GitLab 17.1.
{{< /history >}}
{{< alert type="warning" >}}
This feature is in [beta](../../policy/development_stages_support.md#beta) and subject to change without notice.
For more information, see [epic 11180](https://gitlab.com/groups/gitlab-org/-/epics/11180).
{{< /alert >}}
To enable additional CI analytics features, [configure the ClickHouse integration](../../integration/clickhouse.md).
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [Setting up runner fleet dashboard with ClickHouse](https://www.youtube.com/watch?v=YpGV95Ctbpk).
<!-- Video published on 2023-12-19 -->
## Feedback
To help us improve the runner fleet dashboard, you can provide feedback in
[issue 421737](https://gitlab.com/gitlab-org/gitlab/-/issues/421737).
In particular:
- How easy or difficult it was to set up GitLab to make the dashboard work.
- How useful you found the dashboard.
- What other information you would like to see on that dashboard.
- Any other related thoughts and ideas.
|
https://docs.gitlab.com/ci/long_polling
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/long_polling.md
|
2025-08-13
|
doc/ci/runners
|
[
"doc",
"ci",
"runners"
] |
long_polling.md
|
Verify
|
Runner
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Long polling
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
By default, a GitLab Runner polls a GitLab instance for new CI/CD
jobs periodically. The actual polling interval [depends on the `check_interval` and number of runners configured in the runner configuration file](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#how-check_interval-works).
On a server that handles many runners, this polling can lead to these performance issues:
- Longer queuing times.
- Higher CPU usage on the GitLab instance.
To mitigate these issues, you should enable long polling.
Prerequisites:
- You must be an administrator.
## Enable long polling
You can configure a GitLab instance to hold job requests from runners in a long
poll until a new job is ready.
To do this, enable long polling by configuring the GitLab Workhorse long
polling duration (`apiCiLongPollingDuration`):
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_workhorse['api_ci_long_polling_duration'] = "50s"
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
Enable long polling with the `gitlab.webservice.workhorse.extraArgs` setting.
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
gitlab:
webservice:
workhorse:
extraArgs: "-apiCiLongPollingDuration 50s"
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_workhorse['api_ci_long_polling_duration'] = "50s"
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< /tabs >}}
## Metrics
When long polling is enabled, GitLab Workhorse subscribes to Redis
PubSub channels and awaits notifications. A job request is released
from a long poll when its runner key is changed, or when
`apiCiLongPollingDuration` has been reached. There are a number of
Prometheus metrics that you can monitor:
| Metric | Type | Description | Labels |
| ----- | ---- | ----------- | ------ |
| `gitlab_workhorse_keywatcher_keywatchers` | Gauge | The number of keys that is being watched by GitLab Workhorse | |
| `gitlab_workhorse_keywatcher_redis_subscriptions` | Gauge | The number of Redis PubSub subscriptions | |
| `gitlab_workhorse_keywatcher_total_messages` | Counter | Total number of messages GitLab Workhorse has received on the PubSub channels | |
| `gitlab_workhorse_keywatcher_actions_total` | Counter | Counts of various key watcher actions | `action` |
| `gitlab_workhorse_keywatcher_received_bytes_total` | Counter | Total bytes received on PubSub channels | |
You can see an [example of how one user discovered an issue with long polling with these metrics](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/8329).
## Long polling workflow
The diagram shows how a single runner gets a job with long polling enabled:
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
accTitle: Long polling workflow
accDescr: The flow of a single runner getting a job with long polling enabled
autonumber
participant C as Runner
participant W as Workhorse
participant Redis as Redis
participant R as Rails
participant S as Sidekiq
C->>+W: POST /api/v4/jobs/request
W->>+Redis: New job for runner A?
Redis->>+W: Unknown
W->>+R: POST /api/v4/jobs/request
R->>+Redis: Runner A: last_update = X
R->>W: 204 No job, X-GitLab-Last-Update = X
W->>C: 204 No job, X-GitLab-Last-Update = X
C->>W: POST /api/v4/jobs/request, X-GitLab-Last-Update: X
W->>Redis: Notify when last_update change
Note over W: Request held in long poll
Note over S: CI job created
Note over S, Redis: Update all registered runners
S->>Redis: Runner A: last_update = Z
Redis->>W: Runner: last_update changed
Note over W: Request released from long poll
W->>Rails: POST /api/v4/jobs/request
Rails->>W: 201 Job was scheduled
W->>C: 201 Job was scheduled
```
In step 1, when a runner requests a new job, it issues a `POST` request
(`/api/v4/jobs/request`) to the GitLab server, where it is first handled
by Workhorse.
Workhorse reads the runner token and value from the
`X-GitLab-Last-Update` HTTP header, constructs a key, and subscribes to
a Redis PubSub channel with that key. If no value exists for the key,
then Workhorse immediately forwards the request on to Rails (steps 3 and
4).
Rails checks the job queue. If there are no jobs available for the
runner, Rails returns a `204 No job` with a `last_update` token to the
runner (steps 5 to 7).
The runner uses that `last_update` token and issues another request for
a job, populating the `X-GitLab-Last-Update` HTTP header with this
token. This time, Workhorse checks if the runner's `last_update` token
has changed. If it has not, Workhorse holds onto the request for up to
the duration specified by `apiCiLongPollingDuration`.
If a user triggers a new pipeline or job to run, a background task in
Sidekiq will update the `last_update` value for all runners available to
the job. Runners can be registered for the project, group, and/or
instance.
This "tick" in steps 10 and 11 releases the job request from the
Workhorse long poll queue, and the request gets sent to Rails (step
12). Rails looks for an available job, and assigns the runner to that
job (steps 13 and 14).
With long polling, the runner gets notified immediately after a new job
is available. This not only helps improve reduce job queueing time, but
it also reduces server overhead because the job requests reach
Rails only when there is new work.
## Troubleshooting
When working with long polling, you might encounter the following issues.
### Slow job pickup
Long polling is not enabled by default because in some runner
configurations, the runner doesn't pick up jobs in a timely manner.
See [issue 27709](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/27709).
This can happen if the `concurrent` setting in the runner `config.toml`
is set to a value lower than the number of runners defined. To resolve
this issue, ensure the value of `concurrent` is at equal or greater than the
number of runners.
For example, if you have three `[[runners]]` entries in `config.toml`, make
sure that `concurrent` is set to at least 3.
When long polling is enabled, the runner:
1. Launches `concurrent` number of Goroutines.
1. Waits for the Goroutines to return after long polling.
1. Runs another batch of requests.
For example, consider the case where a single `config.toml` has configured:
- 3 runners for project A.
- 1 runner for project B.
- `concurrent` set to 3.
In this example, a runner launches Goroutines for the first 3 projects.
In the worst case, the runner waits the full long poll interval for project
A before proceeding with requesting a job for project B.
|
---
stage: Verify
group: Runner
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Long polling
breadcrumbs:
- doc
- ci
- runners
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
By default, a GitLab Runner polls a GitLab instance for new CI/CD
jobs periodically. The actual polling interval [depends on the `check_interval` and number of runners configured in the runner configuration file](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#how-check_interval-works).
On a server that handles many runners, this polling can lead to these performance issues:
- Longer queuing times.
- Higher CPU usage on the GitLab instance.
To mitigate these issues, you should enable long polling.
Prerequisites:
- You must be an administrator.
## Enable long polling
You can configure a GitLab instance to hold job requests from runners in a long
poll until a new job is ready.
To do this, enable long polling by configuring the GitLab Workhorse long
polling duration (`apiCiLongPollingDuration`):
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_workhorse['api_ci_long_polling_duration'] = "50s"
```
1. Save the file and reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
{{< /tab >}}
{{< tab title="Helm chart (Kubernetes)" >}}
Enable long polling with the `gitlab.webservice.workhorse.extraArgs` setting.
1. Export the Helm values:
```shell
helm get values gitlab > gitlab_values.yaml
```
1. Edit `gitlab_values.yaml`:
```yaml
gitlab:
webservice:
workhorse:
extraArgs: "-apiCiLongPollingDuration 50s"
```
1. Save the file and apply the new values:
```shell
helm upgrade -f gitlab_values.yaml gitlab gitlab/gitlab
```
{{< /tab >}}
{{< tab title="Docker" >}}
1. Edit `docker-compose.yml`:
```yaml
version: "3.6"
services:
gitlab:
image: 'gitlab/gitlab-ee:latest'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_workhorse['api_ci_long_polling_duration'] = "50s"
```
1. Save the file and restart GitLab:
```shell
docker compose up -d
```
{{< /tab >}}
{{< /tabs >}}
## Metrics
When long polling is enabled, GitLab Workhorse subscribes to Redis
PubSub channels and awaits notifications. A job request is released
from a long poll when its runner key is changed, or when
`apiCiLongPollingDuration` has been reached. There are a number of
Prometheus metrics that you can monitor:
| Metric | Type | Description | Labels |
| ----- | ---- | ----------- | ------ |
| `gitlab_workhorse_keywatcher_keywatchers` | Gauge | The number of keys that is being watched by GitLab Workhorse | |
| `gitlab_workhorse_keywatcher_redis_subscriptions` | Gauge | The number of Redis PubSub subscriptions | |
| `gitlab_workhorse_keywatcher_total_messages` | Counter | Total number of messages GitLab Workhorse has received on the PubSub channels | |
| `gitlab_workhorse_keywatcher_actions_total` | Counter | Counts of various key watcher actions | `action` |
| `gitlab_workhorse_keywatcher_received_bytes_total` | Counter | Total bytes received on PubSub channels | |
You can see an [example of how one user discovered an issue with long polling with these metrics](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/8329).
## Long polling workflow
The diagram shows how a single runner gets a job with long polling enabled:
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
sequenceDiagram
accTitle: Long polling workflow
accDescr: The flow of a single runner getting a job with long polling enabled
autonumber
participant C as Runner
participant W as Workhorse
participant Redis as Redis
participant R as Rails
participant S as Sidekiq
C->>+W: POST /api/v4/jobs/request
W->>+Redis: New job for runner A?
Redis->>+W: Unknown
W->>+R: POST /api/v4/jobs/request
R->>+Redis: Runner A: last_update = X
R->>W: 204 No job, X-GitLab-Last-Update = X
W->>C: 204 No job, X-GitLab-Last-Update = X
C->>W: POST /api/v4/jobs/request, X-GitLab-Last-Update: X
W->>Redis: Notify when last_update change
Note over W: Request held in long poll
Note over S: CI job created
Note over S, Redis: Update all registered runners
S->>Redis: Runner A: last_update = Z
Redis->>W: Runner: last_update changed
Note over W: Request released from long poll
W->>Rails: POST /api/v4/jobs/request
Rails->>W: 201 Job was scheduled
W->>C: 201 Job was scheduled
```
In step 1, when a runner requests a new job, it issues a `POST` request
(`/api/v4/jobs/request`) to the GitLab server, where it is first handled
by Workhorse.
Workhorse reads the runner token and value from the
`X-GitLab-Last-Update` HTTP header, constructs a key, and subscribes to
a Redis PubSub channel with that key. If no value exists for the key,
then Workhorse immediately forwards the request on to Rails (steps 3 and
4).
Rails checks the job queue. If there are no jobs available for the
runner, Rails returns a `204 No job` with a `last_update` token to the
runner (steps 5 to 7).
The runner uses that `last_update` token and issues another request for
a job, populating the `X-GitLab-Last-Update` HTTP header with this
token. This time, Workhorse checks if the runner's `last_update` token
has changed. If it has not, Workhorse holds onto the request for up to
the duration specified by `apiCiLongPollingDuration`.
If a user triggers a new pipeline or job to run, a background task in
Sidekiq will update the `last_update` value for all runners available to
the job. Runners can be registered for the project, group, and/or
instance.
This "tick" in steps 10 and 11 releases the job request from the
Workhorse long poll queue, and the request gets sent to Rails (step
12). Rails looks for an available job, and assigns the runner to that
job (steps 13 and 14).
With long polling, the runner gets notified immediately after a new job
is available. This not only helps improve reduce job queueing time, but
it also reduces server overhead because the job requests reach
Rails only when there is new work.
## Troubleshooting
When working with long polling, you might encounter the following issues.
### Slow job pickup
Long polling is not enabled by default because in some runner
configurations, the runner doesn't pick up jobs in a timely manner.
See [issue 27709](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/27709).
This can happen if the `concurrent` setting in the runner `config.toml`
is set to a value lower than the number of runners defined. To resolve
this issue, ensure the value of `concurrent` is at equal or greater than the
number of runners.
For example, if you have three `[[runners]]` entries in `config.toml`, make
sure that `concurrent` is set to at least 3.
When long polling is enabled, the runner:
1. Launches `concurrent` number of Goroutines.
1. Waits for the Goroutines to return after long polling.
1. Runs another batch of requests.
For example, consider the case where a single `config.toml` has configured:
- 3 runners for project A.
- 1 runner for project B.
- `concurrent` set to 3.
In this example, a runner launches Goroutines for the first 3 projects.
In the worst case, the runner waits the full long poll interval for project
A before proceeding with requesting a job for project B.
|
https://docs.gitlab.com/ci/provision_runners_google_cloud
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/provision_runners_google_cloud.md
|
2025-08-13
|
doc/ci/runners
|
[
"doc",
"ci",
"runners"
] |
provision_runners_google_cloud.md
|
Verify
|
Runner
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Provision runners in Google Cloud Compute Engine
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/438316) in GitLab 16.10 [with a flag](../../administration/feature_flags/_index.md) named `google_cloud_support_feature_flag`. This feature is in [beta](../../policy/development_stages_support.md).
- [Enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/150472) in GitLab 17.1. Feature flag `google_cloud_support_feature_flag` removed.
{{< /history >}}
You can create a project or group runner for GitLab.com and provision it on your Google Cloud project.
When you create a runner, the GitLab UI provides on-screen instructions and scripts to automatically provision the runner
in your Google Cloud project.
A runner authentication token is assigned to your runner when you create it. A [GRIT](https://gitlab.com/gitlab-org/ci-cd/runner-tools/grit) Terraform script uses this token to
register the runner. The runner then uses the token to authenticate with GitLab when it picks up jobs
from the job queue.
After provisioning, an autoscaling fleet of runners is ready to run CI/CD jobs in Google Cloud.
The runner manager creates temporary runners automatically.
Prerequisites:
- For group runners: Owner role for the group.
- For project runners: Maintainer role for the project.
- For your Google Cloud Platform project: [Owner](https://cloud.google.com/iam/docs/understanding-roles#owner) IAM role.
- [Billing enabled](https://cloud.google.com/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project)
for your Google Cloud Platform project.
- A working [`gcloud` CLI tool](https://cloud.google.com/sdk/docs/install) authenticated with the
IAM role on the Google Cloud project.
- [Terraform v1.5 or later](https://releases.hashicorp.com/terraform/1.5.7/) and [Terraform CLI tool](https://developer.hashicorp.com/terraform/install).
- A terminal with Bash installed.
To create a group or project runner and provision it on Google Cloud:
1. On the left sidebar, select **Search or go to** and find your group.
1. Create a new runner.
- To create a new group runner, select **Build > Runners > New group runner**.
- To create a new project runner, select **Settings > CI/CD > Runners > New project runner**.
1. In the **Tags** section, in the **Tags** field, enter the job tags to specify jobs the runner can run.
To use the runner for jobs without tags in addition to the tagged jobs, select **Run untagged**.
1. Optional. In the **Configuration** section, add runner description and additional configurations.
1. Select **Create runner**.
1. In the **Platform** section, select **Google Cloud**.
1. In **Environment**, enter the following details of the Google Cloud environment:
- **Google Cloud project ID**
- **Region**
- **Zone**
- **Machine type**
1. In **Set up GitLab Runner**, select **Setup instructions**. In the dialog:
1. To enable the required services, service account, and permissions, in **Configure Google Cloud project** run the Bash script once for each Google Cloud project.
1. Create a `main.tf` file with the configuration from **Install and register GitLab Runner**.
The script uses the [GitLab Runner Infrastructure Toolkit](https://gitlab.com/gitlab-org/ci-cd/runner-tools/grit/-/blob/main/docs/scenarios/google/linux/docker-autoscaler-default/index.md)
(GRIT) to provision the infrastructure on the Google Cloud project to execute your runner manager.
After you execute the scripts, a runner manager connects with the runner authentication token. The runner manager might
take up to one minute to show as online and start receiving jobs.
|
---
stage: Verify
group: Runner
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Provision runners in Google Cloud Compute Engine
breadcrumbs:
- doc
- ci
- runners
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/438316) in GitLab 16.10 [with a flag](../../administration/feature_flags/_index.md) named `google_cloud_support_feature_flag`. This feature is in [beta](../../policy/development_stages_support.md).
- [Enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/150472) in GitLab 17.1. Feature flag `google_cloud_support_feature_flag` removed.
{{< /history >}}
You can create a project or group runner for GitLab.com and provision it on your Google Cloud project.
When you create a runner, the GitLab UI provides on-screen instructions and scripts to automatically provision the runner
in your Google Cloud project.
A runner authentication token is assigned to your runner when you create it. A [GRIT](https://gitlab.com/gitlab-org/ci-cd/runner-tools/grit) Terraform script uses this token to
register the runner. The runner then uses the token to authenticate with GitLab when it picks up jobs
from the job queue.
After provisioning, an autoscaling fleet of runners is ready to run CI/CD jobs in Google Cloud.
The runner manager creates temporary runners automatically.
Prerequisites:
- For group runners: Owner role for the group.
- For project runners: Maintainer role for the project.
- For your Google Cloud Platform project: [Owner](https://cloud.google.com/iam/docs/understanding-roles#owner) IAM role.
- [Billing enabled](https://cloud.google.com/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project)
for your Google Cloud Platform project.
- A working [`gcloud` CLI tool](https://cloud.google.com/sdk/docs/install) authenticated with the
IAM role on the Google Cloud project.
- [Terraform v1.5 or later](https://releases.hashicorp.com/terraform/1.5.7/) and [Terraform CLI tool](https://developer.hashicorp.com/terraform/install).
- A terminal with Bash installed.
To create a group or project runner and provision it on Google Cloud:
1. On the left sidebar, select **Search or go to** and find your group.
1. Create a new runner.
- To create a new group runner, select **Build > Runners > New group runner**.
- To create a new project runner, select **Settings > CI/CD > Runners > New project runner**.
1. In the **Tags** section, in the **Tags** field, enter the job tags to specify jobs the runner can run.
To use the runner for jobs without tags in addition to the tagged jobs, select **Run untagged**.
1. Optional. In the **Configuration** section, add runner description and additional configurations.
1. Select **Create runner**.
1. In the **Platform** section, select **Google Cloud**.
1. In **Environment**, enter the following details of the Google Cloud environment:
- **Google Cloud project ID**
- **Region**
- **Zone**
- **Machine type**
1. In **Set up GitLab Runner**, select **Setup instructions**. In the dialog:
1. To enable the required services, service account, and permissions, in **Configure Google Cloud project** run the Bash script once for each Google Cloud project.
1. Create a `main.tf` file with the configuration from **Install and register GitLab Runner**.
The script uses the [GitLab Runner Infrastructure Toolkit](https://gitlab.com/gitlab-org/ci-cd/runner-tools/grit/-/blob/main/docs/scenarios/google/linux/docker-autoscaler-default/index.md)
(GRIT) to provision the infrastructure on the Google Cloud project to execute your runner manager.
After you execute the scripts, a runner manager connects with the runner authentication token. The runner manager might
take up to one minute to show as online and start receiving jobs.
|
https://docs.gitlab.com/ci/git_submodules
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/git_submodules.md
|
2025-08-13
|
doc/ci/runners
|
[
"doc",
"ci",
"runners"
] |
git_submodules.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Using Git submodules with GitLab CI/CD
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use [Git submodules](https://git-scm.com/book/en/v2/Git-Tools-Submodules) to keep
a Git repository as a subdirectory of another Git repository. You can clone another
repository into your project and keep your commits separate.
## Configure the `.gitmodules` file
When you use Git submodules, your project should have a file named `.gitmodules`.
You have multiple options to configure it to work in a GitLab CI/CD job.
### Using absolute URLs
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3198) in GitLab Runner 15.11.
{{< /history >}}
For example, your generated `.gitmodules` configuration might look like the following if:
- Your project is located at `https://gitlab.com/secret-group/my-project`.
- Your project depends on `https://gitlab.com/group/project`, which you want
to include as a submodule.
- You check out your sources with an SSH address like `git@gitlab.com:secret-group/my-project.git`.
```ini
[submodule "project"]
path = project
url = git@gitlab.com:group/project.git
```
In this case, use the [`GIT_SUBMODULE_FORCE_HTTPS`](configure_runners.md#rewrite-submodule-urls-to-https) variable
to instruct GitLab Runner to convert the URL to HTTPS before it clones the submodules.
Alternatively, if you also use HTTPS locally, you can configure an HTTPS URL:
```ini
[submodule "project"]
path = project
url = https://gitlab.com/group/project.git
```
You do not need to configure additional variables in this case, but you need to use a
[personal access token](../../user/profile/personal_access_tokens.md) to clone it locally.
### Using relative URLs
{{< alert type="warning" >}}
If you use relative URLs, submodules may resolve incorrectly in forking workflows.
Use absolute URLs instead if you expect your project to have forks.
{{< /alert >}}
When your submodule is on the same GitLab server, you can also use relative URLs in
your `.gitmodules` file:
```ini
[submodule "project"]
path = project
url = ../../project.git
```
The previous configuration instructs Git to automatically deduce the URL to
use when cloning sources. You can clone with HTTPS in all your CI/CD jobs, and you
can continue to use SSH to clone locally.
For submodules not located on the same GitLab server, always use the full URL:
```ini
[submodule "project-x"]
path = project-x
url = https://gitserver.com/group/project-x.git
```
## Use Git submodules in CI/CD jobs
Prerequisites:
- If you use the [`CI_JOB_TOKEN`](../jobs/ci_job_token.md) to clone a submodule in a
pipeline job, you must have at least the Reporter role for the submodule repository to pull the code.
- [CI/CD job token access](../jobs/ci_job_token.md#control-job-token-access-to-your-project) must be properly configured in the upstream submodule project.
To make submodules work correctly in CI/CD jobs:
1. You can set the `GIT_SUBMODULE_STRATEGY` variable to either `normal` or `recursive`
to tell the runner to [fetch your submodules before the job](configure_runners.md#git-submodule-strategy):
```yaml
variables:
GIT_SUBMODULE_STRATEGY: recursive
```
1. For submodules located on the same GitLab server and configured with a Git or SSH URL, make sure
you set the [`GIT_SUBMODULE_FORCE_HTTPS`](configure_runners.md#rewrite-submodule-urls-to-https) variable.
1. Use `GIT_SUBMODULE_DEPTH` to configure the cloning depth of submodules independently of the [`GIT_DEPTH`](configure_runners.md#shallow-cloning) variable:
```yaml
variables:
GIT_SUBMODULE_DEPTH: 1
```
1. You can filter or exclude specific submodules to control which submodules are synchronized using
[`GIT_SUBMODULE_PATHS`](configure_runners.md#sync-or-exclude-specific-submodules-from-ci-jobs).
```yaml
variables:
GIT_SUBMODULE_PATHS: submoduleA submoduleB
```
1. You can provide additional flags to control advanced checkout behavior using
[`GIT_SUBMODULE_UPDATE_FLAGS`](configure_runners.md#git-submodule-update-flags).
```yaml
variables:
GIT_SUBMODULE_STRATEGY: recursive
GIT_SUBMODULE_UPDATE_FLAGS: --jobs 4
```
## Troubleshooting
### Can't find the `.gitmodules` file
The `.gitmodules` file might be hard to find because it is usually a hidden file.
You can check documentation for your specific OS to learn how to find and display
hidden files.
If there is no `.gitmodules` file, it's possible the submodule settings are in a
[`git config`](https://www.atlassian.com/git/tutorials/setting-up-a-repository/git-config) file.
### Error: `fatal: run_command returned non-zero status`
This error can happen in a job when working with submodules and the `GIT_STRATEGY` is set to `fetch`.
Setting the `GIT_STRATEGY` to `clone` should resolve the issue.
### Error: `fatal: could not read Username for 'https://gitlab.com': No such device or address`
If you're using GitLab hosted runners, you may encounter this error when your CI/CD job attempts to clone or fetch Git submodules.
During CI/CD pipeline execution, GitLab Runners automatically perform Git URL substitution to authenticate
through `CI_JOB_TOKEN`:
```shell
git config --global url."https://gitlab-ci-token:${CI_JOB_TOKEN}@${CI_SERVER_FQDN}".insteadOf "${CI_SERVER_FQDN}"
```
For GitLab hosted runners, the `CI_SERVER_FQDN` is different from `https://gitlab.com`.
If your submodule resides in `https://gitlab.com`,
this substitution is not performed, leading to the error.
One way to resolve this error is to create a `pre_get_sources_script` and
configure the URL substitution with `CI_JOB_TOKEN` manually:
```yaml
variables:
GIT_SUBMODULE_STRATEGY: recursive
GIT_SUBMODULE_DEPTH: 1
hooks:
pre_get_sources_script:
- git config --global url."https://gitlab-ci-token:${CI_JOB_TOKEN}@${CI_SERVER_FQDN}".insteadOf "${SUBMODULE_URL}"
```
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Using Git submodules with GitLab CI/CD
breadcrumbs:
- doc
- ci
- runners
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use [Git submodules](https://git-scm.com/book/en/v2/Git-Tools-Submodules) to keep
a Git repository as a subdirectory of another Git repository. You can clone another
repository into your project and keep your commits separate.
## Configure the `.gitmodules` file
When you use Git submodules, your project should have a file named `.gitmodules`.
You have multiple options to configure it to work in a GitLab CI/CD job.
### Using absolute URLs
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3198) in GitLab Runner 15.11.
{{< /history >}}
For example, your generated `.gitmodules` configuration might look like the following if:
- Your project is located at `https://gitlab.com/secret-group/my-project`.
- Your project depends on `https://gitlab.com/group/project`, which you want
to include as a submodule.
- You check out your sources with an SSH address like `git@gitlab.com:secret-group/my-project.git`.
```ini
[submodule "project"]
path = project
url = git@gitlab.com:group/project.git
```
In this case, use the [`GIT_SUBMODULE_FORCE_HTTPS`](configure_runners.md#rewrite-submodule-urls-to-https) variable
to instruct GitLab Runner to convert the URL to HTTPS before it clones the submodules.
Alternatively, if you also use HTTPS locally, you can configure an HTTPS URL:
```ini
[submodule "project"]
path = project
url = https://gitlab.com/group/project.git
```
You do not need to configure additional variables in this case, but you need to use a
[personal access token](../../user/profile/personal_access_tokens.md) to clone it locally.
### Using relative URLs
{{< alert type="warning" >}}
If you use relative URLs, submodules may resolve incorrectly in forking workflows.
Use absolute URLs instead if you expect your project to have forks.
{{< /alert >}}
When your submodule is on the same GitLab server, you can also use relative URLs in
your `.gitmodules` file:
```ini
[submodule "project"]
path = project
url = ../../project.git
```
The previous configuration instructs Git to automatically deduce the URL to
use when cloning sources. You can clone with HTTPS in all your CI/CD jobs, and you
can continue to use SSH to clone locally.
For submodules not located on the same GitLab server, always use the full URL:
```ini
[submodule "project-x"]
path = project-x
url = https://gitserver.com/group/project-x.git
```
## Use Git submodules in CI/CD jobs
Prerequisites:
- If you use the [`CI_JOB_TOKEN`](../jobs/ci_job_token.md) to clone a submodule in a
pipeline job, you must have at least the Reporter role for the submodule repository to pull the code.
- [CI/CD job token access](../jobs/ci_job_token.md#control-job-token-access-to-your-project) must be properly configured in the upstream submodule project.
To make submodules work correctly in CI/CD jobs:
1. You can set the `GIT_SUBMODULE_STRATEGY` variable to either `normal` or `recursive`
to tell the runner to [fetch your submodules before the job](configure_runners.md#git-submodule-strategy):
```yaml
variables:
GIT_SUBMODULE_STRATEGY: recursive
```
1. For submodules located on the same GitLab server and configured with a Git or SSH URL, make sure
you set the [`GIT_SUBMODULE_FORCE_HTTPS`](configure_runners.md#rewrite-submodule-urls-to-https) variable.
1. Use `GIT_SUBMODULE_DEPTH` to configure the cloning depth of submodules independently of the [`GIT_DEPTH`](configure_runners.md#shallow-cloning) variable:
```yaml
variables:
GIT_SUBMODULE_DEPTH: 1
```
1. You can filter or exclude specific submodules to control which submodules are synchronized using
[`GIT_SUBMODULE_PATHS`](configure_runners.md#sync-or-exclude-specific-submodules-from-ci-jobs).
```yaml
variables:
GIT_SUBMODULE_PATHS: submoduleA submoduleB
```
1. You can provide additional flags to control advanced checkout behavior using
[`GIT_SUBMODULE_UPDATE_FLAGS`](configure_runners.md#git-submodule-update-flags).
```yaml
variables:
GIT_SUBMODULE_STRATEGY: recursive
GIT_SUBMODULE_UPDATE_FLAGS: --jobs 4
```
## Troubleshooting
### Can't find the `.gitmodules` file
The `.gitmodules` file might be hard to find because it is usually a hidden file.
You can check documentation for your specific OS to learn how to find and display
hidden files.
If there is no `.gitmodules` file, it's possible the submodule settings are in a
[`git config`](https://www.atlassian.com/git/tutorials/setting-up-a-repository/git-config) file.
### Error: `fatal: run_command returned non-zero status`
This error can happen in a job when working with submodules and the `GIT_STRATEGY` is set to `fetch`.
Setting the `GIT_STRATEGY` to `clone` should resolve the issue.
### Error: `fatal: could not read Username for 'https://gitlab.com': No such device or address`
If you're using GitLab hosted runners, you may encounter this error when your CI/CD job attempts to clone or fetch Git submodules.
During CI/CD pipeline execution, GitLab Runners automatically perform Git URL substitution to authenticate
through `CI_JOB_TOKEN`:
```shell
git config --global url."https://gitlab-ci-token:${CI_JOB_TOKEN}@${CI_SERVER_FQDN}".insteadOf "${CI_SERVER_FQDN}"
```
For GitLab hosted runners, the `CI_SERVER_FQDN` is different from `https://gitlab.com`.
If your submodule resides in `https://gitlab.com`,
this substitution is not performed, leading to the error.
One way to resolve this error is to create a `pre_get_sources_script` and
configure the URL substitution with `CI_JOB_TOKEN` manually:
```yaml
variables:
GIT_SUBMODULE_STRATEGY: recursive
GIT_SUBMODULE_DEPTH: 1
hooks:
pre_get_sources_script:
- git config --global url."https://gitlab-ci-token:${CI_JOB_TOKEN}@${CI_SERVER_FQDN}".insteadOf "${SUBMODULE_URL}"
```
|
https://docs.gitlab.com/ci/runners
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/_index.md
|
2025-08-13
|
doc/ci/runners
|
[
"doc",
"ci",
"runners"
] |
_index.md
|
Verify
|
Runner
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Runners
|
Configuration and job execution.
|
Runners are the agents that run the [GitLab Runner](https://docs.gitlab.com/runner/) application, to execute GitLab CI/CD jobs in a pipeline.
They are responsible for running your builds, tests, deployments, and other CI/CD tasks defined in `.gitlab-ci.yml` files.
## Runner execution flow
The following is a basic workflow of how runners work:
1. A runner must first be [registered](https://docs.gitlab.com/runner/register/) with GitLab,
which establishes a persistent connection between the runner and GitLab.
1. When a pipeline is triggered, GitLab makes the jobs available to the registered runners.
1. Matching runners pick up jobs, one job per runner, and execute them.
1. Results are reported back to GitLab in real-time.
For more information, see [Runner execution flow](https://docs.gitlab.com/runner/#runner-execution-flow).
## Runner job scheduling and execution
When a CI/CD job needs to be executed, GitLab creates a job based on the tasks defined in the `.gitlab-ci.yml` file.
The jobs are placed in a queue. GitLab checks for available runners that match:
- Runner tags
- Runner types (like shared or group)
- Runner status and capacity
- Required capabilities
The assigned runner receives the job details. The runner prepares the environment and runs the job's commands as specified in the `.gitlab-ci.yml` file.
## Runner categories
When deciding on which runners you want to execute your CI/CD jobs, you can choose:
- [GitLab-hosted runners](hosted_runners/_index.md) for GitLab.com or GitLab Dedicated users.
- [Self-managed runners](https://docs.gitlab.com/runner/) for all GitLab installations.
Runners can be group, project, or instance runners. GitLab-hosted runners are instance runners.
### GitLab-hosted runners
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Dedicated
{{< /details >}}
GitLab-hosted runners are:
- Fully managed by GitLab.
- Available immediately without setup.
- Run on fresh VMs for each job.
- Include Linux, Windows, and macOS options.
- Automatically scaled based on demand.
Choose GitLab-hosted runners when:
- You want zero-maintenance CI/CD.
- You need quick setup without infrastructure management.
- Your jobs require isolation between runs.
- You're working with standard build environments.
- You're using GitLab.com or GitLab Dedicated.
### Self-managed runners
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Self-managed runners are:
- Installed and managed by you.
- Run on your own infrastructure.
- Customizable to your needs.
- Support various executors (including Shell, Docker, and Kubernetes).
- Can be shared or set to specific projects or groups.
Choose self-managed runners when:
- You need custom configurations.
- You want to run jobs in your private network.
- You require specific security controls.
- You require project or group runners.
- You need to optimize for speed with runner reuse.
- You want to manage your own infrastructure.
## Related topics
- [Install GitLab Runner](https://docs.gitlab.com/runner/install/)
- [Configure GitLab Runner](https://docs.gitlab.com/runner/configuration/)
- [Administer GitLab Runner](https://docs.gitlab.com/runner/)
- [Hosted runners for GitLab Dedicated](../../administration/dedicated/hosted_runners.md)
|
---
stage: Verify
group: Runner
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Runners
description: Configuration and job execution.
breadcrumbs:
- doc
- ci
- runners
---
Runners are the agents that run the [GitLab Runner](https://docs.gitlab.com/runner/) application, to execute GitLab CI/CD jobs in a pipeline.
They are responsible for running your builds, tests, deployments, and other CI/CD tasks defined in `.gitlab-ci.yml` files.
## Runner execution flow
The following is a basic workflow of how runners work:
1. A runner must first be [registered](https://docs.gitlab.com/runner/register/) with GitLab,
which establishes a persistent connection between the runner and GitLab.
1. When a pipeline is triggered, GitLab makes the jobs available to the registered runners.
1. Matching runners pick up jobs, one job per runner, and execute them.
1. Results are reported back to GitLab in real-time.
For more information, see [Runner execution flow](https://docs.gitlab.com/runner/#runner-execution-flow).
## Runner job scheduling and execution
When a CI/CD job needs to be executed, GitLab creates a job based on the tasks defined in the `.gitlab-ci.yml` file.
The jobs are placed in a queue. GitLab checks for available runners that match:
- Runner tags
- Runner types (like shared or group)
- Runner status and capacity
- Required capabilities
The assigned runner receives the job details. The runner prepares the environment and runs the job's commands as specified in the `.gitlab-ci.yml` file.
## Runner categories
When deciding on which runners you want to execute your CI/CD jobs, you can choose:
- [GitLab-hosted runners](hosted_runners/_index.md) for GitLab.com or GitLab Dedicated users.
- [Self-managed runners](https://docs.gitlab.com/runner/) for all GitLab installations.
Runners can be group, project, or instance runners. GitLab-hosted runners are instance runners.
### GitLab-hosted runners
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Dedicated
{{< /details >}}
GitLab-hosted runners are:
- Fully managed by GitLab.
- Available immediately without setup.
- Run on fresh VMs for each job.
- Include Linux, Windows, and macOS options.
- Automatically scaled based on demand.
Choose GitLab-hosted runners when:
- You want zero-maintenance CI/CD.
- You need quick setup without infrastructure management.
- Your jobs require isolation between runs.
- You're working with standard build environments.
- You're using GitLab.com or GitLab Dedicated.
### Self-managed runners
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Self-managed runners are:
- Installed and managed by you.
- Run on your own infrastructure.
- Customizable to your needs.
- Support various executors (including Shell, Docker, and Kubernetes).
- Can be shared or set to specific projects or groups.
Choose self-managed runners when:
- You need custom configurations.
- You want to run jobs in your private network.
- You require specific security controls.
- You require project or group runners.
- You need to optimize for speed with runner reuse.
- You want to manage your own infrastructure.
## Related topics
- [Install GitLab Runner](https://docs.gitlab.com/runner/install/)
- [Configure GitLab Runner](https://docs.gitlab.com/runner/configuration/)
- [Administer GitLab Runner](https://docs.gitlab.com/runner/)
- [Hosted runners for GitLab Dedicated](../../administration/dedicated/hosted_runners.md)
|
https://docs.gitlab.com/ci/runners/windows
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/runners/windows.md
|
2025-08-13
|
doc/ci/runners/hosted_runners
|
[
"doc",
"ci",
"runners",
"hosted_runners"
] |
windows.md
|
Production Engineering
|
Runners Platform
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Hosted runners on Windows
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
- Status: Beta
{{< /details >}}
Hosted runners on Windows autoscale by launching virtual machines on
the Google Cloud Platform. This solution uses an
[autoscaling driver](https://gitlab.com/gitlab-org/ci-cd/custom-executor-drivers/autoscaler/-/blob/main/docs/README.md)
developed by GitLab for the [custom executor](https://docs.gitlab.com/runner/executors/custom.html).
Hosted runners on Windows are in [beta](../../../policy/development_stages_support.md#beta).
We want to keep iterating to get Windows runners in a stable state and
[generally available](../../../policy/development_stages_support.md#generally-available).
You can follow our work towards this goal in the
[related epic](https://gitlab.com/groups/gitlab-org/-/epics/2162).
## Machine types available for Windows
GitLab offers the following machine type for hosted runners on Windows.
| Runner Tag | vCPUs | Memory | Storage |
| --------------------------- | ----- | ------ | ------- |
| `saas-windows-medium-amd64` | 2 | 7.5 GB | 75 GB |
## Supported Windows versions
The Windows runner virtual machine instances do not use the GitLab Docker executor. This means that you can't specify
[`image`](../../yaml/_index.md#image) or [`services`](../../yaml/_index.md#services) in your pipeline configuration.
You can execute your job in one of the following Windows versions:
| Version | Status |
|--------------|--------|
| Windows 2022 | `GA` |
You can find a full list of available pre-installed software in
the [pre-installed software documentation](https://gitlab.com/gitlab-org/ci-cd/shared-runners/images/gcp/windows-containers/-/blob/main/cookbooks/preinstalled-software/attributes/default.rb).
## Supported shell
Hosted runners on Windows have PowerShell configured as the shell.
The `script` section of your `.gitlab-ci.yml` file therefore requires PowerShell commands.
## Example `.gitlab-ci.yml` file
Use this example `.gitlab-ci.yml` file to get started with hosted runners on Windows:
```yaml
.windows_job:
tags:
- saas-windows-medium-amd64
before_script:
- Set-Variable -Name "time" -Value (date -Format "%H:%m")
- echo ${time}
- echo "started by ${GITLAB_USER_NAME} / @${GITLAB_USER_LOGIN}"
build:
extends:
- .windows_job
stage: build
script:
- echo "running scripts in the build job"
test:
extends:
- .windows_job
stage: test
script:
- echo "running scripts in the test job"
```
## Known issues
- For more information about support for beta features, see [beta](../../../policy/development_stages_support.md#beta).
- The average provisioning time for a new Windows virtual machine (VM) is five minutes, so
you might notice slower start times for builds on the Windows runner
fleet during the beta. Updating the autoscaler to enable the pre-provisioning
of virtual machines is proposed in a future release. This update is intended to
significantly reduce the time it takes to provision a VM on the Windows fleet.
For more information, see [issue 32](https://gitlab.com/gitlab-org/ci-cd/custom-executor-drivers/autoscaler/-/issues/32).
- The Windows runner fleet may be unavailable occasionally
for maintenance or updates.
- The job may stay in a pending state for longer than the
Linux runners.
- There is the possibility that we introduce breaking changes which will
require updates to pipelines that are using the Windows runner
fleet.
|
---
stage: Production Engineering
group: Runners Platform
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Hosted runners on Windows
breadcrumbs:
- doc
- ci
- runners
- hosted_runners
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
- Status: Beta
{{< /details >}}
Hosted runners on Windows autoscale by launching virtual machines on
the Google Cloud Platform. This solution uses an
[autoscaling driver](https://gitlab.com/gitlab-org/ci-cd/custom-executor-drivers/autoscaler/-/blob/main/docs/README.md)
developed by GitLab for the [custom executor](https://docs.gitlab.com/runner/executors/custom.html).
Hosted runners on Windows are in [beta](../../../policy/development_stages_support.md#beta).
We want to keep iterating to get Windows runners in a stable state and
[generally available](../../../policy/development_stages_support.md#generally-available).
You can follow our work towards this goal in the
[related epic](https://gitlab.com/groups/gitlab-org/-/epics/2162).
## Machine types available for Windows
GitLab offers the following machine type for hosted runners on Windows.
| Runner Tag | vCPUs | Memory | Storage |
| --------------------------- | ----- | ------ | ------- |
| `saas-windows-medium-amd64` | 2 | 7.5 GB | 75 GB |
## Supported Windows versions
The Windows runner virtual machine instances do not use the GitLab Docker executor. This means that you can't specify
[`image`](../../yaml/_index.md#image) or [`services`](../../yaml/_index.md#services) in your pipeline configuration.
You can execute your job in one of the following Windows versions:
| Version | Status |
|--------------|--------|
| Windows 2022 | `GA` |
You can find a full list of available pre-installed software in
the [pre-installed software documentation](https://gitlab.com/gitlab-org/ci-cd/shared-runners/images/gcp/windows-containers/-/blob/main/cookbooks/preinstalled-software/attributes/default.rb).
## Supported shell
Hosted runners on Windows have PowerShell configured as the shell.
The `script` section of your `.gitlab-ci.yml` file therefore requires PowerShell commands.
## Example `.gitlab-ci.yml` file
Use this example `.gitlab-ci.yml` file to get started with hosted runners on Windows:
```yaml
.windows_job:
tags:
- saas-windows-medium-amd64
before_script:
- Set-Variable -Name "time" -Value (date -Format "%H:%m")
- echo ${time}
- echo "started by ${GITLAB_USER_NAME} / @${GITLAB_USER_LOGIN}"
build:
extends:
- .windows_job
stage: build
script:
- echo "running scripts in the build job"
test:
extends:
- .windows_job
stage: test
script:
- echo "running scripts in the test job"
```
## Known issues
- For more information about support for beta features, see [beta](../../../policy/development_stages_support.md#beta).
- The average provisioning time for a new Windows virtual machine (VM) is five minutes, so
you might notice slower start times for builds on the Windows runner
fleet during the beta. Updating the autoscaler to enable the pre-provisioning
of virtual machines is proposed in a future release. This update is intended to
significantly reduce the time it takes to provision a VM on the Windows fleet.
For more information, see [issue 32](https://gitlab.com/gitlab-org/ci-cd/custom-executor-drivers/autoscaler/-/issues/32).
- The Windows runner fleet may be unavailable occasionally
for maintenance or updates.
- The job may stay in a pending state for longer than the
Linux runners.
- There is the possibility that we introduce breaking changes which will
require updates to pipelines that are using the Windows runner
fleet.
|
https://docs.gitlab.com/ci/runners/linux
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/runners/linux.md
|
2025-08-13
|
doc/ci/runners/hosted_runners
|
[
"doc",
"ci",
"runners",
"hosted_runners"
] |
linux.md
|
Production Engineering
|
Runners Platform
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Hosted runners on Linux
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
Hosted runners on Linux for GitLab.com run on Google Cloud Compute Engine. Each job gets a fully isolated, ephemeral virtual machine (VM). The default region is `us-east1`.
Each VM uses the Google Container-Optimized OS (COS) and the latest version of Docker Engine running the `docker+machine`
[executor](https://docs.gitlab.com/runner/executors/#docker-machine-executor).
The machine type and underlying processor type might change. Jobs optimized for a specific processor design might behave inconsistently.
[Untagged](../../yaml/_index.md#tags) jobs run on the `small` Linux x86-64 runner.
## Machine types available for Linux - x86-64
GitLab offers the following machine types for hosted runners on Linux x86-64.
<table id="x86-runner-specs" aria-label="Machine types available for Linux x86-64">
<thead>
<tr>
<th>Runner Tag</th>
<th>vCPUs</th>
<th>Memory</th>
<th>Storage</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code class="runner-tag">saas-linux-small-amd64</code> (default)
</td>
<td class="vcpus">2</td>
<td>8 GB</td>
<td>30 GB</td>
</tr>
<tr>
<td>
<code class="runner-tag">saas-linux-medium-amd64</code>
</td>
<td class="vcpus">4</td>
<td>16 GB</td>
<td>50 GB</td>
</tr>
<tr>
<td>
<code class="runner-tag">saas-linux-large-amd64</code> (Premium and Ultimate only)
</td>
<td class="vcpus">8</td>
<td>32 GB</td>
<td>100 GB</td>
</tr>
<tr>
<td>
<code class="runner-tag">saas-linux-xlarge-amd64</code> (Premium and Ultimate only)
</td>
<td class="vcpus">16</td>
<td>64 GB</td>
<td>200 GB</td>
</tr>
<tr>
<td>
<code class="runner-tag">saas-linux-2xlarge-amd64</code> (Premium and Ultimate only)
</td>
<td class="vcpus">32</td>
<td>128 GB</td>
<td>200 GB</td>
</tr>
</tbody>
</table>
## Machine types available for Linux - Arm64
GitLab offers the following machine type for hosted runners on Linux Arm64.
<table id="arm64-runner-specs" aria-label="Machine types available for Linux Arm64">
<thead>
<tr>
<th>Runner Tag</th>
<th>vCPUs</th>
<th>Memory</th>
<th>Storage</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code class="runner-tag">saas-linux-small-arm64</code>
</td>
<td class="vcpus">2</td>
<td>8 GB</td>
<td>30 GB</td>
</tr>
<tr>
<td>
<code class="runner-tag">saas-linux-medium-arm64</code> (Premium and Ultimate only)
</td>
<td class="vcpus">4</td>
<td>16 GB</td>
<td>50 GB</td>
</tr>
<tr>
<td>
<code class="runner-tag">saas-linux-large-arm64</code> (Premium and Ultimate only)
</td>
<td class="vcpus">8</td>
<td>32 GB</td>
<td>100 GB</td>
</tr>
</tbody>
</table>
{{< alert type="note" >}}
Users can experience network connectivity issues when they use Docker-in-Docker with hosted runners on Linux
Arm. This issue occurs when the maximum transmission unit (MTU) value in Google Cloud and Docker don't match.
To resolve this issue, set `--mtu=1400` in the client side Docker configuration.
For more details, see [issue 473739](https://gitlab.com/gitlab-org/gitlab/-/issues/473739#workaround).
{{< /alert >}}
## Container images
As runners on Linux are using the `docker+machine` [executor](https://docs.gitlab.com/runner/executors/#docker-machine-executor),
you can choose any container image by defining the [`image`](../../yaml/_index.md#image) in your `.gitlab-ci.yml` file.
Ensure your selected Docker image is compatible with your processor architecture.
If no image is set, the default is `ruby:3.1`.
## Docker-in-Docker support
Runners with any of the `saas-linux-<size>-<architecture>` tags are configured to run in `privileged` mode
to support [Docker-in-Docker](../../docker/using_docker_build.md#use-docker-in-docker).
With these runners, you can build Docker images natively or run multiple containers in your isolated job.
Runners with the `gitlab-org` tag do not run in `privileged` mode and cannot be used for Docker-in-Docker builds.
## Example `.gitlab-ci.yml` file
To use a machine type other than `small`, add a `tags:` keyword to your job.
For example:
```yaml
job_small:
script:
- echo "This job is untagged and runs on the default small Linux x86-64 instance"
job_medium:
tags:
- saas-linux-medium-amd64
script:
- echo "This job runs on the medium Linux x86-64 instance"
job_large:
tags:
- saas-linux-large-arm64
script:
- echo "This job runs on the large Linux Arm64 instance"
```
|
---
stage: Production Engineering
group: Runners Platform
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Hosted runners on Linux
breadcrumbs:
- doc
- ci
- runners
- hosted_runners
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
Hosted runners on Linux for GitLab.com run on Google Cloud Compute Engine. Each job gets a fully isolated, ephemeral virtual machine (VM). The default region is `us-east1`.
Each VM uses the Google Container-Optimized OS (COS) and the latest version of Docker Engine running the `docker+machine`
[executor](https://docs.gitlab.com/runner/executors/#docker-machine-executor).
The machine type and underlying processor type might change. Jobs optimized for a specific processor design might behave inconsistently.
[Untagged](../../yaml/_index.md#tags) jobs run on the `small` Linux x86-64 runner.
## Machine types available for Linux - x86-64
GitLab offers the following machine types for hosted runners on Linux x86-64.
<table id="x86-runner-specs" aria-label="Machine types available for Linux x86-64">
<thead>
<tr>
<th>Runner Tag</th>
<th>vCPUs</th>
<th>Memory</th>
<th>Storage</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code class="runner-tag">saas-linux-small-amd64</code> (default)
</td>
<td class="vcpus">2</td>
<td>8 GB</td>
<td>30 GB</td>
</tr>
<tr>
<td>
<code class="runner-tag">saas-linux-medium-amd64</code>
</td>
<td class="vcpus">4</td>
<td>16 GB</td>
<td>50 GB</td>
</tr>
<tr>
<td>
<code class="runner-tag">saas-linux-large-amd64</code> (Premium and Ultimate only)
</td>
<td class="vcpus">8</td>
<td>32 GB</td>
<td>100 GB</td>
</tr>
<tr>
<td>
<code class="runner-tag">saas-linux-xlarge-amd64</code> (Premium and Ultimate only)
</td>
<td class="vcpus">16</td>
<td>64 GB</td>
<td>200 GB</td>
</tr>
<tr>
<td>
<code class="runner-tag">saas-linux-2xlarge-amd64</code> (Premium and Ultimate only)
</td>
<td class="vcpus">32</td>
<td>128 GB</td>
<td>200 GB</td>
</tr>
</tbody>
</table>
## Machine types available for Linux - Arm64
GitLab offers the following machine type for hosted runners on Linux Arm64.
<table id="arm64-runner-specs" aria-label="Machine types available for Linux Arm64">
<thead>
<tr>
<th>Runner Tag</th>
<th>vCPUs</th>
<th>Memory</th>
<th>Storage</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<code class="runner-tag">saas-linux-small-arm64</code>
</td>
<td class="vcpus">2</td>
<td>8 GB</td>
<td>30 GB</td>
</tr>
<tr>
<td>
<code class="runner-tag">saas-linux-medium-arm64</code> (Premium and Ultimate only)
</td>
<td class="vcpus">4</td>
<td>16 GB</td>
<td>50 GB</td>
</tr>
<tr>
<td>
<code class="runner-tag">saas-linux-large-arm64</code> (Premium and Ultimate only)
</td>
<td class="vcpus">8</td>
<td>32 GB</td>
<td>100 GB</td>
</tr>
</tbody>
</table>
{{< alert type="note" >}}
Users can experience network connectivity issues when they use Docker-in-Docker with hosted runners on Linux
Arm. This issue occurs when the maximum transmission unit (MTU) value in Google Cloud and Docker don't match.
To resolve this issue, set `--mtu=1400` in the client side Docker configuration.
For more details, see [issue 473739](https://gitlab.com/gitlab-org/gitlab/-/issues/473739#workaround).
{{< /alert >}}
## Container images
As runners on Linux are using the `docker+machine` [executor](https://docs.gitlab.com/runner/executors/#docker-machine-executor),
you can choose any container image by defining the [`image`](../../yaml/_index.md#image) in your `.gitlab-ci.yml` file.
Ensure your selected Docker image is compatible with your processor architecture.
If no image is set, the default is `ruby:3.1`.
## Docker-in-Docker support
Runners with any of the `saas-linux-<size>-<architecture>` tags are configured to run in `privileged` mode
to support [Docker-in-Docker](../../docker/using_docker_build.md#use-docker-in-docker).
With these runners, you can build Docker images natively or run multiple containers in your isolated job.
Runners with the `gitlab-org` tag do not run in `privileged` mode and cannot be used for Docker-in-Docker builds.
## Example `.gitlab-ci.yml` file
To use a machine type other than `small`, add a `tags:` keyword to your job.
For example:
```yaml
job_small:
script:
- echo "This job is untagged and runs on the default small Linux x86-64 instance"
job_medium:
tags:
- saas-linux-medium-amd64
script:
- echo "This job runs on the medium Linux x86-64 instance"
job_large:
tags:
- saas-linux-large-arm64
script:
- echo "This job runs on the large Linux Arm64 instance"
```
|
https://docs.gitlab.com/ci/runners/hosted_runners
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/runners/_index.md
|
2025-08-13
|
doc/ci/runners/hosted_runners
|
[
"doc",
"ci",
"runners",
"hosted_runners"
] |
_index.md
|
Production Engineering
|
Runners Platform
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab-hosted runners
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Dedicated
{{< /details >}}
Use GitLab-hosted runners to run your CI/CD jobs on GitLab.com and GitLab Dedicated.
These runners can build, test, and deploy applications on different environments.
To create and register your own runners, see [self-managed runners](https://docs.gitlab.com/runner/).
## Hosted runners for GitLab.com
{{< details >}}
- Offering: GitLab.com
{{< /details >}}
These runners are fully integrated with GitLab.com and are enabled by default for all projects, with no configuration required.
Your jobs can run on:
- [Hosted runners on Linux](linux.md).
- [GPU-enabled hosted runners](gpu_enabled.md).
- [Hosted runners on Windows](windows.md) ([beta](../../../policy/development_stages_support.md#beta)).
- [Hosted runners on macOS](macos.md) ([beta](../../../policy/development_stages_support.md#beta)).
### GitLab.com hosted runner workflow
When you use hosted runners:
- Each of your jobs runs in a newly provisioned VM, which is dedicated to the specific job.
- The virtual machine where your job runs has `sudo` access with no password.
- The storage is shared by the operating system, the container image with pre-installed software, and a copy of your cloned repository.
This means that the available free disk space for your jobs to use is reduced.
- [Untagged](../../yaml/_index.md#tags) jobs run on the `small` Linux x86-64 runner.
{{< alert type="note" >}}
Jobs handled by hosted runners on GitLab.com time out after 3 hours, regardless of the timeout configured in a project.
{{< /alert >}}
### Security of hosted runners for GitLab.com
The following section provides an overview of the additional built-in layers that harden the security of the GitLab Runner build environment.
Hosted runners for GitLab.com are configured as such:
- Firewall rules only allow outbound communication from the ephemeral VM to the public internet.
- Inbound communication from the public internet to the ephemeral VM is not allowed.
- Firewall rules do not permit communication between VMs.
- The only internal communication allowed to the ephemeral VMs is from the runner manager.
- Ephemeral runner VMs serve a single job and are deleted right after the job execution.
#### Architecture diagram of hosted runners for GitLab.com
The following graphic shows the architecture diagram of hosted runners for GitLab.com

For more information on how runners are authenticating and executing the job payload, see [Runner Execution Flow](https://docs.gitlab.com/runner#runner-execution-flow).
#### Job isolation of hosted runners for GitLab.com
In addition to isolating runners on the network, each ephemeral runner VM only serves a single job and is deleted straight after the job execution.
In the following example, three jobs are executed in a project's pipeline. Each of these jobs runs in a dedicated ephemeral VM.

The build job ran on `runner-ns46nmmj-project-43717858`, test job on `f131a6a2runner-new2m-od-project-43717858` and deploy job on `runner-tmand5m-project-43717858`.
GitLab sends the command to remove the ephemeral runner VM to the Google Compute API immediately after the CI job completes. The [Google Compute Engine hypervisor](https://cloud.google.com/blog/products/gcp/7-ways-we-harden-our-kvm-hypervisor-at-google-cloud-security-in-plaintext)
takes over the task of securely deleting the virtual machine and associated data.
For more information about the security of hosted runners for GitLab.com, see:
- [Google Cloud Infrastructure Security Design Overview whitepaper](https://cloud.google.com/docs/security/infrastructure/design/resources/google_infrastructure_whitepaper_fa.pdf)
- [GitLab Trust Center](https://about.gitlab.com/security/)
- GitLab Security Compliance Controls
### Caching on hosted runners for GitLab.com
The hosted runners share a [distributed cache](https://docs.gitlab.com/runner/configuration/autoscale.html#distributed-runners-caching)
stored in a Google Cloud Storage (GCS) bucket. Cache contents not updated in the last 14 days are automatically
removed, based on the [object lifecycle management policy](https://cloud.google.com/storage/docs/lifecycle).
The maximum size of an uploaded cache artifact can be 5 GB after the cache becomes a compressed archive.
For more information about how caching works, see [Architecture diagram of hosted runners for GitLab.com](#architecture-diagram-of-hosted-runners-for-gitlabcom), and [Caching in GitLab CI/CD](../../caching/_index.md).
### Pricing of hosted runners for GitLab.com
Jobs that run on hosted runners for GitLab.com consume [compute minutes](../../pipelines/compute_minutes.md) allocated to your namespace.
The number of minutes you can use on these runners depends on the included compute minutes in your [subscription plan](https://about.gitlab.com/pricing/) or [additionally purchased compute minutes](../../../subscriptions/gitlab_com/compute_minutes.md).
For more information about the cost factor applied to the machine type based on size, see [cost factor](../../pipelines/compute_minutes.md#cost-factors-of-hosted-runners-for-gitlabcom).
### SLO & Release cycle for hosted runners for GitLab.com
Our SLO objective is to make 90% of CI/CD jobs start executing in 120 seconds or less. The error rate should be less than 0.5%.
We aim to update to the latest version of [GitLab Runner](https://docs.gitlab.com/runner/#gitlab-runner-versions) within a week of its release.
You can find all GitLab Runner breaking changes under [Deprecations and removals](../../../update/deprecations.md).
## Hosted runners for GitLab community contributions
{{< details >}}
- Offering: GitLab.com
{{< /details >}}
If you want to [contribute to GitLab](https://about.gitlab.com/community/contribute/), jobs are picked up by the
`gitlab-shared-runners-manager-X.gitlab.com` fleet of runners, dedicated for GitLab projects and related community forks.
These runners are backed by the same machine type as our `small` Linux x86-64 runners.
Unlike hosted runners for GitLab.com, hosted runners for GitLab community contributions are re-used up to 40 times.
As we want to encourage people to contribute, these runners are free of charge.
## Hosted runners for GitLab Dedicated
{{< details >}}
- Offering: GitLab Dedicated
{{< /details >}}
Hosted runners for GitLab Dedicated are created on demand and are fully integrated with your GitLab Dedicated instance.
For more information, see [hosted runners for GitLab Dedicated](../../../administration/dedicated/hosted_runners.md).
## Supported image lifecycle
Hosted runners on macOS and Windows can only run jobs on supported images. You cannot bring your own image.
Supported images have the following lifecycle:
### Beta
New images are released as beta. This allows us to gather feedback and address potential issues before general availability.
Any jobs running on beta images are not covered by the service-level agreement.
If you use beta images, you can provide feedback by creating an issue.
### General availability
A image becomes generally available after it completes the beta phase and is considered stable.
To become generally available, the image must fulfill the following requirements:
- Successful completion of a beta phase by resolving all reported significant bugs
- Compatibility of installed software with the underlying OS
Jobs that run on generally available images are covered by the defined service-level agreement.
### Deprecated
A maximum of two generally available images are supported at a time. After a new generally available image is released,
the oldest generally available image becomes deprecated. A deprecated image is no longer updated and is deleted after 3 months.
## Usage data
You can [view an estimate](../../pipelines/dedicated_hosted_runner_compute_minutes.md) of
GitLab-hosted Runner usage of Compute minutes on GitLab Dedicated.
|
---
stage: Production Engineering
group: Runners Platform
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: GitLab-hosted runners
breadcrumbs:
- doc
- ci
- runners
- hosted_runners
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Dedicated
{{< /details >}}
Use GitLab-hosted runners to run your CI/CD jobs on GitLab.com and GitLab Dedicated.
These runners can build, test, and deploy applications on different environments.
To create and register your own runners, see [self-managed runners](https://docs.gitlab.com/runner/).
## Hosted runners for GitLab.com
{{< details >}}
- Offering: GitLab.com
{{< /details >}}
These runners are fully integrated with GitLab.com and are enabled by default for all projects, with no configuration required.
Your jobs can run on:
- [Hosted runners on Linux](linux.md).
- [GPU-enabled hosted runners](gpu_enabled.md).
- [Hosted runners on Windows](windows.md) ([beta](../../../policy/development_stages_support.md#beta)).
- [Hosted runners on macOS](macos.md) ([beta](../../../policy/development_stages_support.md#beta)).
### GitLab.com hosted runner workflow
When you use hosted runners:
- Each of your jobs runs in a newly provisioned VM, which is dedicated to the specific job.
- The virtual machine where your job runs has `sudo` access with no password.
- The storage is shared by the operating system, the container image with pre-installed software, and a copy of your cloned repository.
This means that the available free disk space for your jobs to use is reduced.
- [Untagged](../../yaml/_index.md#tags) jobs run on the `small` Linux x86-64 runner.
{{< alert type="note" >}}
Jobs handled by hosted runners on GitLab.com time out after 3 hours, regardless of the timeout configured in a project.
{{< /alert >}}
### Security of hosted runners for GitLab.com
The following section provides an overview of the additional built-in layers that harden the security of the GitLab Runner build environment.
Hosted runners for GitLab.com are configured as such:
- Firewall rules only allow outbound communication from the ephemeral VM to the public internet.
- Inbound communication from the public internet to the ephemeral VM is not allowed.
- Firewall rules do not permit communication between VMs.
- The only internal communication allowed to the ephemeral VMs is from the runner manager.
- Ephemeral runner VMs serve a single job and are deleted right after the job execution.
#### Architecture diagram of hosted runners for GitLab.com
The following graphic shows the architecture diagram of hosted runners for GitLab.com

For more information on how runners are authenticating and executing the job payload, see [Runner Execution Flow](https://docs.gitlab.com/runner#runner-execution-flow).
#### Job isolation of hosted runners for GitLab.com
In addition to isolating runners on the network, each ephemeral runner VM only serves a single job and is deleted straight after the job execution.
In the following example, three jobs are executed in a project's pipeline. Each of these jobs runs in a dedicated ephemeral VM.

The build job ran on `runner-ns46nmmj-project-43717858`, test job on `f131a6a2runner-new2m-od-project-43717858` and deploy job on `runner-tmand5m-project-43717858`.
GitLab sends the command to remove the ephemeral runner VM to the Google Compute API immediately after the CI job completes. The [Google Compute Engine hypervisor](https://cloud.google.com/blog/products/gcp/7-ways-we-harden-our-kvm-hypervisor-at-google-cloud-security-in-plaintext)
takes over the task of securely deleting the virtual machine and associated data.
For more information about the security of hosted runners for GitLab.com, see:
- [Google Cloud Infrastructure Security Design Overview whitepaper](https://cloud.google.com/docs/security/infrastructure/design/resources/google_infrastructure_whitepaper_fa.pdf)
- [GitLab Trust Center](https://about.gitlab.com/security/)
- GitLab Security Compliance Controls
### Caching on hosted runners for GitLab.com
The hosted runners share a [distributed cache](https://docs.gitlab.com/runner/configuration/autoscale.html#distributed-runners-caching)
stored in a Google Cloud Storage (GCS) bucket. Cache contents not updated in the last 14 days are automatically
removed, based on the [object lifecycle management policy](https://cloud.google.com/storage/docs/lifecycle).
The maximum size of an uploaded cache artifact can be 5 GB after the cache becomes a compressed archive.
For more information about how caching works, see [Architecture diagram of hosted runners for GitLab.com](#architecture-diagram-of-hosted-runners-for-gitlabcom), and [Caching in GitLab CI/CD](../../caching/_index.md).
### Pricing of hosted runners for GitLab.com
Jobs that run on hosted runners for GitLab.com consume [compute minutes](../../pipelines/compute_minutes.md) allocated to your namespace.
The number of minutes you can use on these runners depends on the included compute minutes in your [subscription plan](https://about.gitlab.com/pricing/) or [additionally purchased compute minutes](../../../subscriptions/gitlab_com/compute_minutes.md).
For more information about the cost factor applied to the machine type based on size, see [cost factor](../../pipelines/compute_minutes.md#cost-factors-of-hosted-runners-for-gitlabcom).
### SLO & Release cycle for hosted runners for GitLab.com
Our SLO objective is to make 90% of CI/CD jobs start executing in 120 seconds or less. The error rate should be less than 0.5%.
We aim to update to the latest version of [GitLab Runner](https://docs.gitlab.com/runner/#gitlab-runner-versions) within a week of its release.
You can find all GitLab Runner breaking changes under [Deprecations and removals](../../../update/deprecations.md).
## Hosted runners for GitLab community contributions
{{< details >}}
- Offering: GitLab.com
{{< /details >}}
If you want to [contribute to GitLab](https://about.gitlab.com/community/contribute/), jobs are picked up by the
`gitlab-shared-runners-manager-X.gitlab.com` fleet of runners, dedicated for GitLab projects and related community forks.
These runners are backed by the same machine type as our `small` Linux x86-64 runners.
Unlike hosted runners for GitLab.com, hosted runners for GitLab community contributions are re-used up to 40 times.
As we want to encourage people to contribute, these runners are free of charge.
## Hosted runners for GitLab Dedicated
{{< details >}}
- Offering: GitLab Dedicated
{{< /details >}}
Hosted runners for GitLab Dedicated are created on demand and are fully integrated with your GitLab Dedicated instance.
For more information, see [hosted runners for GitLab Dedicated](../../../administration/dedicated/hosted_runners.md).
## Supported image lifecycle
Hosted runners on macOS and Windows can only run jobs on supported images. You cannot bring your own image.
Supported images have the following lifecycle:
### Beta
New images are released as beta. This allows us to gather feedback and address potential issues before general availability.
Any jobs running on beta images are not covered by the service-level agreement.
If you use beta images, you can provide feedback by creating an issue.
### General availability
A image becomes generally available after it completes the beta phase and is considered stable.
To become generally available, the image must fulfill the following requirements:
- Successful completion of a beta phase by resolving all reported significant bugs
- Compatibility of installed software with the underlying OS
Jobs that run on generally available images are covered by the defined service-level agreement.
### Deprecated
A maximum of two generally available images are supported at a time. After a new generally available image is released,
the oldest generally available image becomes deprecated. A deprecated image is no longer updated and is deleted after 3 months.
## Usage data
You can [view an estimate](../../pipelines/dedicated_hosted_runner_compute_minutes.md) of
GitLab-hosted Runner usage of Compute minutes on GitLab Dedicated.
|
https://docs.gitlab.com/ci/runners/macos
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/runners/macos.md
|
2025-08-13
|
doc/ci/runners/hosted_runners
|
[
"doc",
"ci",
"runners",
"hosted_runners"
] |
macos.md
|
Production Engineering
|
Runners Platform
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Hosted runners on macOS
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com
- Status: Beta
{{< /details >}}
Hosted runners on macOS provide an on-demand macOS environment, fully integrated with GitLab [CI/CD](../../_index.md).
You can use these runners to build, test, and deploy apps for the Apple ecosystem (macOS, iOS, watchOS, tvOS).
Our [Mobile DevOps section](../../mobile_devops/mobile_devops_tutorial_ios.md#set-up-your-build-environment) provides features, documentation, and guidance on building and deploying mobile applications for iOS.
Hosted runners on macOS are in [beta](../../../policy/development_stages_support.md#beta) and available for open source programs and customers in Premium and Ultimate plans.
[General availability](../../../policy/development_stages_support.md#generally-available) of Hosted runners on macOS is proposed in [epic 8267](https://gitlab.com/groups/gitlab-org/-/epics/8267).
Review the list of [known issues and usage constraints](#known-issues-and-usage-constraints) that affect hosted runners on macOS before you use them.
## Machine types available for macOS
GitLab offers the following machine type for hosted runners on macOS. To build for an x86-64 target, you can use Rosetta 2 to emulate an Intel x86-64 environment.
| Runner Tag | vCPUS | Memory | Storage |
| ------------------------ | ----- | ------ | ------- |
| `saas-macos-medium-m1` | 4 | 8 GB | 50 GB |
| `saas-macos-large-m2pro` | 6 | 16 GB | 50 GB |
## Supported macOS images
In comparison to our hosted runners on Linux, where you can run any Docker image,
GitLab provides a set of VM images for macOS.
You can execute your build in one of the following images, which you specify
in your `.gitlab-ci.yml` file. Each image runs a specific version of macOS and Xcode.
| VM image | Status | |
|----------------------------|--------------|--------------|
| `macos-14-xcode-15` | `GA` | [Preinstalled Software](https://gitlab-org.gitlab.io/ci-cd/shared-runners/images/macos-image-inventory/macos-14-xcode-15/) |
| `macos-15-xcode-16` | `GA` | [Preinstalled Software](https://gitlab-org.gitlab.io/ci-cd/shared-runners/images/macos-image-inventory/macos-15-xcode-16/) |
If no image is specified, the macOS runner uses `macos-15-xcode-16`.
## Image update policy for macOS
The images and installed components are updated with each GitLab release, to keep the preinstalled software up-to-date. GitLab typically supports multiple versions of preinstalled software. For more information, see the [full list of preinstalled software](https://gitlab.com/gitlab-org/ci-cd/shared-runners/images/job-images/-/tree/main/toolchain).
Major and minor releases of macOS and Xcode are made available in the milestone subsequent to the Apple release.
A new major release image is initially made available as beta, and becomes generally available with the release of the first minor release.
Because only two generally available images are supported at a time, the oldest image becomes deprecated and will be removed after three months according to the [supported image lifecycle](_index.md#supported-image-lifecycle).
When a new major release is generally available, it becomes the default image for all macOS jobs.
## Example `.gitlab-ci.yml` file
The following sample `.gitlab-ci.yml` file shows how to start using the hosted runners on macOS:
```yaml
.macos_saas_runners:
tags:
- saas-macos-medium-m1
image: macos-14-xcode-15
before_script:
- echo "started by ${GITLAB_USER_NAME} / @${GITLAB_USER_LOGIN}"
build:
extends:
- .macos_saas_runners
stage: build
script:
- echo "running scripts in the build job"
test:
extends:
- .macos_saas_runners
stage: test
script:
- echo "running scripts in the test job"
```
## Code signing iOS Projects with fastlane
Before you can integrate GitLab with Apple services, install to a device, or deploy to the Apple App Store, you must [code sign](https://developer.apple.com/documentation/security/code_signing_services) your application.
Included in each runner on macOS VM image is [fastlane](https://fastlane.tools/),
an open-source solution aimed at simplifying mobile app deployment.
For information about how to set up code signing for your application, see the instructions in the [Mobile DevOps documentation](../../mobile_devops/mobile_devops_tutorial_ios.md#configure-code-signing-with-fastlane).
Related topics:
- [Apple Developer Support - Code Signing](https://forums.developer.apple.com/forums/thread/707080)
- [Code Signing Best Practice Guide](https://codesigning.guide/)
- [fastlane authentication with Apple Services guide](https://docs.fastlane.tools/getting-started/ios/authentication/)
## Optimizing Homebrew
By default, Homebrew checks for updates at the start of any operation. Homebrew has a
release cycle that may be more frequent than the GitLab macOS image release cycle. This
difference in release cycles may cause steps that call `brew` to take extra time to complete
while Homebrew makes updates.
To reduce build time due to unintended Homebrew updates, set the `HOMEBREW_NO_AUTO_UPDATE` variable in `.gitlab-ci.yml`:
```yaml
variables:
HOMEBREW_NO_AUTO_UPDATE: 1
```
## Optimizing Cocoapods
If you use Cocoapods in a project, you should consider the following optimizations to improve CI performance.
**Cocoapods CDN**
You can use content delivery network (CDN) access to download packages from the CDN instead of having to clone an entire
project repository. CDN access is available in Cocoapods 1.8 or later and is supported by all GitLab hosted runners on macOS.
To enable CDN access, ensure your Podfile starts with:
```ruby
source 'https://cdn.cocoapods.org/'
```
**Use GitLab caching**
Use caching in Cocoapods packages in GitLab to only run `pod install`
when pods change, which can improve build performance.
To [configure caching](../../caching/_index.md) for your project:
1. Add the `cache` configuration to your `.gitlab-ci.yml` file:
```yaml
cache:
key:
files:
- Podfile.lock
paths:
- Pods
```
1. Add the [`cocoapods-check`](https://guides.cocoapods.org/plugins/optimising-ci-times.html) plugin to your project.
1. Update the job script to check for installed dependencies before it calls `pod install`:
```shell
bundle exec pod check || bundle exec pod install
```
**Include pods in source control**
You can also [include the pods directory in source control](https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control). This eliminates the need to install pods as part of the CI job,
but it does increase the overall size of your project's repository.
## Known issues and usage constraints
- If the VM image does not include the specific software version you need for your job, the required software must be fetched and installed. This causes an increase in job execution time.
- It is not possible to bring your own OS image.
- The keychain for user `gitlab` is not publicly available. You must create a keychain instead.
- Hosted runners on macOS run in headless mode.
Any workloads that require UI interactions such as `testmanagerd` are not supported.
- Job performance might vary between job executions as Apple silicon chips have efficiency and
performance cores. You can't control core allocation or scheduling, which might lead to inconsistencies.
- The availability of AWS bare metal macOS machines used for hosted runners on macOS is limited. Jobs might experience extended queuing times when no machines are available.
- Hosted runner instances on macOS sometimes do not respond to requests, which results in jobs hanging until the maximum job duration is reached.
|
---
stage: Production Engineering
group: Runners Platform
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Hosted runners on macOS
breadcrumbs:
- doc
- ci
- runners
- hosted_runners
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com
- Status: Beta
{{< /details >}}
Hosted runners on macOS provide an on-demand macOS environment, fully integrated with GitLab [CI/CD](../../_index.md).
You can use these runners to build, test, and deploy apps for the Apple ecosystem (macOS, iOS, watchOS, tvOS).
Our [Mobile DevOps section](../../mobile_devops/mobile_devops_tutorial_ios.md#set-up-your-build-environment) provides features, documentation, and guidance on building and deploying mobile applications for iOS.
Hosted runners on macOS are in [beta](../../../policy/development_stages_support.md#beta) and available for open source programs and customers in Premium and Ultimate plans.
[General availability](../../../policy/development_stages_support.md#generally-available) of Hosted runners on macOS is proposed in [epic 8267](https://gitlab.com/groups/gitlab-org/-/epics/8267).
Review the list of [known issues and usage constraints](#known-issues-and-usage-constraints) that affect hosted runners on macOS before you use them.
## Machine types available for macOS
GitLab offers the following machine type for hosted runners on macOS. To build for an x86-64 target, you can use Rosetta 2 to emulate an Intel x86-64 environment.
| Runner Tag | vCPUS | Memory | Storage |
| ------------------------ | ----- | ------ | ------- |
| `saas-macos-medium-m1` | 4 | 8 GB | 50 GB |
| `saas-macos-large-m2pro` | 6 | 16 GB | 50 GB |
## Supported macOS images
In comparison to our hosted runners on Linux, where you can run any Docker image,
GitLab provides a set of VM images for macOS.
You can execute your build in one of the following images, which you specify
in your `.gitlab-ci.yml` file. Each image runs a specific version of macOS and Xcode.
| VM image | Status | |
|----------------------------|--------------|--------------|
| `macos-14-xcode-15` | `GA` | [Preinstalled Software](https://gitlab-org.gitlab.io/ci-cd/shared-runners/images/macos-image-inventory/macos-14-xcode-15/) |
| `macos-15-xcode-16` | `GA` | [Preinstalled Software](https://gitlab-org.gitlab.io/ci-cd/shared-runners/images/macos-image-inventory/macos-15-xcode-16/) |
If no image is specified, the macOS runner uses `macos-15-xcode-16`.
## Image update policy for macOS
The images and installed components are updated with each GitLab release, to keep the preinstalled software up-to-date. GitLab typically supports multiple versions of preinstalled software. For more information, see the [full list of preinstalled software](https://gitlab.com/gitlab-org/ci-cd/shared-runners/images/job-images/-/tree/main/toolchain).
Major and minor releases of macOS and Xcode are made available in the milestone subsequent to the Apple release.
A new major release image is initially made available as beta, and becomes generally available with the release of the first minor release.
Because only two generally available images are supported at a time, the oldest image becomes deprecated and will be removed after three months according to the [supported image lifecycle](_index.md#supported-image-lifecycle).
When a new major release is generally available, it becomes the default image for all macOS jobs.
## Example `.gitlab-ci.yml` file
The following sample `.gitlab-ci.yml` file shows how to start using the hosted runners on macOS:
```yaml
.macos_saas_runners:
tags:
- saas-macos-medium-m1
image: macos-14-xcode-15
before_script:
- echo "started by ${GITLAB_USER_NAME} / @${GITLAB_USER_LOGIN}"
build:
extends:
- .macos_saas_runners
stage: build
script:
- echo "running scripts in the build job"
test:
extends:
- .macos_saas_runners
stage: test
script:
- echo "running scripts in the test job"
```
## Code signing iOS Projects with fastlane
Before you can integrate GitLab with Apple services, install to a device, or deploy to the Apple App Store, you must [code sign](https://developer.apple.com/documentation/security/code_signing_services) your application.
Included in each runner on macOS VM image is [fastlane](https://fastlane.tools/),
an open-source solution aimed at simplifying mobile app deployment.
For information about how to set up code signing for your application, see the instructions in the [Mobile DevOps documentation](../../mobile_devops/mobile_devops_tutorial_ios.md#configure-code-signing-with-fastlane).
Related topics:
- [Apple Developer Support - Code Signing](https://forums.developer.apple.com/forums/thread/707080)
- [Code Signing Best Practice Guide](https://codesigning.guide/)
- [fastlane authentication with Apple Services guide](https://docs.fastlane.tools/getting-started/ios/authentication/)
## Optimizing Homebrew
By default, Homebrew checks for updates at the start of any operation. Homebrew has a
release cycle that may be more frequent than the GitLab macOS image release cycle. This
difference in release cycles may cause steps that call `brew` to take extra time to complete
while Homebrew makes updates.
To reduce build time due to unintended Homebrew updates, set the `HOMEBREW_NO_AUTO_UPDATE` variable in `.gitlab-ci.yml`:
```yaml
variables:
HOMEBREW_NO_AUTO_UPDATE: 1
```
## Optimizing Cocoapods
If you use Cocoapods in a project, you should consider the following optimizations to improve CI performance.
**Cocoapods CDN**
You can use content delivery network (CDN) access to download packages from the CDN instead of having to clone an entire
project repository. CDN access is available in Cocoapods 1.8 or later and is supported by all GitLab hosted runners on macOS.
To enable CDN access, ensure your Podfile starts with:
```ruby
source 'https://cdn.cocoapods.org/'
```
**Use GitLab caching**
Use caching in Cocoapods packages in GitLab to only run `pod install`
when pods change, which can improve build performance.
To [configure caching](../../caching/_index.md) for your project:
1. Add the `cache` configuration to your `.gitlab-ci.yml` file:
```yaml
cache:
key:
files:
- Podfile.lock
paths:
- Pods
```
1. Add the [`cocoapods-check`](https://guides.cocoapods.org/plugins/optimising-ci-times.html) plugin to your project.
1. Update the job script to check for installed dependencies before it calls `pod install`:
```shell
bundle exec pod check || bundle exec pod install
```
**Include pods in source control**
You can also [include the pods directory in source control](https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control). This eliminates the need to install pods as part of the CI job,
but it does increase the overall size of your project's repository.
## Known issues and usage constraints
- If the VM image does not include the specific software version you need for your job, the required software must be fetched and installed. This causes an increase in job execution time.
- It is not possible to bring your own OS image.
- The keychain for user `gitlab` is not publicly available. You must create a keychain instead.
- Hosted runners on macOS run in headless mode.
Any workloads that require UI interactions such as `testmanagerd` are not supported.
- Job performance might vary between job executions as Apple silicon chips have efficiency and
performance cores. You can't control core allocation or scheduling, which might lead to inconsistencies.
- The availability of AWS bare metal macOS machines used for hosted runners on macOS is limited. Jobs might experience extended queuing times when no machines are available.
- Hosted runner instances on macOS sometimes do not respond to requests, which results in jobs hanging until the maximum job duration is reached.
|
https://docs.gitlab.com/ci/runners/gpu_enabled
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/runners/gpu_enabled.md
|
2025-08-13
|
doc/ci/runners/hosted_runners
|
[
"doc",
"ci",
"runners",
"hosted_runners"
] |
gpu_enabled.md
|
Production Engineering
|
Runners Platform
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GPU-enabled hosted runners
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
GitLab provides GPU-enabled hosted runners to accelerate heavy compute workloads for ModelOps
or HPC such as the training or deployment of Large Language Models (LLMs) as part of ModelOps workloads.
GitLab provides GPU-enabled runners only on Linux. For more information about how these runners work, see [Hosted runners on Linux](linux.md)
## Machine types available for GPU-enabled runners
The following machine types are available for GPU-enabled runners on Linux x86-64.
| Runner Tag | vCPUs | Memory | Storage | GPU | GPU Memory |
|----------------------------------------|-------|--------|---------|--------------------------------|------------|
| `saas-linux-medium-amd64-gpu-standard` | 4 | 15 GB | 50 GB | 1 Nvidia Tesla T4 (or similar) | 16 GB |
## Container images with GPU drivers
As with GitLab hosted runners on Linux, your job runs in an isolated virtual machine (VM)
with a bring-your-own-image policy. GitLab mounts the GPU from the host VM into
your isolated environment. To use the GPU, you must use a Docker image with the
GPU driver installed. For Nvidia GPUs, you can use their [CUDA Toolkit](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/cuda).
## Example `.gitlab-ci.yml` file
In the following example of the `.gitlab-ci.yml` file, the Nvidia CUDA base Ubuntu image is used.
In the `script:` section, you install Python.
```yaml
gpu-job:
stage: build
tags:
- saas-linux-medium-amd64-gpu-standard
image: nvcr.io/nvidia/cuda:12.1.1-base-ubuntu22.04
script:
- apt-get update
- apt-get install -y python3.10
- python3.10 --version
```
If you don't want to install larger libraries such as Tensorflow or XGBoost each time you run a job, you can create your own image with all the required components pre-installed.
Watch this demo to learn how to leverage GPU-enabled hosted runners to train an XGBoost model:
<div class="video-fallback">
Video demonstration of GitLab GPU-enabled hosted runners: <a href="https://youtu.be/tElegG4NCZ0">Train XGboost models with GitLab</a>.
</div>
<figure class="video-container">
<iframe src="https://www.youtube-nocookie.com/embed/tElegG4NCZ0" frameborder="0" allowfullscreen> </iframe>
</figure>
|
---
stage: Production Engineering
group: Runners Platform
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: GPU-enabled hosted runners
breadcrumbs:
- doc
- ci
- runners
- hosted_runners
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
GitLab provides GPU-enabled hosted runners to accelerate heavy compute workloads for ModelOps
or HPC such as the training or deployment of Large Language Models (LLMs) as part of ModelOps workloads.
GitLab provides GPU-enabled runners only on Linux. For more information about how these runners work, see [Hosted runners on Linux](linux.md)
## Machine types available for GPU-enabled runners
The following machine types are available for GPU-enabled runners on Linux x86-64.
| Runner Tag | vCPUs | Memory | Storage | GPU | GPU Memory |
|----------------------------------------|-------|--------|---------|--------------------------------|------------|
| `saas-linux-medium-amd64-gpu-standard` | 4 | 15 GB | 50 GB | 1 Nvidia Tesla T4 (or similar) | 16 GB |
## Container images with GPU drivers
As with GitLab hosted runners on Linux, your job runs in an isolated virtual machine (VM)
with a bring-your-own-image policy. GitLab mounts the GPU from the host VM into
your isolated environment. To use the GPU, you must use a Docker image with the
GPU driver installed. For Nvidia GPUs, you can use their [CUDA Toolkit](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/cuda).
## Example `.gitlab-ci.yml` file
In the following example of the `.gitlab-ci.yml` file, the Nvidia CUDA base Ubuntu image is used.
In the `script:` section, you install Python.
```yaml
gpu-job:
stage: build
tags:
- saas-linux-medium-amd64-gpu-standard
image: nvcr.io/nvidia/cuda:12.1.1-base-ubuntu22.04
script:
- apt-get update
- apt-get install -y python3.10
- python3.10 --version
```
If you don't want to install larger libraries such as Tensorflow or XGBoost each time you run a job, you can create your own image with all the required components pre-installed.
Watch this demo to learn how to leverage GPU-enabled hosted runners to train an XGBoost model:
<div class="video-fallback">
Video demonstration of GitLab GPU-enabled hosted runners: <a href="https://youtu.be/tElegG4NCZ0">Train XGboost models with GitLab</a>.
</div>
<figure class="video-container">
<iframe src="https://www.youtube-nocookie.com/embed/tElegG4NCZ0" frameborder="0" allowfullscreen> </iframe>
</figure>
|
https://docs.gitlab.com/ci/kubernetes_dashboard
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/kubernetes_dashboard.md
|
2025-08-13
|
doc/ci/environments
|
[
"doc",
"ci",
"environments"
] |
kubernetes_dashboard.md
|
Deploy
|
Environments
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Dashboard for Kubernetes
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
- Status: Beta
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/390769) in GitLab 16.1, with [flags](../../administration/feature_flags/_index.md) named `environment_settings_to_graphql`, `kas_user_access`, `kas_user_access_project`, and `expose_authorized_cluster_agents`. This feature is in [beta](../../policy/development_stages_support.md#beta).
- Feature flag `environment_settings_to_graphql` [removed](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/124177) in GitLab 16.2.
- Feature flags `kas_user_access`, `kas_user_access_project`, and `expose_authorized_cluster_agents` [removed](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/125835) in GitLab 16.2.
- [Moved](https://gitlab.com/gitlab-org/gitlab/-/issues/431746) to the environment details page in 16.10.
{{< /history >}}
Use the dashboard for Kubernetes to understand the status of your clusters with an intuitive visual interface.
The dashboard works with every connected Kubernetes cluster, whether you deployed them
with CI/CD or GitOps.

## Configure a dashboard
{{< history >}}
- Filtering resources by namespace [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/403618) in GitLab 16.2 [with a flag](../../administration/feature_flags/_index.md) named `kubernetes_namespace_for_environment`. Disabled by default.
- Filtering resources by namespace [enabled by default](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/127043) in GitLab 16.3. Feature flag `kubernetes_namespace_for_environment` removed.
- Selecting the related Flux resource [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/128857) in GitLab 16.3 [with a flag](../../administration/feature_flags/_index.md) named `flux_resource_for_environment`.
- Selecting the related Flux resource [generally available](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/130648) in GitLab 16.4. Feature flag `flux_resource_for_environment` removed.
{{< /history >}}
Configure a dashboard to use it for a given environment.
You can configure dashboard for an environment that already exists, or
add one when you create an environment.
Prerequisites:
- A GitLab agent for Kubernetes is [installed](../../user/clusters/agent/install/_index.md) and [`user_access`](../../user/clusters/agent/user_access.md) is configured for the environment's project or its parent group.
{{< tabs >}}
{{< tab title="The environment already exists" >}}
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment to be associated with the agent for Kubernetes.
1. Select **Edit**.
1. Select a GitLab agent for Kubernetes.
1. Optional. From the **Kubernetes namespace** dropdown list, select a namespace.
1. Optional. From the **Flux resource** dropdown list, select a Flux resource.
1. Select **Save**.
{{< /tab >}}
{{< tab title="The environment doesn't exist" >}}
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select **New environment**.
1. Complete the **Name** field.
1. Select a GitLab agent for Kubernetes.
1. Optional. From the **Kubernetes namespace** dropdown list, select a namespace.
1. Optional. From the **Flux resource** dropdown list, select a Flux resource.
1. Select **Save**.
{{< /tab >}}
{{< /tabs >}}
### Configure a dashboard for a dynamic environment
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/467912) in GitLab 17.6.
{{< /history >}}
To configure a dashboard for a dynamic environment:
- Specify the agent in your `.gitlab-ci.yml` file. You must specify the full path to the agent configuration project,
followed by a colon and the name of the agent.
For example:
```yaml
deploy_review_app:
stage: deploy
script: make deploy
environment:
name: review/$CI_COMMIT_REF_SLUG
kubernetes:
agent: path/to/agent/project:agent-name
```
For more information, see the [CI/CD YAML syntax reference](../yaml/_index.md#environmentkubernetes).
## View a dashboard
{{< history >}}
- Kubernetes watch API integration [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/422945) in GitLab 16.6 [with a flag](../../administration/feature_flags/_index.md) named `k8s_watch_api`. Disabled by default.
- Kubernetes watch API integration [enabled by default](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/136831) in GitLab 16.7.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/427762) in GitLab 17.1. Feature flag `k8s_watch_api` removed.
{{< /history >}}
View a dashboard to see the status of connected clusters.
The status of your Kubernetes resources and Flux reconciliation updates in real time.
To view a configured dashboard:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment associated with the agent for Kubernetes.
1. Select the **Kubernetes overview** tab.
A list of pods is displayed. Select a pod to view its details.
### Flux sync status
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/391581) in GitLab 16.3.
- Customizing the name of the Flux resource [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/128857) in GitLab 16.3 [with a flag](../../administration/feature_flags/_index.md) named `flux_resource_for_environment`.
- Customizing the name of the Flux resource [generally available](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/130648) in GitLab 16.4. Feature flag `flux_resource_for_environment` removed.
{{< /history >}}
You can review the sync status of your Flux deployments from a dashboard.
To display the deployment status, your dashboard must be able to retrieve the `Kustomization` and `HelmRelease` resources,
which requires a namespace to be configured for the environment.
GitLab searches the `Kustomization` and `HelmRelease` resources specified by the **Flux resource** dropdown list in the environment settings.
A dashboard displays one of the following status badges:
| Status | Description |
|---------|-------------|
| **Reconciled** | The deployment successfully reconciled with its environment. |
| **Reconciling** | A reconciliation is in progress. |
| **Stalled** | A reconciliation is stuck because of an error that cannot be resolved without human intervention. |
| **Failed** | The deployment couldn't reconcile because of an unrecoverable error. |
| **Unknown** | The sync status of the deployment couldn't be retrieved. |
| **Unavailable** | The `Kustomization` or `HelmRelease` resource couldn't be retrieved. |
### Trigger Flux reconciliation
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/434248) in GitLab 17.3.
{{< /history >}}
You can manually reconcile your deployment with its Flux resources.
To trigger a reconciliation:
1. On a dashboard, select the sync status badge of a Flux deployment.
1. Select **Actions** ({{< icon name="ellipsis_v" >}}) **> Trigger reconciliation** ({{< icon name="retry" >}}).
### Suspend or resume Flux reconciliation
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/478380) in GitLab 17.5.
{{< /history >}}
You can manually suspend or resume your Flux reconciliation from the UI.
To suspend or resume reconciliation:
1. On a dashboard, select the sync status badge of a Flux deployment.
1. Select **Actions** ({{< icon name="ellipsis_v" >}}), then choose one of the following:
- **Suspend reconciliation** ({{< icon name="stop" >}}) to pause the Flux reconciliation.
- **Resume reconciliation** ({{< icon name="play" >}}) to restart the Flux reconciliation.
### View pod logs
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/13793) in GitLab 17.2.
{{< /history >}}
View pod logs when you want to quickly understand and troubleshoot issues across your environments from a configured dashboard. You can view logs for each container in a pod.
- Select **View logs**, then select the container you want to view logs for.
You can also view pod logs from the pod details.
### Delete a pod
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/467653) in GitLab 17.3.
{{< /history >}}
To restart a failed pod, delete it from the Kubernetes dashboard.
To delete a pod:
1. On the **Kubernetes overview** tab, find the pod you want to delete.
1. Select **Actions** ({{< icon name="ellipsis_v" >}}) **> Delete pod** ({{< icon name="remove" >}}).
You can also delete a pod from the pod details.
## Detailed dashboard
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/11351) in GitLab 16.4, [with a flag](../../administration/feature_flags/_index.md) named `k8s_dashboard`. Disabled by default.
- [Enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/issues/424237) in GitLab 16.7 for a subset of users.
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
This feature is available for testing, but not ready for production use.
{{< /alert >}}
The detailed dashboard provides information about the following Kubernetes resources:
- Pods
- Services
- Deployments
- ReplicaSets
- StatefulSets
- DaemonSets
- Jobs
- CronJobs
Each dashboard displays a list of resources with their statuses, namespaces, and age.
You can select a resource to open a drawer with more information, including labels
and YAML-formatted status, annotations, and spec.

Because of the focus shift described in [this issue](https://gitlab.com/gitlab-org/ci-cd/deploy-stage/environments-group/general/-/issues/53#note_1720060812), work on the detailed dashboard is paused.
To provide feedback on the detailed dashboard, see [issue 460279](https://gitlab.com/gitlab-org/gitlab/-/issues/460279).
### View a detailed dashboard
Prerequisites:
- A GitLab agent for Kubernetes is [configured](../../user/clusters/agent/install/_index.md) and shared with the environment's project, or its parent group, using the [`user_access`](../../user/clusters/agent/user_access.md) keyword.
The detailed dashboard is not linked from the sidebar navigation.
To view a detailed dashboard:
1. Find your agent for Kubernetes ID:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Kubernetes clusters**.
1. Copy the numerical ID of the agent you want to access.
1. Go to one of the following URLs, replacing `<agent_id>` with your agent ID:
| Resource type | URL |
| --- | --- |
| Pods | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/pods`|
| Services | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/services` |
| Deployments | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/deployments` |
| ReplicaSets | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/replicaSets` |
| StatefulSets | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/statefulSets` |
| DaemonSets | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/daemonSets` |
| Jobs | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/jobs` |
| CronJobs | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/cronJobs` |
## Troubleshooting
When working with the dashboard for Kubernetes, you might encounter the following issues.
### User cannot list resource in API group
You might get an error that states `Error: services is forbidden: User "gitlab:user:<user-name>" cannot list resource "<resource-name>" in API group "" at the cluster scope`.
This error happens when a user is not allowed to do the specified operation in the [Kubernetes RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/).
To resolve, check your [RBAC configuration](../../user/clusters/agent/user_access.md#configure-kubernetes-access). If the RBAC is properly configured, contact your Kubernetes administrator.
### GitLab agent dropdown list is empty
When you configure a new environment, the **GitLab agent** dropdown list might be empty, even if you have configured Kubernetes clusters.
To populate the **GitLab agent** dropdown list, grant an agent Kubernetes access with the [`user_access`](../../user/clusters/agent/user_access.md) keyword.
|
---
stage: Deploy
group: Environments
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Dashboard for Kubernetes
breadcrumbs:
- doc
- ci
- environments
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
- Status: Beta
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/390769) in GitLab 16.1, with [flags](../../administration/feature_flags/_index.md) named `environment_settings_to_graphql`, `kas_user_access`, `kas_user_access_project`, and `expose_authorized_cluster_agents`. This feature is in [beta](../../policy/development_stages_support.md#beta).
- Feature flag `environment_settings_to_graphql` [removed](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/124177) in GitLab 16.2.
- Feature flags `kas_user_access`, `kas_user_access_project`, and `expose_authorized_cluster_agents` [removed](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/125835) in GitLab 16.2.
- [Moved](https://gitlab.com/gitlab-org/gitlab/-/issues/431746) to the environment details page in 16.10.
{{< /history >}}
Use the dashboard for Kubernetes to understand the status of your clusters with an intuitive visual interface.
The dashboard works with every connected Kubernetes cluster, whether you deployed them
with CI/CD or GitOps.

## Configure a dashboard
{{< history >}}
- Filtering resources by namespace [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/403618) in GitLab 16.2 [with a flag](../../administration/feature_flags/_index.md) named `kubernetes_namespace_for_environment`. Disabled by default.
- Filtering resources by namespace [enabled by default](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/127043) in GitLab 16.3. Feature flag `kubernetes_namespace_for_environment` removed.
- Selecting the related Flux resource [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/128857) in GitLab 16.3 [with a flag](../../administration/feature_flags/_index.md) named `flux_resource_for_environment`.
- Selecting the related Flux resource [generally available](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/130648) in GitLab 16.4. Feature flag `flux_resource_for_environment` removed.
{{< /history >}}
Configure a dashboard to use it for a given environment.
You can configure dashboard for an environment that already exists, or
add one when you create an environment.
Prerequisites:
- A GitLab agent for Kubernetes is [installed](../../user/clusters/agent/install/_index.md) and [`user_access`](../../user/clusters/agent/user_access.md) is configured for the environment's project or its parent group.
{{< tabs >}}
{{< tab title="The environment already exists" >}}
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment to be associated with the agent for Kubernetes.
1. Select **Edit**.
1. Select a GitLab agent for Kubernetes.
1. Optional. From the **Kubernetes namespace** dropdown list, select a namespace.
1. Optional. From the **Flux resource** dropdown list, select a Flux resource.
1. Select **Save**.
{{< /tab >}}
{{< tab title="The environment doesn't exist" >}}
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select **New environment**.
1. Complete the **Name** field.
1. Select a GitLab agent for Kubernetes.
1. Optional. From the **Kubernetes namespace** dropdown list, select a namespace.
1. Optional. From the **Flux resource** dropdown list, select a Flux resource.
1. Select **Save**.
{{< /tab >}}
{{< /tabs >}}
### Configure a dashboard for a dynamic environment
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/467912) in GitLab 17.6.
{{< /history >}}
To configure a dashboard for a dynamic environment:
- Specify the agent in your `.gitlab-ci.yml` file. You must specify the full path to the agent configuration project,
followed by a colon and the name of the agent.
For example:
```yaml
deploy_review_app:
stage: deploy
script: make deploy
environment:
name: review/$CI_COMMIT_REF_SLUG
kubernetes:
agent: path/to/agent/project:agent-name
```
For more information, see the [CI/CD YAML syntax reference](../yaml/_index.md#environmentkubernetes).
## View a dashboard
{{< history >}}
- Kubernetes watch API integration [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/422945) in GitLab 16.6 [with a flag](../../administration/feature_flags/_index.md) named `k8s_watch_api`. Disabled by default.
- Kubernetes watch API integration [enabled by default](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/136831) in GitLab 16.7.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/427762) in GitLab 17.1. Feature flag `k8s_watch_api` removed.
{{< /history >}}
View a dashboard to see the status of connected clusters.
The status of your Kubernetes resources and Flux reconciliation updates in real time.
To view a configured dashboard:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment associated with the agent for Kubernetes.
1. Select the **Kubernetes overview** tab.
A list of pods is displayed. Select a pod to view its details.
### Flux sync status
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/391581) in GitLab 16.3.
- Customizing the name of the Flux resource [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/128857) in GitLab 16.3 [with a flag](../../administration/feature_flags/_index.md) named `flux_resource_for_environment`.
- Customizing the name of the Flux resource [generally available](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/130648) in GitLab 16.4. Feature flag `flux_resource_for_environment` removed.
{{< /history >}}
You can review the sync status of your Flux deployments from a dashboard.
To display the deployment status, your dashboard must be able to retrieve the `Kustomization` and `HelmRelease` resources,
which requires a namespace to be configured for the environment.
GitLab searches the `Kustomization` and `HelmRelease` resources specified by the **Flux resource** dropdown list in the environment settings.
A dashboard displays one of the following status badges:
| Status | Description |
|---------|-------------|
| **Reconciled** | The deployment successfully reconciled with its environment. |
| **Reconciling** | A reconciliation is in progress. |
| **Stalled** | A reconciliation is stuck because of an error that cannot be resolved without human intervention. |
| **Failed** | The deployment couldn't reconcile because of an unrecoverable error. |
| **Unknown** | The sync status of the deployment couldn't be retrieved. |
| **Unavailable** | The `Kustomization` or `HelmRelease` resource couldn't be retrieved. |
### Trigger Flux reconciliation
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/434248) in GitLab 17.3.
{{< /history >}}
You can manually reconcile your deployment with its Flux resources.
To trigger a reconciliation:
1. On a dashboard, select the sync status badge of a Flux deployment.
1. Select **Actions** ({{< icon name="ellipsis_v" >}}) **> Trigger reconciliation** ({{< icon name="retry" >}}).
### Suspend or resume Flux reconciliation
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/478380) in GitLab 17.5.
{{< /history >}}
You can manually suspend or resume your Flux reconciliation from the UI.
To suspend or resume reconciliation:
1. On a dashboard, select the sync status badge of a Flux deployment.
1. Select **Actions** ({{< icon name="ellipsis_v" >}}), then choose one of the following:
- **Suspend reconciliation** ({{< icon name="stop" >}}) to pause the Flux reconciliation.
- **Resume reconciliation** ({{< icon name="play" >}}) to restart the Flux reconciliation.
### View pod logs
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/13793) in GitLab 17.2.
{{< /history >}}
View pod logs when you want to quickly understand and troubleshoot issues across your environments from a configured dashboard. You can view logs for each container in a pod.
- Select **View logs**, then select the container you want to view logs for.
You can also view pod logs from the pod details.
### Delete a pod
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/467653) in GitLab 17.3.
{{< /history >}}
To restart a failed pod, delete it from the Kubernetes dashboard.
To delete a pod:
1. On the **Kubernetes overview** tab, find the pod you want to delete.
1. Select **Actions** ({{< icon name="ellipsis_v" >}}) **> Delete pod** ({{< icon name="remove" >}}).
You can also delete a pod from the pod details.
## Detailed dashboard
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/11351) in GitLab 16.4, [with a flag](../../administration/feature_flags/_index.md) named `k8s_dashboard`. Disabled by default.
- [Enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/issues/424237) in GitLab 16.7 for a subset of users.
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
This feature is available for testing, but not ready for production use.
{{< /alert >}}
The detailed dashboard provides information about the following Kubernetes resources:
- Pods
- Services
- Deployments
- ReplicaSets
- StatefulSets
- DaemonSets
- Jobs
- CronJobs
Each dashboard displays a list of resources with their statuses, namespaces, and age.
You can select a resource to open a drawer with more information, including labels
and YAML-formatted status, annotations, and spec.

Because of the focus shift described in [this issue](https://gitlab.com/gitlab-org/ci-cd/deploy-stage/environments-group/general/-/issues/53#note_1720060812), work on the detailed dashboard is paused.
To provide feedback on the detailed dashboard, see [issue 460279](https://gitlab.com/gitlab-org/gitlab/-/issues/460279).
### View a detailed dashboard
Prerequisites:
- A GitLab agent for Kubernetes is [configured](../../user/clusters/agent/install/_index.md) and shared with the environment's project, or its parent group, using the [`user_access`](../../user/clusters/agent/user_access.md) keyword.
The detailed dashboard is not linked from the sidebar navigation.
To view a detailed dashboard:
1. Find your agent for Kubernetes ID:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Kubernetes clusters**.
1. Copy the numerical ID of the agent you want to access.
1. Go to one of the following URLs, replacing `<agent_id>` with your agent ID:
| Resource type | URL |
| --- | --- |
| Pods | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/pods`|
| Services | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/services` |
| Deployments | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/deployments` |
| ReplicaSets | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/replicaSets` |
| StatefulSets | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/statefulSets` |
| DaemonSets | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/daemonSets` |
| Jobs | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/jobs` |
| CronJobs | `https://myinstance.gitlab.com/-/kubernetes/<agent_id>/cronJobs` |
## Troubleshooting
When working with the dashboard for Kubernetes, you might encounter the following issues.
### User cannot list resource in API group
You might get an error that states `Error: services is forbidden: User "gitlab:user:<user-name>" cannot list resource "<resource-name>" in API group "" at the cluster scope`.
This error happens when a user is not allowed to do the specified operation in the [Kubernetes RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/).
To resolve, check your [RBAC configuration](../../user/clusters/agent/user_access.md#configure-kubernetes-access). If the RBAC is properly configured, contact your Kubernetes administrator.
### GitLab agent dropdown list is empty
When you configure a new environment, the **GitLab agent** dropdown list might be empty, even if you have configured Kubernetes clusters.
To populate the **GitLab agent** dropdown list, grant an agent Kubernetes access with the [`user_access`](../../user/clusters/agent/user_access.md) keyword.
|
https://docs.gitlab.com/ci/deployments
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/deployments.md
|
2025-08-13
|
doc/ci/environments
|
[
"doc",
"ci",
"environments"
] |
deployments.md
|
Deploy
|
Environments
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Deployments
|
Deployments, rollbacks, safety, and approvals.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
When you deploy a version of your code to an environment, you create a deployment.
There is usually only one active deployment per environment.
GitLab:
- Provides a full history of deployments to each environment.
- Tracks your deployments, so you always know what is deployed on your
servers.
If you have a deployment service like [Kubernetes](../../user/infrastructure/clusters/_index.md)
associated with your project, you can use it to assist with your deployments.
After a deployment is created, you can roll it out to users.
## Configure manual deployments
You can create a job that requires someone to manually start the deployment.
For example:
```yaml
deploy_prod:
stage: deploy
script:
- echo "Deploy to production server"
environment:
name: production
url: https://example.com
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manual
```
The `when: manual` action:
- Exposes the **Run** ({{< icon name="play" >}}) button for the job in the GitLab UI, with the text **Can be manually deployed to <environment>**.
- Means the `deploy_prod` job must be triggered manually.
You can find **Run** ({{< icon name="play" >}}) in the pipelines, environments, deployments, and jobs views.
## Track newly included merge requests per deployment
GitLab can track newly included merge requests per deployment.
When a deployment succeeds, the system calculates commit-diffs between the latest deployment and the previous deployment.
You can fetch tracking information with the [Deployment API](../../api/deployments.md#list-of-merge-requests-associated-with-a-deployment)
or view it at a post-merge pipeline in [merge request pages](../../user/project/merge_requests/_index.md).
To enable tracking configure your environment so either:
- The [environment name](../yaml/_index.md#environmentname) doesn't use folders with `/` (long-lived or top-level environments).
- The [environment tier](_index.md#deployment-tier-of-environments) is either `production` or `staging`.
Here are some example configurations using the [`environment` keyword](../yaml/_index.md#environment) in `.gitlab-ci.yml`:
```yaml
# Trackable
environment: production
environment: production/aws
environment: development
# Non Trackable
environment: review/$CI_COMMIT_REF_SLUG
environment: testing/aws
```
Configuration changes apply only to new deployments. Existing deployment records do not have merge requests linked or unlinked from them.
## Check out deployments locally
A reference in the Git repository is saved for each deployment, so
knowing the state of your current environments is only a `git fetch` away.
In your Git configuration, append the `[remote "<your-remote>"]` block with an extra
fetch line:
```plaintext
fetch = +refs/environments/*:refs/remotes/origin/environments/*
```
## Archive old deployments
When a new deployment happens in your project,
GitLab creates [a special Git-ref to the deployment](#check-out-deployments-locally).
Because these Git-refs are populated from the remote GitLab repository,
you could find that some Git operations, such as `git-fetch` and `git-pull`,
become slower as the number of deployments in your project increases.
To maintain the efficiency of your Git operations, GitLab keeps
only recent deployment refs (up to 50,000) and deletes the rest of the old deployment refs.
Archived deployments are still available, in the UI or by using the API, for auditing purposes.
Also, you can still fetch the deployed commit from the repository
with specifying the commit SHA (for example, `git checkout <deployment-sha>`), even after archive.
{{< alert type="note" >}}
GitLab preserves all commits as [`keep-around` refs](../../user/project/repository/repository_size.md#methods-to-reduce-repository-size)
so that deployed commits are not garbage collected, even if it's not referenced by the deployment refs.
{{< /alert >}}
## Deployment rollback
When you roll back a deployment on a specific commit,
a new deployment is created. This deployment has its own unique job ID.
It points to the commit you're rolling back to.
For the rollback to succeed, the deployment process must be defined in
the job's `script`.
Only the [deployment jobs](../jobs/_index.md#deployment-jobs) are run.
In cases where a previous job generates artifacts that must be regenerated
on deploy, you must manually run the necessary jobs from the pipelines page.
For example, if you use Terraform and your `plan` and `apply` commands are separated
into multiple jobs, you must manually run the jobs to deploy or roll back.
### Retry or roll back a deployment
If there is a problem with a deployment, you can retry it or roll it back.
To retry or roll back a deployment:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment.
1. To the right of the deployment name:
- To retry a deployment, select **Re-deploy to environment**.
- To roll back to a deployment, next to a previously successful deployment, select **Rollback environment**.
{{< alert type="note" >}}
If you have [prevented outdated deployment jobs](deployment_safety.md#prevent-outdated-deployment-jobs) in your project,
the rollback buttons might be hidden or disabled.
In this case, see [job retries for rollback deployments](deployment_safety.md#job-retries-for-rollback-deployments).
{{< /alert >}}
## Related topics
- [Environments](_index.md)
- [Downstream pipelines for deployments](../pipelines/downstream_pipelines.md#downstream-pipelines-for-deployments)
- [Deploy to multiple environments with GitLab CI/CD (blog post)](https://about.gitlab.com/blog/2021/02/05/ci-deployment-and-environments/)
- [Review apps](../review_apps/_index.md)
- [Track deployments of an external deployment tool](external_deployment_tools.md)
## Troubleshooting
When you work with deployments, you might encounter the following issues.
### Deployment refs are not found
GitLab [deletes old deployment refs](#archive-old-deployments)
to keep your Git repository performant.
If you have to restore archived Git-refs on GitLab Self-Managed, ask an administrator
to execute the following command on Rails console:
```ruby
Project.find_by_full_path(<your-project-full-path>).deployments.where(archived: true).each(&:create_ref)
```
GitLab might drop this support in the future for the performance concern.
You can open an issue in [GitLab Issue Tracker](https://gitlab.com/gitlab-org/gitlab/-/issues/new)
to discuss the behavior of this feature.
|
---
stage: Deploy
group: Environments
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Deployments
description: Deployments, rollbacks, safety, and approvals.
breadcrumbs:
- doc
- ci
- environments
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
When you deploy a version of your code to an environment, you create a deployment.
There is usually only one active deployment per environment.
GitLab:
- Provides a full history of deployments to each environment.
- Tracks your deployments, so you always know what is deployed on your
servers.
If you have a deployment service like [Kubernetes](../../user/infrastructure/clusters/_index.md)
associated with your project, you can use it to assist with your deployments.
After a deployment is created, you can roll it out to users.
## Configure manual deployments
You can create a job that requires someone to manually start the deployment.
For example:
```yaml
deploy_prod:
stage: deploy
script:
- echo "Deploy to production server"
environment:
name: production
url: https://example.com
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manual
```
The `when: manual` action:
- Exposes the **Run** ({{< icon name="play" >}}) button for the job in the GitLab UI, with the text **Can be manually deployed to <environment>**.
- Means the `deploy_prod` job must be triggered manually.
You can find **Run** ({{< icon name="play" >}}) in the pipelines, environments, deployments, and jobs views.
## Track newly included merge requests per deployment
GitLab can track newly included merge requests per deployment.
When a deployment succeeds, the system calculates commit-diffs between the latest deployment and the previous deployment.
You can fetch tracking information with the [Deployment API](../../api/deployments.md#list-of-merge-requests-associated-with-a-deployment)
or view it at a post-merge pipeline in [merge request pages](../../user/project/merge_requests/_index.md).
To enable tracking configure your environment so either:
- The [environment name](../yaml/_index.md#environmentname) doesn't use folders with `/` (long-lived or top-level environments).
- The [environment tier](_index.md#deployment-tier-of-environments) is either `production` or `staging`.
Here are some example configurations using the [`environment` keyword](../yaml/_index.md#environment) in `.gitlab-ci.yml`:
```yaml
# Trackable
environment: production
environment: production/aws
environment: development
# Non Trackable
environment: review/$CI_COMMIT_REF_SLUG
environment: testing/aws
```
Configuration changes apply only to new deployments. Existing deployment records do not have merge requests linked or unlinked from them.
## Check out deployments locally
A reference in the Git repository is saved for each deployment, so
knowing the state of your current environments is only a `git fetch` away.
In your Git configuration, append the `[remote "<your-remote>"]` block with an extra
fetch line:
```plaintext
fetch = +refs/environments/*:refs/remotes/origin/environments/*
```
## Archive old deployments
When a new deployment happens in your project,
GitLab creates [a special Git-ref to the deployment](#check-out-deployments-locally).
Because these Git-refs are populated from the remote GitLab repository,
you could find that some Git operations, such as `git-fetch` and `git-pull`,
become slower as the number of deployments in your project increases.
To maintain the efficiency of your Git operations, GitLab keeps
only recent deployment refs (up to 50,000) and deletes the rest of the old deployment refs.
Archived deployments are still available, in the UI or by using the API, for auditing purposes.
Also, you can still fetch the deployed commit from the repository
with specifying the commit SHA (for example, `git checkout <deployment-sha>`), even after archive.
{{< alert type="note" >}}
GitLab preserves all commits as [`keep-around` refs](../../user/project/repository/repository_size.md#methods-to-reduce-repository-size)
so that deployed commits are not garbage collected, even if it's not referenced by the deployment refs.
{{< /alert >}}
## Deployment rollback
When you roll back a deployment on a specific commit,
a new deployment is created. This deployment has its own unique job ID.
It points to the commit you're rolling back to.
For the rollback to succeed, the deployment process must be defined in
the job's `script`.
Only the [deployment jobs](../jobs/_index.md#deployment-jobs) are run.
In cases where a previous job generates artifacts that must be regenerated
on deploy, you must manually run the necessary jobs from the pipelines page.
For example, if you use Terraform and your `plan` and `apply` commands are separated
into multiple jobs, you must manually run the jobs to deploy or roll back.
### Retry or roll back a deployment
If there is a problem with a deployment, you can retry it or roll it back.
To retry or roll back a deployment:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment.
1. To the right of the deployment name:
- To retry a deployment, select **Re-deploy to environment**.
- To roll back to a deployment, next to a previously successful deployment, select **Rollback environment**.
{{< alert type="note" >}}
If you have [prevented outdated deployment jobs](deployment_safety.md#prevent-outdated-deployment-jobs) in your project,
the rollback buttons might be hidden or disabled.
In this case, see [job retries for rollback deployments](deployment_safety.md#job-retries-for-rollback-deployments).
{{< /alert >}}
## Related topics
- [Environments](_index.md)
- [Downstream pipelines for deployments](../pipelines/downstream_pipelines.md#downstream-pipelines-for-deployments)
- [Deploy to multiple environments with GitLab CI/CD (blog post)](https://about.gitlab.com/blog/2021/02/05/ci-deployment-and-environments/)
- [Review apps](../review_apps/_index.md)
- [Track deployments of an external deployment tool](external_deployment_tools.md)
## Troubleshooting
When you work with deployments, you might encounter the following issues.
### Deployment refs are not found
GitLab [deletes old deployment refs](#archive-old-deployments)
to keep your Git repository performant.
If you have to restore archived Git-refs on GitLab Self-Managed, ask an administrator
to execute the following command on Rails console:
```ruby
Project.find_by_full_path(<your-project-full-path>).deployments.where(archived: true).each(&:create_ref)
```
GitLab might drop this support in the future for the performance concern.
You can open an issue in [GitLab Issue Tracker](https://gitlab.com/gitlab-org/gitlab/-/issues/new)
to discuss the behavior of this feature.
|
https://docs.gitlab.com/ci/environments
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/_index.md
|
2025-08-13
|
doc/ci/environments
|
[
"doc",
"ci",
"environments"
] |
_index.md
|
Deploy
|
Environments
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Environments
|
Environments, variables, dashboards, and review apps.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
A GitLab environment represents a specific deployment target for your application, like development, staging, or production. Use it to manage different configurations and deploy code during various stages of your software lifecycle.
With environments, you:
- Keep your deployment process consistent and repeatable
- Track what code is deployed where
- Roll back to previous versions when problems occur
- Protect sensitive environments from unauthorized changes
- Control deployment variables per environment to maintain security boundaries
- Monitor environment health and get alerts if something goes wrong
## View environments and deployments
Prerequisites:
- In a private project, you must have at least the Reporter role. See [Environment permissions](#environment-permissions).
There are a few ways to view a list of environments for a given project:
- On the project's overview page, if at least one environment is available (that is, not stopped).

- On the left sidebar, select **Operate > Environments**.
The environments are displayed.

- To view a list of deployments for an environment, select the environment name,
for example, `staging`.

Deployments show up in this list only after a deployment job has created them.
- To view a list of all manual jobs in a deployment pipeline, select the **Run** ({{< icon name="play" >}}) dropdown list.

### Environment URL
{{< history >}}
- [Changed](https://gitlab.com/gitlab-org/gitlab/-/issues/337417) to persist arbitrary URLs in GitLab 15.2 [with a flag](../../administration/feature_flags/_index.md) named `soft_validation_on_external_url`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/337417) in GitLab 15.3. [Feature flag `soft_validation_on_external_url`](https://gitlab.com/gitlab-org/gitlab/-/issues/367206) removed.
{{< /history >}}
The [environment URL](../yaml/_index.md#environmenturl) is displayed in a few
places in GitLab:
- In a merge request as a link:

- In the Environments view as a button:

- In the Deployments view as a button:

You can see this information in a merge request if:
- The merge request is eventually merged to the default branch (usually `main`).
- That branch also deploys to an environment (for example, `staging` or `production`).
For example:

#### Go from source files to public pages
With GitLab [Route Maps](../review_apps/_index.md#route-maps), you can go directly
from source files to public pages in the environment set for review apps.
## Types of environments
An environment is either static or dynamic.
Static environments:
- Are usually reused by successive deployments.
- Have static names. For example, `staging` or `production`.
- Are created manually or as part of a CI/CD pipeline.
Dynamic environments:
- Are usually created in a CI/CD pipeline and are used by only a single deployment, then either stopped or deleted.
- Have dynamic names, usually based on the value of a CI/CD variable.
- Are a feature of [review apps](../review_apps/_index.md).
An environment has one of three states, depending on whether its [stop job](../yaml/_index.md#environmenton_stop) has run:
- `available`: The environment exists. There might be a deployment.
- `stopping`: The _on stop job_ has started. This state does not apply when there is no on stop job defined.
- `stopped`: Either the _on stop job_ has run, or a user manually stopped the job.
## Create a static environment
You can create a static environment in the UI or in your `.gitlab-ci.yml` file.
### In the UI
Prerequisites:
- You must have at least the Developer role.
To create a static environment in the UI:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select **Create an environment**.
1. Complete the fields.
1. Select **Save**.
### In your `.gitlab-ci.yml` file
Prerequisites:
- You must have at least the Developer role.
To create a static environment, in your `.gitlab-ci.yml` file:
1. Define a job in the `deploy` stage.
1. In the job, define the environment `name` and `url`. If an
environment of that name doesn't exist when the pipeline runs, it is created.
{{< alert type="note" >}}
Some characters cannot be used in environment names. For more information about the
`environment` keywords, see the [`.gitlab-ci.yml` keyword reference](../yaml/_index.md#environment).
{{< /alert >}}
For example, to create an environment named `staging`, with URL `https://staging.example.com`:
```yaml
deploy_staging:
stage: deploy
script:
- echo "Deploy to staging server"
environment:
name: staging
url: https://staging.example.com
```
## Create a dynamic environment
To create a dynamic environment, you use [CI/CD variables](#cicd-variables) that are
unique to each pipeline.
Prerequisites:
- You must have at least the Developer role.
To create a dynamic environment, in your `.gitlab-ci.yml` file:
1. Define a job in the `deploy` stage.
1. In the job, define the following environment attributes:
- `name`: Use a related CI/CD variable like `$CI_COMMIT_REF_SLUG`. Optionally, add a static
prefix to the environment's name, which [groups in the UI](#group-similar-environments) all
environments with the same prefix.
- `url`: Optional. Prefix the hostname with a related CI/CD variable like `$CI_ENVIRONMENT_SLUG`.
{{< alert type="note" >}}
Some characters cannot be used in environment names. For more information about the
`environment` keywords, see the [`.gitlab-ci.yml` keyword reference](../yaml/_index.md#environment).
{{< /alert >}}
In the following example, every time the `deploy_review_app` job runs the environment's name and
URL are defined using unique values.
```yaml
deploy_review_app:
stage: deploy
script: make deploy
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: never
- if: $CI_COMMIT_BRANCH
```
### Set a dynamic environment URL
Some external hosting platforms generate a random URL for each deployment, for example:
`https://94dd65b.amazonaws.com/qa-lambda-1234567`. That makes it difficult to reference the URL in
the `.gitlab-ci.yml` file.
To address this problem, you can configure a deployment job to report back a set of
variables. These variables include the URL that was dynamically generated by the external service.
GitLab supports the [dotenv (`.env`)](https://github.com/bkeepers/dotenv) file format,
and expands the `environment:url` value with variables defined in the `.env` file.
To use this feature, specify the
[`artifacts:reports:dotenv`](../yaml/artifacts_reports.md#artifactsreportsdotenv) keyword in `.gitlab-ci.yml`.
You can also specify a static part of the URL at `environment:url`, such as
`https://$DYNAMIC_ENVIRONMENT_URL`. If the value of `DYNAMIC_ENVIRONMENT_URL` is `example.com`, the
final result is `https://example.com`.
The assigned URL for the `review/your-branch-name` environment is visible in the UI.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [Set dynamic URLs after a job finished](https://youtu.be/70jDXtOf4Ig).
In the following example a review app creates a new environment for each merge request:
- The `review` job is triggered by every push, and creates or updates an environment named
`review/your-branch-name`. The environment URL is set to `$DYNAMIC_ENVIRONMENT_URL`.
- When the `review` job finishes, GitLab updates the `review/your-branch-name` environment's URL.
It parses the `deploy.env` report artifact, registers a list of variables as runtime-created,
expands the `environment:url: $DYNAMIC_ENVIRONMENT_URL` and sets it to the environment
URL.
```yaml
review:
script:
- DYNAMIC_ENVIRONMENT_URL=$(deploy-script) # In script, get the environment URL.
- echo "DYNAMIC_ENVIRONMENT_URL=$DYNAMIC_ENVIRONMENT_URL" >> deploy.env # Add the value to a dotenv file.
artifacts:
reports:
dotenv: deploy.env # Report back dotenv file to rails.
environment:
name: review/$CI_COMMIT_REF_SLUG
url: $DYNAMIC_ENVIRONMENT_URL # and set the variable produced in script to `environment:url`
on_stop: stop_review
stop_review:
script:
- ./teardown-environment
when: manual
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
```
Note the following:
- `stop_review` doesn't generate a dotenv report artifact, so it doesn't recognize the
`DYNAMIC_ENVIRONMENT_URL` environment variable. Therefore you shouldn't set `environment:url` in the
`stop_review` job.
- If the environment URL isn't valid (for example, the URL is malformed), the system doesn't update
the environment URL.
- If the script that runs in `stop_review` exists only in your repository and therefore can't use
`GIT_STRATEGY: none` or `GIT_STRATEGY: empty`, configure [merge request pipelines](../pipelines/merge_request_pipelines.md)
for these jobs. This ensures that runners can fetch the repository even after a feature branch is
deleted. For more information, see [Ref Specs for Runners](../pipelines/_index.md#ref-specs-for-runners).
{{< alert type="note" >}}
For Windows runners, you should use the PowerShell `Add-Content` command to write to `.env` files.
{{< /alert >}}
```powershell
Add-Content -Path deploy.env -Value "DYNAMIC_ENVIRONMENT_URL=$DYNAMIC_ENVIRONMENT_URL"
```
## Deployment tier of environments
Sometimes, instead of using an [industry standard](https://en.wikipedia.org/wiki/Deployment_environment)
environment name, like `production`, you might want to use a code name, like `customer-portal`.
While there is no technical reason not to use a name like `customer-portal`, the name
no longer indicates that the environment is used for production. This can affect how metrics
like [deployment frequency](../../user/analytics/dora_metrics.md#how-deployment-frequency-is-calculated)
are calculated.
To indicate that a specific environment is for a specific use,
you can use tiers:
| Environment tier | Environment name examples |
|------------------|---------------------------|
| `production` | Production, Live |
| `staging` | Staging, Model, Demo |
| `testing` | Test, QC |
| `development` | Dev, [Review apps](../review_apps/_index.md), Trunk |
| `other` | |
By default, GitLab assumes a tier based on [the environment name](../yaml/_index.md#environmentname).
You cannot set an environment tier using the UI.
Instead, you can use the [`deployment_tier` keyword](../yaml/_index.md#environmentdeployment_tier) to specify a tier.
### Rename an environment
{{< history >}}
- Renaming an environment by using the API was [deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/338897) in GitLab 15.9.
- Renaming an environment with the API [removed](https://gitlab.com/gitlab-org/gitlab/-/issues/338897) in GitLab 16.0.
{{< /history >}}
You cannot rename an environment.
To achieve the same result as renaming an environment:
1. [Stop the existing environment](#stop-an-environment-by-using-the-ui).
1. [Delete the existing environment](#delete-an-environment).
1. [Create a new environment](#create-a-static-environment) with the desired name.
## CI/CD variables
To customize your environments and deployments, you can use any of the
[predefined CI/CD variables](../variables/predefined_variables.md),
and define custom CI/CD variables.
### Limit the environment scope of a CI/CD variable
By default, all [CI/CD variables](../variables/_index.md) are available to all jobs in a pipeline.
If a test tool in a job becomes compromised, the tool could attempt to retrieve all
CI/CD variables available to the job. To help mitigate this kind of supply chain attack,
you should limit the environment scope of sensitive variables to only the jobs that require them.
Limit the environment scope of a CI/CD variable by defining which environments it
can be available for. The default environment scope is the `*` wildcard, so any job
can access the variable.
You can use specific matching to select a particular environment. For example, set
the variable's environment scope to `production` to only allow jobs with an [environment](../yaml/_index.md#environment)
of `production` to access the variable.
You can also use wildcard matching (`*`) to select a particular environment group,
like all [review apps](../review_apps/_index.md) with `review/*`.
For example, with these four environments:
- `production`
- `staging`
- `review/feature-1`
- `review/feature-2`
These environment scopes match as follows:
| ↓ Scope / Environment → | `production` | `staging` | `review/feature-1` | `review/feature-2` |
|:------------------------|:-------------|:----------|:-------------------|:-------------------|
| `*` | Match | Match | Match | Match |
| `production` | Match | | | |
| `staging` | | Match | | |
| `review/*` | | | Match | Match |
| `review/feature-1` | | | Match | |
You should not use environment-scoped variables with [`rules`](../yaml/_index.md#rules)
or [`include`](../yaml/_index.md#include). The variables might not be defined when
GitLab validates the pipeline configuration at pipeline creation.
## Search environments
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/10754) in GitLab 15.5.
- [Searching environments within a folder](https://gitlab.com/gitlab-org/gitlab/-/issues/373850) was introduced in GitLab 15.7 with [Feature flag `enable_environments_search_within_folder`](https://gitlab.com/gitlab-org/gitlab/-/issues/382108). Enabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/382108) in GitLab 17.4. Feature flag `enable_environments_search_within_folder` removed.
{{< /history >}}
To search environments by name:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. In the search bar, enter your search term.
- The length of your **search term should be 3 or more characters**.
- Matching applies from the beginning of the environment name.
- For example, `devel` matches the environment name `development`, but `elop` does not.
- For environments with a folder name format, matching applies after the base folder name.
- For example when the name is `review/test-app`, search term `test` matches `review/test-app`.
- Also searching with the folder name prefixed like `review/test` matches `review/test-app`.
## Group similar environments
You can group environments into collapsible sections in the UI.
For example, if all of your environments start with the name `review`,
then in the UI, the environments are grouped under that heading:

The following example shows how to start your environment names with `review`.
The `$CI_COMMIT_REF_SLUG` variable is populated with the branch name at runtime:
```yaml
deploy_review:
stage: deploy
script:
- echo "Deploy a review app"
environment:
name: review/$CI_COMMIT_REF_SLUG
```
## Stopping an environment
Stopping an environment means its deployments are not accessible on the target server. You must stop
an environment before it can be deleted.
When using the `on_stop` action to stop an environment, the job runs if it's not [archived](../../administration/settings/continuous_integration.md#archive-pipelines).
### Stop an environment by using the UI
{{< alert type="note" >}}
To trigger an `on_stop` action and manually stop an environment from the
Environments view, the stop and deploy jobs must be in the same
[`resource_group`](../yaml/_index.md#resource_group).
{{< /alert >}}
To stop an environment in the GitLab UI:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Next to the environment you want to stop, select **Stop**.
1. On the confirmation dialog, select **Stop environment**.
### Default stopping behavior
GitLab automatically stops environments when the associated branch is deleted or merged.
This behavior persists even if no explicit `on_stop` CI/CD job is defined.
However, [issue 428625](https://gitlab.com/gitlab-org/gitlab/-/issues/428625) proposes to change this behavior
so that production and staging environments stop only if an explicit `on_stop` CI/CD job is defined.
You can configure an environment's stopping behavior with the
[`auto_stop_setting`](../../api/environments.md#update-an-existing-environment)
parameter in the Environments API.
### Stop an environment when a branch is deleted
You can configure environments to stop when a branch is deleted.
In the following example, a `deploy_review` job calls a `stop_review` job to clean up and stop the
environment.
- Both jobs must have the same [`rules`](../yaml/_index.md#rules)
or [`only/except`](../yaml/deprecated_keywords.md#only--except) configuration. Otherwise,
the `stop_review` job might not be included in all pipelines that include the
`deploy_review` job, and you cannot trigger `action: stop` to stop the environment automatically.
- The job with [`action: stop` might not run](#the-job-with-action-stop-doesnt-run)
if it's in a later stage than the job that started the environment.
- If you can't use [merge request pipelines](../pipelines/merge_request_pipelines.md),
set [`GIT_STRATEGY`](../runners/configure_runners.md#git-strategy) to `none` or `empty`
in the `stop_review` job. Then, the [runner](https://docs.gitlab.com/runner/) doesn't
try to check out the code after the branch is deleted.
```yaml
deploy_review:
stage: deploy
script:
- echo "Deploy a review app"
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com
on_stop: stop_review
stop_review:
stage: deploy
script:
- echo "Remove review app"
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
when: manual
```
### Stop an environment when a merge request is merged or closed
When you use the [merge request pipelines](../pipelines/merge_request_pipelines.md) configuration,
the `stop` trigger is automatically enabled.
In the following example, the `deploy_review` job calls a `stop_review` job to clean up and stop
the environment.
- When the [**Pipelines must succeed**](../../user/project/merge_requests/auto_merge.md#require-a-successful-pipeline-for-merge) setting is turned on,
you can configure the [`allow_failure: true`](../yaml/_index.md#allow_failure)
keyword on the `stop_review` job to prevent it from
blocking your pipelines and merge requests.
```yaml
deploy_review:
stage: deploy
script:
- echo "Deploy a review app"
environment:
name: review/$CI_COMMIT_REF_SLUG
on_stop: stop_review
rules:
- if: $CI_MERGE_REQUEST_ID
stop_review:
stage: deploy
script:
- echo "Remove review app"
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
rules:
- if: $CI_MERGE_REQUEST_ID
when: manual
```
{{< alert type="note" >}}
When using this functionality together with merge trains, the `stop` job triggers only if [duplicate pipelines are avoided](../jobs/job_rules.md#avoid-duplicate-pipelines).
{{< /alert >}}
### Stop an environment after a certain time period
You can set an environment to stop automatically after a certain time period.
{{< alert type="note" >}}
Due to resource limitations, a background worker for stopping environments runs only once every
hour. This means that environments may not be stopped after the exact time period specified, but are
instead stopped when the background worker detects expired environments.
{{< /alert >}}
In your `.gitlab-ci.yml` file, specify the [`environment:auto_stop_in`](../yaml/_index.md#environmentauto_stop_in)
keyword. Specify the time period in natural language, such as `1 hour and 30 minutes` or `1 day`.
After the time period passes, GitLab automatically triggers a job to stop the environment.
In the following example:
- Each commit on a merge request triggers a `review_app` job that deploys the latest change to the
environment and resets its expiry period.
- If the environment is inactive for more than a week, GitLab automatically triggers the
`stop_review_app` job to stop the environment.
```yaml
review_app:
script: deploy-review-app
environment:
name: review/$CI_COMMIT_REF_SLUG
on_stop: stop_review_app
auto_stop_in: 1 week
rules:
- if: $CI_MERGE_REQUEST_ID
stop_review_app:
script: stop-review-app
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
rules:
- if: $CI_MERGE_REQUEST_ID
when: manual
```
The [`environment:action`](../yaml/_index.md#environmentaction) keyword can be used to reset the time
that an environment is scheduled to stop. For more information, see
[Access an environment for preparation or verification purposes](#access-an-environment-for-preparation-or-verification-purposes).
#### View an environment's scheduled stop date and time
When a environment has been [scheduled to stop after a specified time period](#stop-an-environment-after-a-certain-time-period),
you can view its expiration date and time.
To view an environment's expiration date and time:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the name of the environment.
The expiration date and time is displayed in the upper-left corner, next to the environment's name.
#### Override an environment's scheduled stop date and time
When a environment has been [scheduled to stop after a specified time period](#stop-an-environment-after-a-certain-time-period),
you can override its expiration.
To override an environment's expiration in the UI:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment name.
1. in the upper-right corner, select the thumbtack ({{< icon name="thumbtack" >}}).
To override an environment's expiration in the `.gitlab-ci.yml`:
1. Open the project's `.gitlab-ci.yml`.
1. Update the `auto_stop_in` setting of the corresponding deploy job to `auto_stop_in: never`.
The `auto_stop_in` setting is overridden and the environment remains active until it's stopped
manually.
### Clean up stale environments
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/108616) in GitLab 15.8 [with a flag](../../administration/feature_flags/_index.md) named `stop_stale_environments`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/112098) in GitLab 15.10. Feature flag `stop_stale_environments` removed.
{{< /history >}}
Clean up stale environments when you want to stop old environments in a project.
Prerequisites:
- You must have at least the Maintainer role.
To clean up stale environments:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select **Clean up environments**.
1. Select the date to use for determining which environments to consider stale.
1. Select **Clean up**.
Active environments that haven't been updated after the specified date are stopped.
Protected environments are ignored and not stopped.
### Run a pipeline job when environment is stopped
{{< history >}}
- Feature flag `environment_stop_actions_include_all_finished_deployments` [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/435128) in GitLab 16.9. Disabled by default.
- Feature flag `environment_stop_actions_include_all_finished_deployments` [removed](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/150932) in GitLab 17.0.
{{< /history >}}
You can define a stop job for the environment with an [`on_stop` action](../yaml/_index.md#environmenton_stop) in the environment's deploy job.
The stop jobs of finished deployments in the latest finished pipeline are run when an environment is stopped. A deployment or pipeline is finished if it has the successful, canceled, or failed status.
Prerequisites:
- Both the deploy and stop jobs must have the same rules or only/except configuration.
- The stop job must have the following keywords defined:
- `when`, defined at either:
- [The job level](../yaml/_index.md#when).
- [In a rules clause](../yaml/_index.md#rules). If you use `rules` and `when: manual`, you should
also set [`allow_failure: true`](../yaml/_index.md#allow_failure) so the pipeline can complete
even if the job doesn't run.
- `environment:name`
- `environment:action`
In the following example:
- A `review_app` job calls a `stop_review_app` job after the first job is finished.
- The `stop_review_app` is triggered based on what is defined under `when`. In this
case, it is set to `manual`, so it needs a
[manual action](../jobs/job_control.md#create-a-job-that-must-be-run-manually)
from the GitLab UI to run.
- The `GIT_STRATEGY` is set to `none`. If the `stop_review_app` job is
[automatically triggered](#stopping-an-environment),
the runner doesn't try to check out the code after the branch is deleted.
```yaml
review_app:
stage: deploy
script: make deploy-app
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com
on_stop: stop_review_app
stop_review_app:
stage: deploy
variables:
GIT_STRATEGY: none
script: make delete-app
when: manual
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
```
### Multiple stop actions for an environment
{{< history >}}
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/358911) in GitLab 15.0. [Feature flag `environment_multiple_stop_actions`](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/86685) removed.
{{< /history >}}
To configure multiple **parallel** stop actions on an environment, specify the
[`on_stop`](../yaml/_index.md#environmenton_stop) keyword across multiple
[deployment jobs](../jobs/_index.md#deployment-jobs) for the same `environment`, as defined in the
`.gitlab-ci.yml` file.
When an environment is stopped, the matching `on_stop` actions from only successful deployment jobs are run in parallel, in no particular order.
{{< alert type="note" >}}
All `on_stop` actions for an environment must belong to the same pipeline. To use multiple `on_stop` actions in
[downstream pipelines](../pipelines/downstream_pipelines.md), you must configure the environment actions in
the parent pipeline. For more information, see [downstream pipelines for deployments](../pipelines/downstream_pipelines.md#advanced-example).
{{< /alert >}}
In the following example, for the `test` environment there are two deployment jobs:
- `deploy-to-cloud-a`
- `deploy-to-cloud-b`
When the environment is stopped, the system runs `on_stop` actions `teardown-cloud-a` and
`teardown-cloud-b` in parallel.
```yaml
deploy-to-cloud-a:
script: echo "Deploy to cloud a"
environment:
name: test
on_stop: teardown-cloud-a
deploy-to-cloud-b:
script: echo "Deploy to cloud b"
environment:
name: test
on_stop: teardown-cloud-b
teardown-cloud-a:
script: echo "Delete the resources in cloud a"
environment:
name: test
action: stop
when: manual
teardown-cloud-b:
script: echo "Delete the resources in cloud b"
environment:
name: test
action: stop
when: manual
```
### Stop an environment without running the `on_stop` action
There may be times when you want to stop an environment without running the defined
[`on_stop`](../yaml/_index.md#environmenton_stop) action. For example, you want to delete many
environments without using [compute quota](../pipelines/compute_minutes.md).
To stop an environment without running the defined `on_stop` action, execute the
[Stop an environment API](../../api/environments.md#stop-an-environment) with the parameter
`force=true`.
### Delete an environment
Delete an environment when you want to remove it and all its deployments.
Prerequisites:
- You must have at least the Developer role.
- You must [stop](#stopping-an-environment) the environment before it can be deleted.
To delete an environment:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the **Stopped** tab.
1. Next to the environment you want to delete, select **Delete environment**.
1. On the confirmation dialog, select **Delete environment**.
## Access an environment for preparation or verification purposes
{{< history >}}
- [Updated](https://gitlab.com/gitlab-org/gitlab/-/issues/437133) to reset `auto_stop_in` for `prepare` and `access` actions in GitLab 17.7.
{{< /history >}}
You can define a job that accesses an environment for various purposes, such as verification or preparation. This
effectively bypasses deployment creation, so that you can adjust your CD workflow more accurately.
To do so, add either `action: prepare`, `action: verify`, or `action: access` to the `environment` section of your job:
```yaml
build:
stage: build
script:
- echo "Building the app"
environment:
name: staging
action: prepare
url: https://staging.example.com
```
This gives you access to environment-scoped variables, and can be used to protect builds from unauthorized access. Also,
it's effective to avoid the [prevent outdated deployment jobs](deployment_safety.md#prevent-outdated-deployment-jobs) feature.
If an environment is configured to stop after a certain time period, jobs with the `access` or `prepare`
action will reset the scheduled stop time. The [`environment:auto_stop_in`](../yaml/_index.md#environmentauto_stop_in)
from the most recent successful deployment job to the environment is used when resetting the scheduled time.
For example, if the most recent deployment used `auto_stop_in: 1 week` and is later accessed by a job with
`action: access`, the environment will be rescheduled to stop one week from the completion of the accessing job.
To access an environment without changing the scheduled stop time, use the `verify` action.
## Environment incident management
Production environments can go down unexpectedly, including for reasons outside
of your control. For example, issues with external dependencies, infrastructure,
or human error can cause major issues with an environment. Things like:
- A dependent cloud service goes down.
- A 3rd party library is updated and it's not compatible with your application.
- Someone performs a DDoS attack to a vulnerable endpoint in your server.
- An operator misconfigures infrastructure.
- A bug is introduced into the production application code.
You can use [incident management](../../operations/incident_management/_index.md)
to get alerts when there are critical issues that need immediate attention.
### View the latest alerts for environments
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
If you [set up an alert integration](../../operations/incident_management/integrations.md#configuration),
alerts for environments are shown on the environments page. The alert with the highest
severity is shown, so you can identify which environments need immediate attention.

When the issue that triggered the alert is resolved, it is removed and is no
longer visible on the environments page.
If the alert requires a [rollback](deployments.md#retry-or-roll-back-a-deployment), you can select the
deployment tab from the environment page and select which deployment to roll back to.
### Auto Rollback
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
In a typical Continuous Deployment workflow, the CI pipeline tests every commit before deploying to
production. However, problematic code can still make it to production. For example, inefficient code
that is logically correct can pass tests even though it causes severe performance degradation.
Operators and SREs monitor the system to catch these problems as soon as possible. If they find a
problematic deployment, they can roll back to a previous stable version.
GitLab Auto Rollback eases this workflow by automatically triggering a rollback when a
[critical alert](../../operations/incident_management/alerts.md)
is detected.
For GitLab to select the appropriate environment for the rollback, the alert should contain a `gitlab_environment_name` key with the name of the environment.
GitLab selects and redeploys the most recent successful deployment.
Limitations of GitLab Auto Rollback:
- The rollback is skipped if a deployment is running when the alert is detected.
- A rollback can happen only once in three minutes. If multiple alerts are detected at once, only
one rollback is performed.
GitLab Auto Rollback is turned off by default. To turn it on:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Automatic deployment rollbacks**.
1. Select the checkbox for **Enable automatic rollbacks**.
1. Select **Save changes**.
## Environment permissions
Depending on your role, you can interact with environments in public
and private projects.
### View environments
- In public projects, anyone can view a list of environments, including non-members.
- In private projects, you must have at least the Reporter role to view a list of environments.
### Create and update environments
- You must have at least the Developer role to create a new environment, or update an existing unprotected environment.
- If an existing environment is protected and you don't have access to it, you cannot update the environment.
### Stop and delete environments
- You must have at least the Developer role to stop or delete an unprotected environment.
- If an environment is protected and you don't have access to it, you cannot stop or delete the environment.
### Run deployment jobs in protected environments
If you can push or merge to the protected branch:
- You must have at least the Reporter role.
If you can't push to the protected branch:
- You must be a part of a group with the Reporter role.
See [Deployment-only access to protected environments](protected_environments.md#deployment-only-access-to-protected-environments).
## Web terminals (deprecated)
{{< alert type="warning" >}}
This feature was [deprecated](https://gitlab.com/groups/gitlab-org/configure/-/epics/8) in GitLab 14.5.
{{< /alert >}}
If you deploy to your environments with the help of a deployment service (for example,
the [Kubernetes integration](../../user/infrastructure/clusters/_index.md)), GitLab can open
a terminal session to your environment. You can then debug issues without leaving your web browser.
The Web terminal is a container-based deployment, which often lacks basic tools (like an editor),
and can be stopped or restarted at any time. If this happens, you lose all your
changes. Treat the Web terminal as a debugging tool, not a comprehensive online IDE.
Web terminals:
- Are available to project Maintainers and Owners only.
- Must [be enabled](../../administration/integration/terminal.md).
In the UI, to view the Web terminal, either:
- From the **Actions** menu, select **Terminal**:

- On the page for a specific environment, on the right, select **Terminal** ({{< icon name="terminal">}}).
Select the button to establish the terminal session.
It works like any other terminal. You're in the container created
by your deployment so you can:
- Run shell commands and get responses in real time.
- Check the logs.
- Try out configuration or code tweaks.
You can open multiple terminals to the same environment. They each get their own shell
session and even a multiplexer like `screen` or `tmux`.
## Related topics
- [Dashboard for Kubernetes](kubernetes_dashboard.md)
- [Deployments](deployments.md)
- [Protected environments](protected_environments.md)
- [Environments Dashboard](environments_dashboard.md)
- [Deployment safety](deployment_safety.md#restrict-write-access-to-a-critical-environment)
## Troubleshooting
### The job with `action: stop` doesn't run
In some cases, environments do not stop despite an `on_stop` job being configured. This happens when the job
with the `action: stop` is not in a runnable state due to its `stages:` or `needs:` configuration.
For example:
- The environment might start in a stage that also has a job that failed.
Then the jobs in later stages job don't start. If the job with the `action: stop`
for the environment is also in a later stage, it can't start and the environment isn't deleted.
- The job with the `action: stop` might have a dependency on a job that has not yet completed.
To ensure the `action: stop` can always run when needed, you can:
- Put both jobs in the same stage:
```yaml
stages:
- build
- test
- deploy
...
deploy_review:
stage: deploy
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com
on_stop: stop_review
stop_review:
stage: deploy
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
when: manual
```
- Add a [`needs`](../yaml/_index.md#needs) entry to the `action: stop` job so the
job can start out of stage order:
```yaml
stages:
- build
- test
- deploy
- cleanup
...
deploy_review:
stage: deploy
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com
on_stop: stop_review
stop_review:
stage: cleanup
needs:
- deploy_review
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
when: manual
```
### Error: job would create an environment with an invalid parameter
If your project is configured to [create a dynamic environment](#create-a-dynamic-environment),
you might encounter this error in a deployment job because the dynamically generated parameter can't be used for creating an environment:
```plaintext
This job could not be executed because it would create an environment with an invalid parameter.
```
For example, your project has the following `.gitlab-ci.yml`:
```yaml
deploy:
script: echo
environment: production/$ENVIRONMENT
```
Because the `$ENVIRONMENT` variable does not exist in the pipeline, GitLab tries to
create an environment with a name `production/`, which is invalid in
[the environment name constraint](../yaml/_index.md#environmentname).
To fix this, use one of the following solutions:
- Remove `environment` keyword from the deployment job. GitLab has already been
ignoring the invalid keyword, therefore your deployment pipelines stay intact
even after the keyword removal.
- Ensure the variable exists in the pipeline. Review the
[limitation on supported variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
#### If you get this error on review apps
For example, if you have the following in your `.gitlab-ci.yml`:
```yaml
review:
script: deploy review app
environment: review/$CI_COMMIT_REF_NAME
```
When you create a new merge request with a branch name `bug-fix!`,
the `review` job tries to create an environment with `review/bug-fix!`.
However, the `!` is an invalid character for environments, so the
deployment job fails because it was about to run without an environment.
To fix this, use one of the following solutions:
- Re-create your feature branch without the invalid characters,
such as `bug-fix`.
- Replace the `CI_COMMIT_REF_NAME`
[predefined variable](../variables/predefined_variables.md) with
`CI_COMMIT_REF_SLUG` which strips any invalid characters:
```yaml
review:
script: deploy review app
environment: review/$CI_COMMIT_REF_SLUG
```
|
---
stage: Deploy
group: Environments
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Environments
description: Environments, variables, dashboards, and review apps.
breadcrumbs:
- doc
- ci
- environments
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
A GitLab environment represents a specific deployment target for your application, like development, staging, or production. Use it to manage different configurations and deploy code during various stages of your software lifecycle.
With environments, you:
- Keep your deployment process consistent and repeatable
- Track what code is deployed where
- Roll back to previous versions when problems occur
- Protect sensitive environments from unauthorized changes
- Control deployment variables per environment to maintain security boundaries
- Monitor environment health and get alerts if something goes wrong
## View environments and deployments
Prerequisites:
- In a private project, you must have at least the Reporter role. See [Environment permissions](#environment-permissions).
There are a few ways to view a list of environments for a given project:
- On the project's overview page, if at least one environment is available (that is, not stopped).

- On the left sidebar, select **Operate > Environments**.
The environments are displayed.

- To view a list of deployments for an environment, select the environment name,
for example, `staging`.

Deployments show up in this list only after a deployment job has created them.
- To view a list of all manual jobs in a deployment pipeline, select the **Run** ({{< icon name="play" >}}) dropdown list.

### Environment URL
{{< history >}}
- [Changed](https://gitlab.com/gitlab-org/gitlab/-/issues/337417) to persist arbitrary URLs in GitLab 15.2 [with a flag](../../administration/feature_flags/_index.md) named `soft_validation_on_external_url`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/337417) in GitLab 15.3. [Feature flag `soft_validation_on_external_url`](https://gitlab.com/gitlab-org/gitlab/-/issues/367206) removed.
{{< /history >}}
The [environment URL](../yaml/_index.md#environmenturl) is displayed in a few
places in GitLab:
- In a merge request as a link:

- In the Environments view as a button:

- In the Deployments view as a button:

You can see this information in a merge request if:
- The merge request is eventually merged to the default branch (usually `main`).
- That branch also deploys to an environment (for example, `staging` or `production`).
For example:

#### Go from source files to public pages
With GitLab [Route Maps](../review_apps/_index.md#route-maps), you can go directly
from source files to public pages in the environment set for review apps.
## Types of environments
An environment is either static or dynamic.
Static environments:
- Are usually reused by successive deployments.
- Have static names. For example, `staging` or `production`.
- Are created manually or as part of a CI/CD pipeline.
Dynamic environments:
- Are usually created in a CI/CD pipeline and are used by only a single deployment, then either stopped or deleted.
- Have dynamic names, usually based on the value of a CI/CD variable.
- Are a feature of [review apps](../review_apps/_index.md).
An environment has one of three states, depending on whether its [stop job](../yaml/_index.md#environmenton_stop) has run:
- `available`: The environment exists. There might be a deployment.
- `stopping`: The _on stop job_ has started. This state does not apply when there is no on stop job defined.
- `stopped`: Either the _on stop job_ has run, or a user manually stopped the job.
## Create a static environment
You can create a static environment in the UI or in your `.gitlab-ci.yml` file.
### In the UI
Prerequisites:
- You must have at least the Developer role.
To create a static environment in the UI:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select **Create an environment**.
1. Complete the fields.
1. Select **Save**.
### In your `.gitlab-ci.yml` file
Prerequisites:
- You must have at least the Developer role.
To create a static environment, in your `.gitlab-ci.yml` file:
1. Define a job in the `deploy` stage.
1. In the job, define the environment `name` and `url`. If an
environment of that name doesn't exist when the pipeline runs, it is created.
{{< alert type="note" >}}
Some characters cannot be used in environment names. For more information about the
`environment` keywords, see the [`.gitlab-ci.yml` keyword reference](../yaml/_index.md#environment).
{{< /alert >}}
For example, to create an environment named `staging`, with URL `https://staging.example.com`:
```yaml
deploy_staging:
stage: deploy
script:
- echo "Deploy to staging server"
environment:
name: staging
url: https://staging.example.com
```
## Create a dynamic environment
To create a dynamic environment, you use [CI/CD variables](#cicd-variables) that are
unique to each pipeline.
Prerequisites:
- You must have at least the Developer role.
To create a dynamic environment, in your `.gitlab-ci.yml` file:
1. Define a job in the `deploy` stage.
1. In the job, define the following environment attributes:
- `name`: Use a related CI/CD variable like `$CI_COMMIT_REF_SLUG`. Optionally, add a static
prefix to the environment's name, which [groups in the UI](#group-similar-environments) all
environments with the same prefix.
- `url`: Optional. Prefix the hostname with a related CI/CD variable like `$CI_ENVIRONMENT_SLUG`.
{{< alert type="note" >}}
Some characters cannot be used in environment names. For more information about the
`environment` keywords, see the [`.gitlab-ci.yml` keyword reference](../yaml/_index.md#environment).
{{< /alert >}}
In the following example, every time the `deploy_review_app` job runs the environment's name and
URL are defined using unique values.
```yaml
deploy_review_app:
stage: deploy
script: make deploy
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: never
- if: $CI_COMMIT_BRANCH
```
### Set a dynamic environment URL
Some external hosting platforms generate a random URL for each deployment, for example:
`https://94dd65b.amazonaws.com/qa-lambda-1234567`. That makes it difficult to reference the URL in
the `.gitlab-ci.yml` file.
To address this problem, you can configure a deployment job to report back a set of
variables. These variables include the URL that was dynamically generated by the external service.
GitLab supports the [dotenv (`.env`)](https://github.com/bkeepers/dotenv) file format,
and expands the `environment:url` value with variables defined in the `.env` file.
To use this feature, specify the
[`artifacts:reports:dotenv`](../yaml/artifacts_reports.md#artifactsreportsdotenv) keyword in `.gitlab-ci.yml`.
You can also specify a static part of the URL at `environment:url`, such as
`https://$DYNAMIC_ENVIRONMENT_URL`. If the value of `DYNAMIC_ENVIRONMENT_URL` is `example.com`, the
final result is `https://example.com`.
The assigned URL for the `review/your-branch-name` environment is visible in the UI.
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [Set dynamic URLs after a job finished](https://youtu.be/70jDXtOf4Ig).
In the following example a review app creates a new environment for each merge request:
- The `review` job is triggered by every push, and creates or updates an environment named
`review/your-branch-name`. The environment URL is set to `$DYNAMIC_ENVIRONMENT_URL`.
- When the `review` job finishes, GitLab updates the `review/your-branch-name` environment's URL.
It parses the `deploy.env` report artifact, registers a list of variables as runtime-created,
expands the `environment:url: $DYNAMIC_ENVIRONMENT_URL` and sets it to the environment
URL.
```yaml
review:
script:
- DYNAMIC_ENVIRONMENT_URL=$(deploy-script) # In script, get the environment URL.
- echo "DYNAMIC_ENVIRONMENT_URL=$DYNAMIC_ENVIRONMENT_URL" >> deploy.env # Add the value to a dotenv file.
artifacts:
reports:
dotenv: deploy.env # Report back dotenv file to rails.
environment:
name: review/$CI_COMMIT_REF_SLUG
url: $DYNAMIC_ENVIRONMENT_URL # and set the variable produced in script to `environment:url`
on_stop: stop_review
stop_review:
script:
- ./teardown-environment
when: manual
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
```
Note the following:
- `stop_review` doesn't generate a dotenv report artifact, so it doesn't recognize the
`DYNAMIC_ENVIRONMENT_URL` environment variable. Therefore you shouldn't set `environment:url` in the
`stop_review` job.
- If the environment URL isn't valid (for example, the URL is malformed), the system doesn't update
the environment URL.
- If the script that runs in `stop_review` exists only in your repository and therefore can't use
`GIT_STRATEGY: none` or `GIT_STRATEGY: empty`, configure [merge request pipelines](../pipelines/merge_request_pipelines.md)
for these jobs. This ensures that runners can fetch the repository even after a feature branch is
deleted. For more information, see [Ref Specs for Runners](../pipelines/_index.md#ref-specs-for-runners).
{{< alert type="note" >}}
For Windows runners, you should use the PowerShell `Add-Content` command to write to `.env` files.
{{< /alert >}}
```powershell
Add-Content -Path deploy.env -Value "DYNAMIC_ENVIRONMENT_URL=$DYNAMIC_ENVIRONMENT_URL"
```
## Deployment tier of environments
Sometimes, instead of using an [industry standard](https://en.wikipedia.org/wiki/Deployment_environment)
environment name, like `production`, you might want to use a code name, like `customer-portal`.
While there is no technical reason not to use a name like `customer-portal`, the name
no longer indicates that the environment is used for production. This can affect how metrics
like [deployment frequency](../../user/analytics/dora_metrics.md#how-deployment-frequency-is-calculated)
are calculated.
To indicate that a specific environment is for a specific use,
you can use tiers:
| Environment tier | Environment name examples |
|------------------|---------------------------|
| `production` | Production, Live |
| `staging` | Staging, Model, Demo |
| `testing` | Test, QC |
| `development` | Dev, [Review apps](../review_apps/_index.md), Trunk |
| `other` | |
By default, GitLab assumes a tier based on [the environment name](../yaml/_index.md#environmentname).
You cannot set an environment tier using the UI.
Instead, you can use the [`deployment_tier` keyword](../yaml/_index.md#environmentdeployment_tier) to specify a tier.
### Rename an environment
{{< history >}}
- Renaming an environment by using the API was [deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/338897) in GitLab 15.9.
- Renaming an environment with the API [removed](https://gitlab.com/gitlab-org/gitlab/-/issues/338897) in GitLab 16.0.
{{< /history >}}
You cannot rename an environment.
To achieve the same result as renaming an environment:
1. [Stop the existing environment](#stop-an-environment-by-using-the-ui).
1. [Delete the existing environment](#delete-an-environment).
1. [Create a new environment](#create-a-static-environment) with the desired name.
## CI/CD variables
To customize your environments and deployments, you can use any of the
[predefined CI/CD variables](../variables/predefined_variables.md),
and define custom CI/CD variables.
### Limit the environment scope of a CI/CD variable
By default, all [CI/CD variables](../variables/_index.md) are available to all jobs in a pipeline.
If a test tool in a job becomes compromised, the tool could attempt to retrieve all
CI/CD variables available to the job. To help mitigate this kind of supply chain attack,
you should limit the environment scope of sensitive variables to only the jobs that require them.
Limit the environment scope of a CI/CD variable by defining which environments it
can be available for. The default environment scope is the `*` wildcard, so any job
can access the variable.
You can use specific matching to select a particular environment. For example, set
the variable's environment scope to `production` to only allow jobs with an [environment](../yaml/_index.md#environment)
of `production` to access the variable.
You can also use wildcard matching (`*`) to select a particular environment group,
like all [review apps](../review_apps/_index.md) with `review/*`.
For example, with these four environments:
- `production`
- `staging`
- `review/feature-1`
- `review/feature-2`
These environment scopes match as follows:
| ↓ Scope / Environment → | `production` | `staging` | `review/feature-1` | `review/feature-2` |
|:------------------------|:-------------|:----------|:-------------------|:-------------------|
| `*` | Match | Match | Match | Match |
| `production` | Match | | | |
| `staging` | | Match | | |
| `review/*` | | | Match | Match |
| `review/feature-1` | | | Match | |
You should not use environment-scoped variables with [`rules`](../yaml/_index.md#rules)
or [`include`](../yaml/_index.md#include). The variables might not be defined when
GitLab validates the pipeline configuration at pipeline creation.
## Search environments
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/10754) in GitLab 15.5.
- [Searching environments within a folder](https://gitlab.com/gitlab-org/gitlab/-/issues/373850) was introduced in GitLab 15.7 with [Feature flag `enable_environments_search_within_folder`](https://gitlab.com/gitlab-org/gitlab/-/issues/382108). Enabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/382108) in GitLab 17.4. Feature flag `enable_environments_search_within_folder` removed.
{{< /history >}}
To search environments by name:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. In the search bar, enter your search term.
- The length of your **search term should be 3 or more characters**.
- Matching applies from the beginning of the environment name.
- For example, `devel` matches the environment name `development`, but `elop` does not.
- For environments with a folder name format, matching applies after the base folder name.
- For example when the name is `review/test-app`, search term `test` matches `review/test-app`.
- Also searching with the folder name prefixed like `review/test` matches `review/test-app`.
## Group similar environments
You can group environments into collapsible sections in the UI.
For example, if all of your environments start with the name `review`,
then in the UI, the environments are grouped under that heading:

The following example shows how to start your environment names with `review`.
The `$CI_COMMIT_REF_SLUG` variable is populated with the branch name at runtime:
```yaml
deploy_review:
stage: deploy
script:
- echo "Deploy a review app"
environment:
name: review/$CI_COMMIT_REF_SLUG
```
## Stopping an environment
Stopping an environment means its deployments are not accessible on the target server. You must stop
an environment before it can be deleted.
When using the `on_stop` action to stop an environment, the job runs if it's not [archived](../../administration/settings/continuous_integration.md#archive-pipelines).
### Stop an environment by using the UI
{{< alert type="note" >}}
To trigger an `on_stop` action and manually stop an environment from the
Environments view, the stop and deploy jobs must be in the same
[`resource_group`](../yaml/_index.md#resource_group).
{{< /alert >}}
To stop an environment in the GitLab UI:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Next to the environment you want to stop, select **Stop**.
1. On the confirmation dialog, select **Stop environment**.
### Default stopping behavior
GitLab automatically stops environments when the associated branch is deleted or merged.
This behavior persists even if no explicit `on_stop` CI/CD job is defined.
However, [issue 428625](https://gitlab.com/gitlab-org/gitlab/-/issues/428625) proposes to change this behavior
so that production and staging environments stop only if an explicit `on_stop` CI/CD job is defined.
You can configure an environment's stopping behavior with the
[`auto_stop_setting`](../../api/environments.md#update-an-existing-environment)
parameter in the Environments API.
### Stop an environment when a branch is deleted
You can configure environments to stop when a branch is deleted.
In the following example, a `deploy_review` job calls a `stop_review` job to clean up and stop the
environment.
- Both jobs must have the same [`rules`](../yaml/_index.md#rules)
or [`only/except`](../yaml/deprecated_keywords.md#only--except) configuration. Otherwise,
the `stop_review` job might not be included in all pipelines that include the
`deploy_review` job, and you cannot trigger `action: stop` to stop the environment automatically.
- The job with [`action: stop` might not run](#the-job-with-action-stop-doesnt-run)
if it's in a later stage than the job that started the environment.
- If you can't use [merge request pipelines](../pipelines/merge_request_pipelines.md),
set [`GIT_STRATEGY`](../runners/configure_runners.md#git-strategy) to `none` or `empty`
in the `stop_review` job. Then, the [runner](https://docs.gitlab.com/runner/) doesn't
try to check out the code after the branch is deleted.
```yaml
deploy_review:
stage: deploy
script:
- echo "Deploy a review app"
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com
on_stop: stop_review
stop_review:
stage: deploy
script:
- echo "Remove review app"
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
when: manual
```
### Stop an environment when a merge request is merged or closed
When you use the [merge request pipelines](../pipelines/merge_request_pipelines.md) configuration,
the `stop` trigger is automatically enabled.
In the following example, the `deploy_review` job calls a `stop_review` job to clean up and stop
the environment.
- When the [**Pipelines must succeed**](../../user/project/merge_requests/auto_merge.md#require-a-successful-pipeline-for-merge) setting is turned on,
you can configure the [`allow_failure: true`](../yaml/_index.md#allow_failure)
keyword on the `stop_review` job to prevent it from
blocking your pipelines and merge requests.
```yaml
deploy_review:
stage: deploy
script:
- echo "Deploy a review app"
environment:
name: review/$CI_COMMIT_REF_SLUG
on_stop: stop_review
rules:
- if: $CI_MERGE_REQUEST_ID
stop_review:
stage: deploy
script:
- echo "Remove review app"
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
rules:
- if: $CI_MERGE_REQUEST_ID
when: manual
```
{{< alert type="note" >}}
When using this functionality together with merge trains, the `stop` job triggers only if [duplicate pipelines are avoided](../jobs/job_rules.md#avoid-duplicate-pipelines).
{{< /alert >}}
### Stop an environment after a certain time period
You can set an environment to stop automatically after a certain time period.
{{< alert type="note" >}}
Due to resource limitations, a background worker for stopping environments runs only once every
hour. This means that environments may not be stopped after the exact time period specified, but are
instead stopped when the background worker detects expired environments.
{{< /alert >}}
In your `.gitlab-ci.yml` file, specify the [`environment:auto_stop_in`](../yaml/_index.md#environmentauto_stop_in)
keyword. Specify the time period in natural language, such as `1 hour and 30 minutes` or `1 day`.
After the time period passes, GitLab automatically triggers a job to stop the environment.
In the following example:
- Each commit on a merge request triggers a `review_app` job that deploys the latest change to the
environment and resets its expiry period.
- If the environment is inactive for more than a week, GitLab automatically triggers the
`stop_review_app` job to stop the environment.
```yaml
review_app:
script: deploy-review-app
environment:
name: review/$CI_COMMIT_REF_SLUG
on_stop: stop_review_app
auto_stop_in: 1 week
rules:
- if: $CI_MERGE_REQUEST_ID
stop_review_app:
script: stop-review-app
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
rules:
- if: $CI_MERGE_REQUEST_ID
when: manual
```
The [`environment:action`](../yaml/_index.md#environmentaction) keyword can be used to reset the time
that an environment is scheduled to stop. For more information, see
[Access an environment for preparation or verification purposes](#access-an-environment-for-preparation-or-verification-purposes).
#### View an environment's scheduled stop date and time
When a environment has been [scheduled to stop after a specified time period](#stop-an-environment-after-a-certain-time-period),
you can view its expiration date and time.
To view an environment's expiration date and time:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the name of the environment.
The expiration date and time is displayed in the upper-left corner, next to the environment's name.
#### Override an environment's scheduled stop date and time
When a environment has been [scheduled to stop after a specified time period](#stop-an-environment-after-a-certain-time-period),
you can override its expiration.
To override an environment's expiration in the UI:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment name.
1. in the upper-right corner, select the thumbtack ({{< icon name="thumbtack" >}}).
To override an environment's expiration in the `.gitlab-ci.yml`:
1. Open the project's `.gitlab-ci.yml`.
1. Update the `auto_stop_in` setting of the corresponding deploy job to `auto_stop_in: never`.
The `auto_stop_in` setting is overridden and the environment remains active until it's stopped
manually.
### Clean up stale environments
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/108616) in GitLab 15.8 [with a flag](../../administration/feature_flags/_index.md) named `stop_stale_environments`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/112098) in GitLab 15.10. Feature flag `stop_stale_environments` removed.
{{< /history >}}
Clean up stale environments when you want to stop old environments in a project.
Prerequisites:
- You must have at least the Maintainer role.
To clean up stale environments:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select **Clean up environments**.
1. Select the date to use for determining which environments to consider stale.
1. Select **Clean up**.
Active environments that haven't been updated after the specified date are stopped.
Protected environments are ignored and not stopped.
### Run a pipeline job when environment is stopped
{{< history >}}
- Feature flag `environment_stop_actions_include_all_finished_deployments` [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/435128) in GitLab 16.9. Disabled by default.
- Feature flag `environment_stop_actions_include_all_finished_deployments` [removed](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/150932) in GitLab 17.0.
{{< /history >}}
You can define a stop job for the environment with an [`on_stop` action](../yaml/_index.md#environmenton_stop) in the environment's deploy job.
The stop jobs of finished deployments in the latest finished pipeline are run when an environment is stopped. A deployment or pipeline is finished if it has the successful, canceled, or failed status.
Prerequisites:
- Both the deploy and stop jobs must have the same rules or only/except configuration.
- The stop job must have the following keywords defined:
- `when`, defined at either:
- [The job level](../yaml/_index.md#when).
- [In a rules clause](../yaml/_index.md#rules). If you use `rules` and `when: manual`, you should
also set [`allow_failure: true`](../yaml/_index.md#allow_failure) so the pipeline can complete
even if the job doesn't run.
- `environment:name`
- `environment:action`
In the following example:
- A `review_app` job calls a `stop_review_app` job after the first job is finished.
- The `stop_review_app` is triggered based on what is defined under `when`. In this
case, it is set to `manual`, so it needs a
[manual action](../jobs/job_control.md#create-a-job-that-must-be-run-manually)
from the GitLab UI to run.
- The `GIT_STRATEGY` is set to `none`. If the `stop_review_app` job is
[automatically triggered](#stopping-an-environment),
the runner doesn't try to check out the code after the branch is deleted.
```yaml
review_app:
stage: deploy
script: make deploy-app
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com
on_stop: stop_review_app
stop_review_app:
stage: deploy
variables:
GIT_STRATEGY: none
script: make delete-app
when: manual
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
```
### Multiple stop actions for an environment
{{< history >}}
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/358911) in GitLab 15.0. [Feature flag `environment_multiple_stop_actions`](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/86685) removed.
{{< /history >}}
To configure multiple **parallel** stop actions on an environment, specify the
[`on_stop`](../yaml/_index.md#environmenton_stop) keyword across multiple
[deployment jobs](../jobs/_index.md#deployment-jobs) for the same `environment`, as defined in the
`.gitlab-ci.yml` file.
When an environment is stopped, the matching `on_stop` actions from only successful deployment jobs are run in parallel, in no particular order.
{{< alert type="note" >}}
All `on_stop` actions for an environment must belong to the same pipeline. To use multiple `on_stop` actions in
[downstream pipelines](../pipelines/downstream_pipelines.md), you must configure the environment actions in
the parent pipeline. For more information, see [downstream pipelines for deployments](../pipelines/downstream_pipelines.md#advanced-example).
{{< /alert >}}
In the following example, for the `test` environment there are two deployment jobs:
- `deploy-to-cloud-a`
- `deploy-to-cloud-b`
When the environment is stopped, the system runs `on_stop` actions `teardown-cloud-a` and
`teardown-cloud-b` in parallel.
```yaml
deploy-to-cloud-a:
script: echo "Deploy to cloud a"
environment:
name: test
on_stop: teardown-cloud-a
deploy-to-cloud-b:
script: echo "Deploy to cloud b"
environment:
name: test
on_stop: teardown-cloud-b
teardown-cloud-a:
script: echo "Delete the resources in cloud a"
environment:
name: test
action: stop
when: manual
teardown-cloud-b:
script: echo "Delete the resources in cloud b"
environment:
name: test
action: stop
when: manual
```
### Stop an environment without running the `on_stop` action
There may be times when you want to stop an environment without running the defined
[`on_stop`](../yaml/_index.md#environmenton_stop) action. For example, you want to delete many
environments without using [compute quota](../pipelines/compute_minutes.md).
To stop an environment without running the defined `on_stop` action, execute the
[Stop an environment API](../../api/environments.md#stop-an-environment) with the parameter
`force=true`.
### Delete an environment
Delete an environment when you want to remove it and all its deployments.
Prerequisites:
- You must have at least the Developer role.
- You must [stop](#stopping-an-environment) the environment before it can be deleted.
To delete an environment:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the **Stopped** tab.
1. Next to the environment you want to delete, select **Delete environment**.
1. On the confirmation dialog, select **Delete environment**.
## Access an environment for preparation or verification purposes
{{< history >}}
- [Updated](https://gitlab.com/gitlab-org/gitlab/-/issues/437133) to reset `auto_stop_in` for `prepare` and `access` actions in GitLab 17.7.
{{< /history >}}
You can define a job that accesses an environment for various purposes, such as verification or preparation. This
effectively bypasses deployment creation, so that you can adjust your CD workflow more accurately.
To do so, add either `action: prepare`, `action: verify`, or `action: access` to the `environment` section of your job:
```yaml
build:
stage: build
script:
- echo "Building the app"
environment:
name: staging
action: prepare
url: https://staging.example.com
```
This gives you access to environment-scoped variables, and can be used to protect builds from unauthorized access. Also,
it's effective to avoid the [prevent outdated deployment jobs](deployment_safety.md#prevent-outdated-deployment-jobs) feature.
If an environment is configured to stop after a certain time period, jobs with the `access` or `prepare`
action will reset the scheduled stop time. The [`environment:auto_stop_in`](../yaml/_index.md#environmentauto_stop_in)
from the most recent successful deployment job to the environment is used when resetting the scheduled time.
For example, if the most recent deployment used `auto_stop_in: 1 week` and is later accessed by a job with
`action: access`, the environment will be rescheduled to stop one week from the completion of the accessing job.
To access an environment without changing the scheduled stop time, use the `verify` action.
## Environment incident management
Production environments can go down unexpectedly, including for reasons outside
of your control. For example, issues with external dependencies, infrastructure,
or human error can cause major issues with an environment. Things like:
- A dependent cloud service goes down.
- A 3rd party library is updated and it's not compatible with your application.
- Someone performs a DDoS attack to a vulnerable endpoint in your server.
- An operator misconfigures infrastructure.
- A bug is introduced into the production application code.
You can use [incident management](../../operations/incident_management/_index.md)
to get alerts when there are critical issues that need immediate attention.
### View the latest alerts for environments
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
If you [set up an alert integration](../../operations/incident_management/integrations.md#configuration),
alerts for environments are shown on the environments page. The alert with the highest
severity is shown, so you can identify which environments need immediate attention.

When the issue that triggered the alert is resolved, it is removed and is no
longer visible on the environments page.
If the alert requires a [rollback](deployments.md#retry-or-roll-back-a-deployment), you can select the
deployment tab from the environment page and select which deployment to roll back to.
### Auto Rollback
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
In a typical Continuous Deployment workflow, the CI pipeline tests every commit before deploying to
production. However, problematic code can still make it to production. For example, inefficient code
that is logically correct can pass tests even though it causes severe performance degradation.
Operators and SREs monitor the system to catch these problems as soon as possible. If they find a
problematic deployment, they can roll back to a previous stable version.
GitLab Auto Rollback eases this workflow by automatically triggering a rollback when a
[critical alert](../../operations/incident_management/alerts.md)
is detected.
For GitLab to select the appropriate environment for the rollback, the alert should contain a `gitlab_environment_name` key with the name of the environment.
GitLab selects and redeploys the most recent successful deployment.
Limitations of GitLab Auto Rollback:
- The rollback is skipped if a deployment is running when the alert is detected.
- A rollback can happen only once in three minutes. If multiple alerts are detected at once, only
one rollback is performed.
GitLab Auto Rollback is turned off by default. To turn it on:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Automatic deployment rollbacks**.
1. Select the checkbox for **Enable automatic rollbacks**.
1. Select **Save changes**.
## Environment permissions
Depending on your role, you can interact with environments in public
and private projects.
### View environments
- In public projects, anyone can view a list of environments, including non-members.
- In private projects, you must have at least the Reporter role to view a list of environments.
### Create and update environments
- You must have at least the Developer role to create a new environment, or update an existing unprotected environment.
- If an existing environment is protected and you don't have access to it, you cannot update the environment.
### Stop and delete environments
- You must have at least the Developer role to stop or delete an unprotected environment.
- If an environment is protected and you don't have access to it, you cannot stop or delete the environment.
### Run deployment jobs in protected environments
If you can push or merge to the protected branch:
- You must have at least the Reporter role.
If you can't push to the protected branch:
- You must be a part of a group with the Reporter role.
See [Deployment-only access to protected environments](protected_environments.md#deployment-only-access-to-protected-environments).
## Web terminals (deprecated)
{{< alert type="warning" >}}
This feature was [deprecated](https://gitlab.com/groups/gitlab-org/configure/-/epics/8) in GitLab 14.5.
{{< /alert >}}
If you deploy to your environments with the help of a deployment service (for example,
the [Kubernetes integration](../../user/infrastructure/clusters/_index.md)), GitLab can open
a terminal session to your environment. You can then debug issues without leaving your web browser.
The Web terminal is a container-based deployment, which often lacks basic tools (like an editor),
and can be stopped or restarted at any time. If this happens, you lose all your
changes. Treat the Web terminal as a debugging tool, not a comprehensive online IDE.
Web terminals:
- Are available to project Maintainers and Owners only.
- Must [be enabled](../../administration/integration/terminal.md).
In the UI, to view the Web terminal, either:
- From the **Actions** menu, select **Terminal**:

- On the page for a specific environment, on the right, select **Terminal** ({{< icon name="terminal">}}).
Select the button to establish the terminal session.
It works like any other terminal. You're in the container created
by your deployment so you can:
- Run shell commands and get responses in real time.
- Check the logs.
- Try out configuration or code tweaks.
You can open multiple terminals to the same environment. They each get their own shell
session and even a multiplexer like `screen` or `tmux`.
## Related topics
- [Dashboard for Kubernetes](kubernetes_dashboard.md)
- [Deployments](deployments.md)
- [Protected environments](protected_environments.md)
- [Environments Dashboard](environments_dashboard.md)
- [Deployment safety](deployment_safety.md#restrict-write-access-to-a-critical-environment)
## Troubleshooting
### The job with `action: stop` doesn't run
In some cases, environments do not stop despite an `on_stop` job being configured. This happens when the job
with the `action: stop` is not in a runnable state due to its `stages:` or `needs:` configuration.
For example:
- The environment might start in a stage that also has a job that failed.
Then the jobs in later stages job don't start. If the job with the `action: stop`
for the environment is also in a later stage, it can't start and the environment isn't deleted.
- The job with the `action: stop` might have a dependency on a job that has not yet completed.
To ensure the `action: stop` can always run when needed, you can:
- Put both jobs in the same stage:
```yaml
stages:
- build
- test
- deploy
...
deploy_review:
stage: deploy
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com
on_stop: stop_review
stop_review:
stage: deploy
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
when: manual
```
- Add a [`needs`](../yaml/_index.md#needs) entry to the `action: stop` job so the
job can start out of stage order:
```yaml
stages:
- build
- test
- deploy
- cleanup
...
deploy_review:
stage: deploy
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com
on_stop: stop_review
stop_review:
stage: cleanup
needs:
- deploy_review
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
when: manual
```
### Error: job would create an environment with an invalid parameter
If your project is configured to [create a dynamic environment](#create-a-dynamic-environment),
you might encounter this error in a deployment job because the dynamically generated parameter can't be used for creating an environment:
```plaintext
This job could not be executed because it would create an environment with an invalid parameter.
```
For example, your project has the following `.gitlab-ci.yml`:
```yaml
deploy:
script: echo
environment: production/$ENVIRONMENT
```
Because the `$ENVIRONMENT` variable does not exist in the pipeline, GitLab tries to
create an environment with a name `production/`, which is invalid in
[the environment name constraint](../yaml/_index.md#environmentname).
To fix this, use one of the following solutions:
- Remove `environment` keyword from the deployment job. GitLab has already been
ignoring the invalid keyword, therefore your deployment pipelines stay intact
even after the keyword removal.
- Ensure the variable exists in the pipeline. Review the
[limitation on supported variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
#### If you get this error on review apps
For example, if you have the following in your `.gitlab-ci.yml`:
```yaml
review:
script: deploy review app
environment: review/$CI_COMMIT_REF_NAME
```
When you create a new merge request with a branch name `bug-fix!`,
the `review` job tries to create an environment with `review/bug-fix!`.
However, the `!` is an invalid character for environments, so the
deployment job fails because it was about to run without an environment.
To fix this, use one of the following solutions:
- Re-create your feature branch without the invalid characters,
such as `bug-fix`.
- Replace the `CI_COMMIT_REF_NAME`
[predefined variable](../variables/predefined_variables.md) with
`CI_COMMIT_REF_SLUG` which strips any invalid characters:
```yaml
review:
script: deploy review app
environment: review/$CI_COMMIT_REF_SLUG
```
|
https://docs.gitlab.com/ci/deployment_safety
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/deployment_safety.md
|
2025-08-13
|
doc/ci/environments
|
[
"doc",
"ci",
"environments"
] |
deployment_safety.md
|
Deploy
|
Environments
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Deployment safety
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
[Deployment jobs](../jobs/_index.md#deployment-jobs) are a specific kind of CI/CD
job. They can be more sensitive than other jobs in a pipeline,
and might need to be treated with extra care. GitLab has several features
that help maintain deployment security and stability.
You can:
- Set appropriate roles to your project. See [Project members permissions](../../user/permissions.md#project-members-permissions)
for the different user roles GitLab supports and the permissions of each.
- [Restrict write-access to a critical environment](#restrict-write-access-to-a-critical-environment)
- [Prevent deployments during deploy freeze windows](#prevent-deployments-during-deploy-freeze-windows)
- [Protect production secrets](#protect-production-secrets)
- [Separate project for deployments](#separate-project-for-deployments)
If you are using a continuous deployment workflow and want to ensure that concurrent deployments to the same environment do not happen, you should enable the following options:
- [Ensure only one deployment job runs at a time](#ensure-only-one-deployment-job-runs-at-a-time)
- [Prevent outdated deployment jobs](#prevent-outdated-deployment-jobs)
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [How to secure your CD pipelines/workflow](https://www.youtube.com/watch?v=Mq3C1KveDc0).
## Restrict write access to a critical environment
By default, environments can be modified by any team member that has at least the
Developer role.
If you want to restrict write access to a critical environment (for example a `production` environment),
you can set up [protected environments](protected_environments.md).
## Ensure only one deployment job runs at a time
Pipeline jobs in GitLab CI/CD run in parallel, so it's possible that two deployment
jobs in two different pipelines attempt to deploy to the same environment at the same
time. This is not desired behavior as deployments should happen sequentially.
You can ensure only one deployment job runs at a time with the [`resource_group` keyword](../yaml/_index.md#resource_group) in your `.gitlab-ci.yml`.
For example:
```yaml
deploy:
script: deploy-to-prod
resource_group: prod
```
Example of a problematic pipeline flow **before** using the resource group:
1. `deploy` job in Pipeline-A starts running.
1. `deploy` job in Pipeline-B starts running. *This is a concurrent deployment that could cause an unexpected result.*
1. `deploy` job in Pipeline-A finished.
1. `deploy` job in Pipeline-B finished.
The improved pipeline flow **after** using the resource group:
1. `deploy` job in Pipeline-A starts running.
1. `deploy` job in Pipeline-B attempts to start, but waits for the first `deploy` job to finish.
1. `deploy` job in Pipeline-A finishes.
1. `deploy` job in Pipeline-B starts running.
For more information, see [Resource Group documentation](../resource_groups/_index.md).
## Prevent outdated deployment jobs
{{< history >}}
- [Changed](https://gitlab.com/gitlab-org/gitlab/-/issues/363328) in GitLab 15.5 to prevent outdated job runs.
{{< /history >}}
The effective execution order of pipeline jobs can vary from run to run, which
could cause undesired behavior. For example, a [deployment job](../jobs/_index.md#deployment-jobs)
in a newer pipeline could finish before a deployment job in an older pipeline.
This creates a race condition where the older deployment finishes later,
overwriting the "newer" deployment.
You can prevent older deployment jobs from running when a newer deployment
job is started by enabling the [Prevent outdated deployment jobs](../pipelines/settings.md#prevent-outdated-deployment-jobs) feature.
When an older deployment job starts, it fails and is labeled:
- `failed outdated deployment job` in the pipeline view.
- `The deployment job is older than the latest deployment, and therefore failed.`
when viewing the completed job.
When an older deployment job is manual, the **Run** ({{< icon name="play" >}}) button is disabled with a message
`This deployment job does not run automatically and must be started manually, but it's older than the latest deployment, and therefore can't run.`.
Job age is determined by the job start time, not the commit time, so a newer commit
can be prevented in some circumstances.
### Job retries for rollback deployments
{{< history >}}
- Rollback via job retry [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/378359) in GitLab 15.6.
- Job retries for rollback deployments checkbox [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/410427) in GitLab 16.3.
{{< /history >}}
You might need to quickly roll back to a stable, outdated deployment.
By default, pipeline job retries for [deployment rollback](deployments.md#deployment-rollback) are enabled.
To disable pipeline retries, clear the **Allow job retries for rollback deployments** checkbox. You should disable pipeline retries in sensitive projects.
When a rollback is required, you must run a new pipeline with a previous commit.
### Example
Example of a problematic pipeline flow **before** enabling Prevent outdated deployment jobs:
1. Pipeline-A is created on the default branch.
1. Later, Pipeline-B is created on the default branch (with a newer commit SHA).
1. The `deploy` job in Pipeline-B finishes first, and deploys the newer code.
1. The `deploy` job in Pipeline-A finished later, and deploys the older code, **overwriting** the newer (latest) deployment.
The improved pipeline flow **after** enabling Prevent outdated deployment jobs:
1. Pipeline-A is created on the default branch.
1. Later, Pipeline-B is created on the default branch (with a newer SHA).
1. The `deploy` job in Pipeline-B finishes first, and deploys the newer code.
1. The `deploy` job in Pipeline-A fails, so that it doesn't overwrite the deployment from the newer pipeline.
## Prevent deployments during deploy freeze windows
If you want to prevent deployments for a particular period, for example during a planned
vacation period when most employees are out, you can set up a [Deploy Freeze](../../user/project/releases/_index.md#prevent-unintentional-releases-by-setting-a-deploy-freeze).
During a deploy freeze period, no deployment can be executed. This is helpful to
ensure that deployments do not happen unexpectedly.
The next configured deploy freeze is displayed at the top of the
[environment deployments list](_index.md#view-environments-and-deployments)
page.
## Protect production secrets
Production secrets are needed to deploy successfully. For example, when deploying to the cloud,
cloud providers require these secrets to connect to their services. In the project settings, you can
define and protect CI/CD variables for these secrets. [Protected variables](../variables/_index.md#protect-a-cicd-variable)
are only passed to pipelines running on [protected branches](../../user/project/repository/branches/protected.md)
or [protected tags](../../user/project/protected_tags.md).
The other pipelines don't get the protected variable. You can also
[scope variables to specific environments](../variables/where_variables_can_be_used.md#variables-with-an-environment-scope).
We recommend that you use protected variables on protected environments to make sure that the
secrets aren't exposed unintentionally. You can also define production secrets on the
[runner side](../runners/configure_runners.md#prevent-runners-from-revealing-sensitive-information).
This prevents other users with the Maintainer role from reading the secrets and makes sure
that the runner only runs on protected branches.
For more information, see [pipeline security](../pipelines/_index.md#pipeline-security-on-protected-branches).
## Separate project for deployments
All users with the Maintainer role for the project have access to production secrets. If you need to limit the number of users
that can deploy to a production environment, you can create a separate project and configure a new
permission model that isolates the CD permissions from the original project and prevents the
original users with the Maintainer role for the project from accessing the production secret and CD configuration. You can
connect the CD project to your development projects by using [multi-project pipelines](../pipelines/downstream_pipelines.md#multi-project-pipelines).
## Protect `.gitlab-ci.yml` from change
A `.gitlab-ci.yml` may contain rules to deploy an application to the production server. This
deployment usually runs automatically after pushing a merge request. To prevent developers from
changing the `.gitlab-ci.yml`, you can define it in a different repository. The configuration can
reference a file in another project with a completely different set of permissions (similar to
[separating a project for deployments](#separate-project-for-deployments)).
In this scenario, the `.gitlab-ci.yml` is publicly accessible, but can only be edited by users with
appropriate permissions in the other project.
For more information, see [Custom CI/CD configuration path](../pipelines/settings.md#specify-a-custom-cicd-configuration-file).
## Require an approval before deploying
Before promoting a deployment to a production environment, cross-verifying it with a dedicated testing group is an effective way to ensure safety. For more information, see [Deployment Approvals](deployment_approvals.md).
|
---
stage: Deploy
group: Environments
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Deployment safety
breadcrumbs:
- doc
- ci
- environments
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
[Deployment jobs](../jobs/_index.md#deployment-jobs) are a specific kind of CI/CD
job. They can be more sensitive than other jobs in a pipeline,
and might need to be treated with extra care. GitLab has several features
that help maintain deployment security and stability.
You can:
- Set appropriate roles to your project. See [Project members permissions](../../user/permissions.md#project-members-permissions)
for the different user roles GitLab supports and the permissions of each.
- [Restrict write-access to a critical environment](#restrict-write-access-to-a-critical-environment)
- [Prevent deployments during deploy freeze windows](#prevent-deployments-during-deploy-freeze-windows)
- [Protect production secrets](#protect-production-secrets)
- [Separate project for deployments](#separate-project-for-deployments)
If you are using a continuous deployment workflow and want to ensure that concurrent deployments to the same environment do not happen, you should enable the following options:
- [Ensure only one deployment job runs at a time](#ensure-only-one-deployment-job-runs-at-a-time)
- [Prevent outdated deployment jobs](#prevent-outdated-deployment-jobs)
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview, see [How to secure your CD pipelines/workflow](https://www.youtube.com/watch?v=Mq3C1KveDc0).
## Restrict write access to a critical environment
By default, environments can be modified by any team member that has at least the
Developer role.
If you want to restrict write access to a critical environment (for example a `production` environment),
you can set up [protected environments](protected_environments.md).
## Ensure only one deployment job runs at a time
Pipeline jobs in GitLab CI/CD run in parallel, so it's possible that two deployment
jobs in two different pipelines attempt to deploy to the same environment at the same
time. This is not desired behavior as deployments should happen sequentially.
You can ensure only one deployment job runs at a time with the [`resource_group` keyword](../yaml/_index.md#resource_group) in your `.gitlab-ci.yml`.
For example:
```yaml
deploy:
script: deploy-to-prod
resource_group: prod
```
Example of a problematic pipeline flow **before** using the resource group:
1. `deploy` job in Pipeline-A starts running.
1. `deploy` job in Pipeline-B starts running. *This is a concurrent deployment that could cause an unexpected result.*
1. `deploy` job in Pipeline-A finished.
1. `deploy` job in Pipeline-B finished.
The improved pipeline flow **after** using the resource group:
1. `deploy` job in Pipeline-A starts running.
1. `deploy` job in Pipeline-B attempts to start, but waits for the first `deploy` job to finish.
1. `deploy` job in Pipeline-A finishes.
1. `deploy` job in Pipeline-B starts running.
For more information, see [Resource Group documentation](../resource_groups/_index.md).
## Prevent outdated deployment jobs
{{< history >}}
- [Changed](https://gitlab.com/gitlab-org/gitlab/-/issues/363328) in GitLab 15.5 to prevent outdated job runs.
{{< /history >}}
The effective execution order of pipeline jobs can vary from run to run, which
could cause undesired behavior. For example, a [deployment job](../jobs/_index.md#deployment-jobs)
in a newer pipeline could finish before a deployment job in an older pipeline.
This creates a race condition where the older deployment finishes later,
overwriting the "newer" deployment.
You can prevent older deployment jobs from running when a newer deployment
job is started by enabling the [Prevent outdated deployment jobs](../pipelines/settings.md#prevent-outdated-deployment-jobs) feature.
When an older deployment job starts, it fails and is labeled:
- `failed outdated deployment job` in the pipeline view.
- `The deployment job is older than the latest deployment, and therefore failed.`
when viewing the completed job.
When an older deployment job is manual, the **Run** ({{< icon name="play" >}}) button is disabled with a message
`This deployment job does not run automatically and must be started manually, but it's older than the latest deployment, and therefore can't run.`.
Job age is determined by the job start time, not the commit time, so a newer commit
can be prevented in some circumstances.
### Job retries for rollback deployments
{{< history >}}
- Rollback via job retry [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/378359) in GitLab 15.6.
- Job retries for rollback deployments checkbox [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/410427) in GitLab 16.3.
{{< /history >}}
You might need to quickly roll back to a stable, outdated deployment.
By default, pipeline job retries for [deployment rollback](deployments.md#deployment-rollback) are enabled.
To disable pipeline retries, clear the **Allow job retries for rollback deployments** checkbox. You should disable pipeline retries in sensitive projects.
When a rollback is required, you must run a new pipeline with a previous commit.
### Example
Example of a problematic pipeline flow **before** enabling Prevent outdated deployment jobs:
1. Pipeline-A is created on the default branch.
1. Later, Pipeline-B is created on the default branch (with a newer commit SHA).
1. The `deploy` job in Pipeline-B finishes first, and deploys the newer code.
1. The `deploy` job in Pipeline-A finished later, and deploys the older code, **overwriting** the newer (latest) deployment.
The improved pipeline flow **after** enabling Prevent outdated deployment jobs:
1. Pipeline-A is created on the default branch.
1. Later, Pipeline-B is created on the default branch (with a newer SHA).
1. The `deploy` job in Pipeline-B finishes first, and deploys the newer code.
1. The `deploy` job in Pipeline-A fails, so that it doesn't overwrite the deployment from the newer pipeline.
## Prevent deployments during deploy freeze windows
If you want to prevent deployments for a particular period, for example during a planned
vacation period when most employees are out, you can set up a [Deploy Freeze](../../user/project/releases/_index.md#prevent-unintentional-releases-by-setting-a-deploy-freeze).
During a deploy freeze period, no deployment can be executed. This is helpful to
ensure that deployments do not happen unexpectedly.
The next configured deploy freeze is displayed at the top of the
[environment deployments list](_index.md#view-environments-and-deployments)
page.
## Protect production secrets
Production secrets are needed to deploy successfully. For example, when deploying to the cloud,
cloud providers require these secrets to connect to their services. In the project settings, you can
define and protect CI/CD variables for these secrets. [Protected variables](../variables/_index.md#protect-a-cicd-variable)
are only passed to pipelines running on [protected branches](../../user/project/repository/branches/protected.md)
or [protected tags](../../user/project/protected_tags.md).
The other pipelines don't get the protected variable. You can also
[scope variables to specific environments](../variables/where_variables_can_be_used.md#variables-with-an-environment-scope).
We recommend that you use protected variables on protected environments to make sure that the
secrets aren't exposed unintentionally. You can also define production secrets on the
[runner side](../runners/configure_runners.md#prevent-runners-from-revealing-sensitive-information).
This prevents other users with the Maintainer role from reading the secrets and makes sure
that the runner only runs on protected branches.
For more information, see [pipeline security](../pipelines/_index.md#pipeline-security-on-protected-branches).
## Separate project for deployments
All users with the Maintainer role for the project have access to production secrets. If you need to limit the number of users
that can deploy to a production environment, you can create a separate project and configure a new
permission model that isolates the CD permissions from the original project and prevents the
original users with the Maintainer role for the project from accessing the production secret and CD configuration. You can
connect the CD project to your development projects by using [multi-project pipelines](../pipelines/downstream_pipelines.md#multi-project-pipelines).
## Protect `.gitlab-ci.yml` from change
A `.gitlab-ci.yml` may contain rules to deploy an application to the production server. This
deployment usually runs automatically after pushing a merge request. To prevent developers from
changing the `.gitlab-ci.yml`, you can define it in a different repository. The configuration can
reference a file in another project with a completely different set of permissions (similar to
[separating a project for deployments](#separate-project-for-deployments)).
In this scenario, the `.gitlab-ci.yml` is publicly accessible, but can only be edited by users with
appropriate permissions in the other project.
For more information, see [Custom CI/CD configuration path](../pipelines/settings.md#specify-a-custom-cicd-configuration-file).
## Require an approval before deploying
Before promoting a deployment to a production environment, cross-verifying it with a dedicated testing group is an effective way to ensure safety. For more information, see [Deployment Approvals](deployment_approvals.md).
|
https://docs.gitlab.com/ci/environments_dashboard
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/environments_dashboard.md
|
2025-08-13
|
doc/ci/environments
|
[
"doc",
"ci",
"environments"
] |
environments_dashboard.md
|
Deploy
|
Environments
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Environments Dashboard
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
The Environments Dashboard provides a cross-project
environment-based view that lets you see the big picture
of what is going on in each environment. From a single
location, you can track the progress as changes flow
from development to staging, and then to production (or
through any series of custom environment flows you can set up).
With an at-a-glance view of multiple projects, you can instantly
see which pipelines are green and which are red allowing you to
diagnose if there is a block at a particular point, or if there's
a more systemic problem you need to investigate.
1. On the left sidebar, select **Search or go to**.
1. Select **Your work**.
1. Select **Environments**.

The Environments dashboard displays a paginated list of projects that includes
up to three environments per project.
Each project displays its configured environments.
Review apps and other grouped environments are not displayed.
## Adding a project to the dashboard
To add a project to the dashboard:
1. Select **Add projects** in the home screen of the dashboard.
1. Search and add one or more projects using the **Search your projects** field.
1. Select **Add projects**.
Once added, you can see a summary of each project's environment operational
health, including the latest commit, pipeline status, and deployment time.
The Environments and [Operations](../../user/operations_dashboard/_index.md)
dashboards share the same list of projects. When you add or remove a
project from one, GitLab adds or removes the project from the other.
You can add up to 150 projects for GitLab to display on this dashboard.
## Environment dashboards on GitLab.com
GitLab.com users can add public projects to the Environments
Dashboard for free. If your project is private, the group it belongs
to must have a [GitLab Premium](https://about.gitlab.com/pricing/) plan.
|
---
stage: Deploy
group: Environments
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Environments Dashboard
breadcrumbs:
- doc
- ci
- environments
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
The Environments Dashboard provides a cross-project
environment-based view that lets you see the big picture
of what is going on in each environment. From a single
location, you can track the progress as changes flow
from development to staging, and then to production (or
through any series of custom environment flows you can set up).
With an at-a-glance view of multiple projects, you can instantly
see which pipelines are green and which are red allowing you to
diagnose if there is a block at a particular point, or if there's
a more systemic problem you need to investigate.
1. On the left sidebar, select **Search or go to**.
1. Select **Your work**.
1. Select **Environments**.

The Environments dashboard displays a paginated list of projects that includes
up to three environments per project.
Each project displays its configured environments.
Review apps and other grouped environments are not displayed.
## Adding a project to the dashboard
To add a project to the dashboard:
1. Select **Add projects** in the home screen of the dashboard.
1. Search and add one or more projects using the **Search your projects** field.
1. Select **Add projects**.
Once added, you can see a summary of each project's environment operational
health, including the latest commit, pipeline status, and deployment time.
The Environments and [Operations](../../user/operations_dashboard/_index.md)
dashboards share the same list of projects. When you add or remove a
project from one, GitLab adds or removes the project from the other.
You can add up to 150 projects for GitLab to display on this dashboard.
## Environment dashboards on GitLab.com
GitLab.com users can add public projects to the Environments
Dashboard for free. If your project is private, the group it belongs
to must have a [GitLab Premium](https://about.gitlab.com/pricing/) plan.
|
https://docs.gitlab.com/ci/incremental_rollouts
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/incremental_rollouts.md
|
2025-08-13
|
doc/ci/environments
|
[
"doc",
"ci",
"environments"
] |
incremental_rollouts.md
|
Deploy
|
Environments
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Incremental rollouts with GitLab CI/CD
|
Kubernetes, CI/CD, risk mitigation, and deployment.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
When rolling out changes to your application, it is possible to release production changes
to only a portion of your Kubernetes pods as a risk mitigation strategy. By releasing
production changes gradually, error rates or performance degradation can be monitored, and
if there are no problems, all pods can be updated.
GitLab supports both manually triggered and timed rollouts to a Kubernetes production system
using Incremental Rollouts. When using Manual Rollouts, the release of each tranche
of pods is manually triggered, while in Timed Rollouts, the release is performed in
tranches after a default pause of 5 minutes.
Timed rollouts can also be manually triggered before the pause period has expired.
Manual and Timed rollouts are included automatically in projects controlled by
[Auto DevOps](../../topics/autodevops/_index.md), but they are also configurable through
GitLab CI/CD in the `.gitlab-ci.yml` configuration file.
Manually triggered rollouts can be implemented with Continuous Delivery,
while timed rollouts do not require intervention and can be part of your
Continuous Deployment strategy.
You can also combine both of them in a way that the app is deployed automatically
unless you eventually intervene manually if necessary.
We created sample applications to demonstrate the three options, which you can
use as examples to build your own:
- [Manual incremental rollouts](https://gitlab.com/gl-release/incremental-rollout-example/blob/master/.gitlab-ci.yml)
- [Timed incremental rollouts](https://gitlab.com/gl-release/timed-rollout-example/blob/master/.gitlab-ci.yml)
- [Both manual and timed rollouts](https://gitlab.com/gl-release/incremental-timed-rollout-example/blob/master/.gitlab-ci.yml)
## Manual Rollouts
It is possible to configure GitLab to do incremental rollouts manually through `.gitlab-ci.yml`. Manual configuration
allows more control over the this feature. The steps in an incremental rollout depend on the
number of pods that are defined for the deployment, which are configured when the Kubernetes
cluster is created.
For example, if your application has 10 pods and a 10% rollout job runs, the new instance of the
application is deployed to a single pod while the rest of the pods show the previous instance of the application.
First we [define the template as manual](https://gitlab.com/gl-release/incremental-rollout-example/blob/master/.gitlab-ci.yml#L100-103):
```yaml
.manual_rollout_template: &manual_rollout_template
<<: *rollout_template
stage: production
when: manual
```
Then we [define the rollout amount for each step](https://gitlab.com/gl-release/incremental-rollout-example/blob/master/.gitlab-ci.yml#L152-155):
```yaml
rollout 10%:
<<: *manual_rollout_template
variables:
ROLLOUT_PERCENTAGE: 10
```
After the jobs are built, select **Run** ({{< icon name="play" >}}) next to the job's name
to release each stage of pods. You can also rollback by running a lower percentage job. Once 100%
is reached, you cannot roll back using this method. To roll back a deployment, see [retry or roll back a deployment](deployments.md#retry-or-roll-back-a-deployment).
A [deployable application](https://gitlab.com/gl-release/incremental-rollout-example) is
available, demonstrating manually triggered incremental rollouts.
## Timed Rollouts
Timed rollouts behave in the same way as manual rollouts, except that each job is defined with a
delay in minutes before it deploys. Selecting the job reveals the countdown.

It is possible to combine this functionality with manual incremental rollouts so that the job
counts down and then deploys.
First we [define the template as timed](https://gitlab.com/gl-release/timed-rollout-example/blob/master/.gitlab-ci.yml#L86-89):
```yaml
.timed_rollout_template: &timed_rollout_template
<<: *rollout_template
when: delayed
start_in: 1 minutes
```
We can define the delay period using the `start_in` key:
```yaml
start_in: 1 minutes
```
Then we [define the rollout amount for each step](https://gitlab.com/gl-release/timed-rollout-example/blob/master/.gitlab-ci.yml#L97-101):
```yaml
timed rollout 30%:
<<: *timed_rollout_template
stage: timed rollout 30%
variables:
ROLLOUT_PERCENTAGE: 30
```
A [deployable application](https://gitlab.com/gl-release/timed-rollout-example) is
available, [demonstrating configuration of timed rollouts](https://gitlab.com/gl-release/timed-rollout-example/blob/master/.gitlab-ci.yml#L86-95).
## Blue-Green Deployment
{{< alert type="note" >}}
Teams can leverage an Ingress annotation and [set traffic weight](../../user/project/canary_deployments.md#how-to-change-the-traffic-weight-on-a-canary-ingress-deprecated)
as an alternative approach to the blue-green deployment strategy documented here.
{{< /alert >}}
Also sometimes known as A/B deployment or red-black deployment, this technique is used to reduce
downtime and risk during a deployment. When combined with incremental rollouts, you can
minimize the impact of a deployment causing an issue.
With this technique there are two deployments ("blue" and "green", but any naming can be used).
Only one of these deployments is live at any given time, except during an incremental rollout.
For example, your blue deployment can be active on production, while the
green deployment is "live" for testing, but not deployed to production. If issues
are found, the green deployment can be updated without affecting the production
deployment (currently blue). If testing finds no issues, you switch production to the green
deployment, and blue is now available to test the next release.
This process reduces downtime as there is no need to take down the production deployment
to switch to a different deployment. Both deployments are running in parallel, and
can be switched to at any time.
An [example deployable application](https://gitlab.com/gl-release/blue-green-example)
is available, with a [`.gitlab-ci.yml` CI/CD configuration file](https://gitlab.com/gl-release/blue-green-example/blob/master/.gitlab-ci.yml)
that demonstrates blue-green deployments.
|
---
stage: Deploy
group: Environments
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Incremental rollouts with GitLab CI/CD
description: Kubernetes, CI/CD, risk mitigation, and deployment.
breadcrumbs:
- doc
- ci
- environments
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
When rolling out changes to your application, it is possible to release production changes
to only a portion of your Kubernetes pods as a risk mitigation strategy. By releasing
production changes gradually, error rates or performance degradation can be monitored, and
if there are no problems, all pods can be updated.
GitLab supports both manually triggered and timed rollouts to a Kubernetes production system
using Incremental Rollouts. When using Manual Rollouts, the release of each tranche
of pods is manually triggered, while in Timed Rollouts, the release is performed in
tranches after a default pause of 5 minutes.
Timed rollouts can also be manually triggered before the pause period has expired.
Manual and Timed rollouts are included automatically in projects controlled by
[Auto DevOps](../../topics/autodevops/_index.md), but they are also configurable through
GitLab CI/CD in the `.gitlab-ci.yml` configuration file.
Manually triggered rollouts can be implemented with Continuous Delivery,
while timed rollouts do not require intervention and can be part of your
Continuous Deployment strategy.
You can also combine both of them in a way that the app is deployed automatically
unless you eventually intervene manually if necessary.
We created sample applications to demonstrate the three options, which you can
use as examples to build your own:
- [Manual incremental rollouts](https://gitlab.com/gl-release/incremental-rollout-example/blob/master/.gitlab-ci.yml)
- [Timed incremental rollouts](https://gitlab.com/gl-release/timed-rollout-example/blob/master/.gitlab-ci.yml)
- [Both manual and timed rollouts](https://gitlab.com/gl-release/incremental-timed-rollout-example/blob/master/.gitlab-ci.yml)
## Manual Rollouts
It is possible to configure GitLab to do incremental rollouts manually through `.gitlab-ci.yml`. Manual configuration
allows more control over the this feature. The steps in an incremental rollout depend on the
number of pods that are defined for the deployment, which are configured when the Kubernetes
cluster is created.
For example, if your application has 10 pods and a 10% rollout job runs, the new instance of the
application is deployed to a single pod while the rest of the pods show the previous instance of the application.
First we [define the template as manual](https://gitlab.com/gl-release/incremental-rollout-example/blob/master/.gitlab-ci.yml#L100-103):
```yaml
.manual_rollout_template: &manual_rollout_template
<<: *rollout_template
stage: production
when: manual
```
Then we [define the rollout amount for each step](https://gitlab.com/gl-release/incremental-rollout-example/blob/master/.gitlab-ci.yml#L152-155):
```yaml
rollout 10%:
<<: *manual_rollout_template
variables:
ROLLOUT_PERCENTAGE: 10
```
After the jobs are built, select **Run** ({{< icon name="play" >}}) next to the job's name
to release each stage of pods. You can also rollback by running a lower percentage job. Once 100%
is reached, you cannot roll back using this method. To roll back a deployment, see [retry or roll back a deployment](deployments.md#retry-or-roll-back-a-deployment).
A [deployable application](https://gitlab.com/gl-release/incremental-rollout-example) is
available, demonstrating manually triggered incremental rollouts.
## Timed Rollouts
Timed rollouts behave in the same way as manual rollouts, except that each job is defined with a
delay in minutes before it deploys. Selecting the job reveals the countdown.

It is possible to combine this functionality with manual incremental rollouts so that the job
counts down and then deploys.
First we [define the template as timed](https://gitlab.com/gl-release/timed-rollout-example/blob/master/.gitlab-ci.yml#L86-89):
```yaml
.timed_rollout_template: &timed_rollout_template
<<: *rollout_template
when: delayed
start_in: 1 minutes
```
We can define the delay period using the `start_in` key:
```yaml
start_in: 1 minutes
```
Then we [define the rollout amount for each step](https://gitlab.com/gl-release/timed-rollout-example/blob/master/.gitlab-ci.yml#L97-101):
```yaml
timed rollout 30%:
<<: *timed_rollout_template
stage: timed rollout 30%
variables:
ROLLOUT_PERCENTAGE: 30
```
A [deployable application](https://gitlab.com/gl-release/timed-rollout-example) is
available, [demonstrating configuration of timed rollouts](https://gitlab.com/gl-release/timed-rollout-example/blob/master/.gitlab-ci.yml#L86-95).
## Blue-Green Deployment
{{< alert type="note" >}}
Teams can leverage an Ingress annotation and [set traffic weight](../../user/project/canary_deployments.md#how-to-change-the-traffic-weight-on-a-canary-ingress-deprecated)
as an alternative approach to the blue-green deployment strategy documented here.
{{< /alert >}}
Also sometimes known as A/B deployment or red-black deployment, this technique is used to reduce
downtime and risk during a deployment. When combined with incremental rollouts, you can
minimize the impact of a deployment causing an issue.
With this technique there are two deployments ("blue" and "green", but any naming can be used).
Only one of these deployments is live at any given time, except during an incremental rollout.
For example, your blue deployment can be active on production, while the
green deployment is "live" for testing, but not deployed to production. If issues
are found, the green deployment can be updated without affecting the production
deployment (currently blue). If testing finds no issues, you switch production to the green
deployment, and blue is now available to test the next release.
This process reduces downtime as there is no need to take down the production deployment
to switch to a different deployment. Both deployments are running in parallel, and
can be switched to at any time.
An [example deployable application](https://gitlab.com/gl-release/blue-green-example)
is available, with a [`.gitlab-ci.yml` CI/CD configuration file](https://gitlab.com/gl-release/blue-green-example/blob/master/.gitlab-ci.yml)
that demonstrates blue-green deployments.
|
https://docs.gitlab.com/ci/configure_kubernetes_deployments
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/configure_kubernetes_deployments.md
|
2025-08-13
|
doc/ci/environments
|
[
"doc",
"ci",
"environments"
] |
configure_kubernetes_deployments.md
|
Deploy
|
Environments
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Configure Kubernetes deployments (deprecated)
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< alert type="warning" >}}
This feature was [deprecated](https://gitlab.com/groups/gitlab-org/configure/-/epics/8) in GitLab 14.5.
{{< /alert >}}
If you are deploying to a [Kubernetes cluster](../../user/infrastructure/clusters/_index.md)
associated with your project, you can configure these deployments from your
`.gitlab-ci.yml` file.
{{< alert type="note" >}}
Kubernetes configuration isn't supported for Kubernetes clusters
[managed by GitLab](../../user/project/clusters/gitlab_managed_clusters.md).
{{< /alert >}}
The following configuration options are supported:
- [`namespace`](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/)
In the following example, the job deploys your application to the
`production` Kubernetes namespace.
```yaml
deploy:
stage: deploy
script:
- echo "Deploy to production server"
environment:
name: production
url: https://example.com
kubernetes:
namespace: production
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
When you use the GitLab Kubernetes integration to deploy to a Kubernetes cluster,
you can view cluster and namespace information. On the deployment
job page, it's displayed above the job trace:

## Configure incremental rollouts
Learn how to release production changes to only a portion of your Kubernetes pods with
[incremental rollouts](incremental_rollouts.md).
## Related topics
- [Deploy boards (deprecated)](../../user/project/deploy_boards.md)
|
---
stage: Deploy
group: Environments
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Configure Kubernetes deployments (deprecated)
breadcrumbs:
- doc
- ci
- environments
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< alert type="warning" >}}
This feature was [deprecated](https://gitlab.com/groups/gitlab-org/configure/-/epics/8) in GitLab 14.5.
{{< /alert >}}
If you are deploying to a [Kubernetes cluster](../../user/infrastructure/clusters/_index.md)
associated with your project, you can configure these deployments from your
`.gitlab-ci.yml` file.
{{< alert type="note" >}}
Kubernetes configuration isn't supported for Kubernetes clusters
[managed by GitLab](../../user/project/clusters/gitlab_managed_clusters.md).
{{< /alert >}}
The following configuration options are supported:
- [`namespace`](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/)
In the following example, the job deploys your application to the
`production` Kubernetes namespace.
```yaml
deploy:
stage: deploy
script:
- echo "Deploy to production server"
environment:
name: production
url: https://example.com
kubernetes:
namespace: production
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
When you use the GitLab Kubernetes integration to deploy to a Kubernetes cluster,
you can view cluster and namespace information. On the deployment
job page, it's displayed above the job trace:

## Configure incremental rollouts
Learn how to release production changes to only a portion of your Kubernetes pods with
[incremental rollouts](incremental_rollouts.md).
## Related topics
- [Deploy boards (deprecated)](../../user/project/deploy_boards.md)
|
https://docs.gitlab.com/ci/deployment_approvals
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/deployment_approvals.md
|
2025-08-13
|
doc/ci/environments
|
[
"doc",
"ci",
"environments"
] |
deployment_approvals.md
|
Deploy
|
Environments
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Deployment approvals
|
Require approvals prior to deploying to a Protected Environment
|
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can require additional approvals for deployments to protected
environments. Deployments are blocked until all required approvals are
given.
Use deployment approvals to accommodate testing,
security, or compliance processes. For example, you might want to
require approvals for deployments to production environments.
## Configure deployment approvals
You can require approvals for deployments to protected environments in
a project.
Prerequisites:
- To update an environment, you must have at least the Maintainer role.
To configure deployment approvals for a project:
1. Create a deployment job in the `.gitlab-ci.yml` file of your project:
```yaml
stages:
- deploy
production:
stage: deploy
script:
- 'echo "Deploying to ${CI_ENVIRONMENT_NAME}"'
environment:
name: ${CI_JOB_NAME}
action: start
```
The job does not need to be manual (`when: manual`).
1. Add the required [approval rules](#add-multiple-approval-rules).
The environments in your project require approval before deployment.
### Add multiple approval rules
{{< history >}}
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/345678) in GitLab 15.0. [Feature flag `deployment_approval_rules`](https://gitlab.com/gitlab-org/gitlab/-/issues/345678) removed.
- UI configuration [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/378445) in GitLab 15.11.
{{< /history >}}
Add multiple approval rules to control who can approve and execute deployment jobs.
To configure multiple approval rules, use the [CI/CD settings](protected_environments.md#protecting-environments).
You can [also use the API](../../api/group_protected_environments.md#protect-a-single-environment).
All jobs deploying to the environment are blocked and wait for approvals before running.
Make sure the number of required approvals is less than the number of users allowed to deploy.
A user can give only one approval per deployment,
even if the user is a member of multiple approver groups. [Issue 457541](https://gitlab.com/gitlab-org/gitlab/-/issues/457541) proposes to change this behavior so that the same user can give multiple approvals per deployment from different approver groups.
After a deployment job is approved, you must [run the job manually](../jobs/job_control.md#run-a-manual-job).
### Allow self-approval
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/381418) in GitLab 15.8.
- Automatic approval [removed](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/124638) in GitLab 16.2 due to [usability issues](https://gitlab.com/gitlab-org/gitlab/-/issues/391258).
{{< /history >}}
By default, the user who triggers a deployment pipeline can't also approve the deployment job.
A GitLab administrator can approve or reject all deployments.
To allow self-approval of a deployment job:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Protected environments**.
1. From the **Approval options**, select the **Allow pipeline triggerer to approve deployment** checkbox.
## Approve or reject a deployment
In an environment with multiple approval rules, you can:
- Approve a deployment to allow it to proceed.
- Reject a deployment to prevent it.
Prerequisites:
- You have permission to deploy to the protected environment.
To approve or reject a deployment:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment's name.
1. Find the deployment and select its **Status badge**.
1. Optional. Add a comment which describes your reason for approving or rejecting the deployment.
1. Select **Approve** or **Reject**.
You can also [use the API](../../api/deployments.md#approve-or-reject-a-blocked-deployment).
You can give only one approval per deployment, even if you are a member of multiple
approver groups. [Issue 457541](https://gitlab.com/gitlab-org/gitlab/-/issues/457541)
proposes to change this behavior so that the same user can give multiple
approvals per deployment from different approver groups.
The corresponding deployment job does not run automatically after a deployment is approved.
### View the approval details of a deployment
Prerequisites:
- You have permission to deploy to the protected environment.
A deployment to a protected environment can proceed only after all required approvals have been
granted.
To view the approval details of a deployment:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment's name.
1. Find the deployment and select its **Status badge**.
The approval status details are shown:
- Eligible approvers
- Number of approvals granted, and number of approvals required
- Users who have granted approval
- History of approvals or rejections
## View blocked deployments
Review the status of your deployments, including whether a deployment is blocked.
To view your deployments:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment being deployed to.
A deployment with the **blocked** label is blocked.
To view your deployments, you can also [use the API](../../api/deployments.md#get-a-specific-deployment).
The `status` field indicates whether a deployment is blocked.
## Related topics
- [Deployment approvals feature epic](https://gitlab.com/groups/gitlab-org/-/epics/6832)
|
---
stage: Deploy
group: Environments
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Require approvals prior to deploying to a Protected Environment
title: Deployment approvals
breadcrumbs:
- doc
- ci
- environments
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can require additional approvals for deployments to protected
environments. Deployments are blocked until all required approvals are
given.
Use deployment approvals to accommodate testing,
security, or compliance processes. For example, you might want to
require approvals for deployments to production environments.
## Configure deployment approvals
You can require approvals for deployments to protected environments in
a project.
Prerequisites:
- To update an environment, you must have at least the Maintainer role.
To configure deployment approvals for a project:
1. Create a deployment job in the `.gitlab-ci.yml` file of your project:
```yaml
stages:
- deploy
production:
stage: deploy
script:
- 'echo "Deploying to ${CI_ENVIRONMENT_NAME}"'
environment:
name: ${CI_JOB_NAME}
action: start
```
The job does not need to be manual (`when: manual`).
1. Add the required [approval rules](#add-multiple-approval-rules).
The environments in your project require approval before deployment.
### Add multiple approval rules
{{< history >}}
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/345678) in GitLab 15.0. [Feature flag `deployment_approval_rules`](https://gitlab.com/gitlab-org/gitlab/-/issues/345678) removed.
- UI configuration [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/378445) in GitLab 15.11.
{{< /history >}}
Add multiple approval rules to control who can approve and execute deployment jobs.
To configure multiple approval rules, use the [CI/CD settings](protected_environments.md#protecting-environments).
You can [also use the API](../../api/group_protected_environments.md#protect-a-single-environment).
All jobs deploying to the environment are blocked and wait for approvals before running.
Make sure the number of required approvals is less than the number of users allowed to deploy.
A user can give only one approval per deployment,
even if the user is a member of multiple approver groups. [Issue 457541](https://gitlab.com/gitlab-org/gitlab/-/issues/457541) proposes to change this behavior so that the same user can give multiple approvals per deployment from different approver groups.
After a deployment job is approved, you must [run the job manually](../jobs/job_control.md#run-a-manual-job).
### Allow self-approval
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/381418) in GitLab 15.8.
- Automatic approval [removed](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/124638) in GitLab 16.2 due to [usability issues](https://gitlab.com/gitlab-org/gitlab/-/issues/391258).
{{< /history >}}
By default, the user who triggers a deployment pipeline can't also approve the deployment job.
A GitLab administrator can approve or reject all deployments.
To allow self-approval of a deployment job:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Protected environments**.
1. From the **Approval options**, select the **Allow pipeline triggerer to approve deployment** checkbox.
## Approve or reject a deployment
In an environment with multiple approval rules, you can:
- Approve a deployment to allow it to proceed.
- Reject a deployment to prevent it.
Prerequisites:
- You have permission to deploy to the protected environment.
To approve or reject a deployment:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment's name.
1. Find the deployment and select its **Status badge**.
1. Optional. Add a comment which describes your reason for approving or rejecting the deployment.
1. Select **Approve** or **Reject**.
You can also [use the API](../../api/deployments.md#approve-or-reject-a-blocked-deployment).
You can give only one approval per deployment, even if you are a member of multiple
approver groups. [Issue 457541](https://gitlab.com/gitlab-org/gitlab/-/issues/457541)
proposes to change this behavior so that the same user can give multiple
approvals per deployment from different approver groups.
The corresponding deployment job does not run automatically after a deployment is approved.
### View the approval details of a deployment
Prerequisites:
- You have permission to deploy to the protected environment.
A deployment to a protected environment can proceed only after all required approvals have been
granted.
To view the approval details of a deployment:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment's name.
1. Find the deployment and select its **Status badge**.
The approval status details are shown:
- Eligible approvers
- Number of approvals granted, and number of approvals required
- Users who have granted approval
- History of approvals or rejections
## View blocked deployments
Review the status of your deployments, including whether a deployment is blocked.
To view your deployments:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Operate > Environments**.
1. Select the environment being deployed to.
A deployment with the **blocked** label is blocked.
To view your deployments, you can also [use the API](../../api/deployments.md#get-a-specific-deployment).
The `status` field indicates whether a deployment is blocked.
## Related topics
- [Deployment approvals feature epic](https://gitlab.com/groups/gitlab-org/-/epics/6832)
|
https://docs.gitlab.com/ci/external_deployment_tools
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/external_deployment_tools.md
|
2025-08-13
|
doc/ci/environments
|
[
"doc",
"ci",
"environments"
] |
external_deployment_tools.md
|
Deploy
|
Environments
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Track deployments of an external deployment tool
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
While GitLab offers a [built-in deployment solution](_index.md), you might prefer to use an external deployment tool, such as Heroku or ArgoCD.
GitLab can receive deployment events from these external tools and allows you to track the deployments within GitLab.
For example, the following features are available by setting up tracking:
- [See when a merge request has been deployed, and to which environment](../../user/project/merge_requests/widgets.md#post-merge-pipeline-status).
- [Filter merge requests by environment or deployment date](../../user/project/merge_requests/_index.md#by-environment-or-deployment-date).
- [DevOps Research and Assessment (DORA) metrics](../../user/analytics/dora_metrics.md).
- [View environments and deployments](_index.md#view-environments-and-deployments).
- [Track newly included merge requests per deployment](deployments.md#track-newly-included-merge-requests-per-deployment).
{{< alert type="note" >}}
Some of the features are not available because GitLab can't authorize and leverage those external deployments, including
[Protected Environments](protected_environments.md), [Deployment Approvals](deployment_approvals.md), [Deployment safety](deployment_safety.md), and [Deployment rollback](deployments.md#deployment-rollback).
{{< /alert >}}
## How to set up deployment tracking
External deployment tools usually offer a [webhook](https://en.wikipedia.org/wiki/Webhook) to execute an additional API request when deployment state is changed.
You can configure your tool to make a request to the GitLab [Deployment API](../../api/deployments.md). Here is an overview of the event and API request flow:
- When a deployment starts running, [create a deployment with `running` status](../../api/deployments.md#create-a-deployment).
- When a deployment succeeds, [update the deployment status to `success`](../../api/deployments.md#update-a-deployment).
- When a deployment fails, [update the deployment status to `failed`](../../api/deployments.md#update-a-deployment).
{{< alert type="note" >}}
You can create a [project access token](../../user/project/settings/project_access_tokens.md) for the GitLab API authentication.
{{< /alert >}}
### Example: Track deployments of ArgoCD
You can use [ArgoCD webhook](https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/services/webhook/) to send deployment events to GitLab Deployment API.
Here is an example setup that creates a `success` deployment record in GitLab when ArgoCD successfully deploys a new revision:
1. Create a new webhook. You can save the following manifest file and apply it by `kubectl apply -n argocd -f <manifiest-file-path>`:
```yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: argocd-notifications-cm
data:
trigger.on-deployed: |
- description: Application is synced and healthy. Triggered once per commit.
oncePer: app.status.sync.revision
send:
- gitlab-deployment-status
when: app.status.operationState.phase in ['Succeeded'] and app.status.health.status == 'Healthy'
template.gitlab-deployment-status: |
webhook:
gitlab:
method: POST
path: /projects/<your-project-id>/deployments
body: |
{
"status": "success",
"environment": "production",
"sha": "{{.app.status.operationState.operation.sync.revision}}",
"ref": "main",
"tag": "false"
}
service.webhook.gitlab: |
url: https://gitlab.com/api/v4
headers:
- name: PRIVATE-TOKEN
value: <your-access-token>
- name: Content-type
value: application/json
```
1. Create a new subscription in your application:
```shell
kubectl patch app <your-app-name> -n argocd -p '{"metadata": {"annotations": {"notifications.argoproj.io/subscribe.on-deployed.gitlab":""}}}' --type merge
```
{{< alert type="note" >}}
If a deployment wasn't created as expected, you can troubleshoot with [`argocd-notifications` tool](https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/troubleshooting/).
For example, `argocd-notifications template notify gitlab-deployment-status <your-app-name> --recipient gitlab:argocd-notifications`
triggers API request immediately and renders an error message from GitLab API server if any.
{{< /alert >}}
|
---
stage: Deploy
group: Environments
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Track deployments of an external deployment tool
breadcrumbs:
- doc
- ci
- environments
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
While GitLab offers a [built-in deployment solution](_index.md), you might prefer to use an external deployment tool, such as Heroku or ArgoCD.
GitLab can receive deployment events from these external tools and allows you to track the deployments within GitLab.
For example, the following features are available by setting up tracking:
- [See when a merge request has been deployed, and to which environment](../../user/project/merge_requests/widgets.md#post-merge-pipeline-status).
- [Filter merge requests by environment or deployment date](../../user/project/merge_requests/_index.md#by-environment-or-deployment-date).
- [DevOps Research and Assessment (DORA) metrics](../../user/analytics/dora_metrics.md).
- [View environments and deployments](_index.md#view-environments-and-deployments).
- [Track newly included merge requests per deployment](deployments.md#track-newly-included-merge-requests-per-deployment).
{{< alert type="note" >}}
Some of the features are not available because GitLab can't authorize and leverage those external deployments, including
[Protected Environments](protected_environments.md), [Deployment Approvals](deployment_approvals.md), [Deployment safety](deployment_safety.md), and [Deployment rollback](deployments.md#deployment-rollback).
{{< /alert >}}
## How to set up deployment tracking
External deployment tools usually offer a [webhook](https://en.wikipedia.org/wiki/Webhook) to execute an additional API request when deployment state is changed.
You can configure your tool to make a request to the GitLab [Deployment API](../../api/deployments.md). Here is an overview of the event and API request flow:
- When a deployment starts running, [create a deployment with `running` status](../../api/deployments.md#create-a-deployment).
- When a deployment succeeds, [update the deployment status to `success`](../../api/deployments.md#update-a-deployment).
- When a deployment fails, [update the deployment status to `failed`](../../api/deployments.md#update-a-deployment).
{{< alert type="note" >}}
You can create a [project access token](../../user/project/settings/project_access_tokens.md) for the GitLab API authentication.
{{< /alert >}}
### Example: Track deployments of ArgoCD
You can use [ArgoCD webhook](https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/services/webhook/) to send deployment events to GitLab Deployment API.
Here is an example setup that creates a `success` deployment record in GitLab when ArgoCD successfully deploys a new revision:
1. Create a new webhook. You can save the following manifest file and apply it by `kubectl apply -n argocd -f <manifiest-file-path>`:
```yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: argocd-notifications-cm
data:
trigger.on-deployed: |
- description: Application is synced and healthy. Triggered once per commit.
oncePer: app.status.sync.revision
send:
- gitlab-deployment-status
when: app.status.operationState.phase in ['Succeeded'] and app.status.health.status == 'Healthy'
template.gitlab-deployment-status: |
webhook:
gitlab:
method: POST
path: /projects/<your-project-id>/deployments
body: |
{
"status": "success",
"environment": "production",
"sha": "{{.app.status.operationState.operation.sync.revision}}",
"ref": "main",
"tag": "false"
}
service.webhook.gitlab: |
url: https://gitlab.com/api/v4
headers:
- name: PRIVATE-TOKEN
value: <your-access-token>
- name: Content-type
value: application/json
```
1. Create a new subscription in your application:
```shell
kubectl patch app <your-app-name> -n argocd -p '{"metadata": {"annotations": {"notifications.argoproj.io/subscribe.on-deployed.gitlab":""}}}' --type merge
```
{{< alert type="note" >}}
If a deployment wasn't created as expected, you can troubleshoot with [`argocd-notifications` tool](https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/troubleshooting/).
For example, `argocd-notifications template notify gitlab-deployment-status <your-app-name> --recipient gitlab:argocd-notifications`
triggers API request immediately and renders an error message from GitLab API server if any.
{{< /alert >}}
|
https://docs.gitlab.com/ci/protected_environments
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/protected_environments.md
|
2025-08-13
|
doc/ci/environments
|
[
"doc",
"ci",
"environments"
] |
protected_environments.md
|
Deploy
|
Environments
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Protected environments
| null |
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
[Environments](_index.md) can be used for both testing and
production reasons.
Because deploy jobs can be raised by different users with different roles, it's
important to be able to protect specific environments from the effects of
unauthorized users.
By default, a protected environment ensures that only people with the
appropriate privileges can deploy to it, keeping the environment safe.
{{< alert type="note" >}}
GitLab administrators can use all environments, including protected environments.
{{< /alert >}}
To protect, update, or unprotect an environment, you need to have at least the
Maintainer role.
## Protecting environments
Prerequisites:
- When granting the **Allowed to deploy** permission to an approver group, the user configuring the protected environment must be a **direct member** of the approver group to be added. Otherwise, the group or subgroup does not show up in the dropdown list. For more information see [issue #345140](https://gitlab.com/gitlab-org/gitlab/-/issues/345140).
- When granting **Approvers** permissions to an approver group or project, by default only direct members of the approver group or project receive these permissions. To also grant these permissions to inherited members of the approver group or project:
- Select the **Enable group inheritance** checkbox.
- [Use the API](../../api/protected_environments.md#group-inheritance-types).
To protect an environment:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Protected environments**.
1. Select **Protect an environment**.
1. From the **Environment** list, select the environment you want to protect.
1. In the **Allowed to deploy** list, select the role, users, or groups you
want to give deploy access to. Keep in mind that:
- There are two roles to choose from:
- **Maintainers**: Allows access to all of the project's users with the Maintainer role.
- **Developers**: Allows access to all of the project's users with the Maintainer and Developer role.
- You can also select groups that are already [invited](../../user/project/members/sharing_projects_groups.md#invite-a-group-to-a-project) to the project. Invited groups added to the project with the Reporter role appear in the dropdown list for [deployment-only access](#deployment-only-access-to-protected-environments).
- You can also select specific users. The users must have at least the Developer role to appear in
the **Allowed to deploy** list.
1. In the **Approvers** list, select the role, users, or groups you
want to give deploy access to. Keep in mind that:
- There are two roles to choose from:
- **Maintainers**: Allows access to all of the project's users with the Maintainer role.
- **Developers**: Allows access to all of the project's users with the Maintainer and Developer role.
- You can only select groups that are already [invited](../../user/project/members/sharing_projects_groups.md#invite-a-group-to-a-project) to the project.
- Users must have at least the Developer role to appear in
the **Approvers** list.
1. In the **Approval rules** section:
- Ensure that this number is less than or equal to the number of members in
the rule.
- See [Deployment Approvals](deployment_approvals.md) for more information about this feature.
1. Select **Protect**.
The protected environment now appears in the list of protected environments.
### Use the API to protect an environment
Alternatively, you can use the API to protect an environment:
1. Use a project with a CI that creates an environment. For example:
```yaml
stages:
- test
- deploy
test:
stage: test
script:
- 'echo "Testing Application: ${CI_PROJECT_NAME}"'
production:
stage: deploy
when: manual
script:
- 'echo "Deploying to ${CI_ENVIRONMENT_NAME}"'
environment:
name: ${CI_JOB_NAME}
```
1. Use the UI to [create a new group](../../user/group/_index.md#create-a-group).
For example, this group is called `protected-access-group` and has the group ID `9899826`. Note
that the rest of the examples in these steps use this group.

1. Use the API to add a user to the group as a reporter:
```shell
$ curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" \
--data "user_id=3222377&access_level=20" "https://gitlab.com/api/v4/groups/9899826/members"
{"id":3222377,"name":"Sean Carroll","username":"sfcarroll","state":"active","avatar_url":"https://gitlab.com/uploads/-/system/user/avatar/3222377/avatar.png","web_url":"https://gitlab.com/sfcarroll","access_level":20,"created_at":"2020-10-26T17:37:50.309Z","expires_at":null}
```
1. Use the API to add the group to the project as a reporter:
```shell
$ curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" \
--request POST "https://gitlab.com/api/v4/projects/22034114/share?group_id=9899826&group_access=20"
{"id":1233335,"project_id":22034114,"group_id":9899826,"group_access":20,"expires_at":null}
```
1. Use the API to add the group with protected environment access:
```shell
curl --header 'Content-Type: application/json' --request POST --data '{"name": "production", "deploy_access_levels": [{"group_id": 9899826}]}' \
--header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.com/api/v4/projects/22034114/protected_environments"
```
The group now has access and can be seen in the UI.
## Environment access by group membership
A user may be granted access to protected environments as part of [group membership](../../user/group/_index.md). Users
with the Reporter role can only be granted access to protected environments with this
method.
## Deployment branch access
Users with the Developer role can be granted
access to a protected environment through any of these methods:
- As an individual contributor, through a role.
- Through a group membership.
If the user also has push or merge access to the branch deployed on production,
they have the following privileges:
- [Stop an environment](_index.md#stopping-an-environment).
- [Delete an environment](_index.md#delete-an-environment).
- [Create an environment terminal](_index.md#web-terminals-deprecated).
## Deployment-only access to protected environments
Users granted access to a protected environment, but not push or merge access
to the branch deployed to it, are only granted access to deploy the environment.
[Invited groups](../../user/project/members/sharing_projects_groups.md#invite-a-group-to-a-project) added
to the project with [Reporter role](../../user/permissions.md#project-members-permissions), appear in the dropdown list for deployment-only access.
To add deployment-only access:
1. Create a group with members who are granted to access to the protected environment, if it doesn't exist yet.
1. [Invite the group](../../user/project/members/sharing_projects_groups.md#invite-a-group-to-a-project) to the project with the Reporter role.
1. Follow the steps in [Protecting Environments](#protecting-environments).
## Modifying and unprotecting environments
Maintainers can:
- Update existing protected environments at any time by changing the access in the
**Allowed to Deploy** dropdown list.
- Unprotect a protected environment by selecting the **Unprotect** button for that environment.
After an environment is unprotected, all access entries are deleted and must
be re-entered if the environment is re-protected.
After an approval rule is deleted, previously approved deployments do not show who approved the deployment.
Information on who approved a deployment is still available in the [project audit events](../../user/compliance/audit_events.md#project-audit-events).
If a new rule is added, previous deployments show the new rules without the option to approve the deployment. [Issue 506687](https://gitlab.com/gitlab-org/gitlab/-/issues/506687) proposes to show the full approval history of deployments, even if an approval rule is deleted.
For more information, see [Deployment safety](deployment_safety.md).
## Group-level protected environments
Typically, large enterprise organizations have an explicit permission boundary
between [developers and operators](https://about.gitlab.com/topics/devops/).
Developers build and test their code, and operators deploy and monitor the
application. With group-level protected environments, operators can
restrict access to critical environments from developers. Group-level protected environments
extend the [project-level protected environments](#protecting-environments)
to the group-level.
The permissions of deployments can be illustrated in the following table:
| Environment | Developer | Operator | Category |
|-------------|------------|----------|----------|
| Development | Allowed | Allowed | Lower environment |
| Testing | Allowed | Allowed | Lower environment |
| Staging | Disallowed | Allowed | Higher environment |
| Production | Disallowed | Allowed | Higher environment |
_(Reference: [Deployment environments on Wikipedia](https://en.wikipedia.org/wiki/Deployment_environment))_
### Group-level protected environments names
Contrary to project-level protected environments, group-level protected
environments use the [deployment tier](_index.md#deployment-tier-of-environments)
as their name.
A group may consist of many project environments that have unique names.
For example, Project-A has a `gprd` environment and Project-B has a `Production`
environment, so protecting a specific environment name doesn't scale well.
By using deployment tiers, both are recognized as `production` deployment tier
and are protected at the same time.
### Configure group-level memberships
{{< history >}}
- Operators are required to have Owner+ role from the original Maintainer+ role and this role change is introduced from GitLab 15.3 [with a flag](https://gitlab.com/gitlab-org/gitlab/-/issues/369873) named `group_level_protected_environment_settings_permission`. Enabled by default.
- [Feature flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/369873) in GitLab 15.4.
{{< /history >}}
To maximize the effectiveness of group-level protected environments,
[group-level memberships](../../user/group/_index.md) must be correctly
configured:
- Operators should be given the Owner role
for the top-level group. They can maintain CI/CD configurations for
the higher environments (such as production) in the group-level settings page,
which includes group-level protected environments,
[group-level runners](../runners/runners_scope.md#group-runners), and
[group-level clusters](../../user/group/clusters/_index.md). Those
configurations are inherited to the child projects as read-only entries.
This ensures that only operators can configure the organization-wide
deployment ruleset.
- Developers should be given no more than the Developer role
for the top-level group, or explicitly given the Owner role for a child project.
They do not have access to the CI/CD configurations in the
top-level group, so operators can ensure that the critical configuration won't
be accidentally changed by the developers.
- For subgroups and child projects:
- Regarding [subgroups](../../user/group/subgroups/_index.md), if a higher
group has configured the group-level protected environment, the lower groups
cannot override it.
- [Project-level protected environments](#protecting-environments) can be
combined with the group-level setting. If both group-level and project-level
environment configurations exist, to run a deployment job, the user must be allowed in **both**
rulesets.
- In a project or a subgroup of the top-level group, developers can be
safely assigned the Maintainer role to tune their lower environments (such
as `testing`).
Having this configuration in place:
- If a user is about to run a deployment job in a project and allowed to deploy
to the environment, the deployment job proceeds.
- If a user is about to run a deployment job in a project but disallowed to
deploy to the environment, the deployment job fails with an error message.
### Protect critical environments under a group
To protect a group-level environment, make sure your environments have the correct
[`deployment_tier`](_index.md#deployment-tier-of-environments) defined in `.gitlab-ci.yml`.
#### Using the UI
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/325249) in GitLab 15.1.
{{< /history >}}
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings > CI/CD**.
1. Expand **Protected environments**.
1. From the **Environment** list, select the [deployment tier of environments](_index.md#deployment-tier-of-environments) you want to protect.
1. In the **Allowed to deploy** list, select the [subgroups](../../user/group/subgroups/_index.md) you want to give deploy access to.
1. Select **Protect**.
#### Using the API
Configure the group-level protected environments by using the [REST API](../../api/group_protected_environments.md).
## Deployment approvals
Protected environments can also be used to require manual approvals before deployments. See [Deployment approvals](deployment_approvals.md) for more information.
## Troubleshooting
### Reporter can't run a trigger job that deploys to a protected environment in downstream pipeline
A user who has [deployment-only access to protected environments](#deployment-only-access-to-protected-environments) might **not** be able to run a job if it's with a [`trigger`](../yaml/_index.md#trigger) keyword. This is because the job is missing the [`environment`](../yaml/_index.md#environment) keyword definition to associate the job with the protected environment, therefore the job is recognized as a standard job that uses [regular CI/CD permission model](../../user/permissions.md#cicd).
See [this issue](https://gitlab.com/groups/gitlab-org/-/epics/8483) for more information about supporting `environment` keyword with `trigger` keyword.
|
---
stage: Deploy
group: Environments
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Protected environments
breadcrumbs:
- doc
- ci
- environments
---
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
[Environments](_index.md) can be used for both testing and
production reasons.
Because deploy jobs can be raised by different users with different roles, it's
important to be able to protect specific environments from the effects of
unauthorized users.
By default, a protected environment ensures that only people with the
appropriate privileges can deploy to it, keeping the environment safe.
{{< alert type="note" >}}
GitLab administrators can use all environments, including protected environments.
{{< /alert >}}
To protect, update, or unprotect an environment, you need to have at least the
Maintainer role.
## Protecting environments
Prerequisites:
- When granting the **Allowed to deploy** permission to an approver group, the user configuring the protected environment must be a **direct member** of the approver group to be added. Otherwise, the group or subgroup does not show up in the dropdown list. For more information see [issue #345140](https://gitlab.com/gitlab-org/gitlab/-/issues/345140).
- When granting **Approvers** permissions to an approver group or project, by default only direct members of the approver group or project receive these permissions. To also grant these permissions to inherited members of the approver group or project:
- Select the **Enable group inheritance** checkbox.
- [Use the API](../../api/protected_environments.md#group-inheritance-types).
To protect an environment:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Protected environments**.
1. Select **Protect an environment**.
1. From the **Environment** list, select the environment you want to protect.
1. In the **Allowed to deploy** list, select the role, users, or groups you
want to give deploy access to. Keep in mind that:
- There are two roles to choose from:
- **Maintainers**: Allows access to all of the project's users with the Maintainer role.
- **Developers**: Allows access to all of the project's users with the Maintainer and Developer role.
- You can also select groups that are already [invited](../../user/project/members/sharing_projects_groups.md#invite-a-group-to-a-project) to the project. Invited groups added to the project with the Reporter role appear in the dropdown list for [deployment-only access](#deployment-only-access-to-protected-environments).
- You can also select specific users. The users must have at least the Developer role to appear in
the **Allowed to deploy** list.
1. In the **Approvers** list, select the role, users, or groups you
want to give deploy access to. Keep in mind that:
- There are two roles to choose from:
- **Maintainers**: Allows access to all of the project's users with the Maintainer role.
- **Developers**: Allows access to all of the project's users with the Maintainer and Developer role.
- You can only select groups that are already [invited](../../user/project/members/sharing_projects_groups.md#invite-a-group-to-a-project) to the project.
- Users must have at least the Developer role to appear in
the **Approvers** list.
1. In the **Approval rules** section:
- Ensure that this number is less than or equal to the number of members in
the rule.
- See [Deployment Approvals](deployment_approvals.md) for more information about this feature.
1. Select **Protect**.
The protected environment now appears in the list of protected environments.
### Use the API to protect an environment
Alternatively, you can use the API to protect an environment:
1. Use a project with a CI that creates an environment. For example:
```yaml
stages:
- test
- deploy
test:
stage: test
script:
- 'echo "Testing Application: ${CI_PROJECT_NAME}"'
production:
stage: deploy
when: manual
script:
- 'echo "Deploying to ${CI_ENVIRONMENT_NAME}"'
environment:
name: ${CI_JOB_NAME}
```
1. Use the UI to [create a new group](../../user/group/_index.md#create-a-group).
For example, this group is called `protected-access-group` and has the group ID `9899826`. Note
that the rest of the examples in these steps use this group.

1. Use the API to add a user to the group as a reporter:
```shell
$ curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" \
--data "user_id=3222377&access_level=20" "https://gitlab.com/api/v4/groups/9899826/members"
{"id":3222377,"name":"Sean Carroll","username":"sfcarroll","state":"active","avatar_url":"https://gitlab.com/uploads/-/system/user/avatar/3222377/avatar.png","web_url":"https://gitlab.com/sfcarroll","access_level":20,"created_at":"2020-10-26T17:37:50.309Z","expires_at":null}
```
1. Use the API to add the group to the project as a reporter:
```shell
$ curl --request POST --header "PRIVATE-TOKEN: <your_access_token>" \
--request POST "https://gitlab.com/api/v4/projects/22034114/share?group_id=9899826&group_access=20"
{"id":1233335,"project_id":22034114,"group_id":9899826,"group_access":20,"expires_at":null}
```
1. Use the API to add the group with protected environment access:
```shell
curl --header 'Content-Type: application/json' --request POST --data '{"name": "production", "deploy_access_levels": [{"group_id": 9899826}]}' \
--header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.com/api/v4/projects/22034114/protected_environments"
```
The group now has access and can be seen in the UI.
## Environment access by group membership
A user may be granted access to protected environments as part of [group membership](../../user/group/_index.md). Users
with the Reporter role can only be granted access to protected environments with this
method.
## Deployment branch access
Users with the Developer role can be granted
access to a protected environment through any of these methods:
- As an individual contributor, through a role.
- Through a group membership.
If the user also has push or merge access to the branch deployed on production,
they have the following privileges:
- [Stop an environment](_index.md#stopping-an-environment).
- [Delete an environment](_index.md#delete-an-environment).
- [Create an environment terminal](_index.md#web-terminals-deprecated).
## Deployment-only access to protected environments
Users granted access to a protected environment, but not push or merge access
to the branch deployed to it, are only granted access to deploy the environment.
[Invited groups](../../user/project/members/sharing_projects_groups.md#invite-a-group-to-a-project) added
to the project with [Reporter role](../../user/permissions.md#project-members-permissions), appear in the dropdown list for deployment-only access.
To add deployment-only access:
1. Create a group with members who are granted to access to the protected environment, if it doesn't exist yet.
1. [Invite the group](../../user/project/members/sharing_projects_groups.md#invite-a-group-to-a-project) to the project with the Reporter role.
1. Follow the steps in [Protecting Environments](#protecting-environments).
## Modifying and unprotecting environments
Maintainers can:
- Update existing protected environments at any time by changing the access in the
**Allowed to Deploy** dropdown list.
- Unprotect a protected environment by selecting the **Unprotect** button for that environment.
After an environment is unprotected, all access entries are deleted and must
be re-entered if the environment is re-protected.
After an approval rule is deleted, previously approved deployments do not show who approved the deployment.
Information on who approved a deployment is still available in the [project audit events](../../user/compliance/audit_events.md#project-audit-events).
If a new rule is added, previous deployments show the new rules without the option to approve the deployment. [Issue 506687](https://gitlab.com/gitlab-org/gitlab/-/issues/506687) proposes to show the full approval history of deployments, even if an approval rule is deleted.
For more information, see [Deployment safety](deployment_safety.md).
## Group-level protected environments
Typically, large enterprise organizations have an explicit permission boundary
between [developers and operators](https://about.gitlab.com/topics/devops/).
Developers build and test their code, and operators deploy and monitor the
application. With group-level protected environments, operators can
restrict access to critical environments from developers. Group-level protected environments
extend the [project-level protected environments](#protecting-environments)
to the group-level.
The permissions of deployments can be illustrated in the following table:
| Environment | Developer | Operator | Category |
|-------------|------------|----------|----------|
| Development | Allowed | Allowed | Lower environment |
| Testing | Allowed | Allowed | Lower environment |
| Staging | Disallowed | Allowed | Higher environment |
| Production | Disallowed | Allowed | Higher environment |
_(Reference: [Deployment environments on Wikipedia](https://en.wikipedia.org/wiki/Deployment_environment))_
### Group-level protected environments names
Contrary to project-level protected environments, group-level protected
environments use the [deployment tier](_index.md#deployment-tier-of-environments)
as their name.
A group may consist of many project environments that have unique names.
For example, Project-A has a `gprd` environment and Project-B has a `Production`
environment, so protecting a specific environment name doesn't scale well.
By using deployment tiers, both are recognized as `production` deployment tier
and are protected at the same time.
### Configure group-level memberships
{{< history >}}
- Operators are required to have Owner+ role from the original Maintainer+ role and this role change is introduced from GitLab 15.3 [with a flag](https://gitlab.com/gitlab-org/gitlab/-/issues/369873) named `group_level_protected_environment_settings_permission`. Enabled by default.
- [Feature flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/369873) in GitLab 15.4.
{{< /history >}}
To maximize the effectiveness of group-level protected environments,
[group-level memberships](../../user/group/_index.md) must be correctly
configured:
- Operators should be given the Owner role
for the top-level group. They can maintain CI/CD configurations for
the higher environments (such as production) in the group-level settings page,
which includes group-level protected environments,
[group-level runners](../runners/runners_scope.md#group-runners), and
[group-level clusters](../../user/group/clusters/_index.md). Those
configurations are inherited to the child projects as read-only entries.
This ensures that only operators can configure the organization-wide
deployment ruleset.
- Developers should be given no more than the Developer role
for the top-level group, or explicitly given the Owner role for a child project.
They do not have access to the CI/CD configurations in the
top-level group, so operators can ensure that the critical configuration won't
be accidentally changed by the developers.
- For subgroups and child projects:
- Regarding [subgroups](../../user/group/subgroups/_index.md), if a higher
group has configured the group-level protected environment, the lower groups
cannot override it.
- [Project-level protected environments](#protecting-environments) can be
combined with the group-level setting. If both group-level and project-level
environment configurations exist, to run a deployment job, the user must be allowed in **both**
rulesets.
- In a project or a subgroup of the top-level group, developers can be
safely assigned the Maintainer role to tune their lower environments (such
as `testing`).
Having this configuration in place:
- If a user is about to run a deployment job in a project and allowed to deploy
to the environment, the deployment job proceeds.
- If a user is about to run a deployment job in a project but disallowed to
deploy to the environment, the deployment job fails with an error message.
### Protect critical environments under a group
To protect a group-level environment, make sure your environments have the correct
[`deployment_tier`](_index.md#deployment-tier-of-environments) defined in `.gitlab-ci.yml`.
#### Using the UI
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/325249) in GitLab 15.1.
{{< /history >}}
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings > CI/CD**.
1. Expand **Protected environments**.
1. From the **Environment** list, select the [deployment tier of environments](_index.md#deployment-tier-of-environments) you want to protect.
1. In the **Allowed to deploy** list, select the [subgroups](../../user/group/subgroups/_index.md) you want to give deploy access to.
1. Select **Protect**.
#### Using the API
Configure the group-level protected environments by using the [REST API](../../api/group_protected_environments.md).
## Deployment approvals
Protected environments can also be used to require manual approvals before deployments. See [Deployment approvals](deployment_approvals.md) for more information.
## Troubleshooting
### Reporter can't run a trigger job that deploys to a protected environment in downstream pipeline
A user who has [deployment-only access to protected environments](#deployment-only-access-to-protected-environments) might **not** be able to run a job if it's with a [`trigger`](../yaml/_index.md#trigger) keyword. This is because the job is missing the [`environment`](../yaml/_index.md#environment) keyword definition to associate the job with the protected environment, therefore the job is recognized as a standard job that uses [regular CI/CD permission model](../../user/permissions.md#cicd).
See [this issue](https://gitlab.com/groups/gitlab-org/-/epics/8483) for more information about supporting `environment` keyword with `trigger` keyword.
|
https://docs.gitlab.com/ci/ssh_keys
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/ssh_keys.md
|
2025-08-13
|
doc/ci/jobs
|
[
"doc",
"ci",
"jobs"
] |
ssh_keys.md
|
Software Supply Chain Security
|
Pipeline Security
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Using SSH keys with GitLab CI/CD
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
GitLab does not have built-in support for managing SSH keys in a build
environment (where the GitLab Runner runs).
Use SSH keys when you want to:
- Check out internal submodules.
- Download private packages using your package manager. For example, Bundler.
- Deploy your application to your own server or, for example, Heroku.
- Execute SSH commands from the build environment to a remote server.
- Rsync files from the build environment to a remote server.
The most widely supported method is to inject an SSH key into your build
environment by extending your `.gitlab-ci.yml`, and it's a solution that works
with any type of [executor](https://docs.gitlab.com/runner/executors/)
(like Docker or shell, for example).
## Create and use an SSH key
To create and use an SSH key in GitLab CI/CD:
1. [Create a new SSH key pair](../../user/ssh.md#generate-an-ssh-key-pair) locally with `ssh-keygen`.
1. Add the private key as a [file type CI/CD variable](../variables/_index.md#for-a-project) to
your project. The variable value must end in a newline (`LF` character). To add a newline, press <kbd>Enter</kbd> or <kbd>Return</kbd>
at the end of the last line of the SSH key before saving it in the CI/CD settings.
1. Run the [`ssh-agent`](https://linux.die.net/man/1/ssh-agent) in the job, which loads
the private key.
1. Copy the public key to the servers you want to have access to (usually in `~/.ssh/authorized_keys`).
If you are accessing a private GitLab repository, you also need to add the public key as
a [deploy key](../../user/project/deploy_keys/_index.md).
In the following example, the `ssh-add -` command does not display the value of
`$SSH_PRIVATE_KEY` in the job log, though it could be exposed if you enable
[debug logging](../variables/variables_troubleshooting.md#enable-debug-logging). You might also want to
check the [visibility of your pipelines](../pipelines/settings.md#change-which-users-can-view-your-pipelines).
## SSH keys when using the Docker executor
When your CI/CD jobs run inside Docker containers (meaning the environment is
contained) and you want to deploy your code in a private server, you need a way
to access it. In this case, you can use an SSH key pair.
1. You first must create an SSH key pair. For more information, follow
the instructions to [generate an SSH key](../../user/ssh.md#generate-an-ssh-key-pair).
**Do not** add a passphrase to the SSH key, or the `before_script` will
prompt for it.
1. Create a new [file type CI/CD variable](../variables/_index.md#for-a-project).
- In the **Key** field, enter `SSH_PRIVATE_KEY`.
- In the **Value** field, paste the content of your private key from the key pair that you created earlier.
Make sure the file ends with a newline. To add a newline, press
<kbd>Enter</kbd> or <kbd>Return</kbd> at the end of the last line of the SSH key before saving your changes.
1. Modify your `.gitlab-ci.yml` with a `before_script` action. In the following
example, a Debian based image is assumed. Edit to your needs:
```yaml
before_script:
##
## Install ssh-agent if not already installed, it is required by Docker.
## (change apt-get to yum if you use an RPM-based image)
##
- 'command -v ssh-agent >/dev/null || ( apt-get update -y && apt-get install openssh-client -y )'
##
## Run ssh-agent (inside the build environment)
##
- eval $(ssh-agent -s)
##
## Give the right permissions, otherwise ssh-add will refuse to add files
## Add the SSH key stored in SSH_PRIVATE_KEY file type CI/CD variable to the agent store
##
- chmod 400 "$SSH_PRIVATE_KEY"
- ssh-add "$SSH_PRIVATE_KEY"
##
## Create the SSH directory and give it the right permissions
##
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
##
## Optionally, if you will be using any Git commands, set the user name and
## and email.
##
# - git config --global user.email "user@example.com"
# - git config --global user.name "User name"
```
The [`before_script`](../yaml/_index.md#before_script) can be set as a default
or per-job.
1. Make sure the private server's [SSH host keys are verified](#verifying-the-ssh-host-keys).
1. As a final step, add the public key from the one you created in the first
step to the services that you want to have an access to from inside the build
environment. If you are accessing a private GitLab repository you must add
it as a [deploy key](../../user/project/deploy_keys/_index.md).
That's it! You can now have access to private servers or repositories in your
build environment.
## SSH keys when using the Shell executor
If you are using the Shell executor and not Docker, it is easier to set up an
SSH key.
You can generate the SSH key from the machine that GitLab Runner is installed
on, and use that key for all projects that are run on this machine.
1. First, sign in to the server that runs your jobs.
1. Then, from the terminal, sign in as the `gitlab-runner` user:
```shell
sudo su - gitlab-runner
```
1. Generate the SSH key pair as described in the instructions to
[generate an SSH key](../../user/ssh.md#generate-an-ssh-key-pair).
**Do not** add a passphrase to the SSH key, or the `before_script` will
prompt for it.
1. As a final step, add the public key from the one you created earlier to the
services that you want to have an access to from inside the build environment.
If you are accessing a private GitLab repository you must add it as a
[deploy key](../../user/project/deploy_keys/_index.md).
After generating the key, try to sign in to the remote server to accept the
fingerprint:
```shell
ssh example.com
```
For accessing repositories on GitLab.com, you would use `git@gitlab.com`.
## Verifying the SSH host keys
It is a good practice to check the private server's own public key to make sure
you are not being targeted by a man-in-the-middle attack. If anything
suspicious happens, you notice it because the job fails (the SSH
connection fails when the public keys don't match).
To find out the host keys of your server, run the `ssh-keyscan` command from a
trusted network (ideally, from the private server itself):
```shell
## Use the domain name
ssh-keyscan example.com
## Or use an IP
ssh-keyscan 10.0.2.2
```
Create a new [file type CI/CD variable](../variables/_index.md#use-file-type-cicd-variables)
with `SSH_KNOWN_HOSTS` as "Key", and as a "Value" add the output of `ssh-keyscan`.
Make sure the file ends with a newline. To add a newline, press <kbd>Enter</kbd> or <kbd>Return</kbd>
at the end of the last line of the SSH key before saving your changes.
If you must connect to multiple servers, all the server host keys
must be collected in the **Value** of the variable, one key per line.
{{< alert type="note" >}}
By using a file type CI/CD variable instead of `ssh-keyscan` directly inside
`.gitlab-ci.yml`, it has the benefit that you don't have to change `.gitlab-ci.yml`
if the host domain name changes for some reason. Also, the values are predefined
by you, meaning that if the host keys suddenly change, the CI/CD job doesn't fail,
so there's something wrong with the server or the network.
{{< /alert >}}
Now that the `SSH_KNOWN_HOSTS` variable is created, in addition to the
[content of `.gitlab-ci.yml`](#ssh-keys-when-using-the-docker-executor), you must add:
```yaml
before_script:
##
## Assuming you created the SSH_KNOWN_HOSTS file type CI/CD variable, uncomment the
## following two lines.
##
- cp "$SSH_KNOWN_HOSTS" ~/.ssh/known_hosts
- chmod 644 ~/.ssh/known_hosts
##
## Alternatively, use ssh-keyscan to scan the keys of your private server.
## Replace example.com with your private server's domain name. Repeat that
## command if you have more than one server to connect to. Include the -t
## flag to specify the key type.
##
# - ssh-keyscan -t rsa,ed25519 example.com >> ~/.ssh/known_hosts
# - chmod 644 ~/.ssh/known_hosts
##
## You can optionally disable host key checking. Be aware that by adding that
## you are susceptible to man-in-the-middle attacks.
## WARNING: Use this only with the Docker executor, if you use it with shell
## you will overwrite your user's SSH config.
##
# - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" >> ~/.ssh/config'
```
## Use SSH key without a file type CI/CD variable
If you do not want to use a file type CI/CD variable, the [example SSH Project](https://gitlab.com/gitlab-examples/ssh-private-key/)
shows an alternative method. This method uses a regular CI/CD variable instead of
the file type variable previously recommended.
## Troubleshooting
### `Error loading key "/builds/path/SSH_PRIVATE_KEY": error in libcrypto` message
This message can be returned if there is a formatting error with the SSH key.
When saving the SSH key as a [file type CI/CD variable](../variables/_index.md#use-file-type-cicd-variables),
the value must end with a newline (`LF` character). To add a newline, press <kbd>Enter</kbd> or <kbd>Return</kbd>
at the end of the `-----END OPENSSH PRIVATE KEY-----` line of the SSH key before saving
the variable.
|
---
stage: Software Supply Chain Security
group: Pipeline Security
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Using SSH keys with GitLab CI/CD
breadcrumbs:
- doc
- ci
- jobs
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
GitLab does not have built-in support for managing SSH keys in a build
environment (where the GitLab Runner runs).
Use SSH keys when you want to:
- Check out internal submodules.
- Download private packages using your package manager. For example, Bundler.
- Deploy your application to your own server or, for example, Heroku.
- Execute SSH commands from the build environment to a remote server.
- Rsync files from the build environment to a remote server.
The most widely supported method is to inject an SSH key into your build
environment by extending your `.gitlab-ci.yml`, and it's a solution that works
with any type of [executor](https://docs.gitlab.com/runner/executors/)
(like Docker or shell, for example).
## Create and use an SSH key
To create and use an SSH key in GitLab CI/CD:
1. [Create a new SSH key pair](../../user/ssh.md#generate-an-ssh-key-pair) locally with `ssh-keygen`.
1. Add the private key as a [file type CI/CD variable](../variables/_index.md#for-a-project) to
your project. The variable value must end in a newline (`LF` character). To add a newline, press <kbd>Enter</kbd> or <kbd>Return</kbd>
at the end of the last line of the SSH key before saving it in the CI/CD settings.
1. Run the [`ssh-agent`](https://linux.die.net/man/1/ssh-agent) in the job, which loads
the private key.
1. Copy the public key to the servers you want to have access to (usually in `~/.ssh/authorized_keys`).
If you are accessing a private GitLab repository, you also need to add the public key as
a [deploy key](../../user/project/deploy_keys/_index.md).
In the following example, the `ssh-add -` command does not display the value of
`$SSH_PRIVATE_KEY` in the job log, though it could be exposed if you enable
[debug logging](../variables/variables_troubleshooting.md#enable-debug-logging). You might also want to
check the [visibility of your pipelines](../pipelines/settings.md#change-which-users-can-view-your-pipelines).
## SSH keys when using the Docker executor
When your CI/CD jobs run inside Docker containers (meaning the environment is
contained) and you want to deploy your code in a private server, you need a way
to access it. In this case, you can use an SSH key pair.
1. You first must create an SSH key pair. For more information, follow
the instructions to [generate an SSH key](../../user/ssh.md#generate-an-ssh-key-pair).
**Do not** add a passphrase to the SSH key, or the `before_script` will
prompt for it.
1. Create a new [file type CI/CD variable](../variables/_index.md#for-a-project).
- In the **Key** field, enter `SSH_PRIVATE_KEY`.
- In the **Value** field, paste the content of your private key from the key pair that you created earlier.
Make sure the file ends with a newline. To add a newline, press
<kbd>Enter</kbd> or <kbd>Return</kbd> at the end of the last line of the SSH key before saving your changes.
1. Modify your `.gitlab-ci.yml` with a `before_script` action. In the following
example, a Debian based image is assumed. Edit to your needs:
```yaml
before_script:
##
## Install ssh-agent if not already installed, it is required by Docker.
## (change apt-get to yum if you use an RPM-based image)
##
- 'command -v ssh-agent >/dev/null || ( apt-get update -y && apt-get install openssh-client -y )'
##
## Run ssh-agent (inside the build environment)
##
- eval $(ssh-agent -s)
##
## Give the right permissions, otherwise ssh-add will refuse to add files
## Add the SSH key stored in SSH_PRIVATE_KEY file type CI/CD variable to the agent store
##
- chmod 400 "$SSH_PRIVATE_KEY"
- ssh-add "$SSH_PRIVATE_KEY"
##
## Create the SSH directory and give it the right permissions
##
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
##
## Optionally, if you will be using any Git commands, set the user name and
## and email.
##
# - git config --global user.email "user@example.com"
# - git config --global user.name "User name"
```
The [`before_script`](../yaml/_index.md#before_script) can be set as a default
or per-job.
1. Make sure the private server's [SSH host keys are verified](#verifying-the-ssh-host-keys).
1. As a final step, add the public key from the one you created in the first
step to the services that you want to have an access to from inside the build
environment. If you are accessing a private GitLab repository you must add
it as a [deploy key](../../user/project/deploy_keys/_index.md).
That's it! You can now have access to private servers or repositories in your
build environment.
## SSH keys when using the Shell executor
If you are using the Shell executor and not Docker, it is easier to set up an
SSH key.
You can generate the SSH key from the machine that GitLab Runner is installed
on, and use that key for all projects that are run on this machine.
1. First, sign in to the server that runs your jobs.
1. Then, from the terminal, sign in as the `gitlab-runner` user:
```shell
sudo su - gitlab-runner
```
1. Generate the SSH key pair as described in the instructions to
[generate an SSH key](../../user/ssh.md#generate-an-ssh-key-pair).
**Do not** add a passphrase to the SSH key, or the `before_script` will
prompt for it.
1. As a final step, add the public key from the one you created earlier to the
services that you want to have an access to from inside the build environment.
If you are accessing a private GitLab repository you must add it as a
[deploy key](../../user/project/deploy_keys/_index.md).
After generating the key, try to sign in to the remote server to accept the
fingerprint:
```shell
ssh example.com
```
For accessing repositories on GitLab.com, you would use `git@gitlab.com`.
## Verifying the SSH host keys
It is a good practice to check the private server's own public key to make sure
you are not being targeted by a man-in-the-middle attack. If anything
suspicious happens, you notice it because the job fails (the SSH
connection fails when the public keys don't match).
To find out the host keys of your server, run the `ssh-keyscan` command from a
trusted network (ideally, from the private server itself):
```shell
## Use the domain name
ssh-keyscan example.com
## Or use an IP
ssh-keyscan 10.0.2.2
```
Create a new [file type CI/CD variable](../variables/_index.md#use-file-type-cicd-variables)
with `SSH_KNOWN_HOSTS` as "Key", and as a "Value" add the output of `ssh-keyscan`.
Make sure the file ends with a newline. To add a newline, press <kbd>Enter</kbd> or <kbd>Return</kbd>
at the end of the last line of the SSH key before saving your changes.
If you must connect to multiple servers, all the server host keys
must be collected in the **Value** of the variable, one key per line.
{{< alert type="note" >}}
By using a file type CI/CD variable instead of `ssh-keyscan` directly inside
`.gitlab-ci.yml`, it has the benefit that you don't have to change `.gitlab-ci.yml`
if the host domain name changes for some reason. Also, the values are predefined
by you, meaning that if the host keys suddenly change, the CI/CD job doesn't fail,
so there's something wrong with the server or the network.
{{< /alert >}}
Now that the `SSH_KNOWN_HOSTS` variable is created, in addition to the
[content of `.gitlab-ci.yml`](#ssh-keys-when-using-the-docker-executor), you must add:
```yaml
before_script:
##
## Assuming you created the SSH_KNOWN_HOSTS file type CI/CD variable, uncomment the
## following two lines.
##
- cp "$SSH_KNOWN_HOSTS" ~/.ssh/known_hosts
- chmod 644 ~/.ssh/known_hosts
##
## Alternatively, use ssh-keyscan to scan the keys of your private server.
## Replace example.com with your private server's domain name. Repeat that
## command if you have more than one server to connect to. Include the -t
## flag to specify the key type.
##
# - ssh-keyscan -t rsa,ed25519 example.com >> ~/.ssh/known_hosts
# - chmod 644 ~/.ssh/known_hosts
##
## You can optionally disable host key checking. Be aware that by adding that
## you are susceptible to man-in-the-middle attacks.
## WARNING: Use this only with the Docker executor, if you use it with shell
## you will overwrite your user's SSH config.
##
# - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" >> ~/.ssh/config'
```
## Use SSH key without a file type CI/CD variable
If you do not want to use a file type CI/CD variable, the [example SSH Project](https://gitlab.com/gitlab-examples/ssh-private-key/)
shows an alternative method. This method uses a regular CI/CD variable instead of
the file type variable previously recommended.
## Troubleshooting
### `Error loading key "/builds/path/SSH_PRIVATE_KEY": error in libcrypto` message
This message can be returned if there is a formatting error with the SSH key.
When saving the SSH key as a [file type CI/CD variable](../variables/_index.md#use-file-type-cicd-variables),
the value must end with a newline (`LF` character). To add a newline, press <kbd>Enter</kbd> or <kbd>Return</kbd>
at the end of the `-----END OPENSSH PRIVATE KEY-----` line of the SSH key before saving
the variable.
|
https://docs.gitlab.com/ci/jobs
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/_index.md
|
2025-08-13
|
doc/ci/jobs
|
[
"doc",
"ci",
"jobs"
] |
_index.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
CI/CD Jobs
|
Configuration, rules, caching, artifacts, and logs.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
CI/CD jobs are the fundamental elements of a [GitLab CI/CD pipeline](../pipelines/_index.md).
Jobs are configured in the `.gitlab-ci.yml` file with a list of commands to execute
to accomplish tasks like building, testing, or deploying code.
Jobs:
- Execute on a [runner](../runners/_index.md), for example in a Docker container.
- Run independently from other jobs.
- Have a [job log](job_logs.md) with the full execution log for the job.
Jobs are defined with [YAML keywords](../yaml/_index.md) that define all aspects
of the job's execution, including keywords that:
- Control [how](job_control.md) and [when](job_rules.md) jobs run.
- Group jobs together in collections called [stages](../yaml/_index.md#stages).
Stages run in sequence, while all jobs in a stage can run in parallel.
- Define [CI/CD variables](../variables/_index.md) for flexible configuration.
- Define [caches](../caching/_index.md) to speed up job execution.
- Save files as [artifacts](job_artifacts.md) which can be used by other jobs.
## Add a job to a pipeline
To add a job to a pipeline, add it into your `.gitlab-ci.yml` file. The job must:
- Be defined at the top-level of the YAML configuration.
- Have a unique [job name](#job-names).
- Have either a [`script`](../yaml/_index.md#script) section defining commands to run,
or a [`trigger`](../yaml/_index.md#trigger) section to trigger a [downstream pipeline](../pipelines/downstream_pipelines.md)
to run.
For example:
```yaml
my-ruby-job:
script:
- bundle install
- bundle exec my_ruby_command
my-shell-script-job:
script:
- my_shell_script.sh
```
### Job names
You can't use these keywords as job names:
- `image`
- `services`
- `stages`
- `before_script`
- `after_script`
- `variables`
- `cache`
- `include`
- `pages:deploy` configured for a `deploy` stage
Additionally, these names are valid when quoted, but are
not recommended as they can make pipeline configuration unclear:
- `"true":`
- `"false":`
- `"nil":`
Job names must be 255 characters or fewer.
Use unique names for your jobs. If multiple jobs have the same name in a file,
only one is added to the pipeline, and it's difficult to predict which one is chosen.
If the same job name is used in one or more included files,
[parameters are merged](../yaml/includes.md#override-included-configuration-values).
### Hide a job
To temporarily disable a job without deleting it from the configuration
file, add a period (`.`) to the start of the job name. Hidden jobs do not need to contain
the `script` or `trigger` keywords, but must contain valid YAML configuration.
For example:
```yaml
.hidden_job:
script:
- run test
```
Hidden jobs are not processed by GitLab CI/CD, but they can be used as templates
for reusable configuration with:
- The [`extends` keyword](../yaml/yaml_optimization.md#use-extends-to-reuse-configuration-sections).
- [YAML anchors](../yaml/yaml_optimization.md#anchors).
## Set default values for job keywords
You can use the `default` keyword to set default job keywords and values, which are
used by default by all jobs in a pipeline.
For example:
```yaml
default:
image: 'ruby:2.4'
before_script:
- echo Hello World
rspec-job:
script: bundle exec rspec
```
When the pipeline runs, the job uses the default keywords:
```yaml
rspec-job:
image: 'ruby:2.4'
before_script:
- echo Hello World
script: bundle exec rspec
```
### Control the inheritance of default keywords and variables
You can control the inheritance of:
- [default keywords](../yaml/_index.md#default) with [`inherit:default`](../yaml/_index.md#inheritdefault).
- [default variables](../yaml/_index.md#default) with [`inherit:variables`](../yaml/_index.md#inheritvariables).
For example:
```yaml
default:
image: 'ruby:2.4'
before_script:
- echo Hello World
variables:
DOMAIN: example.com
WEBHOOK_URL: https://my-webhook.example.com
rubocop:
inherit:
default: false
variables: false
script: bundle exec rubocop
rspec:
inherit:
default: [image]
variables: [WEBHOOK_URL]
script: bundle exec rspec
capybara:
inherit:
variables: false
script: bundle exec capybara
karma:
inherit:
default: true
variables: [DOMAIN]
script: karma
```
In this example:
- `rubocop`:
- inherits: Nothing.
- `rspec`:
- inherits: the default `image` and the `WEBHOOK_URL` variable.
- does **not** inherit: the default `before_script` and the `DOMAIN` variable.
- `capybara`:
- inherits: the default `before_script` and `image`.
- does **not** inherit: the `DOMAIN` and `WEBHOOK_URL` variables.
- `karma`:
- inherits: the default `image` and `before_script`, and the `DOMAIN` variable.
- does **not** inherit: `WEBHOOK_URL` variable.
## View jobs in a pipeline
When you access a pipeline, you can see the related jobs for that pipeline.
The order of jobs in a pipeline depends on the type of pipeline graph.
- For [full pipeline graphs](../pipelines/_index.md#pipeline-details), jobs are sorted alphabetically by name.
- For [pipeline mini graphs](../pipelines/_index.md#pipeline-mini-graphs), jobs are sorted by status severity
with failed jobs appearing first, and then alphabetically by name.
Selecting an individual job shows you its [job log](job_logs.md), and allows you to:
- Cancel the job.
- Retry the job, if it failed.
- Run the job again, if it passed.
- Erase the job log.
### View all jobs in a project
{{< details >}}
- Offering: GitLab.com, GitLab Self-Managed
{{< /details >}}
{{< history >}}
- Filtering jobs by job name [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/387547) as an [experiment](../../policy/development_stages_support.md) on GitLab.com and GitLab Self-Managed in GitLab 17.3 [with flags](../../administration/feature_flags/_index.md) named `populate_and_use_build_names_table` for the API and `fe_search_build_by_name` for the UI. Disabled by default.
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag. For more information, see the history.
{{< /alert >}}
Filtering jobs by name is an [experiment](../../policy/development_stages_support.md). For more information about the development of this feature, see [issue 387547](https://gitlab.com/gitlab-org/gitlab/-/issues/387547).
To view the full list of jobs that ran in a project:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Jobs**.
You can filter the list by [job name](#job-names), [job status](#available-job-statuses), and [job source](#available-job-sources).
### Available job statuses
CI/CD jobs can have the following statuses:
- `canceled`: Job was manually canceled or automatically aborted.
- `canceling`: Job is being canceled but `after_script` is running.
- `created`: Job has been created but not yet processed.
- `failed`: Job execution failed.
- `manual`: Job requires manual action to start.
- `pending`: Job is in the queue waiting for a runner.
- `preparing`: Runner is preparing the execution environment.
- `running`: Job is executing on a runner.
- `scheduled`: Job has been scheduled but execution hasn't started.
- `skipped`: Job was skipped due to conditions or dependencies.
- `success`: Job completed successfully.
- `waiting_for_resource`: Job is waiting for resources to become available.
### View the source of a job
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/181159) job source in GitLab 17.9 [with a flag](../../administration/feature_flags/_index.md) named `populate_and_use_build_source_table`. Enabled by default.
- [Generally available](https://gitlab.com/groups/gitlab-org/-/epics/11796) on GitLab.com, GitLab Self-Managed, and GitLab Dedicated in GitLab 17.11.
{{< /history >}}
GitLab CI/CD jobs now include a source attribute that indicates the action that initially triggered a CI/CD job.
Use this attribute to track how a job was initiated or filter job runs based on the specific sources.
#### Available job sources
The source attribute can have the following values:
- `api`: Job initiated by a REST call to the Jobs API.
- `chat`: Job initiated by a chat command using GitLab ChatOps.
- `container_registry_push`: Job initiated by container registry push.
- `duo_workflow`: Job initiated by GitLab Duo Agent Platform.
- `external`: Job initiated by an event in an external repository integrated with GitLab. This does not include pull request events.
- `external_pull_request_event`: Job initiated by a pull request event in an external repository.
- `merge_request_event`: Job initiated by a merge request event.
- `ondemand_dast_scan`:Job initiated by an on-demand DAST scan.
- `ondemand_dast_validation`: Job initiated by an on-demand DAST validation.
- `parent_pipeline`: Job initiated by a parent pipeline
- `pipeline`: Job initiated by a user manually running a pipeline.
- `pipeline_execution_policy`: Job initiated by a triggered pipeline execution policy.
- `pipeline_execution_policy_schedule`: Job initiated by a scheduled pipeline execution policy.
- `push`: Job initiated by a code push.
- `scan_execution_policy`: Job initiated by a scan execution policy.
- `schedule`: Job initiated by a scheduled pipeline.
- `security_orchestration_policy`: Job initiated by a scheduled scan execution policy.
- `trigger`: Job initiated by another job or pipeline.
- `unknown`: Job initiated by an unknown source.
- `web`: Job initiated by a user from the GitLab UI.
- `webide`: Job initiated by a user from the Web IDE.
### Group similar jobs together in pipeline views
If you have many similar jobs, your [pipeline graph](../pipelines/_index.md#pipeline-details)
becomes long and hard to read.
You can automatically group similar jobs together. If the job names are formatted in a certain way,
they are collapsed into a single group in regular pipeline graphs (not the mini graphs).
You can recognize when a pipeline has grouped jobs if you see a number next to a job
name instead of the retry or cancel buttons. The number indicates the amount of grouped
jobs. Hovering over them shows you if all jobs have passed or any has failed. Select to expand them.

To create a group of jobs, in the `.gitlab-ci.yml` file,
separate each job name with a number and one of the following:
- A slash (`/`), for example, `slash-test 1/3`, `slash-test 2/3`, `slash-test 3/3`.
- A colon (`:`), for example, `colon-test 1:3`, `colon-test 2:3`, `colon-test 3:3`.
- A space, for example `space-test 0 3`, `space-test 1 3`, `space-test 2 3`.
You can use these symbols interchangeably.
In the following example, these three jobs are in a group named `build ruby`:
```yaml
build ruby 1/3:
stage: build
script:
- echo "ruby1"
build ruby 2/3:
stage: build
script:
- echo "ruby2"
build ruby 3/3:
stage: build
script:
- echo "ruby3"
```
The pipeline graph displays a group named `build ruby` with three jobs.
The jobs are ordered by comparing the numbers from left to right. You
usually want the first number to be the index and the second number to be the total.
[This regular expression](https://gitlab.com/gitlab-org/gitlab/-/blob/2f3dc314f42dbd79813e6251792853bc231e69dd/app/models/commit_status.rb#L99)
evaluates the job names: `([\b\s:]+((\[.*\])|(\d+[\s:\/\\]+\d+))){1,3}\s*\z`.
One or more `: [...]`, `X Y`, `X/Y`, or `X\Y` sequences are removed from the **end**
of job names only. Matching substrings found at the beginning or in the middle of
job names are not removed.
## Retry jobs
You can retry a job after it completes, regardless of its final state (failed, success, or canceled).
When you retry a job:
- A new job instance is created with a new job ID.
- The job runs with the same parameters and variables as the original job.
- If the job produces artifacts, new artifacts are created and stored.
- The new job associates with the user who initiated the retry, not the user who created the original pipeline.
- Any subsequent jobs that were previously skipped are reassigned to the user who initiated the retry.
When you retry a [trigger job](../yaml/_index.md#trigger) that triggers a downstream pipeline:
- The trigger job generates a new downstream pipeline.
- The downstream pipeline also associates with the user who initiated the retry.
- The downstream pipeline runs with the configuration that exists at the time of the retry,
which might be different from the original run.
### Retry a job
Prerequisites:
- You must have at least the Developer role for the project.
- The job must not be [archived](../../administration/settings/continuous_integration.md#archive-pipelines).
To retry a job from a merge request:
1. On the left sidebar, select **Search or go to** and find your project.
1. From your merge request, do one of the following:
- In the pipeline widget, next to the job you want to retry, select **Run again** ({{< icon name="retry" >}}).
- Select the **Pipelines** tab, next to the job you want to retry, select **Run again** ({{< icon name="retry" >}}).
To retry a job from the job log:
1. Go to the job's log page.
1. In the upper-right corner, select **Run again** ({{< icon name="retry" >}}).
To retry a job from a pipeline:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipelines**.
1. Find the pipeline that contains the job you want to retry.
1. From the pipeline graph, next to the job you want to retry, select **Run again** ({{< icon name="retry" >}}).
### Retry all failed or canceled jobs in a pipeline
If a pipeline has multiple failed or canceled jobs, you can retry all of them at once:
1. On the left sidebar, select **Search or go to** and find your project.
1. Do one of the following:
- Select **Build > Pipelines**.
- Go to a merge request and select the **Pipelines** tab.
1. For the pipeline with failed or canceled jobs, select **Retry all failed or canceled jobs** ({{< icon name="retry" >}}).
## Cancel jobs
You can cancel a CI/CD job that hasn't completed yet.
When you cancel a job, what happens next depends on its state and the GitLab Runner version:
- For jobs that haven't started executing yet, the job is canceled immediately.
- For running jobs:
- For GitLab Runner 16.10 and later with GitLab 17.0 and later, the job is marked as `canceling` while the runner runs the job's [`after_script`](../yaml/_index.md#after_script).
When `after_script` completes, the job is marked as `canceled`.
- For GitLab Runner 16.9 and earlier with GitLab 16.11 and earlier, the job is `canceled` immediately without running `after_script`.
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
stateDiagram-v2
accTitle: CI/CD job state transitions
accDescr: Shows possible state transitions for CI/CD jobs, including cancellation paths.
direction TB
state if_versions <>
[*] --> pending: Job created
pending --> canceled: Cancel requested
canceled --> [*]
pending --> running: Runner picks up job
running --> success: Job succeeds
success --> [*]
running --> failed: Job fails
failed --> [*]
running --> if_versions: Cancel requested
if_versions --> canceling: GitLab 17.0 and later with GitLab Runner 16.10 and later
if_versions --> canceled: GitLab 16.11 and earlier with GitLab Runner 16.9 and earlier
canceling --> canceled: after_script complete
```
If you need to cancel a job immediately without waiting for the `after_script`, use [force cancel](#force-cancel-a-job).
### Cancel a job
Prerequisites:
- You must have at least the Developer role for the project,
or the [minimum role required to cancel a pipeline or job](../pipelines/settings.md#restrict-roles-that-can-cancel-pipelines-or-jobs).
To cancel a job from a merge request:
1. On the left sidebar, select **Search or go to** and find your project.
1. From your merge request, do one of the following:
- In the pipeline widget, next to the job you want to cancel, select **Cancel** ({{< icon name="cancel" >}}).
- Select the **Pipelines** tab, next to the job you want to cancel, select **Cancel** ({{< icon name="cancel" >}}).
To cancel a job from the job log:
1. Go to the job's log page.
1. In the upper-right corner, select **Cancel** ({{< icon name="cancel" >}}).
To cancel a job from a pipeline:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipelines**.
1. Find the pipeline that contains the job you want to cancel.
1. From the pipeline graph, next to the job you want to cancel, select **Cancel** ({{< icon name="cancel" >}}).
### Cancel all running jobs in a pipeline
You can cancel all jobs in a running pipeline at once.
1. On the left sidebar, select **Search or go to** and find your project.
1. Do one of the following:
- Select **Build > Pipelines**.
- Go to a merge request and select the **Pipelines** tab.
1. For the pipeline you want to cancel, select **Cancel the running pipeline** ({{< icon name="cancel" >}}).
### Force cancel a job
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/467107) as an [experiment](../../policy/development_stages_support.md) in GitLab 17.10 [with a flag](../../administration/feature_flags/_index.md) named `force_cancel_build`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/519313) in GitLab 17.11. Feature flag `force_cancel_build` removed.
{{< /history >}}
If you don't want to wait for `after_script` to finish or a job is unresponsive, you can force cancel it.
Force cancel immediately moves a job from the `canceling` state to `canceled`.
When you force cancel a job, the [job token](ci_job_token.md) is immediately revoked.
If the runner is still executing the job, it loses access to GitLab.
The runner aborts the job without waiting for `after_script` to complete.
Prerequisites:
- You must have at least the Maintainer role for the project.
- The job must be in the `canceling` state, which requires:
- GitLab 17.0 and later.
- GitLab Runner 16.10 and later.
To force cancel a job:
1. Go to the job's log page.
1. In the upper-right corner, select **Force cancel**.
## Troubleshoot a failed job
When a pipeline fails or is allowed to fail, there are several places where you
can find the reason:
- In the [pipeline graph](../pipelines/_index.md#pipeline-details), in the pipeline details view.
- In the pipeline widgets, in the merge requests and commit pages.
- In the job views, in the global and detailed views of a job.
In each place, if you hover over the failed job you can see the reason it failed.

You can also see the reason it failed on the Job detail page.
### With Root Cause Analysis
You can use GitLab Duo Root Cause Analysis in GitLab Duo Chat to [troubleshoot failed CI/CD jobs](../../user/gitlab_duo_chat/examples.md#troubleshoot-failed-cicd-jobs-with-root-cause-analysis).
## Deployment jobs
Deployment jobs are CI/CD jobs that use [environments](../environments/_index.md).
A deployment job is any job that uses the `environment` keyword and the [`start` environment `action`](../yaml/_index.md#environmentaction).
Deployment jobs do not need to be in the `deploy` stage. The following `deploy me`
job is an example of a deployment job. `action: start` is the default behavior and
is defined here for clarity, but you can omit it:
```yaml
deploy me:
script:
- deploy-to-cats.sh
environment:
name: production
url: https://cats.example.com
action: start
```
The behavior of deployment jobs can be controlled with
[deployment safety](../environments/deployment_safety.md) settings like
[preventing outdated deployment jobs](../environments/deployment_safety.md#prevent-outdated-deployment-jobs)
and [ensuring only one deployment job runs at a time](../environments/deployment_safety.md#ensure-only-one-deployment-job-runs-at-a-time).
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: CI/CD Jobs
description: Configuration, rules, caching, artifacts, and logs.
breadcrumbs:
- doc
- ci
- jobs
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
CI/CD jobs are the fundamental elements of a [GitLab CI/CD pipeline](../pipelines/_index.md).
Jobs are configured in the `.gitlab-ci.yml` file with a list of commands to execute
to accomplish tasks like building, testing, or deploying code.
Jobs:
- Execute on a [runner](../runners/_index.md), for example in a Docker container.
- Run independently from other jobs.
- Have a [job log](job_logs.md) with the full execution log for the job.
Jobs are defined with [YAML keywords](../yaml/_index.md) that define all aspects
of the job's execution, including keywords that:
- Control [how](job_control.md) and [when](job_rules.md) jobs run.
- Group jobs together in collections called [stages](../yaml/_index.md#stages).
Stages run in sequence, while all jobs in a stage can run in parallel.
- Define [CI/CD variables](../variables/_index.md) for flexible configuration.
- Define [caches](../caching/_index.md) to speed up job execution.
- Save files as [artifacts](job_artifacts.md) which can be used by other jobs.
## Add a job to a pipeline
To add a job to a pipeline, add it into your `.gitlab-ci.yml` file. The job must:
- Be defined at the top-level of the YAML configuration.
- Have a unique [job name](#job-names).
- Have either a [`script`](../yaml/_index.md#script) section defining commands to run,
or a [`trigger`](../yaml/_index.md#trigger) section to trigger a [downstream pipeline](../pipelines/downstream_pipelines.md)
to run.
For example:
```yaml
my-ruby-job:
script:
- bundle install
- bundle exec my_ruby_command
my-shell-script-job:
script:
- my_shell_script.sh
```
### Job names
You can't use these keywords as job names:
- `image`
- `services`
- `stages`
- `before_script`
- `after_script`
- `variables`
- `cache`
- `include`
- `pages:deploy` configured for a `deploy` stage
Additionally, these names are valid when quoted, but are
not recommended as they can make pipeline configuration unclear:
- `"true":`
- `"false":`
- `"nil":`
Job names must be 255 characters or fewer.
Use unique names for your jobs. If multiple jobs have the same name in a file,
only one is added to the pipeline, and it's difficult to predict which one is chosen.
If the same job name is used in one or more included files,
[parameters are merged](../yaml/includes.md#override-included-configuration-values).
### Hide a job
To temporarily disable a job without deleting it from the configuration
file, add a period (`.`) to the start of the job name. Hidden jobs do not need to contain
the `script` or `trigger` keywords, but must contain valid YAML configuration.
For example:
```yaml
.hidden_job:
script:
- run test
```
Hidden jobs are not processed by GitLab CI/CD, but they can be used as templates
for reusable configuration with:
- The [`extends` keyword](../yaml/yaml_optimization.md#use-extends-to-reuse-configuration-sections).
- [YAML anchors](../yaml/yaml_optimization.md#anchors).
## Set default values for job keywords
You can use the `default` keyword to set default job keywords and values, which are
used by default by all jobs in a pipeline.
For example:
```yaml
default:
image: 'ruby:2.4'
before_script:
- echo Hello World
rspec-job:
script: bundle exec rspec
```
When the pipeline runs, the job uses the default keywords:
```yaml
rspec-job:
image: 'ruby:2.4'
before_script:
- echo Hello World
script: bundle exec rspec
```
### Control the inheritance of default keywords and variables
You can control the inheritance of:
- [default keywords](../yaml/_index.md#default) with [`inherit:default`](../yaml/_index.md#inheritdefault).
- [default variables](../yaml/_index.md#default) with [`inherit:variables`](../yaml/_index.md#inheritvariables).
For example:
```yaml
default:
image: 'ruby:2.4'
before_script:
- echo Hello World
variables:
DOMAIN: example.com
WEBHOOK_URL: https://my-webhook.example.com
rubocop:
inherit:
default: false
variables: false
script: bundle exec rubocop
rspec:
inherit:
default: [image]
variables: [WEBHOOK_URL]
script: bundle exec rspec
capybara:
inherit:
variables: false
script: bundle exec capybara
karma:
inherit:
default: true
variables: [DOMAIN]
script: karma
```
In this example:
- `rubocop`:
- inherits: Nothing.
- `rspec`:
- inherits: the default `image` and the `WEBHOOK_URL` variable.
- does **not** inherit: the default `before_script` and the `DOMAIN` variable.
- `capybara`:
- inherits: the default `before_script` and `image`.
- does **not** inherit: the `DOMAIN` and `WEBHOOK_URL` variables.
- `karma`:
- inherits: the default `image` and `before_script`, and the `DOMAIN` variable.
- does **not** inherit: `WEBHOOK_URL` variable.
## View jobs in a pipeline
When you access a pipeline, you can see the related jobs for that pipeline.
The order of jobs in a pipeline depends on the type of pipeline graph.
- For [full pipeline graphs](../pipelines/_index.md#pipeline-details), jobs are sorted alphabetically by name.
- For [pipeline mini graphs](../pipelines/_index.md#pipeline-mini-graphs), jobs are sorted by status severity
with failed jobs appearing first, and then alphabetically by name.
Selecting an individual job shows you its [job log](job_logs.md), and allows you to:
- Cancel the job.
- Retry the job, if it failed.
- Run the job again, if it passed.
- Erase the job log.
### View all jobs in a project
{{< details >}}
- Offering: GitLab.com, GitLab Self-Managed
{{< /details >}}
{{< history >}}
- Filtering jobs by job name [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/387547) as an [experiment](../../policy/development_stages_support.md) on GitLab.com and GitLab Self-Managed in GitLab 17.3 [with flags](../../administration/feature_flags/_index.md) named `populate_and_use_build_names_table` for the API and `fe_search_build_by_name` for the UI. Disabled by default.
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag. For more information, see the history.
{{< /alert >}}
Filtering jobs by name is an [experiment](../../policy/development_stages_support.md). For more information about the development of this feature, see [issue 387547](https://gitlab.com/gitlab-org/gitlab/-/issues/387547).
To view the full list of jobs that ran in a project:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Jobs**.
You can filter the list by [job name](#job-names), [job status](#available-job-statuses), and [job source](#available-job-sources).
### Available job statuses
CI/CD jobs can have the following statuses:
- `canceled`: Job was manually canceled or automatically aborted.
- `canceling`: Job is being canceled but `after_script` is running.
- `created`: Job has been created but not yet processed.
- `failed`: Job execution failed.
- `manual`: Job requires manual action to start.
- `pending`: Job is in the queue waiting for a runner.
- `preparing`: Runner is preparing the execution environment.
- `running`: Job is executing on a runner.
- `scheduled`: Job has been scheduled but execution hasn't started.
- `skipped`: Job was skipped due to conditions or dependencies.
- `success`: Job completed successfully.
- `waiting_for_resource`: Job is waiting for resources to become available.
### View the source of a job
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/181159) job source in GitLab 17.9 [with a flag](../../administration/feature_flags/_index.md) named `populate_and_use_build_source_table`. Enabled by default.
- [Generally available](https://gitlab.com/groups/gitlab-org/-/epics/11796) on GitLab.com, GitLab Self-Managed, and GitLab Dedicated in GitLab 17.11.
{{< /history >}}
GitLab CI/CD jobs now include a source attribute that indicates the action that initially triggered a CI/CD job.
Use this attribute to track how a job was initiated or filter job runs based on the specific sources.
#### Available job sources
The source attribute can have the following values:
- `api`: Job initiated by a REST call to the Jobs API.
- `chat`: Job initiated by a chat command using GitLab ChatOps.
- `container_registry_push`: Job initiated by container registry push.
- `duo_workflow`: Job initiated by GitLab Duo Agent Platform.
- `external`: Job initiated by an event in an external repository integrated with GitLab. This does not include pull request events.
- `external_pull_request_event`: Job initiated by a pull request event in an external repository.
- `merge_request_event`: Job initiated by a merge request event.
- `ondemand_dast_scan`:Job initiated by an on-demand DAST scan.
- `ondemand_dast_validation`: Job initiated by an on-demand DAST validation.
- `parent_pipeline`: Job initiated by a parent pipeline
- `pipeline`: Job initiated by a user manually running a pipeline.
- `pipeline_execution_policy`: Job initiated by a triggered pipeline execution policy.
- `pipeline_execution_policy_schedule`: Job initiated by a scheduled pipeline execution policy.
- `push`: Job initiated by a code push.
- `scan_execution_policy`: Job initiated by a scan execution policy.
- `schedule`: Job initiated by a scheduled pipeline.
- `security_orchestration_policy`: Job initiated by a scheduled scan execution policy.
- `trigger`: Job initiated by another job or pipeline.
- `unknown`: Job initiated by an unknown source.
- `web`: Job initiated by a user from the GitLab UI.
- `webide`: Job initiated by a user from the Web IDE.
### Group similar jobs together in pipeline views
If you have many similar jobs, your [pipeline graph](../pipelines/_index.md#pipeline-details)
becomes long and hard to read.
You can automatically group similar jobs together. If the job names are formatted in a certain way,
they are collapsed into a single group in regular pipeline graphs (not the mini graphs).
You can recognize when a pipeline has grouped jobs if you see a number next to a job
name instead of the retry or cancel buttons. The number indicates the amount of grouped
jobs. Hovering over them shows you if all jobs have passed or any has failed. Select to expand them.

To create a group of jobs, in the `.gitlab-ci.yml` file,
separate each job name with a number and one of the following:
- A slash (`/`), for example, `slash-test 1/3`, `slash-test 2/3`, `slash-test 3/3`.
- A colon (`:`), for example, `colon-test 1:3`, `colon-test 2:3`, `colon-test 3:3`.
- A space, for example `space-test 0 3`, `space-test 1 3`, `space-test 2 3`.
You can use these symbols interchangeably.
In the following example, these three jobs are in a group named `build ruby`:
```yaml
build ruby 1/3:
stage: build
script:
- echo "ruby1"
build ruby 2/3:
stage: build
script:
- echo "ruby2"
build ruby 3/3:
stage: build
script:
- echo "ruby3"
```
The pipeline graph displays a group named `build ruby` with three jobs.
The jobs are ordered by comparing the numbers from left to right. You
usually want the first number to be the index and the second number to be the total.
[This regular expression](https://gitlab.com/gitlab-org/gitlab/-/blob/2f3dc314f42dbd79813e6251792853bc231e69dd/app/models/commit_status.rb#L99)
evaluates the job names: `([\b\s:]+((\[.*\])|(\d+[\s:\/\\]+\d+))){1,3}\s*\z`.
One or more `: [...]`, `X Y`, `X/Y`, or `X\Y` sequences are removed from the **end**
of job names only. Matching substrings found at the beginning or in the middle of
job names are not removed.
## Retry jobs
You can retry a job after it completes, regardless of its final state (failed, success, or canceled).
When you retry a job:
- A new job instance is created with a new job ID.
- The job runs with the same parameters and variables as the original job.
- If the job produces artifacts, new artifacts are created and stored.
- The new job associates with the user who initiated the retry, not the user who created the original pipeline.
- Any subsequent jobs that were previously skipped are reassigned to the user who initiated the retry.
When you retry a [trigger job](../yaml/_index.md#trigger) that triggers a downstream pipeline:
- The trigger job generates a new downstream pipeline.
- The downstream pipeline also associates with the user who initiated the retry.
- The downstream pipeline runs with the configuration that exists at the time of the retry,
which might be different from the original run.
### Retry a job
Prerequisites:
- You must have at least the Developer role for the project.
- The job must not be [archived](../../administration/settings/continuous_integration.md#archive-pipelines).
To retry a job from a merge request:
1. On the left sidebar, select **Search or go to** and find your project.
1. From your merge request, do one of the following:
- In the pipeline widget, next to the job you want to retry, select **Run again** ({{< icon name="retry" >}}).
- Select the **Pipelines** tab, next to the job you want to retry, select **Run again** ({{< icon name="retry" >}}).
To retry a job from the job log:
1. Go to the job's log page.
1. In the upper-right corner, select **Run again** ({{< icon name="retry" >}}).
To retry a job from a pipeline:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipelines**.
1. Find the pipeline that contains the job you want to retry.
1. From the pipeline graph, next to the job you want to retry, select **Run again** ({{< icon name="retry" >}}).
### Retry all failed or canceled jobs in a pipeline
If a pipeline has multiple failed or canceled jobs, you can retry all of them at once:
1. On the left sidebar, select **Search or go to** and find your project.
1. Do one of the following:
- Select **Build > Pipelines**.
- Go to a merge request and select the **Pipelines** tab.
1. For the pipeline with failed or canceled jobs, select **Retry all failed or canceled jobs** ({{< icon name="retry" >}}).
## Cancel jobs
You can cancel a CI/CD job that hasn't completed yet.
When you cancel a job, what happens next depends on its state and the GitLab Runner version:
- For jobs that haven't started executing yet, the job is canceled immediately.
- For running jobs:
- For GitLab Runner 16.10 and later with GitLab 17.0 and later, the job is marked as `canceling` while the runner runs the job's [`after_script`](../yaml/_index.md#after_script).
When `after_script` completes, the job is marked as `canceled`.
- For GitLab Runner 16.9 and earlier with GitLab 16.11 and earlier, the job is `canceled` immediately without running `after_script`.
```mermaid
%%{init: { "fontFamily": "GitLab Sans" }}%%
stateDiagram-v2
accTitle: CI/CD job state transitions
accDescr: Shows possible state transitions for CI/CD jobs, including cancellation paths.
direction TB
state if_versions <>
[*] --> pending: Job created
pending --> canceled: Cancel requested
canceled --> [*]
pending --> running: Runner picks up job
running --> success: Job succeeds
success --> [*]
running --> failed: Job fails
failed --> [*]
running --> if_versions: Cancel requested
if_versions --> canceling: GitLab 17.0 and later with GitLab Runner 16.10 and later
if_versions --> canceled: GitLab 16.11 and earlier with GitLab Runner 16.9 and earlier
canceling --> canceled: after_script complete
```
If you need to cancel a job immediately without waiting for the `after_script`, use [force cancel](#force-cancel-a-job).
### Cancel a job
Prerequisites:
- You must have at least the Developer role for the project,
or the [minimum role required to cancel a pipeline or job](../pipelines/settings.md#restrict-roles-that-can-cancel-pipelines-or-jobs).
To cancel a job from a merge request:
1. On the left sidebar, select **Search or go to** and find your project.
1. From your merge request, do one of the following:
- In the pipeline widget, next to the job you want to cancel, select **Cancel** ({{< icon name="cancel" >}}).
- Select the **Pipelines** tab, next to the job you want to cancel, select **Cancel** ({{< icon name="cancel" >}}).
To cancel a job from the job log:
1. Go to the job's log page.
1. In the upper-right corner, select **Cancel** ({{< icon name="cancel" >}}).
To cancel a job from a pipeline:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipelines**.
1. Find the pipeline that contains the job you want to cancel.
1. From the pipeline graph, next to the job you want to cancel, select **Cancel** ({{< icon name="cancel" >}}).
### Cancel all running jobs in a pipeline
You can cancel all jobs in a running pipeline at once.
1. On the left sidebar, select **Search or go to** and find your project.
1. Do one of the following:
- Select **Build > Pipelines**.
- Go to a merge request and select the **Pipelines** tab.
1. For the pipeline you want to cancel, select **Cancel the running pipeline** ({{< icon name="cancel" >}}).
### Force cancel a job
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/467107) as an [experiment](../../policy/development_stages_support.md) in GitLab 17.10 [with a flag](../../administration/feature_flags/_index.md) named `force_cancel_build`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/519313) in GitLab 17.11. Feature flag `force_cancel_build` removed.
{{< /history >}}
If you don't want to wait for `after_script` to finish or a job is unresponsive, you can force cancel it.
Force cancel immediately moves a job from the `canceling` state to `canceled`.
When you force cancel a job, the [job token](ci_job_token.md) is immediately revoked.
If the runner is still executing the job, it loses access to GitLab.
The runner aborts the job without waiting for `after_script` to complete.
Prerequisites:
- You must have at least the Maintainer role for the project.
- The job must be in the `canceling` state, which requires:
- GitLab 17.0 and later.
- GitLab Runner 16.10 and later.
To force cancel a job:
1. Go to the job's log page.
1. In the upper-right corner, select **Force cancel**.
## Troubleshoot a failed job
When a pipeline fails or is allowed to fail, there are several places where you
can find the reason:
- In the [pipeline graph](../pipelines/_index.md#pipeline-details), in the pipeline details view.
- In the pipeline widgets, in the merge requests and commit pages.
- In the job views, in the global and detailed views of a job.
In each place, if you hover over the failed job you can see the reason it failed.

You can also see the reason it failed on the Job detail page.
### With Root Cause Analysis
You can use GitLab Duo Root Cause Analysis in GitLab Duo Chat to [troubleshoot failed CI/CD jobs](../../user/gitlab_duo_chat/examples.md#troubleshoot-failed-cicd-jobs-with-root-cause-analysis).
## Deployment jobs
Deployment jobs are CI/CD jobs that use [environments](../environments/_index.md).
A deployment job is any job that uses the `environment` keyword and the [`start` environment `action`](../yaml/_index.md#environmentaction).
Deployment jobs do not need to be in the `deploy` stage. The following `deploy me`
job is an example of a deployment job. `action: start` is the default behavior and
is defined here for clarity, but you can omit it:
```yaml
deploy me:
script:
- deploy-to-cats.sh
environment:
name: production
url: https://cats.example.com
action: start
```
The behavior of deployment jobs can be controlled with
[deployment safety](../environments/deployment_safety.md) settings like
[preventing outdated deployment jobs](../environments/deployment_safety.md#prevent-outdated-deployment-jobs)
and [ensuring only one deployment job runs at a time](../environments/deployment_safety.md#ensure-only-one-deployment-job-runs-at-a-time).
|
https://docs.gitlab.com/ci/job_logs
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/job_logs.md
|
2025-08-13
|
doc/ci/jobs
|
[
"doc",
"ci",
"jobs"
] |
job_logs.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
CI/CD job logs
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
A job log displays the full execution history of a [CI/CD job](_index.md).
## View job logs
To view job logs:
1. Select the project for which you want to view job logs.
1. On the left sidebar, select **CI/CD > Pipelines**.
1. Select the pipeline you want to inspect.
1. In the pipeline view, in the list of jobs, select a job to view the job logs page.
To view detailed information about the job and its log output, scroll through the job logs page.
## View job logs in full screen mode
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/363617) in GitLab 16.7.
{{< /history >}}
You can view the contents of a job log in full screen mode by clicking **Show full screen**.
To use full screen mode, your web browser must also support it. If your web browser does not support full screen mode, then the option is not available.
## Expand and collapse job log sections
{{< history >}}
- Support for output of multi-line command bash shell output [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3486) in GitLab 16.5 behind the [GitLab Runner feature flag](https://docs.gitlab.com/runner/configuration/feature-flags.html), `FF_SCRIPT_SECTIONS`.
{{< /history >}}
Job logs are divided into sections that can be collapsed or expanded. Each section displays
the duration.
In the following example:
- Three sections have been collapsed and can be expanded.
- Three sections are expanded and can be collapsed.

### Custom collapsible sections
You can create [collapsible sections in job logs](#expand-and-collapse-job-log-sections)
by manually outputting special codes
that GitLab uses to delimit collapsible sections:
- Section start marker: `\e[0Ksection_start:UNIX_TIMESTAMP:SECTION_NAME\r\e[0K` + `TEXT_OF_SECTION_HEADER`
- Section end marker: `\e[0Ksection_end:UNIX_TIMESTAMP:SECTION_NAME\r\e[0K`
You must add these codes to the script section of the CI configuration.
For example, using `echo`:
```yaml
job1:
script:
- echo -e "\e[0Ksection_start:`date +%s`:my_first_section\r\e[0KHeader of the 1st collapsible section"
- echo 'this line should be hidden when collapsed'
- echo -e "\e[0Ksection_end:`date +%s`:my_first_section\r\e[0K"
```
The escape syntax may differ depending on the shell that your runner uses.
For example if it is using Zsh, you may need to escape the special characters
with `\\e` or `\\r`.
In the example above:
- `date +%s`: Command that produces the Unix timestamp (for example `1560896352`).
- `my_first_section`: The name given to the section. The name can only be composed
of letters, numbers, and the `_`, `.`, or `-` characters.
- `\r\e[0K`: Escape sequence that prevents the section markers from displaying in the
rendered (colored) job log. They are displayed when viewing the raw job log, accessed
in the upper-right corner of the job log by selecting **Show complete raw** ({{< icon name="doc-text" >}}).
- `\r`: carriage return (returns the cursor to the start of the line).
- `\e[0K`: ANSI escape code to clear the line from the cursor position to the end of the line.
(`\e[K` alone does not work; the `0` must be included).
Sample raw job log:
```plaintext
\e[0Ksection_start:1560896352:my_first_section\r\e[0KHeader of the 1st collapsible section
this line should be hidden when collapsed
\e[0Ksection_end:1560896353:my_first_section\r\e[0K
```
Sample job console log:

#### Use a script to improve display of collapsible sections
To remove the `echo` statements that create the section markers from the job output,
you can move the job contents to a script file and invoke it from the job:
1. Create a script that can handle the section headers. For example:
```shell
# function for starting the section
function section_start () {
local section_title="${1}"
local section_description="${2:-$section_title}"
echo -e "section_start:`date +%s`:${section_title}[collapsed=true]\r\e[0K${section_description}"
}
# Function for ending the section
function section_end () {
local section_title="${1}"
echo -e "section_end:`date +%s`:${section_title}\r\e[0K"
}
# Create sections
section_start "my_first_section" "Header of the 1st collapsible section"
echo "this line should be hidden when collapsed"
section_end "my_first_section"
# Repeat as required
```
1. Add the script to the `.gitlab-ci.yml` file:
```yaml
job:
script:
- source script.sh
```
### Pre-collapse sections
You can make the job log automatically collapse collapsible sections by adding the `collapsed` option to the section start.
Add `[collapsed=true]` after the section name and before the `\r`. The section end marker
remains unchanged:
- Section start marker with `[collapsed=true]`: `\e[0Ksection_start:UNIX_TIMESTAMP:SECTION_NAME[collapsed=true]\r\e[0K` + `TEXT_OF_SECTION_HEADER`
- Section end marker (unchanged): `\e[0Ksection_end:UNIX_TIMESTAMP:SECTION_NAME\r\e[0K`
Add the updated section start text to the CI configuration. For example,
using `echo`:
```yaml
job1:
script:
- echo -e "\e[0Ksection_start:`date +%s`:my_first_section[collapsed=true]\r\e[0KHeader of the 1st collapsible section"
- echo 'this line should be hidden automatically after loading the job log'
- echo -e "\e[0Ksection_end:`date +%s`:my_first_section\r\e[0K"
```
## Delete job logs
When you delete a job log you also [erase the entire job](../../api/jobs.md#erase-a-job).
For more details, see [Delete job logs](../../user/storage_management_automation.md#delete-job-logs).
## Job log timestamps
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/455582) in GitLab 17.1 [with a flag](../../administration/feature_flags/_index.md) named `parse_ci_job_timestamps`. Disabled by default.
- Feature flag `parse_ci_job_timestamps` [removed](https://gitlab.com/gitlab-org/gitlab/-/issues/464785) in GitLab 17.2.
{{< /history >}}
You can generate a timestamp in the [ISO 8601 format](https://www.iso.org/iso-8601-date-and-time-format.html)
for each line in a CI/CD job log. With job log timestamps, you can identify the duration
of a specific section in the job. By default, job logs do not include a timestamp for each log line.
When timestamps are enabled, the job log uses approximately 10% more storage space.
Prerequisites:
- You must be on GitLab Runner 17.0 or later.
To enable timestamps in job logs, add a `FF_TIMESTAMPS` [CI/CD variable](../runners/configure_runners.md#configure-runner-behavior-with-variables)
to your pipeline and set it to `true`.
For example, [add the variable to your `.gitlab-ci.yml` file](../variables/_index.md#define-a-cicd-variable-in-the-gitlab-ciyml-file):
```yaml
variables:
FF_TIMESTAMPS: true
job:
script:
- echo "This job's log has ISO 8601 timestamps!"
```
Here's an example log output with `FF_TIMESTAMPS` enabled:

To provide feedback on this feature, leave a comment on [issue 463391](https://gitlab.com/gitlab-org/gitlab/-/issues/463391).
## Troubleshooting
### Job log slow to update
When you visit the job log page for a running job, there could be a delay of up to
60 seconds before a log update. The default refresh time is 60 seconds, but after
the log is viewed in the UI one time, log updates should occur every 3 seconds.
### Error: `This job does not have a trace` in GitLab 18.0 or later
After upgrading a GitLab Self-Managed instance to 18.0 or later, you might see
`This job does not have a trace` errors. This could be caused by a failed upgrade migration
on an instance with both:
- Object storage enabled
- Incremental logging previously enabled with the removed feature flag `ci_enable_live_trace`.
This feature flag is enabled by default in GitLab Environment Toolkit or Helm Chart deployments,
but could also be enabled manually.
To restore the ability to view job logs on affected jobs,
[re-enable incremental logging](../../administration/settings/continuous_integration.md#configure-incremental-logging)
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: CI/CD job logs
breadcrumbs:
- doc
- ci
- jobs
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
A job log displays the full execution history of a [CI/CD job](_index.md).
## View job logs
To view job logs:
1. Select the project for which you want to view job logs.
1. On the left sidebar, select **CI/CD > Pipelines**.
1. Select the pipeline you want to inspect.
1. In the pipeline view, in the list of jobs, select a job to view the job logs page.
To view detailed information about the job and its log output, scroll through the job logs page.
## View job logs in full screen mode
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/363617) in GitLab 16.7.
{{< /history >}}
You can view the contents of a job log in full screen mode by clicking **Show full screen**.
To use full screen mode, your web browser must also support it. If your web browser does not support full screen mode, then the option is not available.
## Expand and collapse job log sections
{{< history >}}
- Support for output of multi-line command bash shell output [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/3486) in GitLab 16.5 behind the [GitLab Runner feature flag](https://docs.gitlab.com/runner/configuration/feature-flags.html), `FF_SCRIPT_SECTIONS`.
{{< /history >}}
Job logs are divided into sections that can be collapsed or expanded. Each section displays
the duration.
In the following example:
- Three sections have been collapsed and can be expanded.
- Three sections are expanded and can be collapsed.

### Custom collapsible sections
You can create [collapsible sections in job logs](#expand-and-collapse-job-log-sections)
by manually outputting special codes
that GitLab uses to delimit collapsible sections:
- Section start marker: `\e[0Ksection_start:UNIX_TIMESTAMP:SECTION_NAME\r\e[0K` + `TEXT_OF_SECTION_HEADER`
- Section end marker: `\e[0Ksection_end:UNIX_TIMESTAMP:SECTION_NAME\r\e[0K`
You must add these codes to the script section of the CI configuration.
For example, using `echo`:
```yaml
job1:
script:
- echo -e "\e[0Ksection_start:`date +%s`:my_first_section\r\e[0KHeader of the 1st collapsible section"
- echo 'this line should be hidden when collapsed'
- echo -e "\e[0Ksection_end:`date +%s`:my_first_section\r\e[0K"
```
The escape syntax may differ depending on the shell that your runner uses.
For example if it is using Zsh, you may need to escape the special characters
with `\\e` or `\\r`.
In the example above:
- `date +%s`: Command that produces the Unix timestamp (for example `1560896352`).
- `my_first_section`: The name given to the section. The name can only be composed
of letters, numbers, and the `_`, `.`, or `-` characters.
- `\r\e[0K`: Escape sequence that prevents the section markers from displaying in the
rendered (colored) job log. They are displayed when viewing the raw job log, accessed
in the upper-right corner of the job log by selecting **Show complete raw** ({{< icon name="doc-text" >}}).
- `\r`: carriage return (returns the cursor to the start of the line).
- `\e[0K`: ANSI escape code to clear the line from the cursor position to the end of the line.
(`\e[K` alone does not work; the `0` must be included).
Sample raw job log:
```plaintext
\e[0Ksection_start:1560896352:my_first_section\r\e[0KHeader of the 1st collapsible section
this line should be hidden when collapsed
\e[0Ksection_end:1560896353:my_first_section\r\e[0K
```
Sample job console log:

#### Use a script to improve display of collapsible sections
To remove the `echo` statements that create the section markers from the job output,
you can move the job contents to a script file and invoke it from the job:
1. Create a script that can handle the section headers. For example:
```shell
# function for starting the section
function section_start () {
local section_title="${1}"
local section_description="${2:-$section_title}"
echo -e "section_start:`date +%s`:${section_title}[collapsed=true]\r\e[0K${section_description}"
}
# Function for ending the section
function section_end () {
local section_title="${1}"
echo -e "section_end:`date +%s`:${section_title}\r\e[0K"
}
# Create sections
section_start "my_first_section" "Header of the 1st collapsible section"
echo "this line should be hidden when collapsed"
section_end "my_first_section"
# Repeat as required
```
1. Add the script to the `.gitlab-ci.yml` file:
```yaml
job:
script:
- source script.sh
```
### Pre-collapse sections
You can make the job log automatically collapse collapsible sections by adding the `collapsed` option to the section start.
Add `[collapsed=true]` after the section name and before the `\r`. The section end marker
remains unchanged:
- Section start marker with `[collapsed=true]`: `\e[0Ksection_start:UNIX_TIMESTAMP:SECTION_NAME[collapsed=true]\r\e[0K` + `TEXT_OF_SECTION_HEADER`
- Section end marker (unchanged): `\e[0Ksection_end:UNIX_TIMESTAMP:SECTION_NAME\r\e[0K`
Add the updated section start text to the CI configuration. For example,
using `echo`:
```yaml
job1:
script:
- echo -e "\e[0Ksection_start:`date +%s`:my_first_section[collapsed=true]\r\e[0KHeader of the 1st collapsible section"
- echo 'this line should be hidden automatically after loading the job log'
- echo -e "\e[0Ksection_end:`date +%s`:my_first_section\r\e[0K"
```
## Delete job logs
When you delete a job log you also [erase the entire job](../../api/jobs.md#erase-a-job).
For more details, see [Delete job logs](../../user/storage_management_automation.md#delete-job-logs).
## Job log timestamps
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/455582) in GitLab 17.1 [with a flag](../../administration/feature_flags/_index.md) named `parse_ci_job_timestamps`. Disabled by default.
- Feature flag `parse_ci_job_timestamps` [removed](https://gitlab.com/gitlab-org/gitlab/-/issues/464785) in GitLab 17.2.
{{< /history >}}
You can generate a timestamp in the [ISO 8601 format](https://www.iso.org/iso-8601-date-and-time-format.html)
for each line in a CI/CD job log. With job log timestamps, you can identify the duration
of a specific section in the job. By default, job logs do not include a timestamp for each log line.
When timestamps are enabled, the job log uses approximately 10% more storage space.
Prerequisites:
- You must be on GitLab Runner 17.0 or later.
To enable timestamps in job logs, add a `FF_TIMESTAMPS` [CI/CD variable](../runners/configure_runners.md#configure-runner-behavior-with-variables)
to your pipeline and set it to `true`.
For example, [add the variable to your `.gitlab-ci.yml` file](../variables/_index.md#define-a-cicd-variable-in-the-gitlab-ciyml-file):
```yaml
variables:
FF_TIMESTAMPS: true
job:
script:
- echo "This job's log has ISO 8601 timestamps!"
```
Here's an example log output with `FF_TIMESTAMPS` enabled:

To provide feedback on this feature, leave a comment on [issue 463391](https://gitlab.com/gitlab-org/gitlab/-/issues/463391).
## Troubleshooting
### Job log slow to update
When you visit the job log page for a running job, there could be a delay of up to
60 seconds before a log update. The default refresh time is 60 seconds, but after
the log is viewed in the UI one time, log updates should occur every 3 seconds.
### Error: `This job does not have a trace` in GitLab 18.0 or later
After upgrading a GitLab Self-Managed instance to 18.0 or later, you might see
`This job does not have a trace` errors. This could be caused by a failed upgrade migration
on an instance with both:
- Object storage enabled
- Incremental logging previously enabled with the removed feature flag `ci_enable_live_trace`.
This feature flag is enabled by default in GitLab Environment Toolkit or Helm Chart deployments,
but could also be enabled manually.
To restore the ability to view job logs on affected jobs,
[re-enable incremental logging](../../administration/settings/continuous_integration.md#configure-incremental-logging)
|
https://docs.gitlab.com/ci/job_troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/job_troubleshooting.md
|
2025-08-13
|
doc/ci/jobs
|
[
"doc",
"ci",
"jobs"
] |
job_troubleshooting.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting jobs
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
When working with jobs, you might encounter the following issues.
## Jobs or pipelines run unexpectedly when using `changes:`
You might have jobs or pipelines that run unexpectedly when using [`rules: changes`](../yaml/_index.md#ruleschanges)
or [`only: changes`](../yaml/deprecated_keywords.md#onlychanges--exceptchanges) without
[merge request pipelines](../pipelines/merge_request_pipelines.md).
Pipelines on branches or tags that don't have an explicit association with a merge request
use a previous SHA to calculate the diff. This calculation is equivalent to `git diff HEAD~`
and can cause unexpected behavior, including:
- The `changes` rule always evaluates to true when pushing a new branch or a new tag to GitLab.
- When pushing a new commit, the changed files are calculated by using the previous commit
as the base SHA.
Additionally, rules with `changes` always evaluate as true in [scheduled pipelines](../pipelines/schedules.md).
All files are considered to have changed when a scheduled pipeline runs, so jobs
might always be added to scheduled pipelines that use `changes`.
## File paths in CI/CD variables
Be careful when using file paths in CI/CD variables. A trailing slash can appear correct
in the variable definition, but can become invalid when expanded in `script:`, `changes:`,
or other keywords. For example:
```yaml
docker_build:
variables:
DOCKERFILES_DIR: 'path/to/files/' # This variable should not have a trailing '/' character
script: echo "A docker job"
rules:
- changes:
- $DOCKERFILES_DIR/*
```
When the `DOCKERFILES_DIR` variable is expanded in the `changes:` section, the full
path becomes `path/to/files//*`. The double slashes might cause unexpected behavior
depending on factors like the keyword used, or the shell and OS of the runner.
## `You are not allowed to download code from this project.` error message
You might see pipelines fail when a GitLab administrator runs a protected manual job
in a private project.
CI/CD jobs usually clone the project when the job starts, and this uses [the permissions](../../user/permissions.md#cicd)
of the user that runs the job. All users, including administrators, must be direct members
of a private project to clone the source of that project. [An issue exists](https://gitlab.com/gitlab-org/gitlab/-/issues/23130)
to change this behavior.
To run protected manual jobs:
- Add the administrator as a direct member of the private project (any role)
- [Impersonate a user](../../administration/admin_area.md#user-impersonation) who is a
direct member of the project.
## A CI/CD job does not use newer configuration when run again
The configuration for a pipeline is only fetched when the pipeline is created.
When you rerun a job, uses the same configuration each time. If you update configuration files,
including separate files added with [`include`](../yaml/_index.md#include), you must
start a new pipeline to use the new configuration.
## `Job may allow multiple pipelines to run for a single action` warning
When you use [`rules`](../yaml/_index.md#rules) with a `when` clause without an `if`
clause, multiple pipelines may run. Usually this occurs when you push a commit to
a branch that has an open merge request associated with it.
To [prevent duplicate pipelines](job_rules.md#avoid-duplicate-pipelines), use
[`workflow: rules`](../yaml/_index.md#workflow) or rewrite your rules to control
which pipelines can run.
## `This GitLab CI configuration is invalid` for variable expressions
You might receive one of several `This GitLab CI configuration is invalid` errors
when working with [CI/CD variable expressions](job_rules.md#cicd-variable-expressions).
These syntax errors can be caused by incorrect usage of quote characters.
In variable expressions, strings should be quoted, while variables should not be quoted.
For example:
```yaml
variables:
ENVIRONMENT: production
job:
script: echo
rules:
- if: $ENVIRONMENT == "production"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
In this example, both `if:` clauses are valid because the `production` string is quoted,
and the CI/CD variables are unquoted.
On the other hand, these `if:` clauses are all invalid:
```yaml
variables:
ENVIRONMENT: production
job:
script: echo
rules: # These rules all cause YAML syntax errors:
- if: ${ENVIRONMENT} == "production"
- if: "$ENVIRONMENT" == "production"
- if: $ENVIRONMENT == production
- if: "production" == "production"
```
In this example:
- `if: ${ENVIRONMENT} == "production"` is invalid, because `${ENVIRONMENT}` is not valid
formatting for CI/CD variables in `if:`.
- `if: "$ENVIRONMENT" == "production"` is invalid, because the variable is quoted.
- `if: $ENVIRONMENT == production` is invalid, because the string is not quoted.
- `if: "production" == "production"` is invalid, because there is no CI/CD variable to compare.
## `get_sources` job section fails because of an HTTP/2 problem
Sometimes, jobs fail with the following cURL error:
```plaintext
++ git -c 'http.userAgent=gitlab-runner <version>' fetch origin +refs/pipelines/<id>:refs/pipelines/<id> ...
error: RPC failed; curl 16 HTTP/2 send again with decreased length
fatal: ...
```
You can work around this problem by configuring Git and `libcurl` to
[use HTTP/1.1](https://git-scm.com/docs/git-config#Documentation/git-config.txt-httpversion).
The configuration can be added to:
- A job's [`pre_get_sources_script`](../yaml/_index.md#hookspre_get_sources_script):
```yaml
job_name:
hooks:
pre_get_sources_script:
- git config --global http.version "HTTP/1.1"
```
- The [runner's `config.toml`](https://docs.gitlab.com/runner/configuration/advanced-configuration.html)
with [Git configuration environment variables](https://git-scm.com/docs/git-config#ENVIRONMENT):
```toml
[[runners]]
...
environment = [
"GIT_CONFIG_COUNT=1",
"GIT_CONFIG_KEY_0=http.version",
"GIT_CONFIG_VALUE_0=HTTP/1.1"
]
```
## Job using `resource_group` gets stuck
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
If a job using [`resource_group`](../yaml/_index.md#resource_group) gets stuck, a
GitLab administrator can try run the following commands from the [rails console](../../administration/operations/rails_console.md#starting-a-rails-console-session):
```ruby
# find resource group by name
resource_group = Project.find_by_full_path('...').resource_groups.find_by(key: 'the-group-name')
busy_resources = resource_group.resources.where('build_id IS NOT NULL')
# identify which builds are occupying the resource
# (I think it should be 1 as of today)
busy_resources.pluck(:build_id)
# it's good to check why this build is holding the resource.
# Is it stuck? Has it been forcefully dropped by the system?
# free up busy resources
busy_resources.update_all(build_id: nil)
```
## `You are not authorized to run this manual job` message
You can receive this message and have a disabled **Run** button when trying to run a manual job if:
- The target environment is a [protected environment](../environments/protected_environments.md)
and your account is not included in the **Allowed to deploy** list.
- The setting to [prevent outdated deployment jobs](../environments/deployment_safety.md#prevent-outdated-deployment-jobs)
is enabled and running the job would overwrite the latest deployment.
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting jobs
breadcrumbs:
- doc
- ci
- jobs
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
When working with jobs, you might encounter the following issues.
## Jobs or pipelines run unexpectedly when using `changes:`
You might have jobs or pipelines that run unexpectedly when using [`rules: changes`](../yaml/_index.md#ruleschanges)
or [`only: changes`](../yaml/deprecated_keywords.md#onlychanges--exceptchanges) without
[merge request pipelines](../pipelines/merge_request_pipelines.md).
Pipelines on branches or tags that don't have an explicit association with a merge request
use a previous SHA to calculate the diff. This calculation is equivalent to `git diff HEAD~`
and can cause unexpected behavior, including:
- The `changes` rule always evaluates to true when pushing a new branch or a new tag to GitLab.
- When pushing a new commit, the changed files are calculated by using the previous commit
as the base SHA.
Additionally, rules with `changes` always evaluate as true in [scheduled pipelines](../pipelines/schedules.md).
All files are considered to have changed when a scheduled pipeline runs, so jobs
might always be added to scheduled pipelines that use `changes`.
## File paths in CI/CD variables
Be careful when using file paths in CI/CD variables. A trailing slash can appear correct
in the variable definition, but can become invalid when expanded in `script:`, `changes:`,
or other keywords. For example:
```yaml
docker_build:
variables:
DOCKERFILES_DIR: 'path/to/files/' # This variable should not have a trailing '/' character
script: echo "A docker job"
rules:
- changes:
- $DOCKERFILES_DIR/*
```
When the `DOCKERFILES_DIR` variable is expanded in the `changes:` section, the full
path becomes `path/to/files//*`. The double slashes might cause unexpected behavior
depending on factors like the keyword used, or the shell and OS of the runner.
## `You are not allowed to download code from this project.` error message
You might see pipelines fail when a GitLab administrator runs a protected manual job
in a private project.
CI/CD jobs usually clone the project when the job starts, and this uses [the permissions](../../user/permissions.md#cicd)
of the user that runs the job. All users, including administrators, must be direct members
of a private project to clone the source of that project. [An issue exists](https://gitlab.com/gitlab-org/gitlab/-/issues/23130)
to change this behavior.
To run protected manual jobs:
- Add the administrator as a direct member of the private project (any role)
- [Impersonate a user](../../administration/admin_area.md#user-impersonation) who is a
direct member of the project.
## A CI/CD job does not use newer configuration when run again
The configuration for a pipeline is only fetched when the pipeline is created.
When you rerun a job, uses the same configuration each time. If you update configuration files,
including separate files added with [`include`](../yaml/_index.md#include), you must
start a new pipeline to use the new configuration.
## `Job may allow multiple pipelines to run for a single action` warning
When you use [`rules`](../yaml/_index.md#rules) with a `when` clause without an `if`
clause, multiple pipelines may run. Usually this occurs when you push a commit to
a branch that has an open merge request associated with it.
To [prevent duplicate pipelines](job_rules.md#avoid-duplicate-pipelines), use
[`workflow: rules`](../yaml/_index.md#workflow) or rewrite your rules to control
which pipelines can run.
## `This GitLab CI configuration is invalid` for variable expressions
You might receive one of several `This GitLab CI configuration is invalid` errors
when working with [CI/CD variable expressions](job_rules.md#cicd-variable-expressions).
These syntax errors can be caused by incorrect usage of quote characters.
In variable expressions, strings should be quoted, while variables should not be quoted.
For example:
```yaml
variables:
ENVIRONMENT: production
job:
script: echo
rules:
- if: $ENVIRONMENT == "production"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
In this example, both `if:` clauses are valid because the `production` string is quoted,
and the CI/CD variables are unquoted.
On the other hand, these `if:` clauses are all invalid:
```yaml
variables:
ENVIRONMENT: production
job:
script: echo
rules: # These rules all cause YAML syntax errors:
- if: ${ENVIRONMENT} == "production"
- if: "$ENVIRONMENT" == "production"
- if: $ENVIRONMENT == production
- if: "production" == "production"
```
In this example:
- `if: ${ENVIRONMENT} == "production"` is invalid, because `${ENVIRONMENT}` is not valid
formatting for CI/CD variables in `if:`.
- `if: "$ENVIRONMENT" == "production"` is invalid, because the variable is quoted.
- `if: $ENVIRONMENT == production` is invalid, because the string is not quoted.
- `if: "production" == "production"` is invalid, because there is no CI/CD variable to compare.
## `get_sources` job section fails because of an HTTP/2 problem
Sometimes, jobs fail with the following cURL error:
```plaintext
++ git -c 'http.userAgent=gitlab-runner <version>' fetch origin +refs/pipelines/<id>:refs/pipelines/<id> ...
error: RPC failed; curl 16 HTTP/2 send again with decreased length
fatal: ...
```
You can work around this problem by configuring Git and `libcurl` to
[use HTTP/1.1](https://git-scm.com/docs/git-config#Documentation/git-config.txt-httpversion).
The configuration can be added to:
- A job's [`pre_get_sources_script`](../yaml/_index.md#hookspre_get_sources_script):
```yaml
job_name:
hooks:
pre_get_sources_script:
- git config --global http.version "HTTP/1.1"
```
- The [runner's `config.toml`](https://docs.gitlab.com/runner/configuration/advanced-configuration.html)
with [Git configuration environment variables](https://git-scm.com/docs/git-config#ENVIRONMENT):
```toml
[[runners]]
...
environment = [
"GIT_CONFIG_COUNT=1",
"GIT_CONFIG_KEY_0=http.version",
"GIT_CONFIG_VALUE_0=HTTP/1.1"
]
```
## Job using `resource_group` gets stuck
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
If a job using [`resource_group`](../yaml/_index.md#resource_group) gets stuck, a
GitLab administrator can try run the following commands from the [rails console](../../administration/operations/rails_console.md#starting-a-rails-console-session):
```ruby
# find resource group by name
resource_group = Project.find_by_full_path('...').resource_groups.find_by(key: 'the-group-name')
busy_resources = resource_group.resources.where('build_id IS NOT NULL')
# identify which builds are occupying the resource
# (I think it should be 1 as of today)
busy_resources.pluck(:build_id)
# it's good to check why this build is holding the resource.
# Is it stuck? Has it been forcefully dropped by the system?
# free up busy resources
busy_resources.update_all(build_id: nil)
```
## `You are not authorized to run this manual job` message
You can receive this message and have a disabled **Run** button when trying to run a manual job if:
- The target environment is a [protected environment](../environments/protected_environments.md)
and your account is not included in the **Allowed to deploy** list.
- The setting to [prevent outdated deployment jobs](../environments/deployment_safety.md#prevent-outdated-deployment-jobs)
is enabled and running the job would overwrite the latest deployment.
|
https://docs.gitlab.com/ci/fine_grained_permissions
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/fine_grained_permissions.md
|
2025-08-13
|
doc/ci/jobs
|
[
"doc",
"ci",
"jobs"
] |
fine_grained_permissions.md
|
Software Supply Chain Security
|
Authorization
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Fine-grained permissions for CI/CD job tokens
| null |
<!--
This documentation is auto-generated by a Rake task.
Please do not edit this file directly. To update this file, run:
`bundle exec rake ci:job_tokens:compile_docs`.
To make changes to the output of the Rake task,
edit `tooling/ci/job_tokens/docs/templates/fine_grained_permissions.md.erb`.
-->
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
- Status: Beta
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/15234) as an [experiment](../../policy/development_stages_support.md#experiment) in GitLab 17.10.
- [Changed](https://gitlab.com/groups/gitlab-org/-/epics/16199) from experiment to beta in GitLab 18.0.
{{< /history >}}
You can use fine-grained permissions to explicitly allow access to a limited set of API endpoints.
These permissions are applied to the CI/CD job tokens in a specified project.
This feature is in [beta](../../policy/development_stages_support.md#beta).
## Add fine-grained permissions to the job token allowlist
Prerequisites:
- You must have at least the Maintainer role for the project.
- You must enable the use of fine-grained permissions for a project.
You can add fine-grained permissions to groups and projects on your job token allowlist. This allows
them to use job tokens to access specific project resources and more accurately control which
resources are available to these groups and projects.
To add fine-grained permissions to groups or projects on the job token allowlist:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Job token permissions**.
1. In the **CI/CD job token allowlist** section, select **Add**.
1. From the dropdown list, select **Group or project**.
1. Enter the path to an existing group or project.
1. Select **Fine-grained permissions**.
1. Grant permissions to the [available API endpoints](#available-api-endpoints).
1. Select **Add**.
GitLab adds the group or project to the job token allowlist with the specified permissions. The group or project can now
access any allowed resources in the current project.
## Available API endpoints
The following endpoints are available for CI/CD job tokens.
`None` means fine-grained permissions cannot control access to this endpoint.
| Permissions | Permission Names | Path | Description |
| ----------- | ---------------- | ---- | ----------- |
| Deployments: Read and write | `ADMIN_DEPLOYMENTS` | `DELETE /projects/:id/deployments/:deployment_id` | Delete a specific deployment |
| Deployments: Read and write | `ADMIN_DEPLOYMENTS` | `POST /projects/:id/deployments/:deployment_id/approval` | Approve or reject a blocked deployment |
| Deployments: Read and write | `ADMIN_DEPLOYMENTS` | `PUT /projects/:id/deployments/:deployment_id` | Update a deployment |
| Deployments: Read and write, Environments: Read and write | `ADMIN_DEPLOYMENTS`, `ADMIN_ENVIRONMENTS` | `POST /projects/:id/deployments` | Create a deployment |
| Deployments: Read | `READ_DEPLOYMENTS` | `GET /projects/:id/deployments/:deployment_id/merge_requests` | List of merge requests associated with a deployment |
| Deployments: Read | `READ_DEPLOYMENTS` | `GET /projects/:id/deployments/:deployment_id` | Get a specific deployment |
| Deployments: Read | `READ_DEPLOYMENTS` | `GET /projects/:id/deployments` | List project deployments |
| Environments: Read and write | `ADMIN_ENVIRONMENTS` | `DELETE /projects/:id/environments/:environment_id` | Delete an environment |
| Environments: Read and write | `ADMIN_ENVIRONMENTS` | `DELETE /projects/:id/environments/review_apps` | Delete multiple stopped review apps |
| Environments: Read and write | `ADMIN_ENVIRONMENTS` | `POST /projects/:id/environments/:environment_id/stop` | Stop an environment |
| Environments: Read and write | `ADMIN_ENVIRONMENTS` | `POST /projects/:id/environments/stop_stale` | Stop stale environments |
| Environments: Read and write | `ADMIN_ENVIRONMENTS` | `POST /projects/:id/environments` | Create a new environment |
| Environments: Read and write | `ADMIN_ENVIRONMENTS` | `PUT /projects/:id/environments/:environment_id` | Update an existing environment |
| Environments: Read | `READ_ENVIRONMENTS` | `GET /projects/:id/environments/:environment_id` | Get a specific environment |
| Environments: Read | `READ_ENVIRONMENTS` | `GET /projects/:id/environments` | List environments |
| Jobs: Read | `READ_JOBS` | `GET /jobs/:id/artifacts` | Download the artifacts file for job |
| Jobs: Read | `READ_JOBS` | `GET /projects/:id/jobs/:job_id/artifacts/*artifact_path` | Download a specific file from artifacts archive |
| Jobs: Read | `READ_JOBS` | `GET /projects/:id/jobs/:job_id/artifacts` | Download the artifacts archive from a job |
| Jobs: Read | `READ_JOBS` | `GET /projects/:id/jobs/artifacts/:ref_name/download` | Download the artifacts archive from a job |
| Jobs: Read | `READ_JOBS` | `GET /projects/:id/jobs/artifacts/:ref_name/raw/*artifact_path` | Download a specific file from artifacts archive from a ref |
| None | | `DELETE /projects/:id/registry/repositories/:repository_id/tags/:tag_name` | Delete repository tag |
| None | | `DELETE /projects/:id/registry/repositories/:repository_id/tags` | Delete repository tags (in bulk) |
| None | | `DELETE /projects/:id/registry/repositories/:repository_id` | Delete repository |
| None | | `GET /group/:id/-/packages/composer/*package_name` | Composer packages endpoint at group level for package versions metadata |
| None | | `GET /group/:id/-/packages/composer/p/:sha` | Composer packages endpoint at group level for packages list |
| None | | `GET /group/:id/-/packages/composer/p2/*package_name` | Composer v2 packages p2 endpoint at group level for package versions metadata |
| None | | `GET /group/:id/-/packages/composer/packages` | Composer packages endpoint at group level |
| None | | `GET /groups/:id/-/packages/npm/*package_name` | NPM registry metadata endpoint |
| None | | `GET /groups/:id/-/packages/pypi/files/:sha256/*file_identifier` | Download a package file from a group |
| None | | `GET /groups/:id/-/packages/pypi/simple/*package_name` | The PyPi Simple Group Package Endpoint |
| None | | `GET /groups/:id/-/packages/pypi/simple` | The PyPi Simple Group Index Endpoint |
| None | | `GET /job/allowed_agents` | Get current agents |
| None | | `GET /job` | Get current job using job token |
| None | | `GET /packages/conan/v1/conans/search` | Search for packages |
| None | | `GET /packages/conan/v1/ping` | Ping the Conan API |
| None | | `GET /packages/conan/v1/users/authenticate` | Authenticate user against conan CLI |
| None | | `GET /packages/conan/v1/users/check_credentials` | Check for valid user credentials per conan CLI |
| None | | `GET /packages/npm/*package_name` | NPM registry metadata endpoint |
| None | | `GET /projects/:id/packages/conan/v1/conans/search` | Search for packages |
| None | | `GET /projects/:id/packages/conan/v1/ping` | Ping the Conan API |
| None | | `GET /projects/:id/packages/conan/v1/users/authenticate` | Authenticate user against conan CLI |
| None | | `GET /projects/:id/packages/conan/v1/users/check_credentials` | Check for valid user credentials per conan CLI |
| None | | `GET /projects/:id/packages/conan/v2/conans/search` | Search for packages |
| None | | `GET /projects/:id/packages/conan/v2/users/authenticate` | Authenticate user against conan CLI |
| None | | `GET /projects/:id/packages/conan/v2/users/check_credentials` | Check for valid user credentials per conan CLI |
| None | | `GET /projects/:id/registry/repositories/:repository_id/tags/:tag_name` | Get details about a repository tag |
| None | | `GET /projects/:id/registry/repositories/:repository_id/tags` | List tags of a repository |
| None | | `GET /projects/:id/registry/repositories` | List container repositories within a project |
| None | | `POST /internal/dast/site_validations/:id/transition` | Transitions a DAST site validation to a new state. |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /groups/:id/-/packages/npm/-/package/*package_name/dist-tags/:tag` | Deletes the given tag |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel` | Delete Package |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /packages/npm/-/package/*package_name/dist-tags/:tag` | Deletes the given tag |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /projects/:id/packages/:package_id/package_files/:package_file_id` | Delete a package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /projects/:id/packages/:package_id` | Delete a project package |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel` | Delete Package |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/revisions/:package_revision` | Delete package revision |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision` | Delete recipe revision |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /projects/:id/packages/npm/-/package/*package_name/dist-tags/:tag` | Deletes the given tag |
| Packages: Read and write | `ADMIN_PACKAGES` | `POST /projects/:id/packages/composer` | Composer packages endpoint for registering packages |
| Packages: Read and write | `ADMIN_PACKAGES` | `POST /projects/:id/packages/pypi/authorize` | Authorize the PyPi package upload from workhorse |
| Packages: Read and write | `ADMIN_PACKAGES` | `POST /projects/:id/packages/pypi` | The PyPi Package upload endpoint |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /groups/:id/-/packages/npm/-/package/*package_name/dist-tags/:tag` | Create or Update the given tag for the given NPM package and version |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/export/:file_name/authorize` | Workhorse authorize the conan recipe file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/export/:file_name` | Upload recipe package files |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/package/:conan_package_reference/:package_revision/:file_name/authorize` | Workhorse authorize the conan package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/package/:conan_package_reference/:package_revision/:file_name` | Upload package files |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /packages/npm/-/package/*package_name/dist-tags/:tag` | Create or Update the given tag for the given NPM package and version |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/export/:file_name/authorize` | Workhorse authorize the conan recipe file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/export/:file_name` | Upload recipe package files |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/package/:conan_package_reference/:package_revision/:file_name/authorize` | Workhorse authorize the conan package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/package/:conan_package_reference/:package_revision/:file_name` | Upload package files |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/files/:file_name/authorize` | Workhorse authorize the conan recipe file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/files/:file_name` | Upload recipe package files |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/revisions/:package_revision/files/:file_name/authorize` | Workhorse authorize the conan package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/revisions/:package_revision/files/:file_name` | Upload package files |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/generic/:package_name/*package_version/(*path/):file_name/authorize` | Workhorse authorize generic package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/generic/:package_name/*package_version/(*path/):file_name` | Upload package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/maven/*path/:file_name/authorize` | Workhorse authorize the maven package file upload |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/maven/*path/:file_name` | Upload the maven package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/npm/-/package/*package_name/dist-tags/:tag` | Create or Update the given tag for the given NPM package and version |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/npm/:package_name` | Create or deprecate NPM package |
| Packages: Read | `READ_PACKAGES` | `GET /groups/:id/-/packages/maven/*path/:file_name` | Download the maven package file at a group level |
| Packages: Read | `READ_PACKAGES` | `GET /groups/:id/-/packages/npm/-/package/*package_name/dist-tags` | Get all tags for a given an NPM package |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/digest` | Recipe Digest |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/download_urls` | Recipe Download Urls |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference/digest` | Package Digest |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference/download_urls` | Package Download Urls |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference` | Package Snapshot |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/search` | Get package references metadata |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel` | Recipe Snapshot |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/export/:file_name` | Download recipe files |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/package/:conan_package_reference/:package_revision/:file_name` | Download package files |
| Packages: Read | `READ_PACKAGES` | `GET /packages/maven/*path/:file_name` | Download the maven package file at instance level |
| Packages: Read | `READ_PACKAGES` | `GET /packages/npm/-/package/*package_name/dist-tags` | Get all tags for a given an NPM package |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/:package_id/package_files` | List package files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/:package_id` | Get a single project package |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/composer/archives/*package_name` | Composer package endpoint to download a package archive |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/digest` | Recipe Digest |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/download_urls` | Recipe Download Urls |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference/digest` | Package Digest |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference/download_urls` | Package Download Urls |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference` | Package Snapshot |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/search` | Get package references metadata |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel` | Recipe Snapshot |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/export/:file_name` | Download recipe files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/package/:conan_package_reference/:package_revision/:file_name` | Download package files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/latest` | Get the latest recipe revision |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/files/:file_name` | Download recipe files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/files` | List recipe files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/latest` | Get the latest package revision |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/revisions/:package_revision/files/:file_name` | Download package files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/revisions/:package_revision/files` | List package files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/revisions` | Get the list of package revisions |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/search` | Get package references metadata |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions` | Get the list of revisions |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/search` | Get package references metadata |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/generic/:package_name/*package_version/(*path/):file_name` | Download package file |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/go/*module_name/@v/:module_version.info` | Version metadata |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/go/*module_name/@v/:module_version.mod` | Download module file |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/go/*module_name/@v/:module_version.zip` | Download module source |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/go/*module_name/@v/list` | List |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/maven/*path/:file_name` | Download the maven package file at a project level |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/npm/*package_name/-/*file_name` | Download the NPM tarball |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/npm/*package_name` | NPM registry metadata endpoint |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/npm/-/package/*package_name/dist-tags` | Get all tags for a given an NPM package |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/pypi/files/:sha256/*file_identifier` | The PyPi package download endpoint |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/pypi/simple/*package_name` | The PyPi Simple Project Package Endpoint |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/pypi/simple` | The PyPi Simple Project Index Endpoint |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages` | Get a list of project packages |
| Packages: Read | `READ_PACKAGES` | `POST /groups/:id/-/packages/npm/-/npm/v1/security/advisories/bulk` | NPM registry bulk advisory endpoint |
| Packages: Read | `READ_PACKAGES` | `POST /groups/:id/-/packages/npm/-/npm/v1/security/audits/quick` | NPM registry quick audit endpoint |
| Packages: Read | `READ_PACKAGES` | `POST /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference/upload_urls` | Package Upload Urls |
| Packages: Read | `READ_PACKAGES` | `POST /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/upload_urls` | Recipe Upload Urls |
| Packages: Read | `READ_PACKAGES` | `POST /packages/npm/-/npm/v1/security/advisories/bulk` | NPM registry bulk advisory endpoint |
| Packages: Read | `READ_PACKAGES` | `POST /packages/npm/-/npm/v1/security/audits/quick` | NPM registry quick audit endpoint |
| Packages: Read | `READ_PACKAGES` | `POST /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference/upload_urls` | Package Upload Urls |
| Packages: Read | `READ_PACKAGES` | `POST /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/upload_urls` | Recipe Upload Urls |
| Packages: Read | `READ_PACKAGES` | `POST /projects/:id/packages/npm/-/npm/v1/security/advisories/bulk` | NPM registry bulk advisory endpoint |
| Packages: Read | `READ_PACKAGES` | `POST /projects/:id/packages/npm/-/npm/v1/security/audits/quick` | NPM registry quick audit endpoint |
| Pipelines: Read and write | `ADMIN_PIPELINES` | `PUT /projects/:id/pipelines/:pipeline_id/metadata` | Updates pipeline metadata |
| Pipelines: Read | `READ_PIPELINES` | `GET /projects/:id/packages/:package_id/pipelines` | Get the pipelines for a single project package |
| Releases: Read and write | `ADMIN_RELEASES` | `DELETE /projects/:id/releases/:tag_name/assets/links/:link_id` | Delete a release link |
| Releases: Read and write | `ADMIN_RELEASES` | `DELETE /projects/:id/releases/:tag_name` | Delete a release |
| Releases: Read and write | `ADMIN_RELEASES` | `POST /projects/:id/catalog/publish` | Publish a new component project release as version to the CI/CD catalog |
| Releases: Read and write | `ADMIN_RELEASES` | `POST /projects/:id/releases/:tag_name/assets/links` | Create a release link |
| Releases: Read and write | `ADMIN_RELEASES` | `POST /projects/:id/releases/:tag_name/evidence` | Collect release evidence |
| Releases: Read and write | `ADMIN_RELEASES` | `POST /projects/:id/releases` | Create a release |
| Releases: Read and write | `ADMIN_RELEASES` | `PUT /projects/:id/releases/:tag_name/assets/links/:link_id` | Update a release link |
| Releases: Read and write | `ADMIN_RELEASES` | `PUT /projects/:id/releases/:tag_name` | Update a release |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/releases/:tag_name/assets/links/:link_id` | Get a release link |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/releases/:tag_name/assets/links` | List links of a release |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/releases/:tag_name/downloads/*direct_asset_path` | Download a project release asset file |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/releases/:tag_name` | Get a release by a tag name |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/releases/permalink/latest(/)(*suffix_path)` | Get the latest project release |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/releases` | List Releases |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/repository/changelog` | Generates a changelog section for a release and returns it |
| Secure files: Read and write | `ADMIN_SECURE_FILES` | `DELETE /projects/:id/secure_files/:secure_file_id` | Remove a secure file |
| Secure files: Read and write | `ADMIN_SECURE_FILES` | `POST /projects/:id/secure_files` | Create a secure file |
| Secure files: Read | `READ_SECURE_FILES` | `GET /projects/:id/secure_files/:secure_file_id/download` | Download secure file |
| Secure files: Read | `READ_SECURE_FILES` | `GET /projects/:id/secure_files/:secure_file_id` | Get the details of a specific secure file in a project |
| Secure files: Read | `READ_SECURE_FILES` | `GET /projects/:id/secure_files` | Get list of secure files in a project |
| Terraform state: Read and write | `ADMIN_TERRAFORM_STATE` | `DELETE /projects/:id/terraform/state/:name/lock` | Unlock a Terraform state of a certain name |
| Terraform state: Read and write | `ADMIN_TERRAFORM_STATE` | `DELETE /projects/:id/terraform/state/:name/versions/:serial` | Delete a Terraform state version |
| Terraform state: Read and write | `ADMIN_TERRAFORM_STATE` | `DELETE /projects/:id/terraform/state/:name` | Delete a Terraform state of a certain name |
| Terraform state: Read and write | `ADMIN_TERRAFORM_STATE` | `POST /projects/:id/terraform/state/:name/lock` | Lock a Terraform state of a certain name |
| Terraform state: Read and write | `ADMIN_TERRAFORM_STATE` | `POST /projects/:id/terraform/state/:name` | Add a new Terraform state or update an existing one |
| Terraform state: Read | `READ_TERRAFORM_STATE` | `GET /projects/:id/terraform/state/:name/versions/:serial` | Get a Terraform state version |
| Terraform state: Read | `READ_TERRAFORM_STATE` | `GET /projects/:id/terraform/state/:name` | Get a Terraform state by its name |
|
---
stage: Software Supply Chain Security
group: Authorization
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Fine-grained permissions for CI/CD job tokens
breadcrumbs:
- doc
- ci
- jobs
---
<!--
This documentation is auto-generated by a Rake task.
Please do not edit this file directly. To update this file, run:
`bundle exec rake ci:job_tokens:compile_docs`.
To make changes to the output of the Rake task,
edit `tooling/ci/job_tokens/docs/templates/fine_grained_permissions.md.erb`.
-->
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
- Status: Beta
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/15234) as an [experiment](../../policy/development_stages_support.md#experiment) in GitLab 17.10.
- [Changed](https://gitlab.com/groups/gitlab-org/-/epics/16199) from experiment to beta in GitLab 18.0.
{{< /history >}}
You can use fine-grained permissions to explicitly allow access to a limited set of API endpoints.
These permissions are applied to the CI/CD job tokens in a specified project.
This feature is in [beta](../../policy/development_stages_support.md#beta).
## Add fine-grained permissions to the job token allowlist
Prerequisites:
- You must have at least the Maintainer role for the project.
- You must enable the use of fine-grained permissions for a project.
You can add fine-grained permissions to groups and projects on your job token allowlist. This allows
them to use job tokens to access specific project resources and more accurately control which
resources are available to these groups and projects.
To add fine-grained permissions to groups or projects on the job token allowlist:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Job token permissions**.
1. In the **CI/CD job token allowlist** section, select **Add**.
1. From the dropdown list, select **Group or project**.
1. Enter the path to an existing group or project.
1. Select **Fine-grained permissions**.
1. Grant permissions to the [available API endpoints](#available-api-endpoints).
1. Select **Add**.
GitLab adds the group or project to the job token allowlist with the specified permissions. The group or project can now
access any allowed resources in the current project.
## Available API endpoints
The following endpoints are available for CI/CD job tokens.
`None` means fine-grained permissions cannot control access to this endpoint.
| Permissions | Permission Names | Path | Description |
| ----------- | ---------------- | ---- | ----------- |
| Deployments: Read and write | `ADMIN_DEPLOYMENTS` | `DELETE /projects/:id/deployments/:deployment_id` | Delete a specific deployment |
| Deployments: Read and write | `ADMIN_DEPLOYMENTS` | `POST /projects/:id/deployments/:deployment_id/approval` | Approve or reject a blocked deployment |
| Deployments: Read and write | `ADMIN_DEPLOYMENTS` | `PUT /projects/:id/deployments/:deployment_id` | Update a deployment |
| Deployments: Read and write, Environments: Read and write | `ADMIN_DEPLOYMENTS`, `ADMIN_ENVIRONMENTS` | `POST /projects/:id/deployments` | Create a deployment |
| Deployments: Read | `READ_DEPLOYMENTS` | `GET /projects/:id/deployments/:deployment_id/merge_requests` | List of merge requests associated with a deployment |
| Deployments: Read | `READ_DEPLOYMENTS` | `GET /projects/:id/deployments/:deployment_id` | Get a specific deployment |
| Deployments: Read | `READ_DEPLOYMENTS` | `GET /projects/:id/deployments` | List project deployments |
| Environments: Read and write | `ADMIN_ENVIRONMENTS` | `DELETE /projects/:id/environments/:environment_id` | Delete an environment |
| Environments: Read and write | `ADMIN_ENVIRONMENTS` | `DELETE /projects/:id/environments/review_apps` | Delete multiple stopped review apps |
| Environments: Read and write | `ADMIN_ENVIRONMENTS` | `POST /projects/:id/environments/:environment_id/stop` | Stop an environment |
| Environments: Read and write | `ADMIN_ENVIRONMENTS` | `POST /projects/:id/environments/stop_stale` | Stop stale environments |
| Environments: Read and write | `ADMIN_ENVIRONMENTS` | `POST /projects/:id/environments` | Create a new environment |
| Environments: Read and write | `ADMIN_ENVIRONMENTS` | `PUT /projects/:id/environments/:environment_id` | Update an existing environment |
| Environments: Read | `READ_ENVIRONMENTS` | `GET /projects/:id/environments/:environment_id` | Get a specific environment |
| Environments: Read | `READ_ENVIRONMENTS` | `GET /projects/:id/environments` | List environments |
| Jobs: Read | `READ_JOBS` | `GET /jobs/:id/artifacts` | Download the artifacts file for job |
| Jobs: Read | `READ_JOBS` | `GET /projects/:id/jobs/:job_id/artifacts/*artifact_path` | Download a specific file from artifacts archive |
| Jobs: Read | `READ_JOBS` | `GET /projects/:id/jobs/:job_id/artifacts` | Download the artifacts archive from a job |
| Jobs: Read | `READ_JOBS` | `GET /projects/:id/jobs/artifacts/:ref_name/download` | Download the artifacts archive from a job |
| Jobs: Read | `READ_JOBS` | `GET /projects/:id/jobs/artifacts/:ref_name/raw/*artifact_path` | Download a specific file from artifacts archive from a ref |
| None | | `DELETE /projects/:id/registry/repositories/:repository_id/tags/:tag_name` | Delete repository tag |
| None | | `DELETE /projects/:id/registry/repositories/:repository_id/tags` | Delete repository tags (in bulk) |
| None | | `DELETE /projects/:id/registry/repositories/:repository_id` | Delete repository |
| None | | `GET /group/:id/-/packages/composer/*package_name` | Composer packages endpoint at group level for package versions metadata |
| None | | `GET /group/:id/-/packages/composer/p/:sha` | Composer packages endpoint at group level for packages list |
| None | | `GET /group/:id/-/packages/composer/p2/*package_name` | Composer v2 packages p2 endpoint at group level for package versions metadata |
| None | | `GET /group/:id/-/packages/composer/packages` | Composer packages endpoint at group level |
| None | | `GET /groups/:id/-/packages/npm/*package_name` | NPM registry metadata endpoint |
| None | | `GET /groups/:id/-/packages/pypi/files/:sha256/*file_identifier` | Download a package file from a group |
| None | | `GET /groups/:id/-/packages/pypi/simple/*package_name` | The PyPi Simple Group Package Endpoint |
| None | | `GET /groups/:id/-/packages/pypi/simple` | The PyPi Simple Group Index Endpoint |
| None | | `GET /job/allowed_agents` | Get current agents |
| None | | `GET /job` | Get current job using job token |
| None | | `GET /packages/conan/v1/conans/search` | Search for packages |
| None | | `GET /packages/conan/v1/ping` | Ping the Conan API |
| None | | `GET /packages/conan/v1/users/authenticate` | Authenticate user against conan CLI |
| None | | `GET /packages/conan/v1/users/check_credentials` | Check for valid user credentials per conan CLI |
| None | | `GET /packages/npm/*package_name` | NPM registry metadata endpoint |
| None | | `GET /projects/:id/packages/conan/v1/conans/search` | Search for packages |
| None | | `GET /projects/:id/packages/conan/v1/ping` | Ping the Conan API |
| None | | `GET /projects/:id/packages/conan/v1/users/authenticate` | Authenticate user against conan CLI |
| None | | `GET /projects/:id/packages/conan/v1/users/check_credentials` | Check for valid user credentials per conan CLI |
| None | | `GET /projects/:id/packages/conan/v2/conans/search` | Search for packages |
| None | | `GET /projects/:id/packages/conan/v2/users/authenticate` | Authenticate user against conan CLI |
| None | | `GET /projects/:id/packages/conan/v2/users/check_credentials` | Check for valid user credentials per conan CLI |
| None | | `GET /projects/:id/registry/repositories/:repository_id/tags/:tag_name` | Get details about a repository tag |
| None | | `GET /projects/:id/registry/repositories/:repository_id/tags` | List tags of a repository |
| None | | `GET /projects/:id/registry/repositories` | List container repositories within a project |
| None | | `POST /internal/dast/site_validations/:id/transition` | Transitions a DAST site validation to a new state. |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /groups/:id/-/packages/npm/-/package/*package_name/dist-tags/:tag` | Deletes the given tag |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel` | Delete Package |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /packages/npm/-/package/*package_name/dist-tags/:tag` | Deletes the given tag |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /projects/:id/packages/:package_id/package_files/:package_file_id` | Delete a package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /projects/:id/packages/:package_id` | Delete a project package |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel` | Delete Package |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/revisions/:package_revision` | Delete package revision |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision` | Delete recipe revision |
| Packages: Read and write | `ADMIN_PACKAGES` | `DELETE /projects/:id/packages/npm/-/package/*package_name/dist-tags/:tag` | Deletes the given tag |
| Packages: Read and write | `ADMIN_PACKAGES` | `POST /projects/:id/packages/composer` | Composer packages endpoint for registering packages |
| Packages: Read and write | `ADMIN_PACKAGES` | `POST /projects/:id/packages/pypi/authorize` | Authorize the PyPi package upload from workhorse |
| Packages: Read and write | `ADMIN_PACKAGES` | `POST /projects/:id/packages/pypi` | The PyPi Package upload endpoint |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /groups/:id/-/packages/npm/-/package/*package_name/dist-tags/:tag` | Create or Update the given tag for the given NPM package and version |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/export/:file_name/authorize` | Workhorse authorize the conan recipe file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/export/:file_name` | Upload recipe package files |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/package/:conan_package_reference/:package_revision/:file_name/authorize` | Workhorse authorize the conan package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/package/:conan_package_reference/:package_revision/:file_name` | Upload package files |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /packages/npm/-/package/*package_name/dist-tags/:tag` | Create or Update the given tag for the given NPM package and version |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/export/:file_name/authorize` | Workhorse authorize the conan recipe file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/export/:file_name` | Upload recipe package files |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/package/:conan_package_reference/:package_revision/:file_name/authorize` | Workhorse authorize the conan package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/package/:conan_package_reference/:package_revision/:file_name` | Upload package files |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/files/:file_name/authorize` | Workhorse authorize the conan recipe file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/files/:file_name` | Upload recipe package files |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/revisions/:package_revision/files/:file_name/authorize` | Workhorse authorize the conan package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/revisions/:package_revision/files/:file_name` | Upload package files |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/generic/:package_name/*package_version/(*path/):file_name/authorize` | Workhorse authorize generic package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/generic/:package_name/*package_version/(*path/):file_name` | Upload package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/maven/*path/:file_name/authorize` | Workhorse authorize the maven package file upload |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/maven/*path/:file_name` | Upload the maven package file |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/npm/-/package/*package_name/dist-tags/:tag` | Create or Update the given tag for the given NPM package and version |
| Packages: Read and write | `ADMIN_PACKAGES` | `PUT /projects/:id/packages/npm/:package_name` | Create or deprecate NPM package |
| Packages: Read | `READ_PACKAGES` | `GET /groups/:id/-/packages/maven/*path/:file_name` | Download the maven package file at a group level |
| Packages: Read | `READ_PACKAGES` | `GET /groups/:id/-/packages/npm/-/package/*package_name/dist-tags` | Get all tags for a given an NPM package |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/digest` | Recipe Digest |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/download_urls` | Recipe Download Urls |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference/digest` | Package Digest |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference/download_urls` | Package Download Urls |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference` | Package Snapshot |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/search` | Get package references metadata |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel` | Recipe Snapshot |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/export/:file_name` | Download recipe files |
| Packages: Read | `READ_PACKAGES` | `GET /packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/package/:conan_package_reference/:package_revision/:file_name` | Download package files |
| Packages: Read | `READ_PACKAGES` | `GET /packages/maven/*path/:file_name` | Download the maven package file at instance level |
| Packages: Read | `READ_PACKAGES` | `GET /packages/npm/-/package/*package_name/dist-tags` | Get all tags for a given an NPM package |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/:package_id/package_files` | List package files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/:package_id` | Get a single project package |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/composer/archives/*package_name` | Composer package endpoint to download a package archive |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/digest` | Recipe Digest |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/download_urls` | Recipe Download Urls |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference/digest` | Package Digest |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference/download_urls` | Package Download Urls |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference` | Package Snapshot |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/search` | Get package references metadata |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel` | Recipe Snapshot |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/export/:file_name` | Download recipe files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v1/files/:package_name/:package_version/:package_username/:package_channel/:recipe_revision/package/:conan_package_reference/:package_revision/:file_name` | Download package files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/latest` | Get the latest recipe revision |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/files/:file_name` | Download recipe files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/files` | List recipe files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/latest` | Get the latest package revision |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/revisions/:package_revision/files/:file_name` | Download package files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/revisions/:package_revision/files` | List package files |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/packages/:conan_package_reference/revisions` | Get the list of package revisions |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions/:recipe_revision/search` | Get package references metadata |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/revisions` | Get the list of revisions |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/conan/v2/conans/:package_name/:package_version/:package_username/:package_channel/search` | Get package references metadata |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/generic/:package_name/*package_version/(*path/):file_name` | Download package file |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/go/*module_name/@v/:module_version.info` | Version metadata |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/go/*module_name/@v/:module_version.mod` | Download module file |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/go/*module_name/@v/:module_version.zip` | Download module source |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/go/*module_name/@v/list` | List |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/maven/*path/:file_name` | Download the maven package file at a project level |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/npm/*package_name/-/*file_name` | Download the NPM tarball |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/npm/*package_name` | NPM registry metadata endpoint |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/npm/-/package/*package_name/dist-tags` | Get all tags for a given an NPM package |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/pypi/files/:sha256/*file_identifier` | The PyPi package download endpoint |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/pypi/simple/*package_name` | The PyPi Simple Project Package Endpoint |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages/pypi/simple` | The PyPi Simple Project Index Endpoint |
| Packages: Read | `READ_PACKAGES` | `GET /projects/:id/packages` | Get a list of project packages |
| Packages: Read | `READ_PACKAGES` | `POST /groups/:id/-/packages/npm/-/npm/v1/security/advisories/bulk` | NPM registry bulk advisory endpoint |
| Packages: Read | `READ_PACKAGES` | `POST /groups/:id/-/packages/npm/-/npm/v1/security/audits/quick` | NPM registry quick audit endpoint |
| Packages: Read | `READ_PACKAGES` | `POST /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference/upload_urls` | Package Upload Urls |
| Packages: Read | `READ_PACKAGES` | `POST /packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/upload_urls` | Recipe Upload Urls |
| Packages: Read | `READ_PACKAGES` | `POST /packages/npm/-/npm/v1/security/advisories/bulk` | NPM registry bulk advisory endpoint |
| Packages: Read | `READ_PACKAGES` | `POST /packages/npm/-/npm/v1/security/audits/quick` | NPM registry quick audit endpoint |
| Packages: Read | `READ_PACKAGES` | `POST /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/packages/:conan_package_reference/upload_urls` | Package Upload Urls |
| Packages: Read | `READ_PACKAGES` | `POST /projects/:id/packages/conan/v1/conans/:package_name/:package_version/:package_username/:package_channel/upload_urls` | Recipe Upload Urls |
| Packages: Read | `READ_PACKAGES` | `POST /projects/:id/packages/npm/-/npm/v1/security/advisories/bulk` | NPM registry bulk advisory endpoint |
| Packages: Read | `READ_PACKAGES` | `POST /projects/:id/packages/npm/-/npm/v1/security/audits/quick` | NPM registry quick audit endpoint |
| Pipelines: Read and write | `ADMIN_PIPELINES` | `PUT /projects/:id/pipelines/:pipeline_id/metadata` | Updates pipeline metadata |
| Pipelines: Read | `READ_PIPELINES` | `GET /projects/:id/packages/:package_id/pipelines` | Get the pipelines for a single project package |
| Releases: Read and write | `ADMIN_RELEASES` | `DELETE /projects/:id/releases/:tag_name/assets/links/:link_id` | Delete a release link |
| Releases: Read and write | `ADMIN_RELEASES` | `DELETE /projects/:id/releases/:tag_name` | Delete a release |
| Releases: Read and write | `ADMIN_RELEASES` | `POST /projects/:id/catalog/publish` | Publish a new component project release as version to the CI/CD catalog |
| Releases: Read and write | `ADMIN_RELEASES` | `POST /projects/:id/releases/:tag_name/assets/links` | Create a release link |
| Releases: Read and write | `ADMIN_RELEASES` | `POST /projects/:id/releases/:tag_name/evidence` | Collect release evidence |
| Releases: Read and write | `ADMIN_RELEASES` | `POST /projects/:id/releases` | Create a release |
| Releases: Read and write | `ADMIN_RELEASES` | `PUT /projects/:id/releases/:tag_name/assets/links/:link_id` | Update a release link |
| Releases: Read and write | `ADMIN_RELEASES` | `PUT /projects/:id/releases/:tag_name` | Update a release |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/releases/:tag_name/assets/links/:link_id` | Get a release link |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/releases/:tag_name/assets/links` | List links of a release |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/releases/:tag_name/downloads/*direct_asset_path` | Download a project release asset file |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/releases/:tag_name` | Get a release by a tag name |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/releases/permalink/latest(/)(*suffix_path)` | Get the latest project release |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/releases` | List Releases |
| Releases: Read | `READ_RELEASES` | `GET /projects/:id/repository/changelog` | Generates a changelog section for a release and returns it |
| Secure files: Read and write | `ADMIN_SECURE_FILES` | `DELETE /projects/:id/secure_files/:secure_file_id` | Remove a secure file |
| Secure files: Read and write | `ADMIN_SECURE_FILES` | `POST /projects/:id/secure_files` | Create a secure file |
| Secure files: Read | `READ_SECURE_FILES` | `GET /projects/:id/secure_files/:secure_file_id/download` | Download secure file |
| Secure files: Read | `READ_SECURE_FILES` | `GET /projects/:id/secure_files/:secure_file_id` | Get the details of a specific secure file in a project |
| Secure files: Read | `READ_SECURE_FILES` | `GET /projects/:id/secure_files` | Get list of secure files in a project |
| Terraform state: Read and write | `ADMIN_TERRAFORM_STATE` | `DELETE /projects/:id/terraform/state/:name/lock` | Unlock a Terraform state of a certain name |
| Terraform state: Read and write | `ADMIN_TERRAFORM_STATE` | `DELETE /projects/:id/terraform/state/:name/versions/:serial` | Delete a Terraform state version |
| Terraform state: Read and write | `ADMIN_TERRAFORM_STATE` | `DELETE /projects/:id/terraform/state/:name` | Delete a Terraform state of a certain name |
| Terraform state: Read and write | `ADMIN_TERRAFORM_STATE` | `POST /projects/:id/terraform/state/:name/lock` | Lock a Terraform state of a certain name |
| Terraform state: Read and write | `ADMIN_TERRAFORM_STATE` | `POST /projects/:id/terraform/state/:name` | Add a new Terraform state or update an existing one |
| Terraform state: Read | `READ_TERRAFORM_STATE` | `GET /projects/:id/terraform/state/:name/versions/:serial` | Get a Terraform state version |
| Terraform state: Read | `READ_TERRAFORM_STATE` | `GET /projects/:id/terraform/state/:name` | Get a Terraform state by its name |
|
https://docs.gitlab.com/ci/job_artifacts
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/job_artifacts.md
|
2025-08-13
|
doc/ci/jobs
|
[
"doc",
"ci",
"jobs"
] |
job_artifacts.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Job artifacts
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Jobs can output an archive of files and directories. This output is known as a job artifact.
You can download job artifacts by using the GitLab UI or the [API](../../api/job_artifacts.md).
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview of job artifacts, watch the video [GitLab CI pipelines, artifacts, and environments](https://www.youtube.com/watch?v=PCKDICEe10s).
Or, for an introduction, watch [GitLab CI pipeline tutorial for beginners](https://www.youtube.com/watch?v=Jav4vbUrqII).
For administrator information about job artifact storage, see [administering job artifacts](../../administration/cicd/job_artifacts.md).
## Create job artifacts
To create job artifacts, use the [`artifacts`](../yaml/_index.md#artifacts) keyword in your `.gitlab-ci.yml` file:
```yaml
pdf:
script: xelatex mycv.tex
artifacts:
paths:
- mycv.pdf
```
In this example, a job named `pdf` calls the `xelatex` command to build a PDF file from the
LaTeX source file, `mycv.tex`.
The [`paths`](../yaml/_index.md#artifactspaths) keyword determines which files to add to the job artifacts.
All paths to files and directories are relative to the repository where the job was created.
### With wildcards
You can use wildcards for paths and directories. For example, to create an artifact
with all the files inside the directories that end with `xyz`:
```yaml
job:
script: echo "build xyz project"
artifacts:
paths:
- path/*xyz/*
```
### With an expiry
The [`expire_in`](../yaml/_index.md#artifactsexpire_in) keyword determines how long
GitLab keeps the artifacts defined in `artifacts:paths`. For example:
```yaml
pdf:
script: xelatex mycv.tex
artifacts:
paths:
- mycv.pdf
expire_in: 1 week
```
If `expire_in` is not defined, the [instance-wide setting](../../administration/settings/continuous_integration.md#set-default-artifacts-expiration)
is used.
To prevent artifacts from expiring, you can select **Keep** from the job details page.
The option is not available when an artifact has no expiry set.
By default, the [latest artifacts are always kept](#keep-artifacts-from-most-recent-successful-jobs).
### With an explicitly defined artifact name
You can explicitly customize artifact names using the [`artifacts:name`](../yaml/_index.md#artifactsname) configuration:
```yaml
job:
artifacts:
name: "job1-artifacts-file"
paths:
- binaries/
```
### Without excluded files
Use [`artifacts:exclude`](../yaml/_index.md#artifactsexclude) to prevent files from
being added to an artifacts archive.
For example, to store all files in `binaries/`, but not `*.o` files located in
subdirectories of `binaries/`.
```yaml
artifacts:
paths:
- binaries/
exclude:
- binaries/**/*.o
```
Unlike [`artifacts:paths`](../yaml/_index.md#artifactspaths), `exclude` paths are not recursive.
To exclude all of the contents of a directory, match them explicitly rather
than matching the directory itself.
For example, to store all files in `binaries/` but nothing located in the `temp/` subdirectory:
```yaml
artifacts:
paths:
- binaries/
exclude:
- binaries/temp/**/*
```
### With untracked files
Use [`artifacts:untracked`](../yaml/_index.md#artifactsuntracked) to add all Git untracked
files as artifacts (along with the paths defined in [`artifacts:paths`](../yaml/_index.md#artifactspaths)). Untracked
files are those that haven't been added to the repository but exist in the repository checkout.
For example, to save all Git untracked files and files in `binaries`:
```yaml
artifacts:
untracked: true
paths:
- binaries/
```
For example, to save all untracked files but [exclude](../yaml/_index.md#artifactsexclude) `*.txt` files:
```yaml
artifacts:
untracked: true
exclude:
- "*.txt"
```
### With variable expansion
Variable expansion is supported for:
- [`artifacts:name`](../yaml/_index.md#artifactsname)
- [`artifacts:paths`](../yaml/_index.md#artifactspaths)
- [`artifacts:exclude`](../yaml/_index.md#artifactsexclude)
Instead of using shell, GitLab Runner uses its
[internal variable expansion mechanism](../variables/where_variables_can_be_used.md#gitlab-runner-internal-variable-expansion-mechanism).
Only [CI/CD variables](../variables/_index.md) are supported in this context.
For example, to create an archive using the current branch or tag name
including only files from a directory named after the current project:
```yaml
job:
artifacts:
name: "$CI_COMMIT_REF_NAME"
paths:
- binaries/${CI_PROJECT_NAME}/
```
When your branch name contains forward slashes (for example, `feature/my-feature`),
use `$CI_COMMIT_REF_SLUG` instead of `$CI_COMMIT_REF_NAME` to ensure proper artifact naming.
Variables are expanded before [globs](https://en.wikipedia.org/wiki/Glob_(programming)).
## Fetching artifacts
By default, jobs fetch all artifacts from jobs defined in previous stages. These artifacts are downloaded into the job's working directory.
You can control which artifacts to download by using these keywords:
- [`dependencies`](../yaml/_index.md#dependencies): Specify which jobs to download artifacts from.
- [`needs`](../yaml/_index.md#needs): Define relationships between jobs and specify which artifacts to download.
When you use these keywords, the default behavior changes and artifacts are fetched from only the jobs you specify.
### Prevent a job from fetching artifacts
To prevent a job from downloading any artifacts, set
[`dependencies`](../yaml/_index.md#dependencies) to an empty array
(`[]`):
```yaml
job:
stage: test
script: make build
dependencies: []
```
## View all job artifacts in a project
{{< history >}}
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/407475) in GitLab 16.0. Feature flag `artifacts_management_page` removed.
{{< /history >}}
You can view all artifacts stored in a project from the **Build > Artifacts** page.
This list displays all jobs and their associated artifacts. Expand an entry to access
all artifacts associated with a job, including:
- Artifacts created with the `artifacts:` keyword.
- [Report artifacts](../yaml/artifacts_reports.md).
- Job logs and metadata, which are stored internally as separate artifacts.
You can download or delete individual artifacts from this list.
## Download job artifacts
You can download job artifacts from:
- Any **Pipelines** list. On the right of the pipeline, select **Download artifacts** ({{< icon name="download" >}}).
- Any **Jobs** list. On the right of the job, select **Download artifacts** ({{< icon name="download" >}}).
- A job's detail page. On the right of the page, select **Download**.
- A merge request **Overview** page. On the right of the latest pipeline, select **Artifacts** ({{< icon name="download" >}}).
- The [**Artifacts**](#view-all-job-artifacts-in-a-project) page. On the right of the job, select **Download** ({{< icon name="download" >}}).
- The [artifacts browser](#browse-the-contents-of-the-artifacts-archive). On the top of the page,
select **Download artifacts archive** ({{< icon name="download" >}}).
[Report artifacts](../yaml/artifacts_reports.md) can only be downloaded from the **Pipelines** list
or **Artifacts** page.
You can download job artifacts from the latest successful pipeline by using [the job artifacts API](../../api/job_artifacts.md).
You cannot download [artifact reports](../yaml/artifacts_reports.md) with the job artifacts API,
unless the report is added as a regular artifact with `artifacts:paths`.
### From a URL
You can download the artifacts archive for a specific job with a publicly accessible
URL for the [job artifacts API](../../api/job_artifacts.md#download-job-artifacts-by-reference-name).
For example:
- To download the latest artifacts of a job named `build` in the `main` branch of a project on GitLab.com:
```plaintext
https://gitlab.com/api/v4/projects/<project-id>/jobs/artifacts/main/download?job=build
```
- To download the file `review/index.html` from the latest job named `build` in the `main` branch of a project on GitLab.com:
```plaintext
https://gitlab.com/api/v4/projects/<project-id>/jobs/artifacts/main/raw/review/index.html?job=build
```
Files returned by this endpoint always have the `plain/text` content type.
In both examples, replace `<project-id>` with a valid project ID. You can find the project ID on the
[project overview page](../../user/project/working_with_projects.md#find-the-project-id).
Artifacts for [parent and child pipelines](../pipelines/downstream_pipelines.md#parent-child-pipelines)
are searched in hierarchical order from parent to child. For example, if both parent and
child pipelines have a job with the same name, the job artifacts from the parent pipeline are returned.
### With a CI/CD job token
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can use a [CI/CD job token](ci_job_token.md) to authenticate with the [jobs artifacts API endpoint](../../api/job_artifacts.md)
and fetch artifacts from a different pipeline. You must specify which job to retrieve artifacts from,
for example:
```yaml
build_submodule:
stage: test
script:
- apt update && apt install -y unzip
- curl --location --output artifacts.zip "https://gitlab.example.com/api/v4/projects/1/jobs/artifacts/main/download?job=test&job_token=$CI_JOB_TOKEN"
- unzip artifacts.zip
```
To fetch artifacts from a job in the same pipeline, use the [`needs:artifacts`](../yaml/_index.md#needsartifacts) keyword.
## Browse the contents of the artifacts archive
You can browse the contents of the artifacts from the UI without downloading the artifact locally,
from:
- Any **Jobs** list. On the right of the job, select **Browse** ({{< icon name="folder-open" >}}).
- A job's detail page. On the right of the page, select **Browse**.
- The **Artifacts** page. On the right of the job, select **Browse** ({{< icon name="folder-open" >}}).
If [GitLab Pages](../../administration/pages/_index.md) is enabled globally, even if it is disabled in the project settings,
you can preview some artifacts file extensions directly in your browser. If the project is internal or private,
you must enable [GitLab Pages access control](../../administration/pages/_index.md#access-control) to enable the preview.
The following extensions are supported:
| File extension | GitLab.com | Linux package with built-in NGINX |
|----------------|--------------------------------------|-----------------------------------|
| `.html` | {{< icon name="check-circle" >}} Yes | {{< icon name="check-circle" >}} Yes |
| `.json` | {{< icon name="check-circle" >}} Yes | {{< icon name="check-circle" >}} Yes |
| `.xml` | {{< icon name="check-circle" >}} Yes | {{< icon name="check-circle" >}} Yes |
| `.txt` | {{< icon name="dotted-circle" >}} No | {{< icon name="check-circle" >}} Yes |
| `.log` | {{< icon name="dotted-circle" >}} No | {{< icon name="check-circle" >}} Yes |
### From a URL
You can browse the job artifacts of the latest successful pipeline for a specific job
with a publicly accessible URL.
For example, to browse the latest artifacts of a job named `build` in the `main` branch of a project on GitLab.com:
```plaintext
https://gitlab.com/<full-project-path>/-/jobs/artifacts/main/browse?job=build
```
Replace `<full-project-path>` with a valid project path, you can find it in the URL for your project.
## Delete job log and artifacts
{{< alert type="warning" >}}
Deleting the job log and artifacts is a destructive action that cannot be reverted. Use with caution.
Deleting certain files, including report artifacts, job logs, and metadata files, affects
GitLab features that use these files as data sources.
{{< /alert >}}
You can delete a job's artifacts and log.
Prerequisites:
- You must be the owner of the job or a user with at least the Maintainer role for the project.
To delete a job:
1. Go to a job's detail page.
1. In the upper-right corner of the job's log, select **Erase job log and artifacts** ({{< icon name="remove" >}}).
You can also delete individual artifacts from the [**Artifacts** page](#bulk-delete-artifacts).
### Bulk delete artifacts
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/33348) in GitLab 15.10 [with a flag](../../administration/feature_flags/_index.md) named `ci_job_artifact_bulk_destroy`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/398581) in GitLab 16.1. Feature flag `ci_job_artifact_bulk_destroy` removed.
{{< /history >}}
You can delete multiple artifacts at the same time:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Artifacts**.
1. Select the checkboxes next to the artifacts you want to delete. You can select up to 50 artifacts.
1. Select **Delete selected**.
## Link to job artifacts in the merge request UI
Use the [`artifacts:expose_as`](../yaml/_index.md#artifactsexpose_as) keyword to display
a link to job artifacts in the [merge request](../../user/project/merge_requests/_index.md) UI.
For example, for an artifact with a single file:
```yaml
test:
script: ["echo 'test' > file.txt"]
artifacts:
expose_as: 'artifact 1'
paths: ['file.txt']
```
With this configuration, GitLab adds **artifact 1** as a link to `file.txt` to the
**View exposed artifact** section of the relevant merge request.
## Keep artifacts from most recent successful jobs
{{< history >}}
- Artifacts for [blocked](https://gitlab.com/gitlab-org/gitlab/-/issues/387087) or [failed](https://gitlab.com/gitlab-org/gitlab/-/issues/266958) pipelines changed to no longer be kept indefinitely in GitLab 16.7.
{{< /history >}}
By default, artifacts are always kept for the most recent successful pipeline on each ref. Any `expire_in` configuration does not apply to the most recent artifacts.
When a new pipeline on the same ref completes successfully, the previous pipeline's artifacts are deleted according to the `expire_in` configuration. The artifacts of the new pipeline are kept automatically.
A pipeline's artifacts are only deleted according to the `expire_in` configuration if a new pipeline runs for the same ref and:
- Succeeds.
- Stops running due to being blocked by a manual job.
Keeping the latest artifacts can use a large amount of storage space in projects
with a lot of jobs or large artifacts. If the latest artifacts are not needed in
a project, you can disable this behavior to save space:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Artifacts**.
1. Clear the **Keep artifacts from most recent successful jobs** checkbox.
After disabling this setting, all new artifacts expire according to the `expire_in` configuration.
Artifacts in old pipelines continue to be kept until a new pipeline runs for the same ref.
Then the artifacts in the earlier pipeline for that ref are allowed to expire too.
You can disable this behavior for all projects on GitLab Self-Managed in the
[instance's CI/CD settings](../../administration/settings/continuous_integration.md#keep-artifacts-from-latest-successful-pipelines).
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Job artifacts
breadcrumbs:
- doc
- ci
- jobs
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Jobs can output an archive of files and directories. This output is known as a job artifact.
You can download job artifacts by using the GitLab UI or the [API](../../api/job_artifacts.md).
<i class="fa fa-youtube-play youtube" aria-hidden="true"></i>
For an overview of job artifacts, watch the video [GitLab CI pipelines, artifacts, and environments](https://www.youtube.com/watch?v=PCKDICEe10s).
Or, for an introduction, watch [GitLab CI pipeline tutorial for beginners](https://www.youtube.com/watch?v=Jav4vbUrqII).
For administrator information about job artifact storage, see [administering job artifacts](../../administration/cicd/job_artifacts.md).
## Create job artifacts
To create job artifacts, use the [`artifacts`](../yaml/_index.md#artifacts) keyword in your `.gitlab-ci.yml` file:
```yaml
pdf:
script: xelatex mycv.tex
artifacts:
paths:
- mycv.pdf
```
In this example, a job named `pdf` calls the `xelatex` command to build a PDF file from the
LaTeX source file, `mycv.tex`.
The [`paths`](../yaml/_index.md#artifactspaths) keyword determines which files to add to the job artifacts.
All paths to files and directories are relative to the repository where the job was created.
### With wildcards
You can use wildcards for paths and directories. For example, to create an artifact
with all the files inside the directories that end with `xyz`:
```yaml
job:
script: echo "build xyz project"
artifacts:
paths:
- path/*xyz/*
```
### With an expiry
The [`expire_in`](../yaml/_index.md#artifactsexpire_in) keyword determines how long
GitLab keeps the artifacts defined in `artifacts:paths`. For example:
```yaml
pdf:
script: xelatex mycv.tex
artifacts:
paths:
- mycv.pdf
expire_in: 1 week
```
If `expire_in` is not defined, the [instance-wide setting](../../administration/settings/continuous_integration.md#set-default-artifacts-expiration)
is used.
To prevent artifacts from expiring, you can select **Keep** from the job details page.
The option is not available when an artifact has no expiry set.
By default, the [latest artifacts are always kept](#keep-artifacts-from-most-recent-successful-jobs).
### With an explicitly defined artifact name
You can explicitly customize artifact names using the [`artifacts:name`](../yaml/_index.md#artifactsname) configuration:
```yaml
job:
artifacts:
name: "job1-artifacts-file"
paths:
- binaries/
```
### Without excluded files
Use [`artifacts:exclude`](../yaml/_index.md#artifactsexclude) to prevent files from
being added to an artifacts archive.
For example, to store all files in `binaries/`, but not `*.o` files located in
subdirectories of `binaries/`.
```yaml
artifacts:
paths:
- binaries/
exclude:
- binaries/**/*.o
```
Unlike [`artifacts:paths`](../yaml/_index.md#artifactspaths), `exclude` paths are not recursive.
To exclude all of the contents of a directory, match them explicitly rather
than matching the directory itself.
For example, to store all files in `binaries/` but nothing located in the `temp/` subdirectory:
```yaml
artifacts:
paths:
- binaries/
exclude:
- binaries/temp/**/*
```
### With untracked files
Use [`artifacts:untracked`](../yaml/_index.md#artifactsuntracked) to add all Git untracked
files as artifacts (along with the paths defined in [`artifacts:paths`](../yaml/_index.md#artifactspaths)). Untracked
files are those that haven't been added to the repository but exist in the repository checkout.
For example, to save all Git untracked files and files in `binaries`:
```yaml
artifacts:
untracked: true
paths:
- binaries/
```
For example, to save all untracked files but [exclude](../yaml/_index.md#artifactsexclude) `*.txt` files:
```yaml
artifacts:
untracked: true
exclude:
- "*.txt"
```
### With variable expansion
Variable expansion is supported for:
- [`artifacts:name`](../yaml/_index.md#artifactsname)
- [`artifacts:paths`](../yaml/_index.md#artifactspaths)
- [`artifacts:exclude`](../yaml/_index.md#artifactsexclude)
Instead of using shell, GitLab Runner uses its
[internal variable expansion mechanism](../variables/where_variables_can_be_used.md#gitlab-runner-internal-variable-expansion-mechanism).
Only [CI/CD variables](../variables/_index.md) are supported in this context.
For example, to create an archive using the current branch or tag name
including only files from a directory named after the current project:
```yaml
job:
artifacts:
name: "$CI_COMMIT_REF_NAME"
paths:
- binaries/${CI_PROJECT_NAME}/
```
When your branch name contains forward slashes (for example, `feature/my-feature`),
use `$CI_COMMIT_REF_SLUG` instead of `$CI_COMMIT_REF_NAME` to ensure proper artifact naming.
Variables are expanded before [globs](https://en.wikipedia.org/wiki/Glob_(programming)).
## Fetching artifacts
By default, jobs fetch all artifacts from jobs defined in previous stages. These artifacts are downloaded into the job's working directory.
You can control which artifacts to download by using these keywords:
- [`dependencies`](../yaml/_index.md#dependencies): Specify which jobs to download artifacts from.
- [`needs`](../yaml/_index.md#needs): Define relationships between jobs and specify which artifacts to download.
When you use these keywords, the default behavior changes and artifacts are fetched from only the jobs you specify.
### Prevent a job from fetching artifacts
To prevent a job from downloading any artifacts, set
[`dependencies`](../yaml/_index.md#dependencies) to an empty array
(`[]`):
```yaml
job:
stage: test
script: make build
dependencies: []
```
## View all job artifacts in a project
{{< history >}}
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/407475) in GitLab 16.0. Feature flag `artifacts_management_page` removed.
{{< /history >}}
You can view all artifacts stored in a project from the **Build > Artifacts** page.
This list displays all jobs and their associated artifacts. Expand an entry to access
all artifacts associated with a job, including:
- Artifacts created with the `artifacts:` keyword.
- [Report artifacts](../yaml/artifacts_reports.md).
- Job logs and metadata, which are stored internally as separate artifacts.
You can download or delete individual artifacts from this list.
## Download job artifacts
You can download job artifacts from:
- Any **Pipelines** list. On the right of the pipeline, select **Download artifacts** ({{< icon name="download" >}}).
- Any **Jobs** list. On the right of the job, select **Download artifacts** ({{< icon name="download" >}}).
- A job's detail page. On the right of the page, select **Download**.
- A merge request **Overview** page. On the right of the latest pipeline, select **Artifacts** ({{< icon name="download" >}}).
- The [**Artifacts**](#view-all-job-artifacts-in-a-project) page. On the right of the job, select **Download** ({{< icon name="download" >}}).
- The [artifacts browser](#browse-the-contents-of-the-artifacts-archive). On the top of the page,
select **Download artifacts archive** ({{< icon name="download" >}}).
[Report artifacts](../yaml/artifacts_reports.md) can only be downloaded from the **Pipelines** list
or **Artifacts** page.
You can download job artifacts from the latest successful pipeline by using [the job artifacts API](../../api/job_artifacts.md).
You cannot download [artifact reports](../yaml/artifacts_reports.md) with the job artifacts API,
unless the report is added as a regular artifact with `artifacts:paths`.
### From a URL
You can download the artifacts archive for a specific job with a publicly accessible
URL for the [job artifacts API](../../api/job_artifacts.md#download-job-artifacts-by-reference-name).
For example:
- To download the latest artifacts of a job named `build` in the `main` branch of a project on GitLab.com:
```plaintext
https://gitlab.com/api/v4/projects/<project-id>/jobs/artifacts/main/download?job=build
```
- To download the file `review/index.html` from the latest job named `build` in the `main` branch of a project on GitLab.com:
```plaintext
https://gitlab.com/api/v4/projects/<project-id>/jobs/artifacts/main/raw/review/index.html?job=build
```
Files returned by this endpoint always have the `plain/text` content type.
In both examples, replace `<project-id>` with a valid project ID. You can find the project ID on the
[project overview page](../../user/project/working_with_projects.md#find-the-project-id).
Artifacts for [parent and child pipelines](../pipelines/downstream_pipelines.md#parent-child-pipelines)
are searched in hierarchical order from parent to child. For example, if both parent and
child pipelines have a job with the same name, the job artifacts from the parent pipeline are returned.
### With a CI/CD job token
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can use a [CI/CD job token](ci_job_token.md) to authenticate with the [jobs artifacts API endpoint](../../api/job_artifacts.md)
and fetch artifacts from a different pipeline. You must specify which job to retrieve artifacts from,
for example:
```yaml
build_submodule:
stage: test
script:
- apt update && apt install -y unzip
- curl --location --output artifacts.zip "https://gitlab.example.com/api/v4/projects/1/jobs/artifacts/main/download?job=test&job_token=$CI_JOB_TOKEN"
- unzip artifacts.zip
```
To fetch artifacts from a job in the same pipeline, use the [`needs:artifacts`](../yaml/_index.md#needsartifacts) keyword.
## Browse the contents of the artifacts archive
You can browse the contents of the artifacts from the UI without downloading the artifact locally,
from:
- Any **Jobs** list. On the right of the job, select **Browse** ({{< icon name="folder-open" >}}).
- A job's detail page. On the right of the page, select **Browse**.
- The **Artifacts** page. On the right of the job, select **Browse** ({{< icon name="folder-open" >}}).
If [GitLab Pages](../../administration/pages/_index.md) is enabled globally, even if it is disabled in the project settings,
you can preview some artifacts file extensions directly in your browser. If the project is internal or private,
you must enable [GitLab Pages access control](../../administration/pages/_index.md#access-control) to enable the preview.
The following extensions are supported:
| File extension | GitLab.com | Linux package with built-in NGINX |
|----------------|--------------------------------------|-----------------------------------|
| `.html` | {{< icon name="check-circle" >}} Yes | {{< icon name="check-circle" >}} Yes |
| `.json` | {{< icon name="check-circle" >}} Yes | {{< icon name="check-circle" >}} Yes |
| `.xml` | {{< icon name="check-circle" >}} Yes | {{< icon name="check-circle" >}} Yes |
| `.txt` | {{< icon name="dotted-circle" >}} No | {{< icon name="check-circle" >}} Yes |
| `.log` | {{< icon name="dotted-circle" >}} No | {{< icon name="check-circle" >}} Yes |
### From a URL
You can browse the job artifacts of the latest successful pipeline for a specific job
with a publicly accessible URL.
For example, to browse the latest artifacts of a job named `build` in the `main` branch of a project on GitLab.com:
```plaintext
https://gitlab.com/<full-project-path>/-/jobs/artifacts/main/browse?job=build
```
Replace `<full-project-path>` with a valid project path, you can find it in the URL for your project.
## Delete job log and artifacts
{{< alert type="warning" >}}
Deleting the job log and artifacts is a destructive action that cannot be reverted. Use with caution.
Deleting certain files, including report artifacts, job logs, and metadata files, affects
GitLab features that use these files as data sources.
{{< /alert >}}
You can delete a job's artifacts and log.
Prerequisites:
- You must be the owner of the job or a user with at least the Maintainer role for the project.
To delete a job:
1. Go to a job's detail page.
1. In the upper-right corner of the job's log, select **Erase job log and artifacts** ({{< icon name="remove" >}}).
You can also delete individual artifacts from the [**Artifacts** page](#bulk-delete-artifacts).
### Bulk delete artifacts
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/33348) in GitLab 15.10 [with a flag](../../administration/feature_flags/_index.md) named `ci_job_artifact_bulk_destroy`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/398581) in GitLab 16.1. Feature flag `ci_job_artifact_bulk_destroy` removed.
{{< /history >}}
You can delete multiple artifacts at the same time:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Artifacts**.
1. Select the checkboxes next to the artifacts you want to delete. You can select up to 50 artifacts.
1. Select **Delete selected**.
## Link to job artifacts in the merge request UI
Use the [`artifacts:expose_as`](../yaml/_index.md#artifactsexpose_as) keyword to display
a link to job artifacts in the [merge request](../../user/project/merge_requests/_index.md) UI.
For example, for an artifact with a single file:
```yaml
test:
script: ["echo 'test' > file.txt"]
artifacts:
expose_as: 'artifact 1'
paths: ['file.txt']
```
With this configuration, GitLab adds **artifact 1** as a link to `file.txt` to the
**View exposed artifact** section of the relevant merge request.
## Keep artifacts from most recent successful jobs
{{< history >}}
- Artifacts for [blocked](https://gitlab.com/gitlab-org/gitlab/-/issues/387087) or [failed](https://gitlab.com/gitlab-org/gitlab/-/issues/266958) pipelines changed to no longer be kept indefinitely in GitLab 16.7.
{{< /history >}}
By default, artifacts are always kept for the most recent successful pipeline on each ref. Any `expire_in` configuration does not apply to the most recent artifacts.
When a new pipeline on the same ref completes successfully, the previous pipeline's artifacts are deleted according to the `expire_in` configuration. The artifacts of the new pipeline are kept automatically.
A pipeline's artifacts are only deleted according to the `expire_in` configuration if a new pipeline runs for the same ref and:
- Succeeds.
- Stops running due to being blocked by a manual job.
Keeping the latest artifacts can use a large amount of storage space in projects
with a lot of jobs or large artifacts. If the latest artifacts are not needed in
a project, you can disable this behavior to save space:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **Artifacts**.
1. Clear the **Keep artifacts from most recent successful jobs** checkbox.
After disabling this setting, all new artifacts expire according to the `expire_in` configuration.
Artifacts in old pipelines continue to be kept until a new pipeline runs for the same ref.
Then the artifacts in the earlier pipeline for that ref are allowed to expire too.
You can disable this behavior for all projects on GitLab Self-Managed in the
[instance's CI/CD settings](../../administration/settings/continuous_integration.md#keep-artifacts-from-latest-successful-pipelines).
|
https://docs.gitlab.com/ci/job_artifacts_troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/job_artifacts_troubleshooting.md
|
2025-08-13
|
doc/ci/jobs
|
[
"doc",
"ci",
"jobs"
] |
job_artifacts_troubleshooting.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting job artifacts
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
When working with [job artifacts](job_artifacts.md), you might encounter the following issues.
## Job does not retrieve certain artifacts
By default, jobs fetch all artifacts from previous stages, but jobs using `dependencies`
or `needs` do not fetch artifacts from all jobs by default.
If you use these keywords, artifacts are fetched from only a subset of jobs. Review
the keyword reference for information on how to fetch artifacts with these keywords:
- [`dependencies`](../yaml/_index.md#dependencies)
- [`needs`](../yaml/_index.md#needs)
- [`needs:artifacts`](../yaml/_index.md#needsartifacts)
## Job artifacts use too much disk space
If job artifacts are using too much disk space, see the
[job artifacts administration documentation](../../administration/cicd/job_artifacts_troubleshooting.md#job-artifacts-using-too-much-disk-space).
## Error message `No files to upload`
This message appears in job logs when a the runner can't find the file to upload. Either
the path to the file is incorrect, or the file was not created. You can check the job
log for other errors or warnings that specify the filename and why it wasn't
generated.
For more detailed job logs, you can [enable CI/CD debug logging](../variables/variables_troubleshooting.md#enable-debug-logging)
and try the job again. This logging might provide more information about why the file
wasn't created.
## Error message `FATAL: invalid argument` when uploading a dotenv artifact on a Windows runner
The PowerShell `echo` command writes files with UCS-2 LE BOM (Byte Order Mark) encoding,
but only UTF-8 is supported. If you try to create a [`dotenv`](../yaml/artifacts_reports.md)
artifact with `echo`, it causes a `FATAL: invalid argument` error.
Use PowerShell `Add-Content` instead, which uses UTF-8:
```yaml
test-job:
stage: test
tags:
- windows
script:
- echo "test job"
- Add-Content -Path build.env -Value "MY_ENV_VAR=true"
artifacts:
reports:
dotenv: build.env
```
## Job artifacts do not expire
If some job artifacts are not expiring as expected, check if the
[**Keep artifacts from most recent successful jobs**](job_artifacts.md#keep-artifacts-from-most-recent-successful-jobs)
setting is enabled.
When this setting is enabled, job artifacts from the latest successful pipeline
of each ref do not expire and are not deleted.
## Error message `This job could not start because it could not retrieve the needed artifacts.`
A job fails to start and returns this error message if it can't fetch the artifacts
it expects. This error is returned when:
- The job's dependencies are not found. By default, jobs in later stages fetch artifacts
from jobs in all earlier stages, so the earlier jobs are all considered dependent.
If the job uses the [`dependencies`](../yaml/_index.md#dependencies) keyword, only
the listed jobs are dependent.
- The artifacts are already expired. You can set a longer expiry with [`artifacts:expire_in`](../yaml/_index.md#artifactsexpire_in).
- The job cannot access the relevant resources due to insufficient permissions.
See these additional troubleshooting steps if the job uses the [`needs:artifacts`](../yaml/_index.md#needsartifacts):
keyword with:
- [`needs:project`](#for-a-job-configured-with-needsproject)
- [`needs:pipeline:job`](#for-a-job-configured-with-needspipelinejob)
### For a job configured with `needs:project`
The `could not retrieve the needed artifacts.` error can happen for a job using
[`needs:project`](../yaml/_index.md#needsproject) with a configuration similar to:
```yaml
rspec:
needs:
- project: my-group/my-project
job: dependency-job
ref: master
artifacts: true
```
To troubleshoot this error, verify that:
- Project `my-group/my-project` is in a group with a Premium subscription plan.
- The user running the job can access resources in `my-group/my-project`.
- The `project`, `job`, and `ref` combination exists and results in the desired dependency.
- Any variables in use evaluate to the correct values.
If you use the `CI_JOB_TOKEN`, add the token to the project's [allowlist](ci_job_token.md#control-job-token-access-to-your-project) to pull artifacts from a different project.
### For a job configured with `needs:pipeline:job`
The `could not retrieve the needed artifacts.` error can happen for a job using
[`needs:pipeline:job`](../yaml/_index.md#needspipelinejob) with a configuration similar to:
```yaml
rspec:
needs:
- pipeline: $UPSTREAM_PIPELINE_ID
job: dependency-job
artifacts: true
```
To troubleshoot this error, verify that:
- The `$UPSTREAM_PIPELINE_ID` CI/CD variable is available in the current pipeline's
parent-child pipeline hierarchy.
- The `pipeline` and `job` combination exists and resolves to an existing pipeline.
- `dependency-job` has run and finished successfully.
## Jobs show `UnlockPipelinesInQueueWorker` after an upgrade
Jobs might stall and show an error that states `UnlockPipelinesInQueueWorker`.
This issue occurs after an upgrade.
The workaround is to enable the `ci_unlock_pipelines_extra_low` feature flag.
To toggle feature flags, you must be an administrator.
On GitLab SaaS:
- Run the following [ChatOps](../chatops/_index.md) command:
```ruby
/chatops run feature set ci_unlock_pipelines_extra_low true
```
On GitLab Self-Managed:
- [Enable the feature flag](../../administration/feature_flags/_index.md) named `ci_unlock_pipelines_extra_low`.
For more information see the comment in [merge request 140318](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/140318#note_1718600424).
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting job artifacts
breadcrumbs:
- doc
- ci
- jobs
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
When working with [job artifacts](job_artifacts.md), you might encounter the following issues.
## Job does not retrieve certain artifacts
By default, jobs fetch all artifacts from previous stages, but jobs using `dependencies`
or `needs` do not fetch artifacts from all jobs by default.
If you use these keywords, artifacts are fetched from only a subset of jobs. Review
the keyword reference for information on how to fetch artifacts with these keywords:
- [`dependencies`](../yaml/_index.md#dependencies)
- [`needs`](../yaml/_index.md#needs)
- [`needs:artifacts`](../yaml/_index.md#needsartifacts)
## Job artifacts use too much disk space
If job artifacts are using too much disk space, see the
[job artifacts administration documentation](../../administration/cicd/job_artifacts_troubleshooting.md#job-artifacts-using-too-much-disk-space).
## Error message `No files to upload`
This message appears in job logs when a the runner can't find the file to upload. Either
the path to the file is incorrect, or the file was not created. You can check the job
log for other errors or warnings that specify the filename and why it wasn't
generated.
For more detailed job logs, you can [enable CI/CD debug logging](../variables/variables_troubleshooting.md#enable-debug-logging)
and try the job again. This logging might provide more information about why the file
wasn't created.
## Error message `FATAL: invalid argument` when uploading a dotenv artifact on a Windows runner
The PowerShell `echo` command writes files with UCS-2 LE BOM (Byte Order Mark) encoding,
but only UTF-8 is supported. If you try to create a [`dotenv`](../yaml/artifacts_reports.md)
artifact with `echo`, it causes a `FATAL: invalid argument` error.
Use PowerShell `Add-Content` instead, which uses UTF-8:
```yaml
test-job:
stage: test
tags:
- windows
script:
- echo "test job"
- Add-Content -Path build.env -Value "MY_ENV_VAR=true"
artifacts:
reports:
dotenv: build.env
```
## Job artifacts do not expire
If some job artifacts are not expiring as expected, check if the
[**Keep artifacts from most recent successful jobs**](job_artifacts.md#keep-artifacts-from-most-recent-successful-jobs)
setting is enabled.
When this setting is enabled, job artifacts from the latest successful pipeline
of each ref do not expire and are not deleted.
## Error message `This job could not start because it could not retrieve the needed artifacts.`
A job fails to start and returns this error message if it can't fetch the artifacts
it expects. This error is returned when:
- The job's dependencies are not found. By default, jobs in later stages fetch artifacts
from jobs in all earlier stages, so the earlier jobs are all considered dependent.
If the job uses the [`dependencies`](../yaml/_index.md#dependencies) keyword, only
the listed jobs are dependent.
- The artifacts are already expired. You can set a longer expiry with [`artifacts:expire_in`](../yaml/_index.md#artifactsexpire_in).
- The job cannot access the relevant resources due to insufficient permissions.
See these additional troubleshooting steps if the job uses the [`needs:artifacts`](../yaml/_index.md#needsartifacts):
keyword with:
- [`needs:project`](#for-a-job-configured-with-needsproject)
- [`needs:pipeline:job`](#for-a-job-configured-with-needspipelinejob)
### For a job configured with `needs:project`
The `could not retrieve the needed artifacts.` error can happen for a job using
[`needs:project`](../yaml/_index.md#needsproject) with a configuration similar to:
```yaml
rspec:
needs:
- project: my-group/my-project
job: dependency-job
ref: master
artifacts: true
```
To troubleshoot this error, verify that:
- Project `my-group/my-project` is in a group with a Premium subscription plan.
- The user running the job can access resources in `my-group/my-project`.
- The `project`, `job`, and `ref` combination exists and results in the desired dependency.
- Any variables in use evaluate to the correct values.
If you use the `CI_JOB_TOKEN`, add the token to the project's [allowlist](ci_job_token.md#control-job-token-access-to-your-project) to pull artifacts from a different project.
### For a job configured with `needs:pipeline:job`
The `could not retrieve the needed artifacts.` error can happen for a job using
[`needs:pipeline:job`](../yaml/_index.md#needspipelinejob) with a configuration similar to:
```yaml
rspec:
needs:
- pipeline: $UPSTREAM_PIPELINE_ID
job: dependency-job
artifacts: true
```
To troubleshoot this error, verify that:
- The `$UPSTREAM_PIPELINE_ID` CI/CD variable is available in the current pipeline's
parent-child pipeline hierarchy.
- The `pipeline` and `job` combination exists and resolves to an existing pipeline.
- `dependency-job` has run and finished successfully.
## Jobs show `UnlockPipelinesInQueueWorker` after an upgrade
Jobs might stall and show an error that states `UnlockPipelinesInQueueWorker`.
This issue occurs after an upgrade.
The workaround is to enable the `ci_unlock_pipelines_extra_low` feature flag.
To toggle feature flags, you must be an administrator.
On GitLab SaaS:
- Run the following [ChatOps](../chatops/_index.md) command:
```ruby
/chatops run feature set ci_unlock_pipelines_extra_low true
```
On GitLab Self-Managed:
- [Enable the feature flag](../../administration/feature_flags/_index.md) named `ci_unlock_pipelines_extra_low`.
For more information see the comment in [merge request 140318](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/140318#note_1718600424).
|
https://docs.gitlab.com/ci/job_rules
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/job_rules.md
|
2025-08-13
|
doc/ci/jobs
|
[
"doc",
"ci",
"jobs"
] |
job_rules.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Specify when jobs run with `rules`
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use [`rules`](../yaml/_index.md#rules) to include or exclude jobs in pipelines.
Rules are evaluated in order until the first match. When a match is found, the job
is either included or excluded from the pipeline, depending on the configuration.
You cannot use dotenv variables created in job scripts in rules, because rules are evaluated before any jobs run.
Future keyword improvements are being discussed in our [epic for improving `rules`](https://gitlab.com/groups/gitlab-org/-/epics/2783),
where anyone can add suggestions or requests.
## `rules` examples
The following example uses `if` to define that the job runs in only two specific cases:
```yaml
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
allow_failure: true
- if: $CI_PIPELINE_SOURCE == "schedule"
```
- If the pipeline is for a merge request, the first rule matches, and the job
is added to the [merge request pipeline](../pipelines/merge_request_pipelines.md)
with attributes of:
- `when: manual` (manual job)
- `allow_failure: true` (the pipeline continues running even if the manual job is not run)
- If the pipeline is **not** for a merge request, the first rule doesn't match, and the
second rule is evaluated.
- If the pipeline is a scheduled pipeline, the second rule matches, and the job
is added to the scheduled pipeline. No attributes were defined, so it is added
with:
- `when: on_success` (default)
- `allow_failure: false` (default)
- In **all other cases**, no rules match, so the job is **not** added to any other pipeline.
Alternatively, you can define a set of rules to exclude jobs in a few cases, but
run them in all other cases:
```yaml
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: never
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- when: on_success
```
- If the pipeline is for a merge request, the job is **not** added to the pipeline.
- If the pipeline is a scheduled pipeline, the job is **not** added to the pipeline.
- In **all other cases**, the job is added to the pipeline, with `when: on_success`.
{{< alert type="warning" >}}
If you use a `when` clause as the final rule (not including `when: never`), two
simultaneous pipelines may start. Both push pipelines and merge request pipelines can
be triggered by the same event (a push to the source branch for an open merge request).
See how to [prevent duplicate pipelines](#avoid-duplicate-pipelines)
for more details.
{{< /alert >}}
### Run jobs for scheduled pipelines
You can configure a job to be executed only when the pipeline has been
scheduled. For example:
```yaml
job:on-schedule:
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
script:
- make world
job:
rules:
- if: $CI_PIPELINE_SOURCE == "push"
script:
- make build
```
In this example, `make world` runs in scheduled pipelines, and `make build`
runs in branch and tag pipelines.
### Skip jobs if the branch is empty
Use [`rules:changes:compare_to`](../yaml/_index.md#ruleschangescompare_to) to
skip a job when the branch is empty, which saves CI/CD resources. The configuration compares the
branch to the default branch, and if the branch:
- Doesn't have changed files, the job doesn't run.
- Has changed files, the job runs.
For example, in a project with `main` as the default branch:
```yaml
job:
script:
- echo "This job only runs for branches that are not empty"
rules:
- if: $CI_COMMIT_BRANCH
changes:
compare_to: 'refs/heads/main'
paths:
- '**/*'
```
The rule for this job compares all files and paths in the current branch
recursively (`**/*`) against the `main` branch. The rule matches and the
job runs only when there are changes to the files in the branch.
## Common `if` clauses with predefined variables
`rules:if` clauses are commonly used with [predefined CI/CD variables](../variables/predefined_variables.md),
especially the [`CI_PIPELINE_SOURCE` predefined variable](#ci_pipeline_source-predefined-variable).
The following example runs the job as a manual job in scheduled pipelines or in push
pipelines (to branches or tags), with `when: on_success` (default). It does not
add the job to any other pipeline type.
```yaml
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: manual
allow_failure: true
- if: $CI_PIPELINE_SOURCE == "push"
```
The following example runs the job as a `when: on_success` job in [merge request pipelines](../pipelines/merge_request_pipelines.md)
and scheduled pipelines. It does not run in any other pipeline type.
```yaml
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_PIPELINE_SOURCE == "schedule"
```
Other commonly used `if` clauses:
- `if: $CI_COMMIT_TAG`: If changes are pushed for a tag.
- `if: $CI_COMMIT_BRANCH`: If changes are pushed to any branch.
- `if: $CI_COMMIT_BRANCH == "main"`: If changes are pushed to `main`.
- `if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH`: If changes are pushed to the default
branch. Use when you want to have the same configuration in multiple
projects with different default branches.
- `if: $CI_COMMIT_BRANCH =~ /regex-expression/`: If the commit branch matches a regular expression.
- `if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_COMMIT_TITLE =~ /Merge branch.*/`:
If the commit branch is the default branch and the commit message title matches a regular expression.
For example, the default commit message for a merge commit starts with `Merge branch`.
- `if: $CUSTOM_VARIABLE == "value1"`: If the custom variable `CUSTOM_VARIABLE` is
exactly `value1`.
### Run jobs only in specific pipeline types
You can use [predefined CI/CD variables](../variables/predefined_variables.md) with
[`rules`](../yaml/_index.md#rules) to choose which pipeline types jobs should run for.
The following table lists some of the variables that you can use, and the pipeline
types the variables can control for:
- Branch pipelines that run for Git `push` events to a branch, like new commits or tags.
- Tag pipelines that run only when a new Git tag is pushed to a branch.
- [Merge request pipelines](../pipelines/merge_request_pipelines.md) that run for changes
to a merge request, like new commits or selecting **Run pipeline**
in a merge request's pipelines tab.
- [Scheduled pipelines](../pipelines/schedules.md).
| Variables | Branch | Tag | Merge request | Scheduled |
|--------------------------------------------|--------|-----|---------------|-----------|
| `CI_COMMIT_BRANCH` | Yes | | | Yes |
| `CI_COMMIT_TAG` | | Yes | | Yes, if the scheduled pipeline is configured to run on a tag. |
| `CI_PIPELINE_SOURCE = push` | Yes | Yes | | |
| `CI_PIPELINE_SOURCE = schedule` | | | | Yes |
| `CI_PIPELINE_SOURCE = merge_request_event` | | | Yes | |
| `CI_MERGE_REQUEST_IID` | | | Yes | |
For example, to configure a job to run for merge request pipelines and scheduled pipelines,
but not branch or tag pipelines:
```yaml
job1:
script:
- echo
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_PIPELINE_SOURCE == "schedule"
- if: $CI_PIPELINE_SOURCE == "push"
when: never
```
### `CI_PIPELINE_SOURCE` predefined variable
Use the `CI_PIPELINE_SOURCE` variable to control when to add jobs for these pipeline types:
| Value | Description |
|---------------------------------|-------------|
| `api` | For pipelines triggered by the [pipelines API](../../api/pipelines.md#create-a-new-pipeline). |
| `chat` | For pipelines created by using a [GitLab ChatOps](../chatops/_index.md) command. |
| `external` | When you use CI services other than GitLab. |
| `external_pull_request_event` | When an [external pull request on GitHub](../ci_cd_for_external_repos/_index.md#pipelines-for-external-pull-requests) is created or updated. |
| `merge_request_event` | For pipelines created when a merge request is created or updated. Required to enable [merge request pipelines](../pipelines/merge_request_pipelines.md), [merged results pipelines](../pipelines/merged_results_pipelines.md), and [merge trains](../pipelines/merge_trains.md). |
| `ondemand_dast_scan` | For [DAST on-demand scan](../../user/application_security/dast/on-demand_scan.md) pipelines. |
| `ondemand_dast_validation` | For [DAST on-demand validation](../../user/application_security/dast/profiles.md#site-profile-validation) pipelines |
| `parent_pipeline` | For pipelines triggered by a [parent/child pipeline](../pipelines/downstream_pipelines.md#parent-child-pipelines). Use this pipeline source in the child pipeline configuration so that it can be triggered by the parent pipeline. |
| `pipeline` | For [multi-project pipelines](../pipelines/downstream_pipelines.md#multi-project-pipelines) created by [using the API with `CI_JOB_TOKEN`](../pipelines/downstream_pipelines.md#trigger-a-multi-project-pipeline-by-using-the-api), or the [`trigger`](../yaml/_index.md#trigger) keyword. |
| `push` | For pipelines triggered by a Git push event, including for branches and tags. |
| `schedule` | For [scheduled pipelines](../pipelines/schedules.md). |
| `security_orchestration_policy` | For [scheduled scan execution policies](../../user/application_security/policies/scan_execution_policies.md) pipelines. |
| `trigger` | For pipelines created by using a [trigger token](../triggers/_index.md#configure-cicd-jobs-to-run-in-triggered-pipelines). |
| `web` | For pipelines created by selecting **New pipeline** in the GitLab UI, from the project's **Build > Pipelines** section. |
| `webide` | For pipelines created by using the [Web IDE](../../user/project/web_ide/_index.md). |
These values are the same as returned for the `source` parameter when using the
[pipelines API endpoint](../../api/pipelines.md#list-project-pipelines).
## Complex rules
You can use all `rules` keywords, like `if`, `changes`, and `exists`, in the same
rule. The rule evaluates to true only when all included keywords evaluate to true.
For example:
```yaml
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $VAR == "string value"
changes: # Include the job and set to when:manual if any of the follow paths match a modified file.
- Dockerfile
- docker/scripts/**/*
when: manual
allow_failure: true
```
If the `Dockerfile` file or any file in `/docker/scripts` has changed **and** `$VAR` == "string value",
then the job runs manually and is allowed to fail.
You can use [parentheses](#join-variable-expressions-together) with `&&` and `||` to build more complicated variable expressions.
```yaml
job1:
script:
- echo This rule uses parentheses.
rules:
- if: ($CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH || $CI_COMMIT_BRANCH == "develop") && $MY_VARIABLE
```
## Avoid duplicate pipelines
If a job uses `rules`, a single action, like pushing a commit to a branch, can trigger
multiple pipelines. You don't have to explicitly configure rules for multiple types
of pipeline to trigger them accidentally.
Some configurations that have the potential to cause duplicate pipelines cause a
[pipeline warning](../debugging.md#pipeline-warnings) to be displayed.
For example:
```yaml
job:
script: echo "This job creates double pipelines!"
rules:
- if: $CUSTOM_VARIABLE == "false"
when: never
- when: always
```
This job does not run when `$CUSTOM_VARIABLE` is false, but it does run in **all**
other pipelines, including **both** push (branch) and merge request pipelines. With
this configuration, every push to an open merge request's source branch
causes duplicated pipelines.
To avoid duplicate pipelines, you can:
- Use [`workflow`](../yaml/_index.md#workflow) to specify which types of pipelines
can run.
- Rewrite the rules to run the job only in very specific cases,
and avoid a final `when` rule:
```yaml
job:
script: echo "This job does NOT create double pipelines!"
rules:
- if: $CUSTOM_VARIABLE == "true" && $CI_PIPELINE_SOURCE == "merge_request_event"
```
You can also avoid duplicate pipelines by changing the job rules to avoid either push (branch)
pipelines or merge request pipelines. However, if you use a `- when: always` rule without
`workflow: rules`, GitLab still displays a [pipeline warning](../debugging.md#pipeline-warnings).
For example, the following does not trigger double pipelines, but is not recommended
without `workflow: rules`:
```yaml
job:
script: echo "This job does NOT create double pipelines!"
rules:
- if: $CI_PIPELINE_SOURCE == "push"
when: never
- when: always
```
You should not include both push and merge request pipelines in the same job without
[`workflow:rules` that prevent duplicate pipelines](../yaml/workflow.md#switch-between-branch-pipelines-and-merge-request-pipelines):
```yaml
job:
script: echo "This job creates double pipelines!"
rules:
- if: $CI_PIPELINE_SOURCE == "push"
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
```
Also, do not mix `only/except` jobs with `rules` jobs in the same pipeline.
It may not cause YAML errors, but the different default behaviors of `only/except`
and `rules` can cause issues that are difficult to troubleshoot:
```yaml
job-with-no-rules:
script: echo "This job runs in branch pipelines."
job-with-rules:
script: echo "This job runs in merge request pipelines."
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
```
For every change pushed to the branch, duplicate pipelines run. One
branch pipeline runs a single job (`job-with-no-rules`), and one merge request pipeline
runs the other job (`job-with-rules`). Jobs with no rules default
to [`except: merge_requests`](../yaml/deprecated_keywords.md#only--except), so `job-with-no-rules`
runs in all cases except merge requests.
## Reuse rules in different jobs
Use [`!reference` tags](../yaml/yaml_optimization.md#reference-tags) to reuse rules in different
jobs. You can combine `!reference` rules with regular job-defined rules. For example:
```yaml
.default_rules:
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
job1:
rules:
- !reference [.default_rules, rules]
script:
- echo "This job runs for the default branch, but not schedules."
job2:
rules:
- !reference [.default_rules, rules]
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
script:
- echo "This job runs for the default branch, but not schedules."
- echo "It also runs for merge requests."
```
## CI/CD variable expressions
Use variable expressions with [`rules:if`](../yaml/_index.md#rules) to control
when jobs should be added to a pipeline.
You can use the equality operators `==` and `!=` to compare a variable with a
string. Both single quotes and double quotes are valid. The variable has to be on the left side of the comparison. For example:
- `if: $VARIABLE == "some value"`
- `if: $VARIABLE != "some value"`
You can compare the values of two variables. For example:
- `if: $VARIABLE_1 == $VARIABLE_2`
- `if: $VARIABLE_1 != $VARIABLE_2`
You can compare a variable to the `null` keyword to see if it is defined. For example:
- `if: $VARIABLE == null`
- `if: $VARIABLE != null`
You can check if a variable is defined but empty. For example:
- `if: $VARIABLE == ""`
- `if: $VARIABLE != ""`
You can check if a variable is both defined and not empty by using just the variable name in
the expression. For example:
- `if: $VARIABLE`
You can also [use CI/CD inputs in variable expressions](../inputs/examples.md#use-cicd-inputs-in-variable-expressions).
### Compare a variable to a regular expression
You can do regular expression matching on variable values with the `=~` and `!~` operators.
Variable pattern matching with regular expressions uses the
[RE2 regular expression syntax](https://github.com/google/re2/wiki/Syntax).
Expressions evaluate as `true` if:
- Matches are found when using `=~`.
- Matches are not found when using `!~`.
For example:
- `if: $VARIABLE =~ /^content.*/`
- `if: $VARIABLE !~ /^content.*/`
Additionally:
- Single-character regular expressions, like `/./`, are not supported and
produce an `invalid expression syntax` error.
- Pattern matching is case-sensitive by default. Use the `i` flag modifier to make a
pattern case-insensitive. For example: `/pattern/i`.
- Only the tag or branch name can be matched by a regular expression.
The repository path, if given, is always matched literally.
- The entire pattern must be surrounded by `/`. For example, you can't use `issue-/.*/`
to match all tag names or branch names that begin with `issue-`, but you can use `/issue-.*/`.
- The `@` symbol denotes the beginning of a ref's repository path.
To match a ref name that contains the `@` character in a regular expression,
you must use the hex character code match `\x40`.
- Use anchors `^` and `$` to avoid the regular expression matching only a substring
of the tag name or branch name. For example, `/^issue-.*$/` is equivalent to `/^issue-/`,
while just `/issue/` would also match a branch called `severe-issues`.
### Store a regular expression in a variable
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/35438) in GitLab 15.0 [with a flag](../../administration/feature_flags/_index.md) named `ci_fix_rules_if_comparison_with_regexp_variable`, disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/359740) and feature flag `ci_fix_rules_if_comparison_with_regexp_variable` removed in GitLab 15.1.
{{< /history >}}
Variables on the right side of `=~` and `!~` expressions are evaluated as regular expressions.
The regular expression must be enclosed in forward slashes (`/`). For example:
```yaml
variables:
pattern: '/^ab.*/'
regex-job1:
variables:
teststring: 'abcde'
script: echo "This job will run, because 'abcde' matches the /^ab.*/ pattern."
rules:
- if: '$teststring =~ $pattern'
regex-job2:
variables:
teststring: 'fghij'
script: echo "This job will not run, because 'fghi' does not match the /^ab.*/ pattern."
rules:
- if: '$teststring =~ $pattern'
```
Variables in a regular expression are **not resolved**. For example:
```yaml
variables:
string1: 'regex-job1'
string2: 'regex-job2'
pattern: '/$string2/'
regex-job1:
script: echo "This job will NOT run, because the 'string1' variable inside the regex pattern is not resolved."
rules:
- if: '$CI_JOB_NAME =~ /$string1/'
regex-job2:
script: echo "This job will NOT run, because the 'string2' variable inside the 'pattern' variable is not resolved."
rules:
- if: '$CI_JOB_NAME =~ $pattern'
```
### Join variable expressions together
You can join multiple expressions using `&&` (and) or `||` (or), for example:
- `$VARIABLE1 =~ /^content.*/ && $VARIABLE2 == "something"`
- `$VARIABLE1 =~ /^content.*/ && $VARIABLE2 =~ /thing$/ && $VARIABLE3`
- `$VARIABLE1 =~ /^content.*/ || $VARIABLE2 =~ /thing$/ && $VARIABLE3`
The precedence of operators follows the [Ruby 2.5 standard](https://ruby-doc.org/core-2.5.0/doc/syntax/precedence_rdoc.html),
so `&&` evaluates before `||`.
You can use parentheses to group expressions together. Parentheses take precedence over
`&&` and `||`, so expressions enclosed in parentheses evaluate first, and the
result is used for the rest of the expression.
Nest parentheses to create complex conditions, and the inner-most expressions
in parentheses evaluate first. For example:
- `($VARIABLE1 =~ /^content.*/ || $VARIABLE2) && ($VARIABLE3 =~ /thing$/ || $VARIABLE4)`
- `($VARIABLE1 =~ /^content.*/ || $VARIABLE2 =~ /thing$/) && $VARIABLE3`
- `$CI_COMMIT_BRANCH == "my-branch" || (($VARIABLE1 == "thing" || $VARIABLE2 == "thing") && $VARIABLE3)`
## Troubleshooting
### Unexpected behavior from regular expression matching with `=~`
When using the `=~` character, make sure the right side of the comparison always contains
a valid regular expression.
If the right side of the comparison is not a valid regular expression enclosed with `/` characters,
the expression evaluates in an unexpected way. In that case, the comparison checks
if the left side is a substring of the right side. For example, `"23" =~ "1234"` evaluates to true,
which is the opposite of `"23" =~ /1234/`, which evaluates to false.
You should not configure your pipeline to rely on this behavior.
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Specify when jobs run with `rules`
breadcrumbs:
- doc
- ci
- jobs
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use [`rules`](../yaml/_index.md#rules) to include or exclude jobs in pipelines.
Rules are evaluated in order until the first match. When a match is found, the job
is either included or excluded from the pipeline, depending on the configuration.
You cannot use dotenv variables created in job scripts in rules, because rules are evaluated before any jobs run.
Future keyword improvements are being discussed in our [epic for improving `rules`](https://gitlab.com/groups/gitlab-org/-/epics/2783),
where anyone can add suggestions or requests.
## `rules` examples
The following example uses `if` to define that the job runs in only two specific cases:
```yaml
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
allow_failure: true
- if: $CI_PIPELINE_SOURCE == "schedule"
```
- If the pipeline is for a merge request, the first rule matches, and the job
is added to the [merge request pipeline](../pipelines/merge_request_pipelines.md)
with attributes of:
- `when: manual` (manual job)
- `allow_failure: true` (the pipeline continues running even if the manual job is not run)
- If the pipeline is **not** for a merge request, the first rule doesn't match, and the
second rule is evaluated.
- If the pipeline is a scheduled pipeline, the second rule matches, and the job
is added to the scheduled pipeline. No attributes were defined, so it is added
with:
- `when: on_success` (default)
- `allow_failure: false` (default)
- In **all other cases**, no rules match, so the job is **not** added to any other pipeline.
Alternatively, you can define a set of rules to exclude jobs in a few cases, but
run them in all other cases:
```yaml
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: never
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- when: on_success
```
- If the pipeline is for a merge request, the job is **not** added to the pipeline.
- If the pipeline is a scheduled pipeline, the job is **not** added to the pipeline.
- In **all other cases**, the job is added to the pipeline, with `when: on_success`.
{{< alert type="warning" >}}
If you use a `when` clause as the final rule (not including `when: never`), two
simultaneous pipelines may start. Both push pipelines and merge request pipelines can
be triggered by the same event (a push to the source branch for an open merge request).
See how to [prevent duplicate pipelines](#avoid-duplicate-pipelines)
for more details.
{{< /alert >}}
### Run jobs for scheduled pipelines
You can configure a job to be executed only when the pipeline has been
scheduled. For example:
```yaml
job:on-schedule:
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
script:
- make world
job:
rules:
- if: $CI_PIPELINE_SOURCE == "push"
script:
- make build
```
In this example, `make world` runs in scheduled pipelines, and `make build`
runs in branch and tag pipelines.
### Skip jobs if the branch is empty
Use [`rules:changes:compare_to`](../yaml/_index.md#ruleschangescompare_to) to
skip a job when the branch is empty, which saves CI/CD resources. The configuration compares the
branch to the default branch, and if the branch:
- Doesn't have changed files, the job doesn't run.
- Has changed files, the job runs.
For example, in a project with `main` as the default branch:
```yaml
job:
script:
- echo "This job only runs for branches that are not empty"
rules:
- if: $CI_COMMIT_BRANCH
changes:
compare_to: 'refs/heads/main'
paths:
- '**/*'
```
The rule for this job compares all files and paths in the current branch
recursively (`**/*`) against the `main` branch. The rule matches and the
job runs only when there are changes to the files in the branch.
## Common `if` clauses with predefined variables
`rules:if` clauses are commonly used with [predefined CI/CD variables](../variables/predefined_variables.md),
especially the [`CI_PIPELINE_SOURCE` predefined variable](#ci_pipeline_source-predefined-variable).
The following example runs the job as a manual job in scheduled pipelines or in push
pipelines (to branches or tags), with `when: on_success` (default). It does not
add the job to any other pipeline type.
```yaml
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: manual
allow_failure: true
- if: $CI_PIPELINE_SOURCE == "push"
```
The following example runs the job as a `when: on_success` job in [merge request pipelines](../pipelines/merge_request_pipelines.md)
and scheduled pipelines. It does not run in any other pipeline type.
```yaml
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_PIPELINE_SOURCE == "schedule"
```
Other commonly used `if` clauses:
- `if: $CI_COMMIT_TAG`: If changes are pushed for a tag.
- `if: $CI_COMMIT_BRANCH`: If changes are pushed to any branch.
- `if: $CI_COMMIT_BRANCH == "main"`: If changes are pushed to `main`.
- `if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH`: If changes are pushed to the default
branch. Use when you want to have the same configuration in multiple
projects with different default branches.
- `if: $CI_COMMIT_BRANCH =~ /regex-expression/`: If the commit branch matches a regular expression.
- `if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $CI_COMMIT_TITLE =~ /Merge branch.*/`:
If the commit branch is the default branch and the commit message title matches a regular expression.
For example, the default commit message for a merge commit starts with `Merge branch`.
- `if: $CUSTOM_VARIABLE == "value1"`: If the custom variable `CUSTOM_VARIABLE` is
exactly `value1`.
### Run jobs only in specific pipeline types
You can use [predefined CI/CD variables](../variables/predefined_variables.md) with
[`rules`](../yaml/_index.md#rules) to choose which pipeline types jobs should run for.
The following table lists some of the variables that you can use, and the pipeline
types the variables can control for:
- Branch pipelines that run for Git `push` events to a branch, like new commits or tags.
- Tag pipelines that run only when a new Git tag is pushed to a branch.
- [Merge request pipelines](../pipelines/merge_request_pipelines.md) that run for changes
to a merge request, like new commits or selecting **Run pipeline**
in a merge request's pipelines tab.
- [Scheduled pipelines](../pipelines/schedules.md).
| Variables | Branch | Tag | Merge request | Scheduled |
|--------------------------------------------|--------|-----|---------------|-----------|
| `CI_COMMIT_BRANCH` | Yes | | | Yes |
| `CI_COMMIT_TAG` | | Yes | | Yes, if the scheduled pipeline is configured to run on a tag. |
| `CI_PIPELINE_SOURCE = push` | Yes | Yes | | |
| `CI_PIPELINE_SOURCE = schedule` | | | | Yes |
| `CI_PIPELINE_SOURCE = merge_request_event` | | | Yes | |
| `CI_MERGE_REQUEST_IID` | | | Yes | |
For example, to configure a job to run for merge request pipelines and scheduled pipelines,
but not branch or tag pipelines:
```yaml
job1:
script:
- echo
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_PIPELINE_SOURCE == "schedule"
- if: $CI_PIPELINE_SOURCE == "push"
when: never
```
### `CI_PIPELINE_SOURCE` predefined variable
Use the `CI_PIPELINE_SOURCE` variable to control when to add jobs for these pipeline types:
| Value | Description |
|---------------------------------|-------------|
| `api` | For pipelines triggered by the [pipelines API](../../api/pipelines.md#create-a-new-pipeline). |
| `chat` | For pipelines created by using a [GitLab ChatOps](../chatops/_index.md) command. |
| `external` | When you use CI services other than GitLab. |
| `external_pull_request_event` | When an [external pull request on GitHub](../ci_cd_for_external_repos/_index.md#pipelines-for-external-pull-requests) is created or updated. |
| `merge_request_event` | For pipelines created when a merge request is created or updated. Required to enable [merge request pipelines](../pipelines/merge_request_pipelines.md), [merged results pipelines](../pipelines/merged_results_pipelines.md), and [merge trains](../pipelines/merge_trains.md). |
| `ondemand_dast_scan` | For [DAST on-demand scan](../../user/application_security/dast/on-demand_scan.md) pipelines. |
| `ondemand_dast_validation` | For [DAST on-demand validation](../../user/application_security/dast/profiles.md#site-profile-validation) pipelines |
| `parent_pipeline` | For pipelines triggered by a [parent/child pipeline](../pipelines/downstream_pipelines.md#parent-child-pipelines). Use this pipeline source in the child pipeline configuration so that it can be triggered by the parent pipeline. |
| `pipeline` | For [multi-project pipelines](../pipelines/downstream_pipelines.md#multi-project-pipelines) created by [using the API with `CI_JOB_TOKEN`](../pipelines/downstream_pipelines.md#trigger-a-multi-project-pipeline-by-using-the-api), or the [`trigger`](../yaml/_index.md#trigger) keyword. |
| `push` | For pipelines triggered by a Git push event, including for branches and tags. |
| `schedule` | For [scheduled pipelines](../pipelines/schedules.md). |
| `security_orchestration_policy` | For [scheduled scan execution policies](../../user/application_security/policies/scan_execution_policies.md) pipelines. |
| `trigger` | For pipelines created by using a [trigger token](../triggers/_index.md#configure-cicd-jobs-to-run-in-triggered-pipelines). |
| `web` | For pipelines created by selecting **New pipeline** in the GitLab UI, from the project's **Build > Pipelines** section. |
| `webide` | For pipelines created by using the [Web IDE](../../user/project/web_ide/_index.md). |
These values are the same as returned for the `source` parameter when using the
[pipelines API endpoint](../../api/pipelines.md#list-project-pipelines).
## Complex rules
You can use all `rules` keywords, like `if`, `changes`, and `exists`, in the same
rule. The rule evaluates to true only when all included keywords evaluate to true.
For example:
```yaml
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $VAR == "string value"
changes: # Include the job and set to when:manual if any of the follow paths match a modified file.
- Dockerfile
- docker/scripts/**/*
when: manual
allow_failure: true
```
If the `Dockerfile` file or any file in `/docker/scripts` has changed **and** `$VAR` == "string value",
then the job runs manually and is allowed to fail.
You can use [parentheses](#join-variable-expressions-together) with `&&` and `||` to build more complicated variable expressions.
```yaml
job1:
script:
- echo This rule uses parentheses.
rules:
- if: ($CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH || $CI_COMMIT_BRANCH == "develop") && $MY_VARIABLE
```
## Avoid duplicate pipelines
If a job uses `rules`, a single action, like pushing a commit to a branch, can trigger
multiple pipelines. You don't have to explicitly configure rules for multiple types
of pipeline to trigger them accidentally.
Some configurations that have the potential to cause duplicate pipelines cause a
[pipeline warning](../debugging.md#pipeline-warnings) to be displayed.
For example:
```yaml
job:
script: echo "This job creates double pipelines!"
rules:
- if: $CUSTOM_VARIABLE == "false"
when: never
- when: always
```
This job does not run when `$CUSTOM_VARIABLE` is false, but it does run in **all**
other pipelines, including **both** push (branch) and merge request pipelines. With
this configuration, every push to an open merge request's source branch
causes duplicated pipelines.
To avoid duplicate pipelines, you can:
- Use [`workflow`](../yaml/_index.md#workflow) to specify which types of pipelines
can run.
- Rewrite the rules to run the job only in very specific cases,
and avoid a final `when` rule:
```yaml
job:
script: echo "This job does NOT create double pipelines!"
rules:
- if: $CUSTOM_VARIABLE == "true" && $CI_PIPELINE_SOURCE == "merge_request_event"
```
You can also avoid duplicate pipelines by changing the job rules to avoid either push (branch)
pipelines or merge request pipelines. However, if you use a `- when: always` rule without
`workflow: rules`, GitLab still displays a [pipeline warning](../debugging.md#pipeline-warnings).
For example, the following does not trigger double pipelines, but is not recommended
without `workflow: rules`:
```yaml
job:
script: echo "This job does NOT create double pipelines!"
rules:
- if: $CI_PIPELINE_SOURCE == "push"
when: never
- when: always
```
You should not include both push and merge request pipelines in the same job without
[`workflow:rules` that prevent duplicate pipelines](../yaml/workflow.md#switch-between-branch-pipelines-and-merge-request-pipelines):
```yaml
job:
script: echo "This job creates double pipelines!"
rules:
- if: $CI_PIPELINE_SOURCE == "push"
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
```
Also, do not mix `only/except` jobs with `rules` jobs in the same pipeline.
It may not cause YAML errors, but the different default behaviors of `only/except`
and `rules` can cause issues that are difficult to troubleshoot:
```yaml
job-with-no-rules:
script: echo "This job runs in branch pipelines."
job-with-rules:
script: echo "This job runs in merge request pipelines."
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
```
For every change pushed to the branch, duplicate pipelines run. One
branch pipeline runs a single job (`job-with-no-rules`), and one merge request pipeline
runs the other job (`job-with-rules`). Jobs with no rules default
to [`except: merge_requests`](../yaml/deprecated_keywords.md#only--except), so `job-with-no-rules`
runs in all cases except merge requests.
## Reuse rules in different jobs
Use [`!reference` tags](../yaml/yaml_optimization.md#reference-tags) to reuse rules in different
jobs. You can combine `!reference` rules with regular job-defined rules. For example:
```yaml
.default_rules:
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
job1:
rules:
- !reference [.default_rules, rules]
script:
- echo "This job runs for the default branch, but not schedules."
job2:
rules:
- !reference [.default_rules, rules]
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
script:
- echo "This job runs for the default branch, but not schedules."
- echo "It also runs for merge requests."
```
## CI/CD variable expressions
Use variable expressions with [`rules:if`](../yaml/_index.md#rules) to control
when jobs should be added to a pipeline.
You can use the equality operators `==` and `!=` to compare a variable with a
string. Both single quotes and double quotes are valid. The variable has to be on the left side of the comparison. For example:
- `if: $VARIABLE == "some value"`
- `if: $VARIABLE != "some value"`
You can compare the values of two variables. For example:
- `if: $VARIABLE_1 == $VARIABLE_2`
- `if: $VARIABLE_1 != $VARIABLE_2`
You can compare a variable to the `null` keyword to see if it is defined. For example:
- `if: $VARIABLE == null`
- `if: $VARIABLE != null`
You can check if a variable is defined but empty. For example:
- `if: $VARIABLE == ""`
- `if: $VARIABLE != ""`
You can check if a variable is both defined and not empty by using just the variable name in
the expression. For example:
- `if: $VARIABLE`
You can also [use CI/CD inputs in variable expressions](../inputs/examples.md#use-cicd-inputs-in-variable-expressions).
### Compare a variable to a regular expression
You can do regular expression matching on variable values with the `=~` and `!~` operators.
Variable pattern matching with regular expressions uses the
[RE2 regular expression syntax](https://github.com/google/re2/wiki/Syntax).
Expressions evaluate as `true` if:
- Matches are found when using `=~`.
- Matches are not found when using `!~`.
For example:
- `if: $VARIABLE =~ /^content.*/`
- `if: $VARIABLE !~ /^content.*/`
Additionally:
- Single-character regular expressions, like `/./`, are not supported and
produce an `invalid expression syntax` error.
- Pattern matching is case-sensitive by default. Use the `i` flag modifier to make a
pattern case-insensitive. For example: `/pattern/i`.
- Only the tag or branch name can be matched by a regular expression.
The repository path, if given, is always matched literally.
- The entire pattern must be surrounded by `/`. For example, you can't use `issue-/.*/`
to match all tag names or branch names that begin with `issue-`, but you can use `/issue-.*/`.
- The `@` symbol denotes the beginning of a ref's repository path.
To match a ref name that contains the `@` character in a regular expression,
you must use the hex character code match `\x40`.
- Use anchors `^` and `$` to avoid the regular expression matching only a substring
of the tag name or branch name. For example, `/^issue-.*$/` is equivalent to `/^issue-/`,
while just `/issue/` would also match a branch called `severe-issues`.
### Store a regular expression in a variable
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/35438) in GitLab 15.0 [with a flag](../../administration/feature_flags/_index.md) named `ci_fix_rules_if_comparison_with_regexp_variable`, disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/359740) and feature flag `ci_fix_rules_if_comparison_with_regexp_variable` removed in GitLab 15.1.
{{< /history >}}
Variables on the right side of `=~` and `!~` expressions are evaluated as regular expressions.
The regular expression must be enclosed in forward slashes (`/`). For example:
```yaml
variables:
pattern: '/^ab.*/'
regex-job1:
variables:
teststring: 'abcde'
script: echo "This job will run, because 'abcde' matches the /^ab.*/ pattern."
rules:
- if: '$teststring =~ $pattern'
regex-job2:
variables:
teststring: 'fghij'
script: echo "This job will not run, because 'fghi' does not match the /^ab.*/ pattern."
rules:
- if: '$teststring =~ $pattern'
```
Variables in a regular expression are **not resolved**. For example:
```yaml
variables:
string1: 'regex-job1'
string2: 'regex-job2'
pattern: '/$string2/'
regex-job1:
script: echo "This job will NOT run, because the 'string1' variable inside the regex pattern is not resolved."
rules:
- if: '$CI_JOB_NAME =~ /$string1/'
regex-job2:
script: echo "This job will NOT run, because the 'string2' variable inside the 'pattern' variable is not resolved."
rules:
- if: '$CI_JOB_NAME =~ $pattern'
```
### Join variable expressions together
You can join multiple expressions using `&&` (and) or `||` (or), for example:
- `$VARIABLE1 =~ /^content.*/ && $VARIABLE2 == "something"`
- `$VARIABLE1 =~ /^content.*/ && $VARIABLE2 =~ /thing$/ && $VARIABLE3`
- `$VARIABLE1 =~ /^content.*/ || $VARIABLE2 =~ /thing$/ && $VARIABLE3`
The precedence of operators follows the [Ruby 2.5 standard](https://ruby-doc.org/core-2.5.0/doc/syntax/precedence_rdoc.html),
so `&&` evaluates before `||`.
You can use parentheses to group expressions together. Parentheses take precedence over
`&&` and `||`, so expressions enclosed in parentheses evaluate first, and the
result is used for the rest of the expression.
Nest parentheses to create complex conditions, and the inner-most expressions
in parentheses evaluate first. For example:
- `($VARIABLE1 =~ /^content.*/ || $VARIABLE2) && ($VARIABLE3 =~ /thing$/ || $VARIABLE4)`
- `($VARIABLE1 =~ /^content.*/ || $VARIABLE2 =~ /thing$/) && $VARIABLE3`
- `$CI_COMMIT_BRANCH == "my-branch" || (($VARIABLE1 == "thing" || $VARIABLE2 == "thing") && $VARIABLE3)`
## Troubleshooting
### Unexpected behavior from regular expression matching with `=~`
When using the `=~` character, make sure the right side of the comparison always contains
a valid regular expression.
If the right side of the comparison is not a valid regular expression enclosed with `/` characters,
the expression evaluates in an unexpected way. In that case, the comparison checks
if the left side is a substring of the right side. For example, `"23" =~ "1234"` evaluates to true,
which is the opposite of `"23" =~ /1234/`, which evaluates to false.
You should not configure your pipeline to rely on this behavior.
|
https://docs.gitlab.com/ci/job_control
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/job_control.md
|
2025-08-13
|
doc/ci/jobs
|
[
"doc",
"ci",
"jobs"
] |
job_control.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Control how jobs run
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Before a new pipeline starts, GitLab checks the pipeline configuration to determine
which jobs can run in that pipeline. You can configure jobs to run depending on
conditions like the value of variables or the pipeline type with [`rules`](job_rules.md).
When using job rules, learn how to [avoid duplicate pipelines](job_rules.md#avoid-duplicate-pipelines). To control pipeline creation, use [workflow:rules](../yaml/workflow.md).
## Create a job that must be run manually
You can require that a job doesn't run unless a user starts it. This is called a **manual job**.
You might want to use a manual job for something like deploying to production.
To specify a job as manual, add [`when: manual`](../yaml/_index.md#when) to the job
in the `.gitlab-ci.yml` file.
By default, manual jobs display as skipped when the pipeline starts.
You can use [protected branches](../../user/project/repository/branches/protected.md) to more strictly
[protect manual deployments](#protect-manual-jobs) from being run by unauthorized users.
Manual jobs that are [archived](../../administration/settings/continuous_integration.md#archive-pipelines) do not run.
### Types of manual jobs
Manual jobs can be either optional or blocking.
In optional manual jobs:
- [`allow_failure`](../yaml/_index.md#allow_failure) is `true`, which is the default
setting for jobs that have `when: manual` defined outside of `rules`.
- The status does not contribute to the overall pipeline status. A pipeline can
succeed even if all of its manual jobs fail.
In blocking manual jobs:
- `allow_failure` is `false`, which is the default setting for jobs that have `when: manual`
defined inside [`rules`](../yaml/_index.md#rules).
- The pipeline stops at the stage where the job is defined. To let the pipeline
continue running, [run the manual job](#run-a-manual-job).
- Merge requests in projects with [**Pipelines must succeed**](../../user/project/merge_requests/auto_merge.md#require-a-successful-pipeline-for-merge)
enabled can't be merged with a blocked pipeline.
- The pipeline shows a status of **blocked**.
When using manual jobs in triggered pipelines with a [`trigger:strategy`](../yaml/_index.md#triggerstrategy),
the type of manual job can affect the trigger job's status while the pipeline runs.
### Run a manual job
To run a manual job, you must have permission to merge to the assigned branch:
1. Go to the pipeline, job, [environment](../environments/deployments.md#configure-manual-deployments),
or deployment view.
1. Next to the manual job, select **Run** ({{< icon name="play" >}}).
### Specify variables when running manual jobs
When running manual jobs you can supply additional job specific CI/CD variables.
Specify variables here when you want to alter the execution of a job that uses
[CI/CD variables](../variables/_index.md).
To run a manual job and specify additional variables:
- Select the **name** of the manual job in the pipeline view, not **Run** ({{< icon name="play" >}}).
- In the form, add variable key and value pairs.
- Select **Run job**.
{{< alert type="warning" >}}
Any project member with permissions to run a manual job can retry the job and view the variables
that were provided when the job was initially run. This includes:
- In public projects: Users with the Developer role or higher.
- In private or internal projects: Users with the Guest role or higher.
Consider this visibility when entering sensitive information as manual job variables.
{{< /alert >}}
If you add a variable that is already defined in the CI/CD settings or `.gitlab-ci.yml` file,
the [variable is overridden](../variables/_index.md#use-pipeline-variables) with the new value.
Any variables overridden by using this process are [expanded](../variables/_index.md#prevent-cicd-variable-expansion)
and not [masked](../variables/_index.md#mask-a-cicd-variable).
#### Retry a manual job with updated variables
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/96199) in GitLab 15.7.
{{< /history >}}
When you retry a manual job that was previously run with manually-specified variables,
you can update the variables or use the same variables.
To retry a manual job with previously-specified variables:
- With the same variables:
- From the job details page, select **Retry** ({{< icon name="retry" >}}).
- With updated variables:
- From the job details page, select **Update CI/CD variables** ({{< icon name="pencil-square" >}}).
- The variables that were specified in the previous run are prefilled in the form.
You can add, modify, or delete CI/CD variables from this form.
- Select **Run job again**.
### Require confirmation for manual jobs
Use [`manual_confirmation`](../yaml/_index.md#manual_confirmation) with `when: manual` to require confirmation for manual jobs.
This helps prevent accidental deployments or deletions for sensitive jobs like those that deploy to production.
When you trigger the job, you must confirm the action before it runs.
### Protect manual jobs
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use [protected environments](../environments/protected_environments.md)
to define a list of users authorized to run a manual job. You can authorize only
the users associated with a protected environment to trigger manual jobs, which can:
- More precisely limit who can deploy to an environment.
- Block a pipeline until an approved user "approves" it.
To protect a manual job:
1. Add an `environment` to the job. For example:
```yaml
deploy_prod:
stage: deploy
script:
- echo "Deploy to production server"
environment:
name: production
url: https://example.com
when: manual
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
1. In the [protected environments settings](../environments/protected_environments.md#protecting-environments),
select the environment (`production` in this example) and add the users, roles or groups
that are authorized to trigger the manual job to the **Allowed to Deploy** list. Only those in
this list can trigger this manual job, and GitLab administrators
who are always able to use protected environments.
You can use protected environments with blocking manual jobs to have a list of users
allowed to approve later pipeline stages. Add `allow_failure: false` to the protected
manual job and the pipeline's next stages only run after the manual job is triggered
by authorized users.
## Run a job after a delay
Use [`when: delayed`](../yaml/_index.md#when) to execute scripts after a waiting period, or if you want to avoid
jobs immediately entering the `pending` state.
You can set the period with `start_in` keyword. The value of `start_in` is an elapsed time
in seconds, unless a unit is provided. The minimum is one second, and the maximum is one week.
Examples of valid values include:
- `'5'` (a value with no unit must be surrounded by single quotes)
- `5 seconds`
- `30 minutes`
- `1 day`
- `1 week`
When a stage includes a delayed job, the pipeline doesn't progress until the delayed job finishes.
You can use this keyword to insert delays between different stages.
The timer of a delayed job starts immediately after the previous stage completes.
Similar to other types of jobs, a delayed job's timer doesn't start unless the previous stage passes.
The following example creates a job named `timed rollout 10%` that is executed 30 minutes after the previous stage completes:
```yaml
timed rollout 10%:
stage: deploy
script: echo 'Rolling out 10% ...'
when: delayed
start_in: 30 minutes
environment: production
```
To stop the active timer of a delayed job, select **Unschedule** ({{< icon name="time-out" >}}).
This job can no longer be scheduled to run automatically. You can, however, execute the job manually.
To start a delayed job manually, select **Unschedule** ({{< icon name="time-out" >}}) to stop the delay timer and then select **Run** ({{< icon name="play" >}}).
Soon GitLab Runner starts the job.
Delayed jobs that are [archived](../../administration/settings/continuous_integration.md#archive-pipelines)
do not run.
## Parallelize large jobs
To split a large job into multiple smaller jobs that run in parallel, use the
[`parallel`](../yaml/_index.md#parallel) keyword in your `.gitlab-ci.yml` file.
Different languages and test suites have different methods to enable parallelization.
For example, use [Semaphore Test Boosters](https://github.com/renderedtext/test-boosters)
and RSpec to run Ruby tests in parallel:
```ruby
# Gemfile
source 'https://rubygems.org'
gem 'rspec'
gem 'semaphore_test_boosters'
```
```yaml
test:
parallel: 3
script:
- bundle
- bundle exec rspec_booster --job $CI_NODE_INDEX/$CI_NODE_TOTAL
```
You can then go to the **Jobs** tab of a new pipeline build and see your RSpec
job split into three separate jobs.
{{< alert type="warning" >}}
Test Boosters reports usage statistics to the author.
{{< /alert >}}
### Run a one-dimensional matrix of parallel jobs
To run a job multiple times in parallel in a single pipeline, but with different variable values for each instance of the job,
use the [`parallel:matrix`](../yaml/_index.md#parallelmatrix) keyword:
```yaml
deploystacks:
stage: deploy
script:
- bin/deploy
parallel:
matrix:
- PROVIDER: [aws, ovh, gcp, vultr]
environment: production/$PROVIDER
```
### Run a matrix of parallel trigger jobs
You can run a [trigger](../yaml/_index.md#trigger) job multiple times in parallel in a single pipeline,
but with different variable values for each instance of the job.
```yaml
deploystacks:
stage: deploy
trigger:
include: path/to/child-pipeline.yml
parallel:
matrix:
- PROVIDER: aws
STACK: [monitoring, app1]
- PROVIDER: ovh
STACK: [monitoring, backup]
- PROVIDER: [gcp, vultr]
STACK: [data]
```
This example generates 6 parallel `deploystacks` trigger jobs, each with different values
for `PROVIDER` and `STACK`, and they create 6 different child pipelines with those variables.
```plaintext
deploystacks: [aws, monitoring]
deploystacks: [aws, app1]
deploystacks: [ovh, monitoring]
deploystacks: [ovh, backup]
deploystacks: [gcp, data]
deploystacks: [vultr, data]
```
### Select different runner tags for each parallel matrix job
You can use variables defined in `parallel: matrix` with the [`tags`](../yaml/_index.md#tags)
keyword for dynamic runner selection:
```yaml
deploystacks:
stage: deploy
script:
- bin/deploy
parallel:
matrix:
- PROVIDER: aws
STACK: [monitoring, app1]
- PROVIDER: gcp
STACK: [data]
tags:
- ${PROVIDER}-${STACK}
environment: $PROVIDER/$STACK
```
### Fetch artifacts from a `parallel:matrix` job
You can fetch artifacts from a job created with [`parallel:matrix`](../yaml/_index.md#parallelmatrix)
by using the [`dependencies`](../yaml/_index.md#dependencies) keyword. Use the job name
as the value for `dependencies` as a string in the form:
```plaintext
<job_name> [<matrix argument 1>, <matrix argument 2>, ... <matrix argument N>]
```
For example, to fetch the artifacts from the job with a `RUBY_VERSION` of `2.7` and
a `PROVIDER` of `aws`:
```yaml
ruby:
image: ruby:${RUBY_VERSION}
parallel:
matrix:
- RUBY_VERSION: ["2.5", "2.6", "2.7", "3.0", "3.1"]
PROVIDER: [aws, gcp]
script: bundle install
deploy:
image: ruby:2.7
stage: deploy
dependencies:
- "ruby: [2.7, aws]"
script: echo hello
environment: production
```
Quotes around the `dependencies` entry are required.
## Specify a parallelized job using needs with multiple parallelized jobs
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/254821) in GitLab 16.3.
{{< /history >}}
You can use variables defined in [`needs:parallel:matrix`](../yaml/_index.md#needsparallelmatrix) with multiple parallelized jobs.
For example:
```yaml
linux:build:
stage: build
script: echo "Building linux..."
parallel:
matrix:
- PROVIDER: aws
STACK:
- monitoring
- app1
- app2
mac:build:
stage: build
script: echo "Building mac..."
parallel:
matrix:
- PROVIDER: [gcp, vultr]
STACK: [data, processing]
linux:rspec:
stage: test
needs:
- job: linux:build
parallel:
matrix:
- PROVIDER: aws
STACK: app1
script: echo "Running rspec on linux..."
mac:rspec:
stage: test
needs:
- job: mac:build
parallel:
matrix:
- PROVIDER: [gcp, vultr]
STACK: [data]
script: echo "Running rspec on mac..."
production:
stage: deploy
script: echo "Running production..."
environment: production
```
This example generates several jobs. The parallel jobs each have different values
for `PROVIDER` and `STACK`.
- 3 parallel `linux:build` jobs:
- `linux:build: [aws, monitoring]`
- `linux:build: [aws, app1]`
- `linux:build: [aws, app2]`
- 4 parallel `mac:build` jobs:
- `mac:build: [gcp, data]`
- `mac:build: [gcp, processing]`
- `mac:build: [vultr, data]`
- `mac:build: [vultr, processing]`
- A `linux:rspec` job.
- A `production` job.
The jobs have three paths of execution:
- Linux path: The `linux:rspec` job runs as soon as the `linux:build: [aws, app1]`
job finishes, without waiting for `mac:build` to finish.
- macOS path: The `mac:rspec` job runs as soon as the `mac:build: [gcp, data]` and
`mac:build: [vultr, data]` jobs finish, without waiting for `linux:build` to finish.
- The `production` job runs as soon as all previous jobs finish.
## Specify needs between parallelized jobs
You can further define the order of each parallel matrix job using [`needs:parallel:matrix`](../yaml/_index.md#needsparallelmatrix).
For example:
```yaml
build_job:
stage: build
script:
# ensure that other parallel job other than build_job [1, A] runs longer
- '[[ "$VERSION" == "1" && "$MODE" == "A" ]] || sleep 30'
- echo build $VERSION $MODE
parallel:
matrix:
- VERSION: [1,2]
MODE: [A, B]
deploy_job:
stage: deploy
script: echo deploy $VERSION $MODE
parallel:
matrix:
- VERSION: [3,4]
MODE: [C, D]
'deploy_job: [3, D]':
stage: deploy
script: echo something
needs:
- 'build_job: [1, A]'
```
This example generates several jobs. The parallel jobs each have different values
for `VERSION` and `MODE`.
- 4 parallel `build_job` jobs:
- `build_job: [1, A]`
- `build_job: [1, B]`
- `build_job: [2, A]`
- `build_job: [2, B]`
- 4 parallel `deploy_job` jobs:
- `deploy_job: [3, C]`
- `deploy_job: [3, D]`
- `deploy_job: [4, C]`
- `deploy_job: [4, D]`
The `deploy_job: [3, D]` job runs as soon as `build_job: [1, A]` job finishes,
without waiting for the other `build_job` jobs to finish.
## Troubleshooting
### Inconsistent user assignment when running manual jobs
In some edge cases, the user that runs a manual job does not get assigned as the user for later jobs
that depend on the manual job.
If you need strict security over who is assigned as the user for jobs that depend on a manual job,
you should [protect the manual job](#protect-manual-jobs).
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Control how jobs run
breadcrumbs:
- doc
- ci
- jobs
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Before a new pipeline starts, GitLab checks the pipeline configuration to determine
which jobs can run in that pipeline. You can configure jobs to run depending on
conditions like the value of variables or the pipeline type with [`rules`](job_rules.md).
When using job rules, learn how to [avoid duplicate pipelines](job_rules.md#avoid-duplicate-pipelines). To control pipeline creation, use [workflow:rules](../yaml/workflow.md).
## Create a job that must be run manually
You can require that a job doesn't run unless a user starts it. This is called a **manual job**.
You might want to use a manual job for something like deploying to production.
To specify a job as manual, add [`when: manual`](../yaml/_index.md#when) to the job
in the `.gitlab-ci.yml` file.
By default, manual jobs display as skipped when the pipeline starts.
You can use [protected branches](../../user/project/repository/branches/protected.md) to more strictly
[protect manual deployments](#protect-manual-jobs) from being run by unauthorized users.
Manual jobs that are [archived](../../administration/settings/continuous_integration.md#archive-pipelines) do not run.
### Types of manual jobs
Manual jobs can be either optional or blocking.
In optional manual jobs:
- [`allow_failure`](../yaml/_index.md#allow_failure) is `true`, which is the default
setting for jobs that have `when: manual` defined outside of `rules`.
- The status does not contribute to the overall pipeline status. A pipeline can
succeed even if all of its manual jobs fail.
In blocking manual jobs:
- `allow_failure` is `false`, which is the default setting for jobs that have `when: manual`
defined inside [`rules`](../yaml/_index.md#rules).
- The pipeline stops at the stage where the job is defined. To let the pipeline
continue running, [run the manual job](#run-a-manual-job).
- Merge requests in projects with [**Pipelines must succeed**](../../user/project/merge_requests/auto_merge.md#require-a-successful-pipeline-for-merge)
enabled can't be merged with a blocked pipeline.
- The pipeline shows a status of **blocked**.
When using manual jobs in triggered pipelines with a [`trigger:strategy`](../yaml/_index.md#triggerstrategy),
the type of manual job can affect the trigger job's status while the pipeline runs.
### Run a manual job
To run a manual job, you must have permission to merge to the assigned branch:
1. Go to the pipeline, job, [environment](../environments/deployments.md#configure-manual-deployments),
or deployment view.
1. Next to the manual job, select **Run** ({{< icon name="play" >}}).
### Specify variables when running manual jobs
When running manual jobs you can supply additional job specific CI/CD variables.
Specify variables here when you want to alter the execution of a job that uses
[CI/CD variables](../variables/_index.md).
To run a manual job and specify additional variables:
- Select the **name** of the manual job in the pipeline view, not **Run** ({{< icon name="play" >}}).
- In the form, add variable key and value pairs.
- Select **Run job**.
{{< alert type="warning" >}}
Any project member with permissions to run a manual job can retry the job and view the variables
that were provided when the job was initially run. This includes:
- In public projects: Users with the Developer role or higher.
- In private or internal projects: Users with the Guest role or higher.
Consider this visibility when entering sensitive information as manual job variables.
{{< /alert >}}
If you add a variable that is already defined in the CI/CD settings or `.gitlab-ci.yml` file,
the [variable is overridden](../variables/_index.md#use-pipeline-variables) with the new value.
Any variables overridden by using this process are [expanded](../variables/_index.md#prevent-cicd-variable-expansion)
and not [masked](../variables/_index.md#mask-a-cicd-variable).
#### Retry a manual job with updated variables
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/96199) in GitLab 15.7.
{{< /history >}}
When you retry a manual job that was previously run with manually-specified variables,
you can update the variables or use the same variables.
To retry a manual job with previously-specified variables:
- With the same variables:
- From the job details page, select **Retry** ({{< icon name="retry" >}}).
- With updated variables:
- From the job details page, select **Update CI/CD variables** ({{< icon name="pencil-square" >}}).
- The variables that were specified in the previous run are prefilled in the form.
You can add, modify, or delete CI/CD variables from this form.
- Select **Run job again**.
### Require confirmation for manual jobs
Use [`manual_confirmation`](../yaml/_index.md#manual_confirmation) with `when: manual` to require confirmation for manual jobs.
This helps prevent accidental deployments or deletions for sensitive jobs like those that deploy to production.
When you trigger the job, you must confirm the action before it runs.
### Protect manual jobs
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use [protected environments](../environments/protected_environments.md)
to define a list of users authorized to run a manual job. You can authorize only
the users associated with a protected environment to trigger manual jobs, which can:
- More precisely limit who can deploy to an environment.
- Block a pipeline until an approved user "approves" it.
To protect a manual job:
1. Add an `environment` to the job. For example:
```yaml
deploy_prod:
stage: deploy
script:
- echo "Deploy to production server"
environment:
name: production
url: https://example.com
when: manual
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
1. In the [protected environments settings](../environments/protected_environments.md#protecting-environments),
select the environment (`production` in this example) and add the users, roles or groups
that are authorized to trigger the manual job to the **Allowed to Deploy** list. Only those in
this list can trigger this manual job, and GitLab administrators
who are always able to use protected environments.
You can use protected environments with blocking manual jobs to have a list of users
allowed to approve later pipeline stages. Add `allow_failure: false` to the protected
manual job and the pipeline's next stages only run after the manual job is triggered
by authorized users.
## Run a job after a delay
Use [`when: delayed`](../yaml/_index.md#when) to execute scripts after a waiting period, or if you want to avoid
jobs immediately entering the `pending` state.
You can set the period with `start_in` keyword. The value of `start_in` is an elapsed time
in seconds, unless a unit is provided. The minimum is one second, and the maximum is one week.
Examples of valid values include:
- `'5'` (a value with no unit must be surrounded by single quotes)
- `5 seconds`
- `30 minutes`
- `1 day`
- `1 week`
When a stage includes a delayed job, the pipeline doesn't progress until the delayed job finishes.
You can use this keyword to insert delays between different stages.
The timer of a delayed job starts immediately after the previous stage completes.
Similar to other types of jobs, a delayed job's timer doesn't start unless the previous stage passes.
The following example creates a job named `timed rollout 10%` that is executed 30 minutes after the previous stage completes:
```yaml
timed rollout 10%:
stage: deploy
script: echo 'Rolling out 10% ...'
when: delayed
start_in: 30 minutes
environment: production
```
To stop the active timer of a delayed job, select **Unschedule** ({{< icon name="time-out" >}}).
This job can no longer be scheduled to run automatically. You can, however, execute the job manually.
To start a delayed job manually, select **Unschedule** ({{< icon name="time-out" >}}) to stop the delay timer and then select **Run** ({{< icon name="play" >}}).
Soon GitLab Runner starts the job.
Delayed jobs that are [archived](../../administration/settings/continuous_integration.md#archive-pipelines)
do not run.
## Parallelize large jobs
To split a large job into multiple smaller jobs that run in parallel, use the
[`parallel`](../yaml/_index.md#parallel) keyword in your `.gitlab-ci.yml` file.
Different languages and test suites have different methods to enable parallelization.
For example, use [Semaphore Test Boosters](https://github.com/renderedtext/test-boosters)
and RSpec to run Ruby tests in parallel:
```ruby
# Gemfile
source 'https://rubygems.org'
gem 'rspec'
gem 'semaphore_test_boosters'
```
```yaml
test:
parallel: 3
script:
- bundle
- bundle exec rspec_booster --job $CI_NODE_INDEX/$CI_NODE_TOTAL
```
You can then go to the **Jobs** tab of a new pipeline build and see your RSpec
job split into three separate jobs.
{{< alert type="warning" >}}
Test Boosters reports usage statistics to the author.
{{< /alert >}}
### Run a one-dimensional matrix of parallel jobs
To run a job multiple times in parallel in a single pipeline, but with different variable values for each instance of the job,
use the [`parallel:matrix`](../yaml/_index.md#parallelmatrix) keyword:
```yaml
deploystacks:
stage: deploy
script:
- bin/deploy
parallel:
matrix:
- PROVIDER: [aws, ovh, gcp, vultr]
environment: production/$PROVIDER
```
### Run a matrix of parallel trigger jobs
You can run a [trigger](../yaml/_index.md#trigger) job multiple times in parallel in a single pipeline,
but with different variable values for each instance of the job.
```yaml
deploystacks:
stage: deploy
trigger:
include: path/to/child-pipeline.yml
parallel:
matrix:
- PROVIDER: aws
STACK: [monitoring, app1]
- PROVIDER: ovh
STACK: [monitoring, backup]
- PROVIDER: [gcp, vultr]
STACK: [data]
```
This example generates 6 parallel `deploystacks` trigger jobs, each with different values
for `PROVIDER` and `STACK`, and they create 6 different child pipelines with those variables.
```plaintext
deploystacks: [aws, monitoring]
deploystacks: [aws, app1]
deploystacks: [ovh, monitoring]
deploystacks: [ovh, backup]
deploystacks: [gcp, data]
deploystacks: [vultr, data]
```
### Select different runner tags for each parallel matrix job
You can use variables defined in `parallel: matrix` with the [`tags`](../yaml/_index.md#tags)
keyword for dynamic runner selection:
```yaml
deploystacks:
stage: deploy
script:
- bin/deploy
parallel:
matrix:
- PROVIDER: aws
STACK: [monitoring, app1]
- PROVIDER: gcp
STACK: [data]
tags:
- ${PROVIDER}-${STACK}
environment: $PROVIDER/$STACK
```
### Fetch artifacts from a `parallel:matrix` job
You can fetch artifacts from a job created with [`parallel:matrix`](../yaml/_index.md#parallelmatrix)
by using the [`dependencies`](../yaml/_index.md#dependencies) keyword. Use the job name
as the value for `dependencies` as a string in the form:
```plaintext
<job_name> [<matrix argument 1>, <matrix argument 2>, ... <matrix argument N>]
```
For example, to fetch the artifacts from the job with a `RUBY_VERSION` of `2.7` and
a `PROVIDER` of `aws`:
```yaml
ruby:
image: ruby:${RUBY_VERSION}
parallel:
matrix:
- RUBY_VERSION: ["2.5", "2.6", "2.7", "3.0", "3.1"]
PROVIDER: [aws, gcp]
script: bundle install
deploy:
image: ruby:2.7
stage: deploy
dependencies:
- "ruby: [2.7, aws]"
script: echo hello
environment: production
```
Quotes around the `dependencies` entry are required.
## Specify a parallelized job using needs with multiple parallelized jobs
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/254821) in GitLab 16.3.
{{< /history >}}
You can use variables defined in [`needs:parallel:matrix`](../yaml/_index.md#needsparallelmatrix) with multiple parallelized jobs.
For example:
```yaml
linux:build:
stage: build
script: echo "Building linux..."
parallel:
matrix:
- PROVIDER: aws
STACK:
- monitoring
- app1
- app2
mac:build:
stage: build
script: echo "Building mac..."
parallel:
matrix:
- PROVIDER: [gcp, vultr]
STACK: [data, processing]
linux:rspec:
stage: test
needs:
- job: linux:build
parallel:
matrix:
- PROVIDER: aws
STACK: app1
script: echo "Running rspec on linux..."
mac:rspec:
stage: test
needs:
- job: mac:build
parallel:
matrix:
- PROVIDER: [gcp, vultr]
STACK: [data]
script: echo "Running rspec on mac..."
production:
stage: deploy
script: echo "Running production..."
environment: production
```
This example generates several jobs. The parallel jobs each have different values
for `PROVIDER` and `STACK`.
- 3 parallel `linux:build` jobs:
- `linux:build: [aws, monitoring]`
- `linux:build: [aws, app1]`
- `linux:build: [aws, app2]`
- 4 parallel `mac:build` jobs:
- `mac:build: [gcp, data]`
- `mac:build: [gcp, processing]`
- `mac:build: [vultr, data]`
- `mac:build: [vultr, processing]`
- A `linux:rspec` job.
- A `production` job.
The jobs have three paths of execution:
- Linux path: The `linux:rspec` job runs as soon as the `linux:build: [aws, app1]`
job finishes, without waiting for `mac:build` to finish.
- macOS path: The `mac:rspec` job runs as soon as the `mac:build: [gcp, data]` and
`mac:build: [vultr, data]` jobs finish, without waiting for `linux:build` to finish.
- The `production` job runs as soon as all previous jobs finish.
## Specify needs between parallelized jobs
You can further define the order of each parallel matrix job using [`needs:parallel:matrix`](../yaml/_index.md#needsparallelmatrix).
For example:
```yaml
build_job:
stage: build
script:
# ensure that other parallel job other than build_job [1, A] runs longer
- '[[ "$VERSION" == "1" && "$MODE" == "A" ]] || sleep 30'
- echo build $VERSION $MODE
parallel:
matrix:
- VERSION: [1,2]
MODE: [A, B]
deploy_job:
stage: deploy
script: echo deploy $VERSION $MODE
parallel:
matrix:
- VERSION: [3,4]
MODE: [C, D]
'deploy_job: [3, D]':
stage: deploy
script: echo something
needs:
- 'build_job: [1, A]'
```
This example generates several jobs. The parallel jobs each have different values
for `VERSION` and `MODE`.
- 4 parallel `build_job` jobs:
- `build_job: [1, A]`
- `build_job: [1, B]`
- `build_job: [2, A]`
- `build_job: [2, B]`
- 4 parallel `deploy_job` jobs:
- `deploy_job: [3, C]`
- `deploy_job: [3, D]`
- `deploy_job: [4, C]`
- `deploy_job: [4, D]`
The `deploy_job: [3, D]` job runs as soon as `build_job: [1, A]` job finishes,
without waiting for the other `build_job` jobs to finish.
## Troubleshooting
### Inconsistent user assignment when running manual jobs
In some edge cases, the user that runs a manual job does not get assigned as the user for later jobs
that depend on the manual job.
If you need strict security over who is assigned as the user for jobs that depend on a manual job,
you should [protect the manual job](#protect-manual-jobs).
|
https://docs.gitlab.com/ci/ci_job_token
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/ci_job_token.md
|
2025-08-13
|
doc/ci/jobs
|
[
"doc",
"ci",
"jobs"
] |
ci_job_token.md
|
Software Supply Chain Security
|
Pipeline Security
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab CI/CD job token
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
When a CI/CD pipeline job is about to run, GitLab generates a unique token and makes it available
to the job as the [`CI_JOB_TOKEN` predefined variable](../variables/predefined_variables.md).
The token is valid only while the job is running. After the job finishes, the token access
is revoked and you cannot use the token anymore.
Use a CI/CD job token to authenticate with certain GitLab features from running jobs.
The token receives the same access level as the user that triggered the pipeline,
but has [access to fewer resources](#job-token-access) than a personal access token. A user can cause a job to run
with an action like pushing a commit, triggering a manual job, or being the owner of a scheduled pipeline.
This user must have a [role that has the required privileges](../../user/permissions.md#cicd)
to access the resources.
You can use a job token to authenticate with GitLab to access another group or project's resources (the target project).
By default, the job token's group or project must be [added to the target project's allowlist](#add-a-group-or-project-to-the-job-token-allowlist).
If a project is public or internal, you can access some features without being on the allowlist.
For example, you can fetch artifacts from the project's public pipelines.
This access can also [be restricted](#limit-job-token-scope-for-public-or-internal-projects).
## Job token access
CI/CD job tokens can access the following resources:
| Resource | Notes |
| ----------------------------------------------------------------------------------------------------- | ----- |
| [Container registry](../../user/packages/container_registry/build_and_push_images.md#use-gitlab-cicd) | Used as the `$CI_REGISTRY_PASSWORD` [predefined variable](../variables/predefined_variables.md) to authenticate with the container registry associated with the job's project. |
| [Package registry](../../user/packages/package_registry/_index.md#to-build-packages) | Used to authenticate with the registry. |
| [Terraform module registry](../../user/packages/terraform_module_registry/_index.md) | Used to authenticate with the registry. |
| [Secure files](../secure_files/_index.md#use-secure-files-in-cicd-jobs) | Used by the [`download-secure-files`](https://gitlab.com/gitlab-org/incubation-engineering/mobile-devops/download-secure-files) tool to use secure files in jobs. |
| [Container registry API](../../api/container_registry.md) | Can authenticate only with the container registry associated with the job's project. |
| [Deployments API](../../api/deployments.md) | Can access all endpoints in this API. |
| [Environments API](../../api/environments.md) | Can access all endpoints in this API. |
| [Jobs API](../../api/jobs.md#get-job-tokens-job) | Can access only the `GET /job` endpoint. |
| [Job artifacts API](../../api/job_artifacts.md) | Can access all endpoints in this API. |
| [Packages API](../../api/packages.md) | Can access all endpoints in this API. |
| [Pipeline trigger tokens API](../../api/pipeline_triggers.md#trigger-a-pipeline-with-a-token) | Can access only the `POST /projects/:id/trigger/pipeline` endpoint. |
| [Pipelines API](../../api/pipelines.md#update-pipeline-metadata) | Can access only the `PUT /projects/:id/pipelines/:pipeline_id/metadata` endpoint. |
| [Release links API](../../api/releases/links.md) | Can access all endpoints in this API. |
| [Releases API](../../api/releases/_index.md) | Can access all endpoints in this API. |
| [Repositories API](../../api/repositories.md#generate-changelog-data) | Can access only the `GET /projects/:id/repository/changelog` endpoint. |
An open [proposal](https://gitlab.com/groups/gitlab-org/-/epics/3559) exists to make permissions
more granular.
## GitLab CI/CD job token security
If a job token is leaked, it could potentially be used to access private data accessible
to the user that triggered the CI/CD job. To help prevent leaking or misuse of this token,
GitLab:
- Masks the job token in job logs.
- Grants permissions to the job token only when the job is running.
You should also configure your [runners](../runners/_index.md) to be secure:
- Avoid using Docker `privileged` mode if the machines are re-used.
- Avoid using the [`shell` executor](https://docs.gitlab.com/runner/executors/shell.html) when jobs
run on the same machine.
An insecure GitLab Runner configuration increases the risk that someone can steal tokens from other
jobs.
## Control job token access to your project
You can control which groups or projects can use a job token to authenticate and access some of your project's resources.
By default, job token access is restricted to only CI/CD jobs that run in pipelines in
your project. To allow another group or project to authenticate with a job token from the other
project's pipeline:
- You must [add the group or project to the job token allowlist](#add-a-group-or-project-to-the-job-token-allowlist).
- The user that triggers the job must be a member of your project.
- The user must have the [permissions](../../user/permissions.md) to perform the action.
If your project is public or internal, some publicly accessible resources can be accessed
with a job token from any project. These resources can also be [limited to only projects on the allowlist](#limit-job-token-scope-for-public-or-internal-projects).
GitLab Self-Managed administrators can [override and enforce this setting](../../administration/settings/continuous_integration.md#access-job-token-permission-settings).
When the setting is enforced, the CI/CD job token is always restricted to the project's allowlist.
### Add a group or project to the job token allowlist
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/346298/) in GitLab 15.9. [Deployed behind the `:inbound_ci_scoped_job_token` feature flag](../../administration/feature_flags/_index.md), enabled by default.
- [Feature flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/346298/) in GitLab 15.10.
- **Allow access to this project with a CI_JOB_TOKEN** setting [renamed to **Limit access to this project**](https://gitlab.com/gitlab-org/gitlab/-/issues/411406) in GitLab 16.3.
- Adding groups to the job token allowlist [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/415519) in GitLab 17.0.
- **Token Access** section renamed to **Job token permissions**, and [**Limit access to this project** setting renamed to **Authorized groups and projects**](https://gitlab.com/gitlab-org/gitlab/-/issues/415519) in GitLab 17.2.
- **Add project** option [renamed to **Add**](https://gitlab.com/gitlab-org/gitlab/-/issues/470880/) in GitLab 17.6.
{{< /history >}}
You can add groups or projects to your job token allowlist to allow access to your project's resources
with a job token for authentication. By default, the allowlist of any project only includes itself.
Add groups or projects to the allowlist only when cross-project access is needed.
Adding a project to the allowlist does not give additional [permissions](../../user/permissions.md)
to the members of the allowlisted project. They must already have permissions to access the resources
in your project to use a job token from the allowlisted project to access your project.
For example, project A can add project B to project A's allowlist. CI/CD jobs
in project B (the "allowed project") can now use CI/CD job tokens to
authenticate API calls to access project A.
Prerequisites:
- You must have at least the Maintainer role for the current project. If the allowed project
is internal or private, you must have at least the Guest role in that project.
- You must not have more than 200 groups and projects added to the allowlist.
To add a group or project to the allowlist:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Job token permissions**.
1. Select **Add group or project**.
1. Input the path to the group or project to add to the allowlist, and select **Add**.
You can also add a group or project to the allowlist [with the API](../../api/graphql/reference/_index.md#mutationcijobtokenscopeaddgrouporproject).
### Auto-populate a project's allowlist
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/478540) in GitLab 17.10.
{{< /history >}}
You can populate a project's allowlist using the data from the [job token authentication log](#job-token-authentication-log)
with the UI or a Rake task.
In either case, GitLab uses the authentication log to determine which projects or groups to add to the allowlist
and adds those entries for you.
This process creates at most 200 entries in the project's allowlist. If more than 200 entries exist in the authentication log,
it [compacts the allowlist](#allowlist-compaction) to stay under the 200 entry limit.
#### With the UI
{{< history >}}
- Introduced in [GitLab 17.10](https://gitlab.com/gitlab-org/gitlab/-/issues/498125).
{{< /history >}}
To auto-populate the allowlist through the UI:
1. On the left sidebar, select **Search or go** to and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Job token permissions**.
1. Select **Add** and choose **All projects in authentication log** from the dropdown list.
1. A dialog asks you to confirm the action, select **Add entries**.
After the process completes, the allowlist contains the entries from the authentication log.
If not already set, the **Authorized groups and projects** is set to **Only this project and any groups and projects in the allowlist**.
#### With a Rake task
GitLab administrators with [rails console access](../../administration/operations/rails_console.md)
can run a Rake task to auto-populate the allowlist for all or a subset of projects on an instance.
This task also sets the **Authorized groups and projects** setting to **Only this project and any groups and projects in the allowlist**.
The `ci:job_tokens:allowlist:autopopulate_and_enforce` Rake task has the following configuration options:
- `PREVIEW`: Do a dry run and output the steps that would have been taken, but do not change any data.
- `ONLY_PROJECT_IDS`: Do the migration for only the supplied project IDs (maximum of 1000 IDs).
- `EXCLUDE_PROJECT_IDS`: Do the migration for all projects on the instance, except
for the supplied project IDs (maximum of 1000 IDs).
`ONLY_PROJECT_IDS` and `EXCLUDE_PROJECT_IDS` cannot be used at the same time.
For example:
- `ci:job_tokens:allowlist:autopopulate_and_enforce PREVIEW=true`
- `ci:job_tokens:allowlist:autopopulate_and_enforce PREVIEW=true ONLY_PROJECT_IDS=2,3`
- `ci:job_tokens:allowlist:autopopulate_and_enforce PREVIEW=true EXCLUDE_PROJECT_IDS=2,3`
- `ci:job_tokens:allowlist:autopopulate_and_enforce`
- `ci:job_tokens:allowlist:autopopulate_and_enforce ONLY_PROJECT_IDS=2,3`
- `ci:job_tokens:allowlist:autopopulate_and_enforce EXCLUDE_PROJECT_IDS=2,3`
To run the Rake task for:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```shell
sudo gitlab-rake ci:job_tokens:allowlist:autopopulate_and_enforce
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
```shell
sudo -u git -H bundle exec rake ci:job_tokens:allowlist:autopopulate_and_enforce
```
{{< /tab >}}
{{< /tabs >}}
#### Allowlist compaction
The allowlist compaction algorithm:
1. Scans the authorization log to identify the nearest common groups for projects.
1. Consolidates multiple project-level entries into single group-level entries.
1. Updates the allowlist with these consolidated entries.
For example, with an allowlist similar to:
```plaintext
group1/group2/group3/project1
group1/group2/group3/project2
group1/group2/group4/project3
group1/group2/group4/project4
group1/group5/group6/project5
```
The compaction algorithm:
1. Compacts the list to:
```plaintext
group1/group2/group3
group1/group2/group4
group1/group5/group6
```
1. If the allowlist is over the 200 entry limit, the algorithm compacts again:
```plaintext
group1/group2
group1/group5
```
1. If the allowlist is still over the 200 entry limit, the algorithm continues:
```plaintext
group1
```
This process is performed until the number of allowlist entries is 200 or fewer.
### Limit job token scope for public or internal projects
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/405369) in GitLab 16.6.
{{< /history >}}
Projects not in the allowlist can use a job token to authenticate with public or internal projects to:
- Fetch artifacts.
- Access the container registry.
- Access the package registry.
- Access releases, deployments, and environments.
You can limit access to these actions to only the projects on the allowlist by setting
each feature to be only visible to project members.
Prerequisites:
- You must have the Maintainer role for the project.
To set a feature to be only visible to project members:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **General**.
1. Expand **Visibility, project features, permissions**.
1. Set the visibility to **Only project members** for the features you want to restrict access to.
- The ability to fetch artifacts is controlled by the CI/CD visibility setting.
1. Select **Save changes**.
### Allow any project to access your project
{{< details >}}
- Offering: GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- **Allow access to this project with a CI_JOB_TOKEN** setting [renamed to **Limit access to this project**](https://gitlab.com/gitlab-org/gitlab/-/issues/411406) in GitLab 16.3.
- **Token Access** section renamed to **Job token permissions**, and [**Limit access to this project** setting renamed to **Authorized groups and projects**](https://gitlab.com/gitlab-org/gitlab/-/issues/415519) in GitLab 17.2.
{{< /history >}}
{{< alert type="warning" >}}
It is a security risk to disable the token access limit and allowlist. A malicious user could try to compromise
a pipeline created in an unauthorized project. If the pipeline was created by one of
your maintainers, the job token could be used in an attempt to access your project.
{{< /alert >}}
If you disable the CI/CD job token allowlist, jobs from any project can access your project
with a job token. The user that triggers the pipeline must have permission to access your project.
You should only disable this setting for testing or a similar reason,
and you should enable it again as soon as possible.
This option is only available on GitLab Self-Managed or GitLab Dedicated instances with the
[**Enable and enforce job token allowlist for all projects** setting](../../administration/settings/continuous_integration.md#enforce-job-token-allowlist)
disabled.
Prerequisites:
- You must have at least the Maintainer role for the project.
To disable the job token allowlist:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Job token permissions**.
1. Under **Authorized groups and projects**, select **All groups and projects**.
1. Recommended. When finished testing, select **This project and any groups and projects in the allowlist** to re-enable the job token allowlist.
You can also modify this setting with the [GraphQL](../../api/graphql/reference/_index.md#mutationprojectcicdsettingsupdate)
(`inboundJobTokenScopeEnabled`) or [REST](../../api/project_job_token_scopes.md#patch-a-projects-cicd-job-token-access-settings) API.
### Allow Git push requests to your project repository
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/389060) in GitLab 17.2. [with a flag](../../administration/feature_flags/_index.md) named `allow_push_repository_for_job_token`. Disabled by default.
- **Token Access** section renamed to **Job token permissions**, and [**Limit access to this project** setting renamed to **Authorized groups and projects**](https://gitlab.com/gitlab-org/gitlab/-/issues/415519) in GitLab 17.2.
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
This feature is available for testing, but not ready for production use.
{{< /alert >}}
{{< alert type="warning" >}}
Pushing to the project repository by authenticating with a CI/CD job token is still in development
and not yet optimized for performance. If you enable this feature for testing, you must
thoroughly test and implement validation measures to prevent infinite loops of "push" pipelines
triggering more pipelines.
{{< /alert >}}
You can allow Git push requests to your project repository that are authenticated
with a CI/CD job token. When enabled, access is allowed only for the tokens generated
in CI/CD jobs that run in pipelines in your project. This permission is disabled by default.
Prerequisites:
- You must have at least the Maintainer role for the project.
To grant permission to job tokens generated in your project to push to the project's repository:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Job token permissions**.
1. In the **Permissions** section, select **Allow Git push requests to the repository**.
The job token has the same access permissions as the user that started the job.
Job tokens from other [projects or groups in the allowlist](#add-a-group-or-project-to-the-job-token-allowlist)
cannot push to the repository in your project.
You can also control this setting with the [`ci_push_repository_for_job_token_allowed`](../../api/projects.md#edit-a-project)
parameter in the `projects` REST API endpoint.
## Fine-grained permissions for job tokens
Fine-grained permissions for job tokens are an [experiment](../../policy/development_stages_support.md#experiment). For information on this feature and the available resources, see [fine-grained permissions for CI/CD job tokens](fine_grained_permissions.md). Feedback is welcome on this [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/519575).
## Use a job token
### To `git clone` a private project's repository
You can use the job token to authenticate and clone a repository from a private project
in a CI/CD job. Use `gitlab-ci-token` as the user, and the value of the job token as the password. For example:
```shell
git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.example.com/<namespace>/<project>
```
You can use this job token to clone a repository even if the HTTPS protocol is [disabled by group, project, or instance settings](../../administration/settings/visibility_and_access_controls.md#configure-enabled-git-access-protocols). You cannot use a job token to push to a repository, but [issue 389060](https://gitlab.com/gitlab-org/gitlab/-/issues/389060)
proposes to change this behavior.
### To authenticate a REST API request
You can use a job token to authenticate requests for allowed REST API endpoints. For example:
```shell
curl --verbose --request POST --form "token=$CI_JOB_TOKEN" --form ref=master "https://gitlab.com/api/v4/projects/1234/trigger/pipeline"
```
Additionally, there are multiple valid methods for passing the job token in the request:
- Form: `--form "token=$CI_JOB_TOKEN"`
- Header: `--header "JOB-TOKEN: $CI_JOB_TOKEN"`
- Data: `--data "job_token=$CI_JOB_TOKEN"`
- Query string in the URL: `?job_token=$CI_JOB_TOKEN`
<!--- start_remove The following content will be removed on remove_date: '2025-08-15' -->
## Limit your project's job token access (removed)
{{< history >}}
- Deprecated in GitLab 16.0.
- [Removed](https://gitlab.com/gitlab-org/gitlab/-/issues/537186) in GitLab 18.0.
{{< /history >}}
{{< alert type="warning" >}}
The [**Limit access from this project**](#configure-the-job-token-scope-removed)
setting is disabled by default for all new projects and was removed
in GitLab 18.0. Project maintainers or owners can configure the [**Limit access to this project**](#add-a-group-or-project-to-the-job-token-allowlist)
setting instead.
{{< /alert >}}
Control your project's job token scope by creating an allowlist of projects which
can be accessed by your project's job token.
By default, the allowlist includes your current project.
Other projects can be added and removed by maintainers with access to both projects.
With the setting disabled, all projects are considered in the allowlist and the job token is
limited only by the user's access permissions.
For example, when the setting is enabled, jobs in a pipeline in project `A` have
a `CI_JOB_TOKEN` scope limited to project `A`. If the job needs to use the token
to make an API request to project `B`, then `B` must be added to the allowlist for `A`.
### Configure the job token scope (removed)
{{< history >}}
- **Limit CI_JOB_TOKEN access** setting [renamed to **Limit access from this project**](https://gitlab.com/gitlab-org/gitlab/-/issues/411406) in GitLab 16.3.
- **Token Access** setting [renamed to **Job token permissions**](https://gitlab.com/gitlab-org/gitlab/-/issues/415519) in GitLab 17.2.
{{< /history >}}
Prerequisites:
- You must not have more than 200 projects added to the token's scope.
To configure the job token scope:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Job token permissions**.
1. Toggle **Limit access from this project** to enabled.
1. Optional. Add existing projects to the token's access scope. The user adding a
project must have the Maintainer role in both projects.
<!--- end_remove -->
## Job token authentication log
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/467292/) in GitLab 17.6.
{{< /history >}}
You can track which other projects use a CI/CD job token to authenticate with your project
in an authentication log. To check the log:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Job token permissions**. The **Authentication log** section displays the
list of other projects that accessed your project by authenticating with a job token.
1. Optional. Select **Download CSV** to download the full authentication log, in CSV format.
The authentication log displays a maximum of 100 authentication events. If the number of events
is more than 100, download the CSV file to view the log.
New authentications to a project can take up to 5 minutes to appear in the authentication log.
## Use legacy format for CI/CD tokens
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/work_items/514860) in GitLab 17.10.
{{< /history >}}
Beginning in GitLab 19.0, CI/CD job tokens use the JWT standard by default. Projects can continue to use the legacy format by configuring the top-level group for their project. This setting is only available until the GitLab 20.0 release.
To use the legacy format for your CI/CD tokens:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings** > **CI/CD**.
1. Expand **General pipelines**.
1. Turn off **Enable JWT format for CI/CD job tokens**.
Your CI/CD tokens now use the legacy format. If you want to use the JWT format again later, you can re-enable this setting.
## Troubleshooting
CI job token failures are usually shown as responses like `404 Not Found` or similar:
- Unauthorized Git clone:
```plaintext
$ git clone https://gitlab-ci-token:$CI_JOB_TOKEN@gitlab.com/fabiopitino/test2.git
Cloning into 'test2'...
remote: The project you were looking for could not be found or you don't have permission to view it.
fatal: repository 'https://gitlab-ci-token:[MASKED]@gitlab.com/<namespace>/<project>.git/' not found
```
- Unauthorized package download:
```plaintext
$ wget --header="JOB-TOKEN: $CI_JOB_TOKEN" ${CI_API_V4_URL}/projects/1234/packages/generic/my_package/0.0.1/file.txt
--2021-09-23 11:00:13-- https://gitlab.com/api/v4/projects/1234/packages/generic/my_package/0.0.1/file.txt
Resolving gitlab.com (gitlab.com)... 172.65.251.78, 2606:4700:90:0:f22e:fbec:5bed:a9b9
Connecting to gitlab.com (gitlab.com)|172.65.251.78|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2021-09-23 11:00:13 ERROR 404: Not Found.
```
- Unauthorized API request:
```plaintext
$ curl --verbose --request POST --form "token=$CI_JOB_TOKEN" --form ref=master "https://gitlab.com/api/v4/projects/1234/trigger/pipeline"
< HTTP/2 404
< date: Thu, 23 Sep 2021 11:00:12 GMT
{"message":"404 Not Found"}
< content-type: application/json
```
While troubleshooting CI/CD job token authentication issues, be aware that:
- A [GraphQL example mutation](../../api/graphql/getting_started.md#update-project-settings)
is available to toggle the scope settings per project.
- [This comment](https://gitlab.com/gitlab-org/gitlab/-/issues/351740#note_1335673157)
demonstrates how to use GraphQL with Bash and cURL to:
- Enable the inbound token access scope.
- Give access to project B from project A, or add B to A's allowlist.
- To remove project access.
- The CI job token becomes invalid if the job is no longer running, has been erased,
or if the project is in the process of being deleted.
### JWT format job token errors
There are some known issues with the JWT format for CI/CD job tokens.
#### `Error when persisting the task ARN.` error with EC2 Fargate Runner custom executor
There is [a bug](https://gitlab.com/gitlab-org/ci-cd/custom-executor-drivers/fargate/-/issues/86)
in version `0.5.0` and earlier of the EC2 Fargate custom executor. This issue causes this error:
- `Error when persisting the task ARN. Will stop the task for cleanup`
To fix this issue, upgrade to version `0.5.1` or later of the Fargate custom executor.
#### `invalid character '\n' in string literal` error with `base64` encoding
If you use `base64` to encode job tokens, you could receive an `invalid character '\n'` error.
The default behavior of the `base64` command wraps strings that are longer than 79 characters.
When `base64` encoding JWT format job tokens during job execution, for example with
`echo $CI_JOB_TOKEN | base64`, the token is rendered invalid.
To fix this issue, use `base64 -w0` to disable automatically wrapping the token.
|
---
stage: Software Supply Chain Security
group: Pipeline Security
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: GitLab CI/CD job token
breadcrumbs:
- doc
- ci
- jobs
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
When a CI/CD pipeline job is about to run, GitLab generates a unique token and makes it available
to the job as the [`CI_JOB_TOKEN` predefined variable](../variables/predefined_variables.md).
The token is valid only while the job is running. After the job finishes, the token access
is revoked and you cannot use the token anymore.
Use a CI/CD job token to authenticate with certain GitLab features from running jobs.
The token receives the same access level as the user that triggered the pipeline,
but has [access to fewer resources](#job-token-access) than a personal access token. A user can cause a job to run
with an action like pushing a commit, triggering a manual job, or being the owner of a scheduled pipeline.
This user must have a [role that has the required privileges](../../user/permissions.md#cicd)
to access the resources.
You can use a job token to authenticate with GitLab to access another group or project's resources (the target project).
By default, the job token's group or project must be [added to the target project's allowlist](#add-a-group-or-project-to-the-job-token-allowlist).
If a project is public or internal, you can access some features without being on the allowlist.
For example, you can fetch artifacts from the project's public pipelines.
This access can also [be restricted](#limit-job-token-scope-for-public-or-internal-projects).
## Job token access
CI/CD job tokens can access the following resources:
| Resource | Notes |
| ----------------------------------------------------------------------------------------------------- | ----- |
| [Container registry](../../user/packages/container_registry/build_and_push_images.md#use-gitlab-cicd) | Used as the `$CI_REGISTRY_PASSWORD` [predefined variable](../variables/predefined_variables.md) to authenticate with the container registry associated with the job's project. |
| [Package registry](../../user/packages/package_registry/_index.md#to-build-packages) | Used to authenticate with the registry. |
| [Terraform module registry](../../user/packages/terraform_module_registry/_index.md) | Used to authenticate with the registry. |
| [Secure files](../secure_files/_index.md#use-secure-files-in-cicd-jobs) | Used by the [`download-secure-files`](https://gitlab.com/gitlab-org/incubation-engineering/mobile-devops/download-secure-files) tool to use secure files in jobs. |
| [Container registry API](../../api/container_registry.md) | Can authenticate only with the container registry associated with the job's project. |
| [Deployments API](../../api/deployments.md) | Can access all endpoints in this API. |
| [Environments API](../../api/environments.md) | Can access all endpoints in this API. |
| [Jobs API](../../api/jobs.md#get-job-tokens-job) | Can access only the `GET /job` endpoint. |
| [Job artifacts API](../../api/job_artifacts.md) | Can access all endpoints in this API. |
| [Packages API](../../api/packages.md) | Can access all endpoints in this API. |
| [Pipeline trigger tokens API](../../api/pipeline_triggers.md#trigger-a-pipeline-with-a-token) | Can access only the `POST /projects/:id/trigger/pipeline` endpoint. |
| [Pipelines API](../../api/pipelines.md#update-pipeline-metadata) | Can access only the `PUT /projects/:id/pipelines/:pipeline_id/metadata` endpoint. |
| [Release links API](../../api/releases/links.md) | Can access all endpoints in this API. |
| [Releases API](../../api/releases/_index.md) | Can access all endpoints in this API. |
| [Repositories API](../../api/repositories.md#generate-changelog-data) | Can access only the `GET /projects/:id/repository/changelog` endpoint. |
An open [proposal](https://gitlab.com/groups/gitlab-org/-/epics/3559) exists to make permissions
more granular.
## GitLab CI/CD job token security
If a job token is leaked, it could potentially be used to access private data accessible
to the user that triggered the CI/CD job. To help prevent leaking or misuse of this token,
GitLab:
- Masks the job token in job logs.
- Grants permissions to the job token only when the job is running.
You should also configure your [runners](../runners/_index.md) to be secure:
- Avoid using Docker `privileged` mode if the machines are re-used.
- Avoid using the [`shell` executor](https://docs.gitlab.com/runner/executors/shell.html) when jobs
run on the same machine.
An insecure GitLab Runner configuration increases the risk that someone can steal tokens from other
jobs.
## Control job token access to your project
You can control which groups or projects can use a job token to authenticate and access some of your project's resources.
By default, job token access is restricted to only CI/CD jobs that run in pipelines in
your project. To allow another group or project to authenticate with a job token from the other
project's pipeline:
- You must [add the group or project to the job token allowlist](#add-a-group-or-project-to-the-job-token-allowlist).
- The user that triggers the job must be a member of your project.
- The user must have the [permissions](../../user/permissions.md) to perform the action.
If your project is public or internal, some publicly accessible resources can be accessed
with a job token from any project. These resources can also be [limited to only projects on the allowlist](#limit-job-token-scope-for-public-or-internal-projects).
GitLab Self-Managed administrators can [override and enforce this setting](../../administration/settings/continuous_integration.md#access-job-token-permission-settings).
When the setting is enforced, the CI/CD job token is always restricted to the project's allowlist.
### Add a group or project to the job token allowlist
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/346298/) in GitLab 15.9. [Deployed behind the `:inbound_ci_scoped_job_token` feature flag](../../administration/feature_flags/_index.md), enabled by default.
- [Feature flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/346298/) in GitLab 15.10.
- **Allow access to this project with a CI_JOB_TOKEN** setting [renamed to **Limit access to this project**](https://gitlab.com/gitlab-org/gitlab/-/issues/411406) in GitLab 16.3.
- Adding groups to the job token allowlist [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/415519) in GitLab 17.0.
- **Token Access** section renamed to **Job token permissions**, and [**Limit access to this project** setting renamed to **Authorized groups and projects**](https://gitlab.com/gitlab-org/gitlab/-/issues/415519) in GitLab 17.2.
- **Add project** option [renamed to **Add**](https://gitlab.com/gitlab-org/gitlab/-/issues/470880/) in GitLab 17.6.
{{< /history >}}
You can add groups or projects to your job token allowlist to allow access to your project's resources
with a job token for authentication. By default, the allowlist of any project only includes itself.
Add groups or projects to the allowlist only when cross-project access is needed.
Adding a project to the allowlist does not give additional [permissions](../../user/permissions.md)
to the members of the allowlisted project. They must already have permissions to access the resources
in your project to use a job token from the allowlisted project to access your project.
For example, project A can add project B to project A's allowlist. CI/CD jobs
in project B (the "allowed project") can now use CI/CD job tokens to
authenticate API calls to access project A.
Prerequisites:
- You must have at least the Maintainer role for the current project. If the allowed project
is internal or private, you must have at least the Guest role in that project.
- You must not have more than 200 groups and projects added to the allowlist.
To add a group or project to the allowlist:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Job token permissions**.
1. Select **Add group or project**.
1. Input the path to the group or project to add to the allowlist, and select **Add**.
You can also add a group or project to the allowlist [with the API](../../api/graphql/reference/_index.md#mutationcijobtokenscopeaddgrouporproject).
### Auto-populate a project's allowlist
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/478540) in GitLab 17.10.
{{< /history >}}
You can populate a project's allowlist using the data from the [job token authentication log](#job-token-authentication-log)
with the UI or a Rake task.
In either case, GitLab uses the authentication log to determine which projects or groups to add to the allowlist
and adds those entries for you.
This process creates at most 200 entries in the project's allowlist. If more than 200 entries exist in the authentication log,
it [compacts the allowlist](#allowlist-compaction) to stay under the 200 entry limit.
#### With the UI
{{< history >}}
- Introduced in [GitLab 17.10](https://gitlab.com/gitlab-org/gitlab/-/issues/498125).
{{< /history >}}
To auto-populate the allowlist through the UI:
1. On the left sidebar, select **Search or go** to and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Job token permissions**.
1. Select **Add** and choose **All projects in authentication log** from the dropdown list.
1. A dialog asks you to confirm the action, select **Add entries**.
After the process completes, the allowlist contains the entries from the authentication log.
If not already set, the **Authorized groups and projects** is set to **Only this project and any groups and projects in the allowlist**.
#### With a Rake task
GitLab administrators with [rails console access](../../administration/operations/rails_console.md)
can run a Rake task to auto-populate the allowlist for all or a subset of projects on an instance.
This task also sets the **Authorized groups and projects** setting to **Only this project and any groups and projects in the allowlist**.
The `ci:job_tokens:allowlist:autopopulate_and_enforce` Rake task has the following configuration options:
- `PREVIEW`: Do a dry run and output the steps that would have been taken, but do not change any data.
- `ONLY_PROJECT_IDS`: Do the migration for only the supplied project IDs (maximum of 1000 IDs).
- `EXCLUDE_PROJECT_IDS`: Do the migration for all projects on the instance, except
for the supplied project IDs (maximum of 1000 IDs).
`ONLY_PROJECT_IDS` and `EXCLUDE_PROJECT_IDS` cannot be used at the same time.
For example:
- `ci:job_tokens:allowlist:autopopulate_and_enforce PREVIEW=true`
- `ci:job_tokens:allowlist:autopopulate_and_enforce PREVIEW=true ONLY_PROJECT_IDS=2,3`
- `ci:job_tokens:allowlist:autopopulate_and_enforce PREVIEW=true EXCLUDE_PROJECT_IDS=2,3`
- `ci:job_tokens:allowlist:autopopulate_and_enforce`
- `ci:job_tokens:allowlist:autopopulate_and_enforce ONLY_PROJECT_IDS=2,3`
- `ci:job_tokens:allowlist:autopopulate_and_enforce EXCLUDE_PROJECT_IDS=2,3`
To run the Rake task for:
{{< tabs >}}
{{< tab title="Linux package (Omnibus)" >}}
```shell
sudo gitlab-rake ci:job_tokens:allowlist:autopopulate_and_enforce
```
{{< /tab >}}
{{< tab title="Self-compiled (source)" >}}
```shell
sudo -u git -H bundle exec rake ci:job_tokens:allowlist:autopopulate_and_enforce
```
{{< /tab >}}
{{< /tabs >}}
#### Allowlist compaction
The allowlist compaction algorithm:
1. Scans the authorization log to identify the nearest common groups for projects.
1. Consolidates multiple project-level entries into single group-level entries.
1. Updates the allowlist with these consolidated entries.
For example, with an allowlist similar to:
```plaintext
group1/group2/group3/project1
group1/group2/group3/project2
group1/group2/group4/project3
group1/group2/group4/project4
group1/group5/group6/project5
```
The compaction algorithm:
1. Compacts the list to:
```plaintext
group1/group2/group3
group1/group2/group4
group1/group5/group6
```
1. If the allowlist is over the 200 entry limit, the algorithm compacts again:
```plaintext
group1/group2
group1/group5
```
1. If the allowlist is still over the 200 entry limit, the algorithm continues:
```plaintext
group1
```
This process is performed until the number of allowlist entries is 200 or fewer.
### Limit job token scope for public or internal projects
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/405369) in GitLab 16.6.
{{< /history >}}
Projects not in the allowlist can use a job token to authenticate with public or internal projects to:
- Fetch artifacts.
- Access the container registry.
- Access the package registry.
- Access releases, deployments, and environments.
You can limit access to these actions to only the projects on the allowlist by setting
each feature to be only visible to project members.
Prerequisites:
- You must have the Maintainer role for the project.
To set a feature to be only visible to project members:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **General**.
1. Expand **Visibility, project features, permissions**.
1. Set the visibility to **Only project members** for the features you want to restrict access to.
- The ability to fetch artifacts is controlled by the CI/CD visibility setting.
1. Select **Save changes**.
### Allow any project to access your project
{{< details >}}
- Offering: GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- **Allow access to this project with a CI_JOB_TOKEN** setting [renamed to **Limit access to this project**](https://gitlab.com/gitlab-org/gitlab/-/issues/411406) in GitLab 16.3.
- **Token Access** section renamed to **Job token permissions**, and [**Limit access to this project** setting renamed to **Authorized groups and projects**](https://gitlab.com/gitlab-org/gitlab/-/issues/415519) in GitLab 17.2.
{{< /history >}}
{{< alert type="warning" >}}
It is a security risk to disable the token access limit and allowlist. A malicious user could try to compromise
a pipeline created in an unauthorized project. If the pipeline was created by one of
your maintainers, the job token could be used in an attempt to access your project.
{{< /alert >}}
If you disable the CI/CD job token allowlist, jobs from any project can access your project
with a job token. The user that triggers the pipeline must have permission to access your project.
You should only disable this setting for testing or a similar reason,
and you should enable it again as soon as possible.
This option is only available on GitLab Self-Managed or GitLab Dedicated instances with the
[**Enable and enforce job token allowlist for all projects** setting](../../administration/settings/continuous_integration.md#enforce-job-token-allowlist)
disabled.
Prerequisites:
- You must have at least the Maintainer role for the project.
To disable the job token allowlist:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Job token permissions**.
1. Under **Authorized groups and projects**, select **All groups and projects**.
1. Recommended. When finished testing, select **This project and any groups and projects in the allowlist** to re-enable the job token allowlist.
You can also modify this setting with the [GraphQL](../../api/graphql/reference/_index.md#mutationprojectcicdsettingsupdate)
(`inboundJobTokenScopeEnabled`) or [REST](../../api/project_job_token_scopes.md#patch-a-projects-cicd-job-token-access-settings) API.
### Allow Git push requests to your project repository
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/389060) in GitLab 17.2. [with a flag](../../administration/feature_flags/_index.md) named `allow_push_repository_for_job_token`. Disabled by default.
- **Token Access** section renamed to **Job token permissions**, and [**Limit access to this project** setting renamed to **Authorized groups and projects**](https://gitlab.com/gitlab-org/gitlab/-/issues/415519) in GitLab 17.2.
{{< /history >}}
{{< alert type="flag" >}}
The availability of this feature is controlled by a feature flag.
For more information, see the history.
This feature is available for testing, but not ready for production use.
{{< /alert >}}
{{< alert type="warning" >}}
Pushing to the project repository by authenticating with a CI/CD job token is still in development
and not yet optimized for performance. If you enable this feature for testing, you must
thoroughly test and implement validation measures to prevent infinite loops of "push" pipelines
triggering more pipelines.
{{< /alert >}}
You can allow Git push requests to your project repository that are authenticated
with a CI/CD job token. When enabled, access is allowed only for the tokens generated
in CI/CD jobs that run in pipelines in your project. This permission is disabled by default.
Prerequisites:
- You must have at least the Maintainer role for the project.
To grant permission to job tokens generated in your project to push to the project's repository:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Job token permissions**.
1. In the **Permissions** section, select **Allow Git push requests to the repository**.
The job token has the same access permissions as the user that started the job.
Job tokens from other [projects or groups in the allowlist](#add-a-group-or-project-to-the-job-token-allowlist)
cannot push to the repository in your project.
You can also control this setting with the [`ci_push_repository_for_job_token_allowed`](../../api/projects.md#edit-a-project)
parameter in the `projects` REST API endpoint.
## Fine-grained permissions for job tokens
Fine-grained permissions for job tokens are an [experiment](../../policy/development_stages_support.md#experiment). For information on this feature and the available resources, see [fine-grained permissions for CI/CD job tokens](fine_grained_permissions.md). Feedback is welcome on this [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/519575).
## Use a job token
### To `git clone` a private project's repository
You can use the job token to authenticate and clone a repository from a private project
in a CI/CD job. Use `gitlab-ci-token` as the user, and the value of the job token as the password. For example:
```shell
git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.example.com/<namespace>/<project>
```
You can use this job token to clone a repository even if the HTTPS protocol is [disabled by group, project, or instance settings](../../administration/settings/visibility_and_access_controls.md#configure-enabled-git-access-protocols). You cannot use a job token to push to a repository, but [issue 389060](https://gitlab.com/gitlab-org/gitlab/-/issues/389060)
proposes to change this behavior.
### To authenticate a REST API request
You can use a job token to authenticate requests for allowed REST API endpoints. For example:
```shell
curl --verbose --request POST --form "token=$CI_JOB_TOKEN" --form ref=master "https://gitlab.com/api/v4/projects/1234/trigger/pipeline"
```
Additionally, there are multiple valid methods for passing the job token in the request:
- Form: `--form "token=$CI_JOB_TOKEN"`
- Header: `--header "JOB-TOKEN: $CI_JOB_TOKEN"`
- Data: `--data "job_token=$CI_JOB_TOKEN"`
- Query string in the URL: `?job_token=$CI_JOB_TOKEN`
<!--- start_remove The following content will be removed on remove_date: '2025-08-15' -->
## Limit your project's job token access (removed)
{{< history >}}
- Deprecated in GitLab 16.0.
- [Removed](https://gitlab.com/gitlab-org/gitlab/-/issues/537186) in GitLab 18.0.
{{< /history >}}
{{< alert type="warning" >}}
The [**Limit access from this project**](#configure-the-job-token-scope-removed)
setting is disabled by default for all new projects and was removed
in GitLab 18.0. Project maintainers or owners can configure the [**Limit access to this project**](#add-a-group-or-project-to-the-job-token-allowlist)
setting instead.
{{< /alert >}}
Control your project's job token scope by creating an allowlist of projects which
can be accessed by your project's job token.
By default, the allowlist includes your current project.
Other projects can be added and removed by maintainers with access to both projects.
With the setting disabled, all projects are considered in the allowlist and the job token is
limited only by the user's access permissions.
For example, when the setting is enabled, jobs in a pipeline in project `A` have
a `CI_JOB_TOKEN` scope limited to project `A`. If the job needs to use the token
to make an API request to project `B`, then `B` must be added to the allowlist for `A`.
### Configure the job token scope (removed)
{{< history >}}
- **Limit CI_JOB_TOKEN access** setting [renamed to **Limit access from this project**](https://gitlab.com/gitlab-org/gitlab/-/issues/411406) in GitLab 16.3.
- **Token Access** setting [renamed to **Job token permissions**](https://gitlab.com/gitlab-org/gitlab/-/issues/415519) in GitLab 17.2.
{{< /history >}}
Prerequisites:
- You must not have more than 200 projects added to the token's scope.
To configure the job token scope:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Job token permissions**.
1. Toggle **Limit access from this project** to enabled.
1. Optional. Add existing projects to the token's access scope. The user adding a
project must have the Maintainer role in both projects.
<!--- end_remove -->
## Job token authentication log
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/467292/) in GitLab 17.6.
{{< /history >}}
You can track which other projects use a CI/CD job token to authenticate with your project
in an authentication log. To check the log:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings** > **CI/CD**.
1. Expand **Job token permissions**. The **Authentication log** section displays the
list of other projects that accessed your project by authenticating with a job token.
1. Optional. Select **Download CSV** to download the full authentication log, in CSV format.
The authentication log displays a maximum of 100 authentication events. If the number of events
is more than 100, download the CSV file to view the log.
New authentications to a project can take up to 5 minutes to appear in the authentication log.
## Use legacy format for CI/CD tokens
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/work_items/514860) in GitLab 17.10.
{{< /history >}}
Beginning in GitLab 19.0, CI/CD job tokens use the JWT standard by default. Projects can continue to use the legacy format by configuring the top-level group for their project. This setting is only available until the GitLab 20.0 release.
To use the legacy format for your CI/CD tokens:
1. On the left sidebar, select **Search or go to** and find your group.
1. Select **Settings** > **CI/CD**.
1. Expand **General pipelines**.
1. Turn off **Enable JWT format for CI/CD job tokens**.
Your CI/CD tokens now use the legacy format. If you want to use the JWT format again later, you can re-enable this setting.
## Troubleshooting
CI job token failures are usually shown as responses like `404 Not Found` or similar:
- Unauthorized Git clone:
```plaintext
$ git clone https://gitlab-ci-token:$CI_JOB_TOKEN@gitlab.com/fabiopitino/test2.git
Cloning into 'test2'...
remote: The project you were looking for could not be found or you don't have permission to view it.
fatal: repository 'https://gitlab-ci-token:[MASKED]@gitlab.com/<namespace>/<project>.git/' not found
```
- Unauthorized package download:
```plaintext
$ wget --header="JOB-TOKEN: $CI_JOB_TOKEN" ${CI_API_V4_URL}/projects/1234/packages/generic/my_package/0.0.1/file.txt
--2021-09-23 11:00:13-- https://gitlab.com/api/v4/projects/1234/packages/generic/my_package/0.0.1/file.txt
Resolving gitlab.com (gitlab.com)... 172.65.251.78, 2606:4700:90:0:f22e:fbec:5bed:a9b9
Connecting to gitlab.com (gitlab.com)|172.65.251.78|:443... connected.
HTTP request sent, awaiting response... 404 Not Found
2021-09-23 11:00:13 ERROR 404: Not Found.
```
- Unauthorized API request:
```plaintext
$ curl --verbose --request POST --form "token=$CI_JOB_TOKEN" --form ref=master "https://gitlab.com/api/v4/projects/1234/trigger/pipeline"
< HTTP/2 404
< date: Thu, 23 Sep 2021 11:00:12 GMT
{"message":"404 Not Found"}
< content-type: application/json
```
While troubleshooting CI/CD job token authentication issues, be aware that:
- A [GraphQL example mutation](../../api/graphql/getting_started.md#update-project-settings)
is available to toggle the scope settings per project.
- [This comment](https://gitlab.com/gitlab-org/gitlab/-/issues/351740#note_1335673157)
demonstrates how to use GraphQL with Bash and cURL to:
- Enable the inbound token access scope.
- Give access to project B from project A, or add B to A's allowlist.
- To remove project access.
- The CI job token becomes invalid if the job is no longer running, has been erased,
or if the project is in the process of being deleted.
### JWT format job token errors
There are some known issues with the JWT format for CI/CD job tokens.
#### `Error when persisting the task ARN.` error with EC2 Fargate Runner custom executor
There is [a bug](https://gitlab.com/gitlab-org/ci-cd/custom-executor-drivers/fargate/-/issues/86)
in version `0.5.0` and earlier of the EC2 Fargate custom executor. This issue causes this error:
- `Error when persisting the task ARN. Will stop the task for cleanup`
To fix this issue, upgrade to version `0.5.1` or later of the Fargate custom executor.
#### `invalid character '\n' in string literal` error with `base64` encoding
If you use `base64` to encode job tokens, you could receive an `invalid character '\n'` error.
The default behavior of the `base64` command wraps strings that are longer than 79 characters.
When `base64` encoding JWT format job tokens during job execution, for example with
`echo $CI_JOB_TOKEN | base64`, the token is rendered invalid.
To fix this issue, use `base64 -w0` to disable automatically wrapping the token.
|
https://docs.gitlab.com/ci/caching
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/_index.md
|
2025-08-13
|
doc/ci/caching
|
[
"doc",
"ci",
"caching"
] |
_index.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Caching in GitLab CI/CD
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
A cache is one or more files a job downloads and saves. Subsequent jobs that use
the same cache don't have to download the files again, so they execute more quickly.
To learn how to define the cache in your `.gitlab-ci.yml` file,
see the [`cache` reference](../yaml/_index.md#cache).
## How cache is different from artifacts
Use cache for dependencies, like packages you download from the internet.
Cache is stored where GitLab Runner is installed and uploaded to S3 if
[distributed cache is enabled](https://docs.gitlab.com/runner/configuration/autoscale.html#distributed-runners-caching).
Use artifacts to pass intermediate build results between stages.
Artifacts are generated by a job, stored in GitLab, and can be downloaded.
Both artifacts and caches define their paths relative to the project directory, and
can't link to files outside it.
### Cache
- Define cache per job by using the `cache` keyword. Otherwise it is disabled.
- Subsequent pipelines can use the cache.
- Subsequent jobs in the same pipeline can use the cache, if the dependencies are identical.
- Different projects cannot share the cache.
- By default, protected and non-protected branches [do not share the cache](#cache-key-names). However, you can [change this behavior](#use-the-same-cache-for-all-branches).
### Artifacts
- Define artifacts per job.
- Subsequent jobs in later stages of the same pipeline can use artifacts.
- Artifacts expire after 30 days by default. You can define a custom [expiration time](../yaml/_index.md#artifactsexpire_in).
- The latest artifacts do not expire if [keep latest artifacts](../jobs/job_artifacts.md#keep-artifacts-from-most-recent-successful-jobs) is enabled.
- Use [dependencies](../yaml/_index.md#dependencies) to control which jobs fetch the artifacts.
## Good caching practices
To ensure maximum availability of the cache, do one or more of the following:
- [Tag your runners](../runners/configure_runners.md#control-jobs-that-a-runner-can-run) and use the tag on jobs
that share the cache.
- [Use runners that are only available to a particular project](../runners/runners_scope.md#prevent-a-project-runner-from-being-enabled-for-other-projects).
- [Use a `key`](../yaml/_index.md#cachekey) that fits your workflow. For example,
you can configure a different cache for each branch.
For runners to work with caches efficiently, you must do one of the following:
- Use a single runner for all your jobs.
- Use multiple runners that have
[distributed caching](https://docs.gitlab.com/runner/configuration/autoscale.html#distributed-runners-caching),
where the cache is stored in S3 buckets. Instance runners on GitLab.com behave this way. These runners can be in autoscale mode,
but they don't have to be. To manage cache objects,
apply lifecycle rules to delete the cache objects after a period of time.
Lifecycle rules are available on the object storage server.
- Use multiple runners with the same architecture and have these runners
share a common network-mounted directory to store the cache. This directory should use NFS or something similar.
These runners must be in autoscale mode.
## Use multiple caches
You can have a maximum of four caches:
```yaml
test-job:
stage: build
cache:
- key:
files:
- Gemfile.lock
paths:
- vendor/ruby
- key:
files:
- yarn.lock
paths:
- .yarn-cache/
script:
- bundle config set --local path 'vendor/ruby'
- bundle install
- yarn install --cache-folder .yarn-cache
- echo Run tests...
```
If multiple caches are combined with a fallback cache key,
the global fallback cache is fetched every time a cache is not found.
## Use a fallback cache key
### Per-cache fallback keys
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/110467) in GitLab 16.0
{{< /history >}}
Each cache entry supports up to five fallback keys with the [`fallback_keys` keyword](../yaml/_index.md#cachefallback_keys).
When a job does not find a cache key, the job attempts to retrieve a fallback cache instead.
Fallback keys are searched in order until a cache is found. If no cache is found,
the job runs without using a cache. For example:
```yaml
test-job:
stage: build
cache:
- key: cache-$CI_COMMIT_REF_SLUG
fallback_keys:
- cache-$CI_DEFAULT_BRANCH
- cache-default
paths:
- vendor/ruby
script:
- bundle config set --local path 'vendor/ruby'
- bundle install
- echo Run tests...
```
In this example:
1. The job looks for the `cache-$CI_COMMIT_REF_SLUG` cache.
1. If `cache-$CI_COMMIT_REF_SLUG` is not found, the job looks for `cache-$CI_DEFAULT_BRANCH`
as a fallback option.
1. If `cache-$CI_DEFAULT_BRANCH` is also not found, the job looks for `cache-default`
as a second fallback option.
1. If none are found, the job downloads all the Ruby dependencies without using a cache,
but creates a new cache for `cache-$CI_COMMIT_REF_SLUG` when the job completes.
Fallback keys follow the same processing logic as `cache:key`:
- If you [clear caches manually](#clear-the-cache-manually), per-cache fallback keys are appended
with an index like other cache keys.
- If the [**Use separate caches for protected branches** setting](#cache-key-names) is enabled,
per-cache fallback keys are appended with `-protected` or `-non_protected`.
### Global fallback key
You can use the `$CI_COMMIT_REF_SLUG` [predefined variable](../variables/predefined_variables.md)
to specify your [`cache:key`](../yaml/_index.md#cachekey). For example, if your
`$CI_COMMIT_REF_SLUG` is `test`, you can set a job to download cache that's tagged with `test`.
If a cache with this tag is not found, you can use `CACHE_FALLBACK_KEY` to
specify a cache to use when none exists.
In the following example, if the `$CI_COMMIT_REF_SLUG` is not found, the job uses the key defined
by the `CACHE_FALLBACK_KEY` variable:
```yaml
variables:
CACHE_FALLBACK_KEY: fallback-key
job1:
script:
- echo
cache:
key: "$CI_COMMIT_REF_SLUG"
paths:
- binaries/
```
The order of caches extraction is:
1. Retrieval attempt for `cache:key`
1. Retrieval attempts for each entry in order in `fallback_keys`
1. Retrieval attempt for the global fallback key in `CACHE_FALLBACK_KEY`
The cache extraction process stops after the first successful cache is retrieved.
## Disable cache for specific jobs
If you define the cache globally, each job uses the
same definition. You can override this behavior for each job.
To disable it completely for a job, use an empty list:
```yaml
job:
cache: []
```
## Inherit global configuration, but override specific settings per job
You can override cache settings without overwriting the global cache by using
[anchors](../yaml/yaml_optimization.md#anchors). For example, if you want to override the
`policy` for one job:
```yaml
default:
cache: &global_cache
key: $CI_COMMIT_REF_SLUG
paths:
- node_modules/
- public/
- vendor/
policy: pull-push
job:
cache:
# inherit all global cache settings
<<: *global_cache
# override the policy
policy: pull
```
For more information, see [`cache: policy`](../yaml/_index.md#cachepolicy).
## Common use cases for caches
Usually you use caches to avoid downloading content, like dependencies
or libraries, each time you run a job. Node.js packages,
PHP packages, Ruby gems, Python libraries, and others can be cached.
For examples, see the [GitLab CI/CD templates](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates).
### Share caches between jobs in the same branch
To have jobs in each branch use the same cache, define a cache with the `key: $CI_COMMIT_REF_SLUG`:
```yaml
cache:
key: $CI_COMMIT_REF_SLUG
```
This configuration prevents you from accidentally overwriting the cache. However, the
first pipeline for a merge request is slow. The next time a commit is pushed to the branch, the
cache is re-used and jobs run faster.
To enable per-job and per-branch caching:
```yaml
cache:
key: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"
```
To enable per-stage and per-branch caching:
```yaml
cache:
key: "$CI_JOB_STAGE-$CI_COMMIT_REF_SLUG"
```
### Share caches across jobs in different branches
To share a cache across all branches and all jobs, use the same key for everything:
```yaml
cache:
key: one-key-to-rule-them-all
```
To share a cache between branches, but have a unique cache for each job:
```yaml
cache:
key: $CI_JOB_NAME
```
### Use a variable to control a job's cache policy
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/371480) in GitLab 16.1.
{{< /history >}}
To reduce duplication of jobs where the only difference is the pull policy, you can use a [CI/CD variable](../variables/_index.md).
For example:
```yaml
conditional-policy:
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
variables:
POLICY: pull-push
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
variables:
POLICY: pull
stage: build
cache:
key: gems
policy: $POLICY
paths:
- vendor/bundle
script:
- echo "This job pulls and pushes the cache depending on the branch"
- echo "Downloading dependencies..."
```
In this example, the job's cache policy is:
- `pull-push` for changes to the default branch.
- `pull` for changes to other branches.
### Cache Node.js dependencies
If your project uses [npm](https://www.npmjs.com/) to install Node.js
dependencies, the following example defines a default `cache` so that all jobs inherit it.
By default, npm stores cache data in the home folder (`~/.npm`). However, you
[can't cache things outside of the project directory](../yaml/_index.md#cachepaths).
Instead, tell npm to use `./.npm`, and cache it per-branch:
```yaml
default:
image: node:latest
cache: # Cache modules in between jobs
key: $CI_COMMIT_REF_SLUG
paths:
- .npm/
before_script:
- npm ci --cache .npm --prefer-offline
test_async:
script:
- node ./specs/start.js ./specs/async.spec.js
```
#### Compute the cache key from the lock file
You can use [`cache:key:files`](../yaml/_index.md#cachekeyfiles) to compute the cache
key from a lock file like `package-lock.json` or `yarn.lock`, and reuse it in many jobs.
```yaml
default:
cache: # Cache modules using lock file
key:
files:
- package-lock.json
paths:
- .npm/
```
If you're using [Yarn](https://yarnpkg.com/), you can use [`yarn-offline-mirror`](https://classic.yarnpkg.com/blog/2016/11/24/offline-mirror/)
to cache the zipped `node_modules` tarballs. The cache generates more quickly, because
fewer files have to be compressed:
```yaml
job:
script:
- echo 'yarn-offline-mirror ".yarn-cache/"' >> .yarnrc
- echo 'yarn-offline-mirror-pruning true' >> .yarnrc
- yarn install --frozen-lockfile --no-progress
cache:
key:
files:
- yarn.lock
paths:
- .yarn-cache/
```
### Cache C/C++ compilation using Ccache
If you are compiling C/C++ projects, you can use [Ccache](https://ccache.dev/) to
speed up your build times. Ccache speeds up recompilation by caching previous compilations
and detecting when the same compilation is being done again. When building big projects like the Linux kernel,
you can expect significantly faster compilations.
Use `cache` to reuse the created cache between jobs, for example:
```yaml
job:
cache:
paths:
- ccache
before_script:
- export PATH="/usr/lib/ccache:$PATH" # Override compiler path with ccache (this example is for Debian)
- export CCACHE_DIR="${CI_PROJECT_DIR}/ccache"
- export CCACHE_BASEDIR="${CI_PROJECT_DIR}"
- export CCACHE_COMPILERCHECK=content # Compiler mtime might change in the container, use checksums instead
script:
- ccache --zero-stats || true
- time make # Actually build your code while measuring time and cache efficiency.
- ccache --show-stats || true
```
If you have multiple projects in a single repository you do not need a separate `CCACHE_BASEDIR` for each of them.
### Cache PHP dependencies
If your project uses [Composer](https://getcomposer.org/) to install
PHP dependencies, the following example defines a default `cache` so that
all jobs inherit it. PHP libraries modules are installed in `vendor/` and
are cached per-branch:
```yaml
default:
image: php:latest
cache: # Cache libraries in between jobs
key: $CI_COMMIT_REF_SLUG
paths:
- vendor/
before_script:
# Install and run Composer
- curl --show-error --silent "https://getcomposer.org/installer" | php
- php composer.phar install
test:
script:
- vendor/bin/phpunit --configuration phpunit.xml --coverage-text --colors=never
```
### Cache Python dependencies
If your project uses [pip](https://pip.pypa.io/en/stable/) to install
Python dependencies, the following example defines a default `cache` so that
all jobs inherit it. pip's cache is defined under `.cache/pip/` and is cached per-branch:
```yaml
default:
image: python:latest
cache: # Pip's cache doesn't store the python packages
paths: # https://pip.pypa.io/en/stable/topics/caching/
- .cache/pip
before_script:
- python -V # Print out python version for debugging
- pip install virtualenv
- virtualenv venv
- source venv/bin/activate
variables: # Change pip's cache directory to be inside the project directory because we can only cache local items.
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
test:
script:
- python setup.py test
- pip install ruff
- ruff --format=gitlab .
```
### Cache Ruby dependencies
If your project uses [Bundler](https://bundler.io) to install
gem dependencies, the following example defines a default `cache` so that all
jobs inherit it. Gems are installed in `vendor/ruby/` and are cached per-branch:
```yaml
default:
image: ruby:latest
cache: # Cache gems in between builds
key: $CI_COMMIT_REF_SLUG
paths:
- vendor/ruby
before_script:
- ruby -v # Print out ruby version for debugging
- bundle config set --local path 'vendor/ruby' # The location to install the specified gems to
- bundle install -j $(nproc) # Install dependencies into ./vendor/ruby
rspec:
script:
- rspec spec
```
If you have jobs that need different gems, use the `prefix`
keyword in the global `cache` definition. This configuration generates a different
cache for each job.
For example, a testing job might not need the same gems as a job that deploys to
production:
```yaml
default:
cache:
key:
files:
- Gemfile.lock
prefix: $CI_JOB_NAME
paths:
- vendor/ruby
test_job:
stage: test
before_script:
- bundle config set --local path 'vendor/ruby'
- bundle install --without production
script:
- bundle exec rspec
deploy_job:
stage: production
before_script:
- bundle config set --local path 'vendor/ruby' # The location to install the specified gems to
- bundle install --without test
script:
- bundle exec deploy
```
### Cache Go dependencies
If your project uses [Go Modules](https://go.dev/wiki/Modules) to install
Go dependencies, the following example defines `cache` in a `go-cache` template, that
any job can extend. Go modules are installed in `${GOPATH}/pkg/mod/` and
are cached for all of the `go` projects:
```yaml
.go-cache:
variables:
GOPATH: $CI_PROJECT_DIR/.go
before_script:
- mkdir -p .go
cache:
paths:
- .go/pkg/mod/
test:
image: golang:latest
extends: .go-cache
script:
- go test ./... -v -short
```
### Cache curl downloads
If your project uses [cURL](https://curl.se/) to download dependencies or files,
you can cache the downloaded content. The files are automatically updated when
newer downloads are available.
```yaml
job:
script:
- curl --remote-time --time-cond .curl-cache/caching.md --output .curl-cache/caching.md "https://docs.gitlab.com/ci/caching/"
cache:
paths:
- .curl-cache/
```
In this example cURL downloads a file from a webserver and saves it to a local file in `.curl-cache/`.
The `--remote-time` flag saves the last modification time reported by the server,
and cURL compares it to the timestamp of the cached file with `--time-cond`. If the remote file has
a more recent timestamp the local cache is automatically updated.
## Availability of the cache
Caching is an optimization, but it isn't guaranteed to always work. You might need
to regenerate cached files in each job that needs them.
After you define a [cache in `.gitlab-ci.yml`](../yaml/_index.md#cache),
the availability of the cache depends on:
- The runner's executor type.
- Whether different runners are used to pass the cache between jobs.
### Where the caches are stored
All caches defined for a job are archived in a single `cache.zip` file.
The runner configuration defines where the file is stored. By default, the cache
is stored on the machine where GitLab Runner is installed. The location also depends on the type of executor.
| Runner executor | Default path of the cache |
| ---------------------- | ------------------------- |
| [Shell](https://docs.gitlab.com/runner/executors/shell.html) | Locally, under the `gitlab-runner` user's home directory: `/home/gitlab-runner/cache/<user>/<project>/<cache-key>/cache.zip`. |
| [Docker](https://docs.gitlab.com/runner/executors/docker.html) | Locally, under [Docker volumes](https://docs.gitlab.com/runner/executors/docker.html#configure-directories-for-the-container-build-and-cache): `/var/lib/docker/volumes/<volume-id>/_data/<user>/<project>/<cache-key>/cache.zip`. |
| [Docker Machine](https://docs.gitlab.com/runner/executors/docker_machine.html) (autoscale runners) | The same as the Docker executor. |
If you use cache and artifacts to store the same path in your jobs, the cache might
be overwritten because caches are restored before artifacts.
#### Cache key names
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/330047) in GitLab 15.0.
{{< /history >}}
A suffix is added to the cache key, with the exception of the [global fallback cache key](#global-fallback-key).
As an example, assuming that `cache.key` is set to `$CI_COMMIT_REF_SLUG`, and that we have two branches `main`
and `feature`, then the following table represents the resulting cache keys:
| Branch name | Cache key |
|-------------|-----------|
| `main` | `main-protected` |
| `feature` | `feature-non_protected` |
##### Use the same cache for all branches
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/361643) in GitLab 15.0.
{{< /history >}}
If you do not want to use [cache key names](#cache-key-names),
you can have all branches (protected and unprotected) use the same cache.
The cache separation with [cache key names](#cache-key-names) is a security feature
and should only be disabled in an environment where all users with Developer role are highly trusted.
To use the same cache for all branches:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Clear the **Use separate caches for protected branches** checkbox.
1. Select **Save changes**.
### How archiving and extracting works
This example shows two jobs in two consecutive stages:
```yaml
stages:
- build
- test
default:
cache:
key: build-cache
paths:
- vendor/
before_script:
- echo "Hello"
job A:
stage: build
script:
- mkdir vendor/
- echo "build" > vendor/hello.txt
after_script:
- echo "World"
job B:
stage: test
script:
- cat vendor/hello.txt
```
If one machine has one runner installed, then all jobs for your project
run on the same host:
1. Pipeline starts.
1. `job A` runs.
1. The cache is extracted (if found).
1. `before_script` is executed.
1. `script` is executed.
1. `after_script` is executed.
1. `cache` runs and the `vendor/` directory is zipped into `cache.zip`.
This file is then saved in the directory based on the
[runner's setting](#where-the-caches-are-stored) and the `cache: key`.
1. `job B` runs.
1. The cache is extracted (if found).
1. `before_script` is executed.
1. `script` is executed.
1. Pipeline finishes.
By using a single runner on a single machine, you don't have the issue where
`job B` might execute on a runner different from `job A`. This setup guarantees the
cache can be reused between stages. It only works if the execution goes from the `build` stage
to the `test` stage in the same runner/machine. Otherwise, the cache [might not be available](#cache-mismatch).
During the caching process, there's also a couple of things to consider:
- If some other job, with another cache configuration had saved its
cache in the same zip file, it is overwritten. If the S3 based shared cache is
used, the file is additionally uploaded to S3 to an object based on the cache
key. So, two jobs with different paths, but the same cache key, overwrites
their cache.
- When extracting the cache from `cache.zip`, everything in the zip file is
extracted in the job's working directory (usually the repository which is
pulled down), and the runner doesn't mind if the archive of `job A` overwrites
things in the archive of `job B`.
It works this way because the cache created for one runner
often isn't valid when used by a different one. A different runner may run on a
different architecture (for example, when the cache includes binary files). Also,
because the different steps might be executed by runners running on different
machines, it is a safe default.
## Clearing the cache
Runners use [cache](../yaml/_index.md#cache) to speed up the execution
of your jobs by reusing existing data. This can sometimes lead to
inconsistent behavior.
There are two ways to start with a fresh copy of the cache.
### Clear the cache by changing `cache:key`
Change the value for `cache: key` in your `.gitlab-ci.yml` file.
The next time the pipeline runs, the cache is stored in a different location.
### Clear the cache manually
You can clear the cache in the GitLab UI:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipelines**.
1. In the upper-right corner, select **Clear runner caches**.
On the next commit, your CI/CD jobs use a new cache.
{{< alert type="note" >}}
Each time you clear the cache manually, the [internal cache name](#where-the-caches-are-stored) is updated. The name uses the format `cache-<index>`, and the index increments by one. The old cache is not deleted. You can manually delete these files from the runner storage.
{{< /alert >}}
## Troubleshooting
### Cache mismatch
If you have a cache mismatch, follow these steps to troubleshoot.
| Reason for a cache mismatch | How to fix it |
| --------------------------- | ------------- |
| You use multiple standalone runners (not in autoscale mode) attached to one project without a shared cache. | Use only one runner for your project or use multiple runners with distributed cache enabled. |
| You use runners in autoscale mode without a distributed cache enabled. | Configure the autoscale runner to use a distributed cache. |
| The machine the runner is installed on is low on disk space or, if you've set up distributed cache, the S3 bucket where the cache is stored doesn't have enough space. | Make sure you clear some space to allow new caches to be stored. There's no automatic way to do this. |
| You use the same `key` for jobs where they cache different paths. | Use different cache keys so that the cache archive is stored to a different location and doesn't overwrite wrong caches. |
| You have not enabled the [distributed runner caching on your runners](https://docs.gitlab.com/runner/configuration/autoscale.html#distributed-runners-caching). | Set `Shared = false` and re-provision your runners. |
#### Cache mismatch example 1
If you have only one runner assigned to your project, the cache
is stored on the runner's machine by default.
If two jobs have the same cache key but a different path, the caches can be overwritten.
For example:
```yaml
stages:
- build
- test
job A:
stage: build
script: make build
cache:
key: same-key
paths:
- public/
job B:
stage: test
script: make test
cache:
key: same-key
paths:
- vendor/
```
1. `job A` runs.
1. `public/` is cached as `cache.zip`.
1. `job B` runs.
1. The previous cache, if any, is unzipped.
1. `vendor/` is cached as `cache.zip` and overwrites the previous one.
1. The next time `job A` runs it uses the cache of `job B` which is different
and thus isn't effective.
To fix this issue, use different `keys` for each job.
#### Cache mismatch example 2
In this example, you have more than one runner assigned to your
project, and distributed cache is not enabled.
The second time the pipeline runs, you want `job A` and `job B` to re-use their cache (which in this case
is different):
```yaml
stages:
- build
- test
job A:
stage: build
script: build
cache:
key: keyA
paths:
- vendor/
job B:
stage: test
script: test
cache:
key: keyB
paths:
- vendor/
```
Even if the `key` is different, the cached files might get "cleaned" before each
stage if the jobs run on different runners in subsequent pipelines.
### Concurrent runners missing local cache
If you have configured multiple concurrent runners with the Docker executor, locally cached files might
not be present for concurrently-running jobs as you expect. The names of cache volumes are constructed
uniquely for each runner instance, so files cached by one runner instance are not found in the cache by another runner
instance.
To share the cache between concurrent runners, you can either:
- Use the `[runners.docker]` section of the runners' `config.toml` to configure a single mount point on the host that
is mapped to `/cache` in each container, preventing the runner from creating unique volume names.
- Use a distributed cache.
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Caching in GitLab CI/CD
breadcrumbs:
- doc
- ci
- caching
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
A cache is one or more files a job downloads and saves. Subsequent jobs that use
the same cache don't have to download the files again, so they execute more quickly.
To learn how to define the cache in your `.gitlab-ci.yml` file,
see the [`cache` reference](../yaml/_index.md#cache).
## How cache is different from artifacts
Use cache for dependencies, like packages you download from the internet.
Cache is stored where GitLab Runner is installed and uploaded to S3 if
[distributed cache is enabled](https://docs.gitlab.com/runner/configuration/autoscale.html#distributed-runners-caching).
Use artifacts to pass intermediate build results between stages.
Artifacts are generated by a job, stored in GitLab, and can be downloaded.
Both artifacts and caches define their paths relative to the project directory, and
can't link to files outside it.
### Cache
- Define cache per job by using the `cache` keyword. Otherwise it is disabled.
- Subsequent pipelines can use the cache.
- Subsequent jobs in the same pipeline can use the cache, if the dependencies are identical.
- Different projects cannot share the cache.
- By default, protected and non-protected branches [do not share the cache](#cache-key-names). However, you can [change this behavior](#use-the-same-cache-for-all-branches).
### Artifacts
- Define artifacts per job.
- Subsequent jobs in later stages of the same pipeline can use artifacts.
- Artifacts expire after 30 days by default. You can define a custom [expiration time](../yaml/_index.md#artifactsexpire_in).
- The latest artifacts do not expire if [keep latest artifacts](../jobs/job_artifacts.md#keep-artifacts-from-most-recent-successful-jobs) is enabled.
- Use [dependencies](../yaml/_index.md#dependencies) to control which jobs fetch the artifacts.
## Good caching practices
To ensure maximum availability of the cache, do one or more of the following:
- [Tag your runners](../runners/configure_runners.md#control-jobs-that-a-runner-can-run) and use the tag on jobs
that share the cache.
- [Use runners that are only available to a particular project](../runners/runners_scope.md#prevent-a-project-runner-from-being-enabled-for-other-projects).
- [Use a `key`](../yaml/_index.md#cachekey) that fits your workflow. For example,
you can configure a different cache for each branch.
For runners to work with caches efficiently, you must do one of the following:
- Use a single runner for all your jobs.
- Use multiple runners that have
[distributed caching](https://docs.gitlab.com/runner/configuration/autoscale.html#distributed-runners-caching),
where the cache is stored in S3 buckets. Instance runners on GitLab.com behave this way. These runners can be in autoscale mode,
but they don't have to be. To manage cache objects,
apply lifecycle rules to delete the cache objects after a period of time.
Lifecycle rules are available on the object storage server.
- Use multiple runners with the same architecture and have these runners
share a common network-mounted directory to store the cache. This directory should use NFS or something similar.
These runners must be in autoscale mode.
## Use multiple caches
You can have a maximum of four caches:
```yaml
test-job:
stage: build
cache:
- key:
files:
- Gemfile.lock
paths:
- vendor/ruby
- key:
files:
- yarn.lock
paths:
- .yarn-cache/
script:
- bundle config set --local path 'vendor/ruby'
- bundle install
- yarn install --cache-folder .yarn-cache
- echo Run tests...
```
If multiple caches are combined with a fallback cache key,
the global fallback cache is fetched every time a cache is not found.
## Use a fallback cache key
### Per-cache fallback keys
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/110467) in GitLab 16.0
{{< /history >}}
Each cache entry supports up to five fallback keys with the [`fallback_keys` keyword](../yaml/_index.md#cachefallback_keys).
When a job does not find a cache key, the job attempts to retrieve a fallback cache instead.
Fallback keys are searched in order until a cache is found. If no cache is found,
the job runs without using a cache. For example:
```yaml
test-job:
stage: build
cache:
- key: cache-$CI_COMMIT_REF_SLUG
fallback_keys:
- cache-$CI_DEFAULT_BRANCH
- cache-default
paths:
- vendor/ruby
script:
- bundle config set --local path 'vendor/ruby'
- bundle install
- echo Run tests...
```
In this example:
1. The job looks for the `cache-$CI_COMMIT_REF_SLUG` cache.
1. If `cache-$CI_COMMIT_REF_SLUG` is not found, the job looks for `cache-$CI_DEFAULT_BRANCH`
as a fallback option.
1. If `cache-$CI_DEFAULT_BRANCH` is also not found, the job looks for `cache-default`
as a second fallback option.
1. If none are found, the job downloads all the Ruby dependencies without using a cache,
but creates a new cache for `cache-$CI_COMMIT_REF_SLUG` when the job completes.
Fallback keys follow the same processing logic as `cache:key`:
- If you [clear caches manually](#clear-the-cache-manually), per-cache fallback keys are appended
with an index like other cache keys.
- If the [**Use separate caches for protected branches** setting](#cache-key-names) is enabled,
per-cache fallback keys are appended with `-protected` or `-non_protected`.
### Global fallback key
You can use the `$CI_COMMIT_REF_SLUG` [predefined variable](../variables/predefined_variables.md)
to specify your [`cache:key`](../yaml/_index.md#cachekey). For example, if your
`$CI_COMMIT_REF_SLUG` is `test`, you can set a job to download cache that's tagged with `test`.
If a cache with this tag is not found, you can use `CACHE_FALLBACK_KEY` to
specify a cache to use when none exists.
In the following example, if the `$CI_COMMIT_REF_SLUG` is not found, the job uses the key defined
by the `CACHE_FALLBACK_KEY` variable:
```yaml
variables:
CACHE_FALLBACK_KEY: fallback-key
job1:
script:
- echo
cache:
key: "$CI_COMMIT_REF_SLUG"
paths:
- binaries/
```
The order of caches extraction is:
1. Retrieval attempt for `cache:key`
1. Retrieval attempts for each entry in order in `fallback_keys`
1. Retrieval attempt for the global fallback key in `CACHE_FALLBACK_KEY`
The cache extraction process stops after the first successful cache is retrieved.
## Disable cache for specific jobs
If you define the cache globally, each job uses the
same definition. You can override this behavior for each job.
To disable it completely for a job, use an empty list:
```yaml
job:
cache: []
```
## Inherit global configuration, but override specific settings per job
You can override cache settings without overwriting the global cache by using
[anchors](../yaml/yaml_optimization.md#anchors). For example, if you want to override the
`policy` for one job:
```yaml
default:
cache: &global_cache
key: $CI_COMMIT_REF_SLUG
paths:
- node_modules/
- public/
- vendor/
policy: pull-push
job:
cache:
# inherit all global cache settings
<<: *global_cache
# override the policy
policy: pull
```
For more information, see [`cache: policy`](../yaml/_index.md#cachepolicy).
## Common use cases for caches
Usually you use caches to avoid downloading content, like dependencies
or libraries, each time you run a job. Node.js packages,
PHP packages, Ruby gems, Python libraries, and others can be cached.
For examples, see the [GitLab CI/CD templates](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates).
### Share caches between jobs in the same branch
To have jobs in each branch use the same cache, define a cache with the `key: $CI_COMMIT_REF_SLUG`:
```yaml
cache:
key: $CI_COMMIT_REF_SLUG
```
This configuration prevents you from accidentally overwriting the cache. However, the
first pipeline for a merge request is slow. The next time a commit is pushed to the branch, the
cache is re-used and jobs run faster.
To enable per-job and per-branch caching:
```yaml
cache:
key: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"
```
To enable per-stage and per-branch caching:
```yaml
cache:
key: "$CI_JOB_STAGE-$CI_COMMIT_REF_SLUG"
```
### Share caches across jobs in different branches
To share a cache across all branches and all jobs, use the same key for everything:
```yaml
cache:
key: one-key-to-rule-them-all
```
To share a cache between branches, but have a unique cache for each job:
```yaml
cache:
key: $CI_JOB_NAME
```
### Use a variable to control a job's cache policy
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/371480) in GitLab 16.1.
{{< /history >}}
To reduce duplication of jobs where the only difference is the pull policy, you can use a [CI/CD variable](../variables/_index.md).
For example:
```yaml
conditional-policy:
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
variables:
POLICY: pull-push
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
variables:
POLICY: pull
stage: build
cache:
key: gems
policy: $POLICY
paths:
- vendor/bundle
script:
- echo "This job pulls and pushes the cache depending on the branch"
- echo "Downloading dependencies..."
```
In this example, the job's cache policy is:
- `pull-push` for changes to the default branch.
- `pull` for changes to other branches.
### Cache Node.js dependencies
If your project uses [npm](https://www.npmjs.com/) to install Node.js
dependencies, the following example defines a default `cache` so that all jobs inherit it.
By default, npm stores cache data in the home folder (`~/.npm`). However, you
[can't cache things outside of the project directory](../yaml/_index.md#cachepaths).
Instead, tell npm to use `./.npm`, and cache it per-branch:
```yaml
default:
image: node:latest
cache: # Cache modules in between jobs
key: $CI_COMMIT_REF_SLUG
paths:
- .npm/
before_script:
- npm ci --cache .npm --prefer-offline
test_async:
script:
- node ./specs/start.js ./specs/async.spec.js
```
#### Compute the cache key from the lock file
You can use [`cache:key:files`](../yaml/_index.md#cachekeyfiles) to compute the cache
key from a lock file like `package-lock.json` or `yarn.lock`, and reuse it in many jobs.
```yaml
default:
cache: # Cache modules using lock file
key:
files:
- package-lock.json
paths:
- .npm/
```
If you're using [Yarn](https://yarnpkg.com/), you can use [`yarn-offline-mirror`](https://classic.yarnpkg.com/blog/2016/11/24/offline-mirror/)
to cache the zipped `node_modules` tarballs. The cache generates more quickly, because
fewer files have to be compressed:
```yaml
job:
script:
- echo 'yarn-offline-mirror ".yarn-cache/"' >> .yarnrc
- echo 'yarn-offline-mirror-pruning true' >> .yarnrc
- yarn install --frozen-lockfile --no-progress
cache:
key:
files:
- yarn.lock
paths:
- .yarn-cache/
```
### Cache C/C++ compilation using Ccache
If you are compiling C/C++ projects, you can use [Ccache](https://ccache.dev/) to
speed up your build times. Ccache speeds up recompilation by caching previous compilations
and detecting when the same compilation is being done again. When building big projects like the Linux kernel,
you can expect significantly faster compilations.
Use `cache` to reuse the created cache between jobs, for example:
```yaml
job:
cache:
paths:
- ccache
before_script:
- export PATH="/usr/lib/ccache:$PATH" # Override compiler path with ccache (this example is for Debian)
- export CCACHE_DIR="${CI_PROJECT_DIR}/ccache"
- export CCACHE_BASEDIR="${CI_PROJECT_DIR}"
- export CCACHE_COMPILERCHECK=content # Compiler mtime might change in the container, use checksums instead
script:
- ccache --zero-stats || true
- time make # Actually build your code while measuring time and cache efficiency.
- ccache --show-stats || true
```
If you have multiple projects in a single repository you do not need a separate `CCACHE_BASEDIR` for each of them.
### Cache PHP dependencies
If your project uses [Composer](https://getcomposer.org/) to install
PHP dependencies, the following example defines a default `cache` so that
all jobs inherit it. PHP libraries modules are installed in `vendor/` and
are cached per-branch:
```yaml
default:
image: php:latest
cache: # Cache libraries in between jobs
key: $CI_COMMIT_REF_SLUG
paths:
- vendor/
before_script:
# Install and run Composer
- curl --show-error --silent "https://getcomposer.org/installer" | php
- php composer.phar install
test:
script:
- vendor/bin/phpunit --configuration phpunit.xml --coverage-text --colors=never
```
### Cache Python dependencies
If your project uses [pip](https://pip.pypa.io/en/stable/) to install
Python dependencies, the following example defines a default `cache` so that
all jobs inherit it. pip's cache is defined under `.cache/pip/` and is cached per-branch:
```yaml
default:
image: python:latest
cache: # Pip's cache doesn't store the python packages
paths: # https://pip.pypa.io/en/stable/topics/caching/
- .cache/pip
before_script:
- python -V # Print out python version for debugging
- pip install virtualenv
- virtualenv venv
- source venv/bin/activate
variables: # Change pip's cache directory to be inside the project directory because we can only cache local items.
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
test:
script:
- python setup.py test
- pip install ruff
- ruff --format=gitlab .
```
### Cache Ruby dependencies
If your project uses [Bundler](https://bundler.io) to install
gem dependencies, the following example defines a default `cache` so that all
jobs inherit it. Gems are installed in `vendor/ruby/` and are cached per-branch:
```yaml
default:
image: ruby:latest
cache: # Cache gems in between builds
key: $CI_COMMIT_REF_SLUG
paths:
- vendor/ruby
before_script:
- ruby -v # Print out ruby version for debugging
- bundle config set --local path 'vendor/ruby' # The location to install the specified gems to
- bundle install -j $(nproc) # Install dependencies into ./vendor/ruby
rspec:
script:
- rspec spec
```
If you have jobs that need different gems, use the `prefix`
keyword in the global `cache` definition. This configuration generates a different
cache for each job.
For example, a testing job might not need the same gems as a job that deploys to
production:
```yaml
default:
cache:
key:
files:
- Gemfile.lock
prefix: $CI_JOB_NAME
paths:
- vendor/ruby
test_job:
stage: test
before_script:
- bundle config set --local path 'vendor/ruby'
- bundle install --without production
script:
- bundle exec rspec
deploy_job:
stage: production
before_script:
- bundle config set --local path 'vendor/ruby' # The location to install the specified gems to
- bundle install --without test
script:
- bundle exec deploy
```
### Cache Go dependencies
If your project uses [Go Modules](https://go.dev/wiki/Modules) to install
Go dependencies, the following example defines `cache` in a `go-cache` template, that
any job can extend. Go modules are installed in `${GOPATH}/pkg/mod/` and
are cached for all of the `go` projects:
```yaml
.go-cache:
variables:
GOPATH: $CI_PROJECT_DIR/.go
before_script:
- mkdir -p .go
cache:
paths:
- .go/pkg/mod/
test:
image: golang:latest
extends: .go-cache
script:
- go test ./... -v -short
```
### Cache curl downloads
If your project uses [cURL](https://curl.se/) to download dependencies or files,
you can cache the downloaded content. The files are automatically updated when
newer downloads are available.
```yaml
job:
script:
- curl --remote-time --time-cond .curl-cache/caching.md --output .curl-cache/caching.md "https://docs.gitlab.com/ci/caching/"
cache:
paths:
- .curl-cache/
```
In this example cURL downloads a file from a webserver and saves it to a local file in `.curl-cache/`.
The `--remote-time` flag saves the last modification time reported by the server,
and cURL compares it to the timestamp of the cached file with `--time-cond`. If the remote file has
a more recent timestamp the local cache is automatically updated.
## Availability of the cache
Caching is an optimization, but it isn't guaranteed to always work. You might need
to regenerate cached files in each job that needs them.
After you define a [cache in `.gitlab-ci.yml`](../yaml/_index.md#cache),
the availability of the cache depends on:
- The runner's executor type.
- Whether different runners are used to pass the cache between jobs.
### Where the caches are stored
All caches defined for a job are archived in a single `cache.zip` file.
The runner configuration defines where the file is stored. By default, the cache
is stored on the machine where GitLab Runner is installed. The location also depends on the type of executor.
| Runner executor | Default path of the cache |
| ---------------------- | ------------------------- |
| [Shell](https://docs.gitlab.com/runner/executors/shell.html) | Locally, under the `gitlab-runner` user's home directory: `/home/gitlab-runner/cache/<user>/<project>/<cache-key>/cache.zip`. |
| [Docker](https://docs.gitlab.com/runner/executors/docker.html) | Locally, under [Docker volumes](https://docs.gitlab.com/runner/executors/docker.html#configure-directories-for-the-container-build-and-cache): `/var/lib/docker/volumes/<volume-id>/_data/<user>/<project>/<cache-key>/cache.zip`. |
| [Docker Machine](https://docs.gitlab.com/runner/executors/docker_machine.html) (autoscale runners) | The same as the Docker executor. |
If you use cache and artifacts to store the same path in your jobs, the cache might
be overwritten because caches are restored before artifacts.
#### Cache key names
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/330047) in GitLab 15.0.
{{< /history >}}
A suffix is added to the cache key, with the exception of the [global fallback cache key](#global-fallback-key).
As an example, assuming that `cache.key` is set to `$CI_COMMIT_REF_SLUG`, and that we have two branches `main`
and `feature`, then the following table represents the resulting cache keys:
| Branch name | Cache key |
|-------------|-----------|
| `main` | `main-protected` |
| `feature` | `feature-non_protected` |
##### Use the same cache for all branches
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/361643) in GitLab 15.0.
{{< /history >}}
If you do not want to use [cache key names](#cache-key-names),
you can have all branches (protected and unprotected) use the same cache.
The cache separation with [cache key names](#cache-key-names) is a security feature
and should only be disabled in an environment where all users with Developer role are highly trusted.
To use the same cache for all branches:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Settings > CI/CD**.
1. Expand **General pipelines**.
1. Clear the **Use separate caches for protected branches** checkbox.
1. Select **Save changes**.
### How archiving and extracting works
This example shows two jobs in two consecutive stages:
```yaml
stages:
- build
- test
default:
cache:
key: build-cache
paths:
- vendor/
before_script:
- echo "Hello"
job A:
stage: build
script:
- mkdir vendor/
- echo "build" > vendor/hello.txt
after_script:
- echo "World"
job B:
stage: test
script:
- cat vendor/hello.txt
```
If one machine has one runner installed, then all jobs for your project
run on the same host:
1. Pipeline starts.
1. `job A` runs.
1. The cache is extracted (if found).
1. `before_script` is executed.
1. `script` is executed.
1. `after_script` is executed.
1. `cache` runs and the `vendor/` directory is zipped into `cache.zip`.
This file is then saved in the directory based on the
[runner's setting](#where-the-caches-are-stored) and the `cache: key`.
1. `job B` runs.
1. The cache is extracted (if found).
1. `before_script` is executed.
1. `script` is executed.
1. Pipeline finishes.
By using a single runner on a single machine, you don't have the issue where
`job B` might execute on a runner different from `job A`. This setup guarantees the
cache can be reused between stages. It only works if the execution goes from the `build` stage
to the `test` stage in the same runner/machine. Otherwise, the cache [might not be available](#cache-mismatch).
During the caching process, there's also a couple of things to consider:
- If some other job, with another cache configuration had saved its
cache in the same zip file, it is overwritten. If the S3 based shared cache is
used, the file is additionally uploaded to S3 to an object based on the cache
key. So, two jobs with different paths, but the same cache key, overwrites
their cache.
- When extracting the cache from `cache.zip`, everything in the zip file is
extracted in the job's working directory (usually the repository which is
pulled down), and the runner doesn't mind if the archive of `job A` overwrites
things in the archive of `job B`.
It works this way because the cache created for one runner
often isn't valid when used by a different one. A different runner may run on a
different architecture (for example, when the cache includes binary files). Also,
because the different steps might be executed by runners running on different
machines, it is a safe default.
## Clearing the cache
Runners use [cache](../yaml/_index.md#cache) to speed up the execution
of your jobs by reusing existing data. This can sometimes lead to
inconsistent behavior.
There are two ways to start with a fresh copy of the cache.
### Clear the cache by changing `cache:key`
Change the value for `cache: key` in your `.gitlab-ci.yml` file.
The next time the pipeline runs, the cache is stored in a different location.
### Clear the cache manually
You can clear the cache in the GitLab UI:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipelines**.
1. In the upper-right corner, select **Clear runner caches**.
On the next commit, your CI/CD jobs use a new cache.
{{< alert type="note" >}}
Each time you clear the cache manually, the [internal cache name](#where-the-caches-are-stored) is updated. The name uses the format `cache-<index>`, and the index increments by one. The old cache is not deleted. You can manually delete these files from the runner storage.
{{< /alert >}}
## Troubleshooting
### Cache mismatch
If you have a cache mismatch, follow these steps to troubleshoot.
| Reason for a cache mismatch | How to fix it |
| --------------------------- | ------------- |
| You use multiple standalone runners (not in autoscale mode) attached to one project without a shared cache. | Use only one runner for your project or use multiple runners with distributed cache enabled. |
| You use runners in autoscale mode without a distributed cache enabled. | Configure the autoscale runner to use a distributed cache. |
| The machine the runner is installed on is low on disk space or, if you've set up distributed cache, the S3 bucket where the cache is stored doesn't have enough space. | Make sure you clear some space to allow new caches to be stored. There's no automatic way to do this. |
| You use the same `key` for jobs where they cache different paths. | Use different cache keys so that the cache archive is stored to a different location and doesn't overwrite wrong caches. |
| You have not enabled the [distributed runner caching on your runners](https://docs.gitlab.com/runner/configuration/autoscale.html#distributed-runners-caching). | Set `Shared = false` and re-provision your runners. |
#### Cache mismatch example 1
If you have only one runner assigned to your project, the cache
is stored on the runner's machine by default.
If two jobs have the same cache key but a different path, the caches can be overwritten.
For example:
```yaml
stages:
- build
- test
job A:
stage: build
script: make build
cache:
key: same-key
paths:
- public/
job B:
stage: test
script: make test
cache:
key: same-key
paths:
- vendor/
```
1. `job A` runs.
1. `public/` is cached as `cache.zip`.
1. `job B` runs.
1. The previous cache, if any, is unzipped.
1. `vendor/` is cached as `cache.zip` and overwrites the previous one.
1. The next time `job A` runs it uses the cache of `job B` which is different
and thus isn't effective.
To fix this issue, use different `keys` for each job.
#### Cache mismatch example 2
In this example, you have more than one runner assigned to your
project, and distributed cache is not enabled.
The second time the pipeline runs, you want `job A` and `job B` to re-use their cache (which in this case
is different):
```yaml
stages:
- build
- test
job A:
stage: build
script: build
cache:
key: keyA
paths:
- vendor/
job B:
stage: test
script: test
cache:
key: keyB
paths:
- vendor/
```
Even if the `key` is different, the cached files might get "cleaned" before each
stage if the jobs run on different runners in subsequent pipelines.
### Concurrent runners missing local cache
If you have configured multiple concurrent runners with the Docker executor, locally cached files might
not be present for concurrently-running jobs as you expect. The names of cache volumes are constructed
uniquely for each runner instance, so files cached by one runner instance are not found in the cache by another runner
instance.
To share the cache between concurrent runners, you can either:
- Use the `[runners.docker]` section of the runners' `config.toml` to configure a single mount point on the host that
is mapped to `/cache` in each container, preventing the runner from creating unique volume names.
- Use a distributed cache.
|
https://docs.gitlab.com/ci/yaml_optimization
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/yaml_optimization.md
|
2025-08-13
|
doc/ci/yaml
|
[
"doc",
"ci",
"yaml"
] |
yaml_optimization.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Optimize GitLab CI/CD configuration files
|
Use YAML anchors, !reference tags, and the `extends` keyword to reduce CI/CD configuration file complexity.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can reduce complexity and duplicated configuration in your GitLab CI/CD configuration
files by using:
- YAML-specific features like [anchors (`&`)](#anchors), aliases (`*`), and map merging (`<<`).
Read more about the various [YAML features](https://learnxinyminutes.com/docs/yaml/).
- The [`extends` keyword](#use-extends-to-reuse-configuration-sections),
which is more flexible and readable. You should use `extends` where possible.
## Anchors
YAML has a feature called 'anchors' that you can use to duplicate
content across your document.
Use anchors to duplicate or inherit properties. Use anchors with [hidden jobs](../jobs/_index.md#hide-a-job)
to provide templates for your jobs. When there are duplicate keys, the latest included key wins, overriding the other keys.
In certain cases (see [YAML anchors for scripts](#yaml-anchors-for-scripts)), you can use YAML anchors to build arrays with multiple components defined elsewhere. For example:
```yaml
.default_scripts: &default_scripts
- ./default-script1.sh
- ./default-script2.sh
job1:
script:
- *default_scripts
- ./job-script.sh
```
You can't use YAML anchors across multiple files when using the [`include`](_index.md#include)
keyword. Anchors are only valid in the file they were defined in. To reuse configuration
from different YAML files, use [`!reference` tags](#reference-tags) or the
[`extends` keyword](#use-extends-to-reuse-configuration-sections).
The following example uses anchors and map merging. It creates two jobs,
`test1` and `test2`, that inherit the `.job_template` configuration, each
with their own custom `script` defined:
```yaml
.job_template: &job_configuration # Hidden yaml configuration that defines an anchor named 'job_configuration'
image: ruby:2.6
services:
- postgres
- redis
test1:
<<: *job_configuration # Add the contents of the 'job_configuration' alias
script:
- test1 project
test2:
<<: *job_configuration # Add the contents of the 'job_configuration' alias
script:
- test2 project
```
`&` sets up the name of the anchor (`job_configuration`), `<<` means "merge the
given hash into the current one," and `*` includes the named anchor
(`job_configuration` again). The [expanded](../pipeline_editor/_index.md#view-full-configuration) version of this example is:
```yaml
.job_template:
image: ruby:2.6
services:
- postgres
- redis
test1:
image: ruby:2.6
services:
- postgres
- redis
script:
- test1 project
test2:
image: ruby:2.6
services:
- postgres
- redis
script:
- test2 project
```
You can use anchors to define two sets of services. For example, `test:postgres`
and `test:mysql` share the `script` defined in `.job_template`, but use different
`services`, defined in `.postgres_services` and `.mysql_services`:
```yaml
.job_template: &job_configuration
script:
- test project
tags:
- dev
.postgres_services:
services: &postgres_configuration
- postgres
- ruby
.mysql_services:
services: &mysql_configuration
- mysql
- ruby
test:postgres:
<<: *job_configuration
services: *postgres_configuration
tags:
- postgres
test:mysql:
<<: *job_configuration
services: *mysql_configuration
```
The [expanded](../pipeline_editor/_index.md#view-full-configuration) version is:
```yaml
.job_template:
script:
- test project
tags:
- dev
.postgres_services:
services:
- postgres
- ruby
.mysql_services:
services:
- mysql
- ruby
test:postgres:
script:
- test project
services:
- postgres
- ruby
tags:
- postgres
test:mysql:
script:
- test project
services:
- mysql
- ruby
tags:
- dev
```
You can see that the hidden jobs are conveniently used as templates, and
`tags: [postgres]` overwrites `tags: [dev]`.
### YAML anchors for scripts
{{< history >}}
- Support for anchors with the [`stages`](_index.md#stages) keyword [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/439451) in GitLab 16.9.
{{< /history >}}
You can use [YAML anchors](#anchors) with [script](_index.md#script), [`before_script`](_index.md#before_script),
and [`after_script`](_index.md#after_script) to use predefined commands in multiple jobs:
```yaml
.some-script-before: &some-script-before
- echo "Execute this script first"
.some-script: &some-script
- echo "Execute this script second"
- echo "Execute this script too"
.some-script-after: &some-script-after
- echo "Execute this script last"
job1:
before_script:
- *some-script-before
script:
- *some-script
- echo "Execute something, for this job only"
after_script:
- *some-script-after
job2:
script:
- *some-script-before
- *some-script
- echo "Execute something else, for this job only"
- *some-script-after
```
## Use `extends` to reuse configuration sections
You can use the [`extends` keyword](_index.md#extends) to reuse configuration in
multiple jobs. It is similar to [YAML anchors](#anchors), but simpler and you can
[use `extends` with `includes`](#use-extends-and-include-together).
`extends` supports multi-level inheritance. You should avoid using more than three levels,
due to the additional complexity, but you can use as many as eleven. The following example has two levels of inheritance:
```yaml
.tests:
rules:
- if: $CI_PIPELINE_SOURCE == "push"
.rspec:
extends: .tests
script: rake rspec
rspec 1:
variables:
RSPEC_SUITE: '1'
extends: .rspec
rspec 2:
variables:
RSPEC_SUITE: '2'
extends: .rspec
spinach:
extends: .tests
script: rake spinach
```
### Exclude a key from `extends`
To exclude a key from the extended content, you must assign it to `null`, for example:
```yaml
.base:
script: test
variables:
VAR1: base var 1
test1:
extends: .base
variables:
VAR1: test1 var 1
VAR2: test2 var 2
test2:
extends: .base
variables:
VAR2: test2 var 2
test3:
extends: .base
variables: {}
test4:
extends: .base
variables: null
```
Merged configuration:
```yaml
test1:
script: test
variables:
VAR1: test1 var 1
VAR2: test2 var 2
test2:
script: test
variables:
VAR1: base var 1
VAR2: test2 var 2
test3:
script: test
variables:
VAR1: base var 1
test4:
script: test
variables: null
```
### Use `extends` and `include` together
To reuse configuration from different configuration files,
combine `extends` and [`include`](_index.md#include).
In the following example, a `script` is defined in the `included.yml` file.
Then, in the `.gitlab-ci.yml` file, `extends` refers
to the contents of the `script`:
- `included.yml`:
```yaml
.template:
script:
- echo Hello!
```
- `.gitlab-ci.yml`:
```yaml
include: included.yml
useTemplate:
image: alpine
extends: .template
```
### Merge details
You can use `extends` to merge hashes but not arrays.
When there are duplicate keys, GitLab performs a reverse deep merge based on the keys.
Keys from the last member always override anything defined on other
levels. For example:
```yaml
.only-important:
variables:
URL: "http://my-url.internal"
IMPORTANT_VAR: "the details"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_COMMIT_BRANCH == "stable"
tags:
- production
script:
- echo "Hello world!"
.in-docker:
variables:
URL: "http://docker-url.internal"
tags:
- docker
image: alpine
rspec:
variables:
GITLAB: "is-awesome"
extends:
- .only-important
- .in-docker
script:
- rake rspec
```
The result is this `rspec` job:
```yaml
rspec:
variables:
URL: "http://docker-url.internal"
IMPORTANT_VAR: "the details"
GITLAB: "is-awesome"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_COMMIT_BRANCH == "stable"
tags:
- docker
image: alpine
script:
- rake rspec
```
In this example:
- The `variables` sections merge, but `URL: "http://docker-url.internal"` overwrites `URL: "http://my-url.internal"`.
- `tags: ['docker']` overwrites `tags: ['production']`.
- `script` does not merge, but `script: ['rake rspec']` overwrites
`script: ['echo "Hello world!"']`. You can use [YAML anchors](yaml_optimization.md#anchors) to merge arrays.
## `!reference` tags
Use the `!reference` custom YAML tag to select keyword configuration from other job
sections and reuse it in the current section. Unlike [YAML anchors](#anchors), you can
use `!reference` tags to reuse configuration from [included](_index.md#include) configuration
files as well.
In the following example, a `script` and an `after_script` from two different locations are
reused in the `test` job:
- `configs.yml`:
```yaml
.setup:
script:
- echo creating environment
```
- `.gitlab-ci.yml`:
```yaml
include:
- local: configs.yml
.teardown:
after_script:
- echo deleting environment
test:
script:
- !reference [.setup, script]
- echo running my own command
after_script:
- !reference [.teardown, after_script]
```
In the following example, `test-vars-1` reuses all the variables in `.vars`, while `test-vars-2`
selects a specific variable and reuses it as a new `MY_VAR` variable.
```yaml
.vars:
variables:
URL: "http://my-url.internal"
IMPORTANT_VAR: "the details"
test-vars-1:
variables: !reference [.vars, variables]
script:
- printenv
test-vars-2:
variables:
MY_VAR: !reference [.vars, variables, IMPORTANT_VAR]
script:
- printenv
```
There's a [known issue](../debugging.md#config-should-be-an-array-of-hashes-error-message) when using `!reference` tags with the [`parallel:matrix` keyword](_index.md#parallelmatrix).
### Nest `!reference` tags in `script`, `before_script`, and `after_script`
{{< history >}}
- Support for `!reference` with the [`stages`](_index.md#stages) keyword [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/439451) in GitLab 16.9.
{{< /history >}}
You can nest `!reference` tags up to 10 levels deep in `script`, `before_script`, and `after_script` sections. Use nested tags to define reusable sections when building more complex scripts. For example:
```yaml
.snippets:
one:
- echo "ONE!"
two:
- !reference [.snippets, one]
- echo "TWO!"
three:
- !reference [.snippets, two]
- echo "THREE!"
nested-references:
script:
- !reference [.snippets, three]
```
In this example, the `nested-references` job runs all three `echo` commands.
### Configure your IDE to support `!reference` tags
The [pipeline editor](../pipeline_editor/_index.md) supports `!reference` tags. However, the schema rules for custom YAML
tags like `!reference` might be treated as invalid by your editor by default.
You can configure some editors to accept `!reference` tags. For example:
- In VS Code, you can set `vscode-yaml` to parse `customTags` in your `settings.json` file:
```json
"yaml.customTags": [
"!reference sequence"
]
```
- In Sublime Text, if you are using the `LSP-yaml` package, you can set `customTags` in your `LSP-yaml` user settings:
```json
{
"settings": {
"yaml.customTags": ["!reference sequence"]
}
}
```
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Optimize GitLab CI/CD configuration files
description: Use YAML anchors, !reference tags, and the `extends` keyword to reduce
CI/CD configuration file complexity.
breadcrumbs:
- doc
- ci
- yaml
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can reduce complexity and duplicated configuration in your GitLab CI/CD configuration
files by using:
- YAML-specific features like [anchors (`&`)](#anchors), aliases (`*`), and map merging (`<<`).
Read more about the various [YAML features](https://learnxinyminutes.com/docs/yaml/).
- The [`extends` keyword](#use-extends-to-reuse-configuration-sections),
which is more flexible and readable. You should use `extends` where possible.
## Anchors
YAML has a feature called 'anchors' that you can use to duplicate
content across your document.
Use anchors to duplicate or inherit properties. Use anchors with [hidden jobs](../jobs/_index.md#hide-a-job)
to provide templates for your jobs. When there are duplicate keys, the latest included key wins, overriding the other keys.
In certain cases (see [YAML anchors for scripts](#yaml-anchors-for-scripts)), you can use YAML anchors to build arrays with multiple components defined elsewhere. For example:
```yaml
.default_scripts: &default_scripts
- ./default-script1.sh
- ./default-script2.sh
job1:
script:
- *default_scripts
- ./job-script.sh
```
You can't use YAML anchors across multiple files when using the [`include`](_index.md#include)
keyword. Anchors are only valid in the file they were defined in. To reuse configuration
from different YAML files, use [`!reference` tags](#reference-tags) or the
[`extends` keyword](#use-extends-to-reuse-configuration-sections).
The following example uses anchors and map merging. It creates two jobs,
`test1` and `test2`, that inherit the `.job_template` configuration, each
with their own custom `script` defined:
```yaml
.job_template: &job_configuration # Hidden yaml configuration that defines an anchor named 'job_configuration'
image: ruby:2.6
services:
- postgres
- redis
test1:
<<: *job_configuration # Add the contents of the 'job_configuration' alias
script:
- test1 project
test2:
<<: *job_configuration # Add the contents of the 'job_configuration' alias
script:
- test2 project
```
`&` sets up the name of the anchor (`job_configuration`), `<<` means "merge the
given hash into the current one," and `*` includes the named anchor
(`job_configuration` again). The [expanded](../pipeline_editor/_index.md#view-full-configuration) version of this example is:
```yaml
.job_template:
image: ruby:2.6
services:
- postgres
- redis
test1:
image: ruby:2.6
services:
- postgres
- redis
script:
- test1 project
test2:
image: ruby:2.6
services:
- postgres
- redis
script:
- test2 project
```
You can use anchors to define two sets of services. For example, `test:postgres`
and `test:mysql` share the `script` defined in `.job_template`, but use different
`services`, defined in `.postgres_services` and `.mysql_services`:
```yaml
.job_template: &job_configuration
script:
- test project
tags:
- dev
.postgres_services:
services: &postgres_configuration
- postgres
- ruby
.mysql_services:
services: &mysql_configuration
- mysql
- ruby
test:postgres:
<<: *job_configuration
services: *postgres_configuration
tags:
- postgres
test:mysql:
<<: *job_configuration
services: *mysql_configuration
```
The [expanded](../pipeline_editor/_index.md#view-full-configuration) version is:
```yaml
.job_template:
script:
- test project
tags:
- dev
.postgres_services:
services:
- postgres
- ruby
.mysql_services:
services:
- mysql
- ruby
test:postgres:
script:
- test project
services:
- postgres
- ruby
tags:
- postgres
test:mysql:
script:
- test project
services:
- mysql
- ruby
tags:
- dev
```
You can see that the hidden jobs are conveniently used as templates, and
`tags: [postgres]` overwrites `tags: [dev]`.
### YAML anchors for scripts
{{< history >}}
- Support for anchors with the [`stages`](_index.md#stages) keyword [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/439451) in GitLab 16.9.
{{< /history >}}
You can use [YAML anchors](#anchors) with [script](_index.md#script), [`before_script`](_index.md#before_script),
and [`after_script`](_index.md#after_script) to use predefined commands in multiple jobs:
```yaml
.some-script-before: &some-script-before
- echo "Execute this script first"
.some-script: &some-script
- echo "Execute this script second"
- echo "Execute this script too"
.some-script-after: &some-script-after
- echo "Execute this script last"
job1:
before_script:
- *some-script-before
script:
- *some-script
- echo "Execute something, for this job only"
after_script:
- *some-script-after
job2:
script:
- *some-script-before
- *some-script
- echo "Execute something else, for this job only"
- *some-script-after
```
## Use `extends` to reuse configuration sections
You can use the [`extends` keyword](_index.md#extends) to reuse configuration in
multiple jobs. It is similar to [YAML anchors](#anchors), but simpler and you can
[use `extends` with `includes`](#use-extends-and-include-together).
`extends` supports multi-level inheritance. You should avoid using more than three levels,
due to the additional complexity, but you can use as many as eleven. The following example has two levels of inheritance:
```yaml
.tests:
rules:
- if: $CI_PIPELINE_SOURCE == "push"
.rspec:
extends: .tests
script: rake rspec
rspec 1:
variables:
RSPEC_SUITE: '1'
extends: .rspec
rspec 2:
variables:
RSPEC_SUITE: '2'
extends: .rspec
spinach:
extends: .tests
script: rake spinach
```
### Exclude a key from `extends`
To exclude a key from the extended content, you must assign it to `null`, for example:
```yaml
.base:
script: test
variables:
VAR1: base var 1
test1:
extends: .base
variables:
VAR1: test1 var 1
VAR2: test2 var 2
test2:
extends: .base
variables:
VAR2: test2 var 2
test3:
extends: .base
variables: {}
test4:
extends: .base
variables: null
```
Merged configuration:
```yaml
test1:
script: test
variables:
VAR1: test1 var 1
VAR2: test2 var 2
test2:
script: test
variables:
VAR1: base var 1
VAR2: test2 var 2
test3:
script: test
variables:
VAR1: base var 1
test4:
script: test
variables: null
```
### Use `extends` and `include` together
To reuse configuration from different configuration files,
combine `extends` and [`include`](_index.md#include).
In the following example, a `script` is defined in the `included.yml` file.
Then, in the `.gitlab-ci.yml` file, `extends` refers
to the contents of the `script`:
- `included.yml`:
```yaml
.template:
script:
- echo Hello!
```
- `.gitlab-ci.yml`:
```yaml
include: included.yml
useTemplate:
image: alpine
extends: .template
```
### Merge details
You can use `extends` to merge hashes but not arrays.
When there are duplicate keys, GitLab performs a reverse deep merge based on the keys.
Keys from the last member always override anything defined on other
levels. For example:
```yaml
.only-important:
variables:
URL: "http://my-url.internal"
IMPORTANT_VAR: "the details"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_COMMIT_BRANCH == "stable"
tags:
- production
script:
- echo "Hello world!"
.in-docker:
variables:
URL: "http://docker-url.internal"
tags:
- docker
image: alpine
rspec:
variables:
GITLAB: "is-awesome"
extends:
- .only-important
- .in-docker
script:
- rake rspec
```
The result is this `rspec` job:
```yaml
rspec:
variables:
URL: "http://docker-url.internal"
IMPORTANT_VAR: "the details"
GITLAB: "is-awesome"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_COMMIT_BRANCH == "stable"
tags:
- docker
image: alpine
script:
- rake rspec
```
In this example:
- The `variables` sections merge, but `URL: "http://docker-url.internal"` overwrites `URL: "http://my-url.internal"`.
- `tags: ['docker']` overwrites `tags: ['production']`.
- `script` does not merge, but `script: ['rake rspec']` overwrites
`script: ['echo "Hello world!"']`. You can use [YAML anchors](yaml_optimization.md#anchors) to merge arrays.
## `!reference` tags
Use the `!reference` custom YAML tag to select keyword configuration from other job
sections and reuse it in the current section. Unlike [YAML anchors](#anchors), you can
use `!reference` tags to reuse configuration from [included](_index.md#include) configuration
files as well.
In the following example, a `script` and an `after_script` from two different locations are
reused in the `test` job:
- `configs.yml`:
```yaml
.setup:
script:
- echo creating environment
```
- `.gitlab-ci.yml`:
```yaml
include:
- local: configs.yml
.teardown:
after_script:
- echo deleting environment
test:
script:
- !reference [.setup, script]
- echo running my own command
after_script:
- !reference [.teardown, after_script]
```
In the following example, `test-vars-1` reuses all the variables in `.vars`, while `test-vars-2`
selects a specific variable and reuses it as a new `MY_VAR` variable.
```yaml
.vars:
variables:
URL: "http://my-url.internal"
IMPORTANT_VAR: "the details"
test-vars-1:
variables: !reference [.vars, variables]
script:
- printenv
test-vars-2:
variables:
MY_VAR: !reference [.vars, variables, IMPORTANT_VAR]
script:
- printenv
```
There's a [known issue](../debugging.md#config-should-be-an-array-of-hashes-error-message) when using `!reference` tags with the [`parallel:matrix` keyword](_index.md#parallelmatrix).
### Nest `!reference` tags in `script`, `before_script`, and `after_script`
{{< history >}}
- Support for `!reference` with the [`stages`](_index.md#stages) keyword [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/439451) in GitLab 16.9.
{{< /history >}}
You can nest `!reference` tags up to 10 levels deep in `script`, `before_script`, and `after_script` sections. Use nested tags to define reusable sections when building more complex scripts. For example:
```yaml
.snippets:
one:
- echo "ONE!"
two:
- !reference [.snippets, one]
- echo "TWO!"
three:
- !reference [.snippets, two]
- echo "THREE!"
nested-references:
script:
- !reference [.snippets, three]
```
In this example, the `nested-references` job runs all three `echo` commands.
### Configure your IDE to support `!reference` tags
The [pipeline editor](../pipeline_editor/_index.md) supports `!reference` tags. However, the schema rules for custom YAML
tags like `!reference` might be treated as invalid by your editor by default.
You can configure some editors to accept `!reference` tags. For example:
- In VS Code, you can set `vscode-yaml` to parse `customTags` in your `settings.json` file:
```json
"yaml.customTags": [
"!reference sequence"
]
```
- In Sublime Text, if you are using the `LSP-yaml` package, you can set `customTags` in your `LSP-yaml` user settings:
```json
{
"settings": {
"yaml.customTags": ["!reference sequence"]
}
}
```
|
https://docs.gitlab.com/ci/artifacts_reports
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/artifacts_reports.md
|
2025-08-13
|
doc/ci/yaml
|
[
"doc",
"ci",
"yaml"
] |
artifacts_reports.md
|
Verify
|
Pipeline Execution
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab CI/CD artifacts reports types
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use [`artifacts:reports`](_index.md#artifactsreports) to:
- Collect test reports, code quality reports, security reports, and other artifacts generated by included templates in
jobs.
- Some of these reports are used to display information in:
- Merge requests.
- Pipeline views.
- [Security dashboards](../../user/application_security/security_dashboard/_index.md).
Artifacts created for `artifacts: reports` are always uploaded, regardless of the job results (success or failure).
You can use [`artifacts:expire_in`](_index.md#artifactsexpire_in) to set an expiration
time for the artifacts, which overrides the instance's [default setting](../../administration/settings/continuous_integration.md#set-maximum-artifacts-size).
GitLab.com might have a [different default artifacts expiry value](../../user/gitlab_com/_index.md#cicd).
Some `artifacts:reports` types can be generated by multiple jobs in the same pipeline, and used by merge request or
pipeline features from each job.
To browse the report output files, ensure you include the [`artifacts:paths`](_index.md#artifactspaths) keyword in your job definition.
{{< alert type="note" >}}
Combined reports in parent pipelines using [artifacts from child pipelines](_index.md#needspipelinejob) is
not supported. Support for this feature is proposed in [epic 8205](https://gitlab.com/groups/gitlab-org/-/epics/8205).
{{< /alert >}}
## `artifacts:reports:accessibility`
The `accessibility` report uses [pa11y](https://pa11y.org/) to report on the accessibility impact
of changes introduced in merge requests.
GitLab can display the results of one or more reports in the merge request
[accessibility widget](../testing/accessibility_testing.md#accessibility-merge-request-widget).
For more information, see [Accessibility testing](../testing/accessibility_testing.md).
## `artifacts:reports:annotations`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/38337) in GitLab 16.3.
{{< /history >}}
The `annotations` report is used to attach auxiliary data to a job.
An annotations report is a JSON file with annotation sections. Each annotation
section can have any desired name and can have any number of annotations of the
same or differing types.
Each annotation is a single key (the annotation type), containing the subkeys with
the data for that annotation.
### Annotation types
#### `external_link`
An `external_link` annotation can be attached to a job to add a link to the job
output page. The value of an `external_link` annotation is an object with the
following keys:
| Key | Description |
|---------|-------------|
| `label` | The human-readable label associated with the link. |
| `url` | The URL pointed to by the link. |
### Example report
The following is an example of what a job annotations report might look like:
```json
{
"my_annotation_section_1": [
{
"external_link": {
"label": "URL 1",
"url": "https://url1.example.com/"
}
},
{
"external_link": {
"label": "URL 2",
"url": "https://url2.example.com/"
}
}
]
}
```
## `artifacts:reports:api_fuzzing`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
The `api_fuzzing` report collects [API Fuzzing bugs](../../user/application_security/api_fuzzing/_index.md)
as artifacts.
GitLab can display the results of one or more reports in:
- The merge request [security widget](../../user/application_security/api_fuzzing/configuration/enabling_the_analyzer.md#view-details-of-an-api-fuzzing-vulnerability).
- The [Project Vulnerability report](../../user/application_security/vulnerability_report/_index.md).
- The pipeline [**Security** tab](../../user/application_security/detect/security_scanning_results.md).
- The [security dashboard](../../user/application_security/api_fuzzing/configuration/enabling_the_analyzer.md#security-dashboard).
## `artifacts:reports:browser_performance`
{{< details >}}
- Tier: Premium, Ultimate
{{< /details >}}
The `browser_performance` report collects [Browser Performance Testing metrics](../testing/browser_performance_testing.md)
as an artifact. This artifact is a JSON file output by the [Sitespeed plugin](https://gitlab.com/gitlab-org/gl-performance).
GitLab can display the results of one report in the merge request
[browser performance testing widget](../testing/browser_performance_testing.md#how-browser-performance-testing-works).
GitLab cannot display the combined results of multiple `browser_performance` reports.
## `artifacts:reports:coverage_report`
Use `coverage_report:` to collect [coverage report](../testing/_index.md) in Cobertura or JaCoCo formats.
The `coverage_format:` Can be either [`cobertura`](../testing/code_coverage/cobertura.md) or
[`jacoco`](../testing/code_coverage/jacoco.md).
Cobertura was originally developed for Java, but there are many third-party ports for other languages such as
JavaScript, Python, and Ruby.
```yaml
artifacts:
reports:
coverage_report:
coverage_format: cobertura
path: coverage/cobertura-coverage.xml
```
The collected coverage report is uploaded to GitLab as an artifact.
You can generate multiple JaCoCo or Cobertura reports and include them in the final
job artifact using [wildcards](../jobs/job_artifacts.md#with-wildcards).
The results of the reports are aggregated in the final coverage report.
The results of coverage reports appear in merge request [diff annotations](../testing/code_coverage/_index.md#coverage-visualization).
{{< alert type="note" >}}
Coverage reports from child pipelines appear in merge request diff annotations,
but the artifacts themselves are not shared with parent pipelines.
{{< /alert >}}
## `artifacts:reports:codequality`
The `codequality` report collects [code quality issues](../testing/code_quality.md). The
collected code quality report uploads to GitLab as an artifact.
GitLab can display the results of one or more reports in:
- The merge request [code quality widget](../testing/code_quality.md#merge-request-widget).
- The merge request [diff annotations](../testing/code_quality.md#merge-request-changes-view).
- The [full report](../testing/metrics_reports.md).
The [`artifacts:expire_in`](_index.md#artifactsexpire_in) value is set to `1 week`.
## `artifacts:reports:container_scanning`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
The `container_scanning` report collects [Container Scanning vulnerabilities](../../user/application_security/container_scanning/_index.md).
The collected Container Scanning report uploads to GitLab as an artifact.
GitLab can display the results of one or more reports in:
- The merge request [container scanning widget](../../user/application_security/container_scanning/_index.md).
- The pipeline [**Security** tab](../../user/application_security/detect/security_scanning_results.md).
- The [security dashboard](../../user/application_security/security_dashboard/_index.md).
- The [Project Vulnerability report](../../user/application_security/vulnerability_report/_index.md).
## `artifacts:reports:coverage_fuzzing`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
The `coverage_fuzzing` report collects [coverage fuzzing bugs](../../user/application_security/coverage_fuzzing/_index.md).
The collected coverage fuzzing report uploads to GitLab as an artifact.
GitLab can display the results of one or more reports in:
- The merge request [coverage fuzzing widget](../../user/application_security/coverage_fuzzing/_index.md#interacting-with-the-vulnerabilities).
- The pipeline [**Security** tab](../../user/application_security/detect/security_scanning_results.md).
- The [Project Vulnerability report](../../user/application_security/vulnerability_report/_index.md).
- The [security dashboard](../../user/application_security/security_dashboard/_index.md).
## `artifacts:reports:cyclonedx`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
This report is a Software Bill of Materials describing the components of a project
following the [CycloneDX](https://cyclonedx.org/docs/1.4) protocol format.
You can specify multiple CycloneDX reports per job. These can be either supplied
as a list of filenames, a filename pattern, or both:
- A filename pattern (`cyclonedx: gl-sbom-*.json`, `junit: test-results/**/*.json`).
- An array of filenames (`cyclonedx: [gl-sbom-npm-npm.cdx.json, gl-sbom-bundler-gem.cdx.json]`).
- A combination of both (`cyclonedx: [gl-sbom-*.json, my-cyclonedx.json]`).
- Directories are not supported(`cyclonedx: test-results`, `cyclonedx: test-results/**`).
The following example shows a job that exposes CycloneDX artifacts:
```yaml
artifacts:
reports:
cyclonedx:
- gl-sbom-npm-npm.cdx.json
- gl-sbom-bundler-gem.cdx.json
```
## `artifacts:reports:dast`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
The `dast` report collects [DAST vulnerabilities](../../user/application_security/dast/_index.md). The collected DAST
report uploads to GitLab as an artifact.
GitLab can display the results of one or more reports in:
- The merge request security widget.
- The pipeline [**Security** tab](../../user/application_security/detect/security_scanning_results.md).
- The [Project Vulnerability report](../../user/application_security/vulnerability_report/_index.md).
- The [security dashboard](../../user/application_security/security_dashboard/_index.md).
## `artifacts:reports:dependency_scanning`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
The `dependency_scanning` report collects [Dependency Scanning vulnerabilities](../../user/application_security/dependency_scanning/_index.md).
The collected Dependency Scanning report uploads to GitLab as an artifact.
GitLab can display the results of one or more reports in:
- The merge request [dependency scanning widget](../../user/application_security/dependency_scanning/_index.md).
- The pipeline [**Security** tab](../../user/application_security/detect/security_scanning_results.md).
- The [security dashboard](../../user/application_security/security_dashboard/_index.md).
- The [Project Vulnerability report](../../user/application_security/vulnerability_report/_index.md).
- The [dependency list](../../user/application_security/dependency_list/_index.md).
## `artifacts:reports:dotenv`
The `dotenv` report collects a set of environment variables as artifacts.
The collected variables are registered as runtime-created variables of the job,
which you can [use in subsequent job scripts](../variables/job_scripts.md#pass-an-environment-variable-to-another-job)
or to [set dynamic environment URLs after a job finishes](../environments/_index.md#set-a-dynamic-environment-url).
If duplicate environment variables are present in a `dotenv` report, the last one specified is used.
You should avoid storing sensitive data like credentials in dotenv reports, as the
reports can be downloaded from the pipeline details page. If necessary, you can use
[artifacts:access](_index.md#artifactsaccess) to restrict the users that can download
the report artifacts in a job.
GitLab uses the [`dotenv` gem](https://github.com/bkeepers/dotenv) for handling dotenv files,
and handles dotenv files differently than [the original dotenv rules](https://github.com/motdotla/dotenv?tab=readme-ov-file#what-rules-does-the-parsing-engine-follow):
- The variable key can contain only letters, digits, and underscores (`_`).
- The maximum size of the `.env` file is 5 KB.
This limit [can be changed on GitLab Self-Managed](../../administration/instance_limits.md#limit-dotenv-file-size).
- On GitLab.com, [the maximum number of inherited variables](../../user/gitlab_com/_index.md#cicd)
is 50 for Free, 100 for Premium and 150 for Ultimate. The default for
GitLab Self-Managed is 20, and can be changed by changing the
`dotenv_variables` [application limit](../../administration/instance_limits.md#limit-dotenv-variables).
- Variable substitution in the `.env` file is not supported.
- [Multiline values in the `.env` file](https://github.com/motdotla/dotenv#multiline-values) are not supported.
- The `.env` file can't have empty lines or comments (starting with `#`).
- Key values in the `env` file cannot have spaces or newline characters (`\n`), including when using single or double quotes.
- Quote escaping during parsing (`key = 'value'` -> `{key: "value"}`) is not supported.
- Only UTF-8 encoding is [supported](../jobs/job_artifacts_troubleshooting.md#error-message-fatal-invalid-argument-when-uploading-a-dotenv-artifact-on-a-windows-runner).
## `artifacts:reports:junit`
The `junit` report collects [JUnit report format XML files](https://www.ibm.com/docs/en/developer-for-zos/16.0?topic=formats-junit-xml-format).
The collected Unit test reports upload to GitLab as an artifact. Although JUnit was originally developed in Java, there
are many third-party ports for other languages such as JavaScript, Python, and Ruby.
See [Unit test reports](../testing/unit_test_reports.md) for more details and examples.
The following example shows how to collect a JUnit XML report from Ruby RSpec tests:
```yaml
rspec:
stage: test
script:
- bundle install
- rspec --format RspecJunitFormatter --out rspec.xml
artifacts:
reports:
junit: rspec.xml
```
GitLab can display the results of one or more reports in:
- The merge request [**Test summary** panel](../testing/unit_test_reports.md#view-test-results-in-merge-requests).
- The [pipeline **Tests** tab](../testing/unit_test_reports.md#view-test-results-in-pipelines).
Some JUnit tools export to multiple XML files. You can specify multiple test report paths in a single job to
concatenate them into a single file. Use either:
- A filename pattern (`junit: rspec-*.xml`, `junit: test-results/**/*.xml`).
- An array of filenames (`junit: [rspec-1.xml, rspec-2.xml, rspec-3.xml]`).
- A combination of both (`junit: [rspec.xml, test-results/TEST-*.xml]`).
- Directories are not supported(`junit: test-results`, `junit: test-results/**`).
## `artifacts:reports:load_performance`
{{< details >}}
- Tier: Premium, Ultimate
{{< /details >}}
The `load_performance` report collects [Load Performance Testing metrics](../testing/load_performance_testing.md).
The report is uploaded to GitLab as an artifact.
GitLab can display the results of only one report in the merge request
[load testing widget](../testing/load_performance_testing.md#how-load-performance-testing-works).
GitLab cannot display the combined results of multiple `load_performance` reports.
## `artifacts:reports:metrics`
{{< details >}}
- Tier: Premium, Ultimate
{{< /details >}}
The `metrics` report collects [Metrics](../testing/metrics_reports.md). The collected Metrics report uploads to GitLab as an
artifact.
GitLab can display the results of one or more reports in the merge request
[metrics reports widget](../testing/metrics_reports.md).
## `artifacts:reports:requirements`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
The `requirements` report collects `requirements.json` files. The collected Requirements report uploads to GitLab as an
artifact and existing [requirements](../../user/project/requirements/_index.md) are marked as Satisfied.
GitLab can display the results of one or more reports in the
[project requirements](../../user/project/requirements/_index.md#view-a-requirement).
<!--- start_remove The following content will be removed on remove_date: '2025-08-15' -->
## `artifacts:reports:repository_xray` (deprecated)
{{< details >}}
- Tier: Premium, Ultimate
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/432235) in GitLab 16.7.
{{< /history >}}
The `repository_xray` report collects information about your repository for use by GitLab Duo Code Suggestions.
{{< alert type="warning" >}}
This feature was [deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/500146) in GitLab 17.6
and is planned for removal in 18.0. Use [Enable Repository X-Ray](../../user/project/repository/code_suggestions/repository_xray.md#enable-repository-x-ray) instead.
{{< /alert >}}
<!--- end_remove -->
## `artifacts:reports:sast`
The `sast` report collects [SAST vulnerabilities](../../user/application_security/sast/_index.md).
The collected SAST report uploads to GitLab as an artifact.
For more information, see:
- [View SAST results](../../user/application_security/sast/_index.md#understanding-the-results)
- [SAST output](../../user/application_security/sast/_index.md#download-a-sast-report)
## `artifacts:reports:secret_detection`
The `secret-detection` report collects [detected secrets](../../user/application_security/secret_detection/pipeline/_index.md).
The collected Secret Detection report is uploaded to GitLab.
GitLab can display the results of one or more reports in:
- The merge request [secret scanning widget](../../user/application_security/secret_detection/pipeline/_index.md).
- The [pipeline security tab](../../user/application_security/detect/security_scanning_results.md).
- The [security dashboard](../../user/application_security/security_dashboard/_index.md).
## `artifacts:reports:terraform`
The `terraform` report obtains an OpenTofu `tfplan.json` file. [JQ processing required to remove credentials](../../user/infrastructure/iac/mr_integration.md#configure-opentofu-report-artifacts).
The collected OpenTofu plan report uploads to GitLab as an artifact.
GitLab can display the results of one or more reports in the merge request
[OpenTofu widget](../../user/infrastructure/iac/mr_integration.md#output-opentofu-plan-information-into-a-merge-request).
For more information, see [Output `tofu plan` information into a merge request](../../user/infrastructure/iac/mr_integration.md).
|
---
stage: Verify
group: Pipeline Execution
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: GitLab CI/CD artifacts reports types
breadcrumbs:
- doc
- ci
- yaml
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use [`artifacts:reports`](_index.md#artifactsreports) to:
- Collect test reports, code quality reports, security reports, and other artifacts generated by included templates in
jobs.
- Some of these reports are used to display information in:
- Merge requests.
- Pipeline views.
- [Security dashboards](../../user/application_security/security_dashboard/_index.md).
Artifacts created for `artifacts: reports` are always uploaded, regardless of the job results (success or failure).
You can use [`artifacts:expire_in`](_index.md#artifactsexpire_in) to set an expiration
time for the artifacts, which overrides the instance's [default setting](../../administration/settings/continuous_integration.md#set-maximum-artifacts-size).
GitLab.com might have a [different default artifacts expiry value](../../user/gitlab_com/_index.md#cicd).
Some `artifacts:reports` types can be generated by multiple jobs in the same pipeline, and used by merge request or
pipeline features from each job.
To browse the report output files, ensure you include the [`artifacts:paths`](_index.md#artifactspaths) keyword in your job definition.
{{< alert type="note" >}}
Combined reports in parent pipelines using [artifacts from child pipelines](_index.md#needspipelinejob) is
not supported. Support for this feature is proposed in [epic 8205](https://gitlab.com/groups/gitlab-org/-/epics/8205).
{{< /alert >}}
## `artifacts:reports:accessibility`
The `accessibility` report uses [pa11y](https://pa11y.org/) to report on the accessibility impact
of changes introduced in merge requests.
GitLab can display the results of one or more reports in the merge request
[accessibility widget](../testing/accessibility_testing.md#accessibility-merge-request-widget).
For more information, see [Accessibility testing](../testing/accessibility_testing.md).
## `artifacts:reports:annotations`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/38337) in GitLab 16.3.
{{< /history >}}
The `annotations` report is used to attach auxiliary data to a job.
An annotations report is a JSON file with annotation sections. Each annotation
section can have any desired name and can have any number of annotations of the
same or differing types.
Each annotation is a single key (the annotation type), containing the subkeys with
the data for that annotation.
### Annotation types
#### `external_link`
An `external_link` annotation can be attached to a job to add a link to the job
output page. The value of an `external_link` annotation is an object with the
following keys:
| Key | Description |
|---------|-------------|
| `label` | The human-readable label associated with the link. |
| `url` | The URL pointed to by the link. |
### Example report
The following is an example of what a job annotations report might look like:
```json
{
"my_annotation_section_1": [
{
"external_link": {
"label": "URL 1",
"url": "https://url1.example.com/"
}
},
{
"external_link": {
"label": "URL 2",
"url": "https://url2.example.com/"
}
}
]
}
```
## `artifacts:reports:api_fuzzing`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
The `api_fuzzing` report collects [API Fuzzing bugs](../../user/application_security/api_fuzzing/_index.md)
as artifacts.
GitLab can display the results of one or more reports in:
- The merge request [security widget](../../user/application_security/api_fuzzing/configuration/enabling_the_analyzer.md#view-details-of-an-api-fuzzing-vulnerability).
- The [Project Vulnerability report](../../user/application_security/vulnerability_report/_index.md).
- The pipeline [**Security** tab](../../user/application_security/detect/security_scanning_results.md).
- The [security dashboard](../../user/application_security/api_fuzzing/configuration/enabling_the_analyzer.md#security-dashboard).
## `artifacts:reports:browser_performance`
{{< details >}}
- Tier: Premium, Ultimate
{{< /details >}}
The `browser_performance` report collects [Browser Performance Testing metrics](../testing/browser_performance_testing.md)
as an artifact. This artifact is a JSON file output by the [Sitespeed plugin](https://gitlab.com/gitlab-org/gl-performance).
GitLab can display the results of one report in the merge request
[browser performance testing widget](../testing/browser_performance_testing.md#how-browser-performance-testing-works).
GitLab cannot display the combined results of multiple `browser_performance` reports.
## `artifacts:reports:coverage_report`
Use `coverage_report:` to collect [coverage report](../testing/_index.md) in Cobertura or JaCoCo formats.
The `coverage_format:` Can be either [`cobertura`](../testing/code_coverage/cobertura.md) or
[`jacoco`](../testing/code_coverage/jacoco.md).
Cobertura was originally developed for Java, but there are many third-party ports for other languages such as
JavaScript, Python, and Ruby.
```yaml
artifacts:
reports:
coverage_report:
coverage_format: cobertura
path: coverage/cobertura-coverage.xml
```
The collected coverage report is uploaded to GitLab as an artifact.
You can generate multiple JaCoCo or Cobertura reports and include them in the final
job artifact using [wildcards](../jobs/job_artifacts.md#with-wildcards).
The results of the reports are aggregated in the final coverage report.
The results of coverage reports appear in merge request [diff annotations](../testing/code_coverage/_index.md#coverage-visualization).
{{< alert type="note" >}}
Coverage reports from child pipelines appear in merge request diff annotations,
but the artifacts themselves are not shared with parent pipelines.
{{< /alert >}}
## `artifacts:reports:codequality`
The `codequality` report collects [code quality issues](../testing/code_quality.md). The
collected code quality report uploads to GitLab as an artifact.
GitLab can display the results of one or more reports in:
- The merge request [code quality widget](../testing/code_quality.md#merge-request-widget).
- The merge request [diff annotations](../testing/code_quality.md#merge-request-changes-view).
- The [full report](../testing/metrics_reports.md).
The [`artifacts:expire_in`](_index.md#artifactsexpire_in) value is set to `1 week`.
## `artifacts:reports:container_scanning`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
The `container_scanning` report collects [Container Scanning vulnerabilities](../../user/application_security/container_scanning/_index.md).
The collected Container Scanning report uploads to GitLab as an artifact.
GitLab can display the results of one or more reports in:
- The merge request [container scanning widget](../../user/application_security/container_scanning/_index.md).
- The pipeline [**Security** tab](../../user/application_security/detect/security_scanning_results.md).
- The [security dashboard](../../user/application_security/security_dashboard/_index.md).
- The [Project Vulnerability report](../../user/application_security/vulnerability_report/_index.md).
## `artifacts:reports:coverage_fuzzing`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
The `coverage_fuzzing` report collects [coverage fuzzing bugs](../../user/application_security/coverage_fuzzing/_index.md).
The collected coverage fuzzing report uploads to GitLab as an artifact.
GitLab can display the results of one or more reports in:
- The merge request [coverage fuzzing widget](../../user/application_security/coverage_fuzzing/_index.md#interacting-with-the-vulnerabilities).
- The pipeline [**Security** tab](../../user/application_security/detect/security_scanning_results.md).
- The [Project Vulnerability report](../../user/application_security/vulnerability_report/_index.md).
- The [security dashboard](../../user/application_security/security_dashboard/_index.md).
## `artifacts:reports:cyclonedx`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
This report is a Software Bill of Materials describing the components of a project
following the [CycloneDX](https://cyclonedx.org/docs/1.4) protocol format.
You can specify multiple CycloneDX reports per job. These can be either supplied
as a list of filenames, a filename pattern, or both:
- A filename pattern (`cyclonedx: gl-sbom-*.json`, `junit: test-results/**/*.json`).
- An array of filenames (`cyclonedx: [gl-sbom-npm-npm.cdx.json, gl-sbom-bundler-gem.cdx.json]`).
- A combination of both (`cyclonedx: [gl-sbom-*.json, my-cyclonedx.json]`).
- Directories are not supported(`cyclonedx: test-results`, `cyclonedx: test-results/**`).
The following example shows a job that exposes CycloneDX artifacts:
```yaml
artifacts:
reports:
cyclonedx:
- gl-sbom-npm-npm.cdx.json
- gl-sbom-bundler-gem.cdx.json
```
## `artifacts:reports:dast`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
The `dast` report collects [DAST vulnerabilities](../../user/application_security/dast/_index.md). The collected DAST
report uploads to GitLab as an artifact.
GitLab can display the results of one or more reports in:
- The merge request security widget.
- The pipeline [**Security** tab](../../user/application_security/detect/security_scanning_results.md).
- The [Project Vulnerability report](../../user/application_security/vulnerability_report/_index.md).
- The [security dashboard](../../user/application_security/security_dashboard/_index.md).
## `artifacts:reports:dependency_scanning`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
The `dependency_scanning` report collects [Dependency Scanning vulnerabilities](../../user/application_security/dependency_scanning/_index.md).
The collected Dependency Scanning report uploads to GitLab as an artifact.
GitLab can display the results of one or more reports in:
- The merge request [dependency scanning widget](../../user/application_security/dependency_scanning/_index.md).
- The pipeline [**Security** tab](../../user/application_security/detect/security_scanning_results.md).
- The [security dashboard](../../user/application_security/security_dashboard/_index.md).
- The [Project Vulnerability report](../../user/application_security/vulnerability_report/_index.md).
- The [dependency list](../../user/application_security/dependency_list/_index.md).
## `artifacts:reports:dotenv`
The `dotenv` report collects a set of environment variables as artifacts.
The collected variables are registered as runtime-created variables of the job,
which you can [use in subsequent job scripts](../variables/job_scripts.md#pass-an-environment-variable-to-another-job)
or to [set dynamic environment URLs after a job finishes](../environments/_index.md#set-a-dynamic-environment-url).
If duplicate environment variables are present in a `dotenv` report, the last one specified is used.
You should avoid storing sensitive data like credentials in dotenv reports, as the
reports can be downloaded from the pipeline details page. If necessary, you can use
[artifacts:access](_index.md#artifactsaccess) to restrict the users that can download
the report artifacts in a job.
GitLab uses the [`dotenv` gem](https://github.com/bkeepers/dotenv) for handling dotenv files,
and handles dotenv files differently than [the original dotenv rules](https://github.com/motdotla/dotenv?tab=readme-ov-file#what-rules-does-the-parsing-engine-follow):
- The variable key can contain only letters, digits, and underscores (`_`).
- The maximum size of the `.env` file is 5 KB.
This limit [can be changed on GitLab Self-Managed](../../administration/instance_limits.md#limit-dotenv-file-size).
- On GitLab.com, [the maximum number of inherited variables](../../user/gitlab_com/_index.md#cicd)
is 50 for Free, 100 for Premium and 150 for Ultimate. The default for
GitLab Self-Managed is 20, and can be changed by changing the
`dotenv_variables` [application limit](../../administration/instance_limits.md#limit-dotenv-variables).
- Variable substitution in the `.env` file is not supported.
- [Multiline values in the `.env` file](https://github.com/motdotla/dotenv#multiline-values) are not supported.
- The `.env` file can't have empty lines or comments (starting with `#`).
- Key values in the `env` file cannot have spaces or newline characters (`\n`), including when using single or double quotes.
- Quote escaping during parsing (`key = 'value'` -> `{key: "value"}`) is not supported.
- Only UTF-8 encoding is [supported](../jobs/job_artifacts_troubleshooting.md#error-message-fatal-invalid-argument-when-uploading-a-dotenv-artifact-on-a-windows-runner).
## `artifacts:reports:junit`
The `junit` report collects [JUnit report format XML files](https://www.ibm.com/docs/en/developer-for-zos/16.0?topic=formats-junit-xml-format).
The collected Unit test reports upload to GitLab as an artifact. Although JUnit was originally developed in Java, there
are many third-party ports for other languages such as JavaScript, Python, and Ruby.
See [Unit test reports](../testing/unit_test_reports.md) for more details and examples.
The following example shows how to collect a JUnit XML report from Ruby RSpec tests:
```yaml
rspec:
stage: test
script:
- bundle install
- rspec --format RspecJunitFormatter --out rspec.xml
artifacts:
reports:
junit: rspec.xml
```
GitLab can display the results of one or more reports in:
- The merge request [**Test summary** panel](../testing/unit_test_reports.md#view-test-results-in-merge-requests).
- The [pipeline **Tests** tab](../testing/unit_test_reports.md#view-test-results-in-pipelines).
Some JUnit tools export to multiple XML files. You can specify multiple test report paths in a single job to
concatenate them into a single file. Use either:
- A filename pattern (`junit: rspec-*.xml`, `junit: test-results/**/*.xml`).
- An array of filenames (`junit: [rspec-1.xml, rspec-2.xml, rspec-3.xml]`).
- A combination of both (`junit: [rspec.xml, test-results/TEST-*.xml]`).
- Directories are not supported(`junit: test-results`, `junit: test-results/**`).
## `artifacts:reports:load_performance`
{{< details >}}
- Tier: Premium, Ultimate
{{< /details >}}
The `load_performance` report collects [Load Performance Testing metrics](../testing/load_performance_testing.md).
The report is uploaded to GitLab as an artifact.
GitLab can display the results of only one report in the merge request
[load testing widget](../testing/load_performance_testing.md#how-load-performance-testing-works).
GitLab cannot display the combined results of multiple `load_performance` reports.
## `artifacts:reports:metrics`
{{< details >}}
- Tier: Premium, Ultimate
{{< /details >}}
The `metrics` report collects [Metrics](../testing/metrics_reports.md). The collected Metrics report uploads to GitLab as an
artifact.
GitLab can display the results of one or more reports in the merge request
[metrics reports widget](../testing/metrics_reports.md).
## `artifacts:reports:requirements`
{{< details >}}
- Tier: Ultimate
{{< /details >}}
The `requirements` report collects `requirements.json` files. The collected Requirements report uploads to GitLab as an
artifact and existing [requirements](../../user/project/requirements/_index.md) are marked as Satisfied.
GitLab can display the results of one or more reports in the
[project requirements](../../user/project/requirements/_index.md#view-a-requirement).
<!--- start_remove The following content will be removed on remove_date: '2025-08-15' -->
## `artifacts:reports:repository_xray` (deprecated)
{{< details >}}
- Tier: Premium, Ultimate
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/432235) in GitLab 16.7.
{{< /history >}}
The `repository_xray` report collects information about your repository for use by GitLab Duo Code Suggestions.
{{< alert type="warning" >}}
This feature was [deprecated](https://gitlab.com/gitlab-org/gitlab/-/issues/500146) in GitLab 17.6
and is planned for removal in 18.0. Use [Enable Repository X-Ray](../../user/project/repository/code_suggestions/repository_xray.md#enable-repository-x-ray) instead.
{{< /alert >}}
<!--- end_remove -->
## `artifacts:reports:sast`
The `sast` report collects [SAST vulnerabilities](../../user/application_security/sast/_index.md).
The collected SAST report uploads to GitLab as an artifact.
For more information, see:
- [View SAST results](../../user/application_security/sast/_index.md#understanding-the-results)
- [SAST output](../../user/application_security/sast/_index.md#download-a-sast-report)
## `artifacts:reports:secret_detection`
The `secret-detection` report collects [detected secrets](../../user/application_security/secret_detection/pipeline/_index.md).
The collected Secret Detection report is uploaded to GitLab.
GitLab can display the results of one or more reports in:
- The merge request [secret scanning widget](../../user/application_security/secret_detection/pipeline/_index.md).
- The [pipeline security tab](../../user/application_security/detect/security_scanning_results.md).
- The [security dashboard](../../user/application_security/security_dashboard/_index.md).
## `artifacts:reports:terraform`
The `terraform` report obtains an OpenTofu `tfplan.json` file. [JQ processing required to remove credentials](../../user/infrastructure/iac/mr_integration.md#configure-opentofu-report-artifacts).
The collected OpenTofu plan report uploads to GitLab as an artifact.
GitLab can display the results of one or more reports in the merge request
[OpenTofu widget](../../user/infrastructure/iac/mr_integration.md#output-opentofu-plan-information-into-a-merge-request).
For more information, see [Output `tofu plan` information into a merge request](../../user/infrastructure/iac/mr_integration.md).
|
https://docs.gitlab.com/ci/needs
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/needs.md
|
2025-08-13
|
doc/ci/yaml
|
[
"doc",
"ci",
"yaml"
] |
needs.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Make jobs start earlier with `needs`
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can use the [`needs`](_index.md#needs) keyword to create dependencies between jobs
in a pipeline. Jobs run as soon as their dependencies are met, regardless of the pipeline's `stages`
configuration. You can even configure a pipeline with no stages defined (effectively one large stage)
and jobs still run in the proper order. This pipeline structure is a kind of
[directed acyclic graph](https://en.wikipedia.org/wiki/Directed_acyclic_graph).
For example, you may have a specific tool or separate website that is built
as part of your main project. Using `needs`, you can specify dependencies between
these jobs and GitLab executes the jobs as soon as possible instead of waiting
for each stage to complete.
Unlike other solutions for CI/CD, GitLab does not require you to choose between staged
or stageless execution flow. You can implement a hybrid combination of staged and stageless
in a single pipeline, using only the `needs` keyword to enable the feature for any job.
Consider a monorepo as follows:
```plaintext
./service_a
./service_b
./service_c
./service_d
```
This project could have a pipeline organized into three stages:
| build | test | deploy |
|-----------|----------|--------|
| `build_a` | `test_a` | `deploy_a` |
| `build_b` | `test_b` | `deploy_b` |
| `build_c` | `test_c` | `deploy_c` |
| `build_d` | `test_d` | `deploy_d` |
You can improve job execution by using `needs` to relate the `a` jobs to each other
separately from the `b`, `c`, and `d` jobs. `build_a` could take a very long time to build,
but `test_b` doesn't need to wait, it can be configured to start as soon as `build_b` is finished,
which could be much faster.
If desired, `c` and `d` jobs can be left to run in stage sequence.
The `needs` keyword also works with the [`parallel`](_index.md#parallel) keyword,
giving you powerful options for parallelization in your pipeline.
## Use cases
You can use the [`needs`](_index.md#needs) keyword to define several different kinds of
dependencies between jobs in a CI/CD pipeline. You can set dependencies to fan in or out,
and even merge back together (diamond dependencies). These dependencies could be used for
pipelines that:
- Handle multi-platform builds.
- Have a complex web of dependencies like an operating system build.
- Have a deployment graph of independently deployable but related microservices.
Additionally, `needs` can help improve the overall speed of pipelines and provide fast feedback.
By creating dependencies that don't unnecessarily
block each other, your pipelines run as quickly as possible regardless of
pipeline stages, ensuring output (including errors) is available to developers
as quickly as possible.
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Make jobs start earlier with `needs`
breadcrumbs:
- doc
- ci
- yaml
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can use the [`needs`](_index.md#needs) keyword to create dependencies between jobs
in a pipeline. Jobs run as soon as their dependencies are met, regardless of the pipeline's `stages`
configuration. You can even configure a pipeline with no stages defined (effectively one large stage)
and jobs still run in the proper order. This pipeline structure is a kind of
[directed acyclic graph](https://en.wikipedia.org/wiki/Directed_acyclic_graph).
For example, you may have a specific tool or separate website that is built
as part of your main project. Using `needs`, you can specify dependencies between
these jobs and GitLab executes the jobs as soon as possible instead of waiting
for each stage to complete.
Unlike other solutions for CI/CD, GitLab does not require you to choose between staged
or stageless execution flow. You can implement a hybrid combination of staged and stageless
in a single pipeline, using only the `needs` keyword to enable the feature for any job.
Consider a monorepo as follows:
```plaintext
./service_a
./service_b
./service_c
./service_d
```
This project could have a pipeline organized into three stages:
| build | test | deploy |
|-----------|----------|--------|
| `build_a` | `test_a` | `deploy_a` |
| `build_b` | `test_b` | `deploy_b` |
| `build_c` | `test_c` | `deploy_c` |
| `build_d` | `test_d` | `deploy_d` |
You can improve job execution by using `needs` to relate the `a` jobs to each other
separately from the `b`, `c`, and `d` jobs. `build_a` could take a very long time to build,
but `test_b` doesn't need to wait, it can be configured to start as soon as `build_b` is finished,
which could be much faster.
If desired, `c` and `d` jobs can be left to run in stage sequence.
The `needs` keyword also works with the [`parallel`](_index.md#parallel) keyword,
giving you powerful options for parallelization in your pipeline.
## Use cases
You can use the [`needs`](_index.md#needs) keyword to define several different kinds of
dependencies between jobs in a CI/CD pipeline. You can set dependencies to fan in or out,
and even merge back together (diamond dependencies). These dependencies could be used for
pipelines that:
- Handle multi-platform builds.
- Have a complex web of dependencies like an operating system build.
- Have a deployment graph of independently deployable but related microservices.
Additionally, `needs` can help improve the overall speed of pipelines and provide fast feedback.
By creating dependencies that don't unnecessarily
block each other, your pipelines run as quickly as possible regardless of
pipeline stages, ensuring output (including errors) is available to developers
as quickly as possible.
|
https://docs.gitlab.com/ci/workflow
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/workflow.md
|
2025-08-13
|
doc/ci/yaml
|
[
"doc",
"ci",
"yaml"
] |
workflow.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab CI/CD `workflow` keyword
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use the [`workflow`](_index.md#workflow) keyword to control when pipelines are created.
The `workflow` keyword is evaluated before jobs. For example, if a job is configured to run
for tags, but the workflow prevents tag pipelines, the job never runs.
## Common `if` clauses for `workflow:rules`
Some example `if` clauses for `workflow: rules`:
| Example rules | Details |
|------------------------------------------------------|---------|
| `if: '$CI_PIPELINE_SOURCE == "merge_request_event"'` | Control when merge request pipelines run. |
| `if: '$CI_PIPELINE_SOURCE == "push"'` | Control when both branch pipelines and tag pipelines run. |
| `if: $CI_COMMIT_TAG` | Control when tag pipelines run. |
| `if: $CI_COMMIT_BRANCH` | Control when branch pipelines run. |
See the [common `if` clauses for `rules`](../jobs/job_rules.md#common-if-clauses-with-predefined-variables) for more examples.
## `workflow: rules` examples
In the following example:
- Pipelines run for all `push` events (changes to branches and new tags).
- Pipelines for push events with commit messages that end with `-draft` don't run, because
they are set to `when: never`.
- Pipelines for schedules or merge requests don't run either, because no rules evaluate to true for them.
```yaml
workflow:
rules:
- if: $CI_COMMIT_MESSAGE =~ /-draft$/
when: never
- if: $CI_PIPELINE_SOURCE == "push"
```
This example has strict rules, and pipelines do **not** run in any other case.
Alternatively, all of the rules can be `when: never`, with a final
`when: always` rule. Pipelines that match the `when: never` rules do not run.
All other pipeline types run. For example:
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: $CI_PIPELINE_SOURCE == "push"
when: never
- when: always
```
This example prevents pipelines for schedules or `push` (branches and tags) pipelines.
The final `when: always` rule runs all other pipeline types, **including** merge
request pipelines.
### Switch between branch pipelines and merge request pipelines
To make the pipeline switch from branch pipelines to merge request pipelines after
a merge request is created, add a `workflow: rules` section to your `.gitlab-ci.yml` file.
If you use both pipeline types at the same time, [duplicate pipelines](../jobs/job_rules.md#avoid-duplicate-pipelines)
might run at the same time. To prevent duplicate pipelines, use the
[`CI_OPEN_MERGE_REQUESTS` variable](../variables/predefined_variables.md).
The following example is for a project that runs branch and merge request pipelines only,
but does not run pipelines for any other case. It runs:
- Branch pipelines when a merge request is not open for the branch.
- Merge request pipelines when a merge request is open for the branch.
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
when: never
- if: $CI_COMMIT_BRANCH
```
If GitLab attempts to trigger:
- A merge request pipeline, start the pipeline. For example, a merge request pipeline
can be triggered by a push to a branch with an associated open merge request.
- A branch pipeline, but a merge request is open for that branch, do not run the branch pipeline.
For example, a branch pipeline can be triggered by a change to a branch, an API call,
a scheduled pipeline, and so on.
- A branch pipeline, but there is no merge request open for the branch, run the branch pipeline.
You can also add a rule to an existing `workflow` section to switch from branch pipelines
to merge request pipelines when a merge request is created.
Add this rule to the top of the `workflow` section, followed by the other rules that
were already present:
```yaml
workflow:
rules:
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS && $CI_PIPELINE_SOURCE == "push"
when: never
- # Previously defined workflow rules here
```
[Triggered pipelines](../triggers/_index.md) that run on a branch have a `$CI_COMMIT_BRANCH`
set and could be blocked by a similar rule. Triggered pipelines have a pipeline source
of `trigger` or `pipeline`, so `&& $CI_PIPELINE_SOURCE == "push"` ensures the rule
does not block triggered pipelines.
### Git Flow with merge request pipelines
You can use `workflow: rules` with merge request pipelines. With these rules,
you can use [merge request pipeline features](../pipelines/merge_request_pipelines.md)
with feature branches, while keeping long-lived branches to support multiple versions
of your software.
For example, to only run pipelines for your merge requests, tags, and protected branches:
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_TAG
- if: $CI_COMMIT_REF_PROTECTED == "true"
```
This example assumes that your long-lived branches are [protected](../../user/project/repository/branches/protected.md).
### Skip pipelines for draft merge requests
You can use `workflow: rules` to skip pipelines for draft merge requests. With these rules, you can avoid using compute minutes until development is complete.
For example, the following rules will disable CI builds for merge requests with `[Draft]`, `(Draft)`, or `Draft:` in the title:
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TITLE =~ /^(\[Draft\]|\(Draft\)|Draft:)/
when: never
stages:
- build
build-job:
stage: build
script:
- echo "Testing"
```
## Troubleshooting
### Merge request stuck with `Checking pipeline status.` message
If a merge request displays `Checking pipeline status.`, but the message never goes
away (the "spinner" never stops spinning), it might be due to `workflow:rules`.
This issue can happen if a project has [**Pipelines must succeed**](../../user/project/merge_requests/auto_merge.md#require-a-successful-pipeline-for-merge)
enabled, but the `workflow:rules` prevent a pipeline from running for the merge request.
For example, with this workflow, merge requests cannot be merged, because no
pipeline can run:
```yaml
workflow:
rules:
- changes:
- .gitlab/**/**.md
when: never
```
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: GitLab CI/CD `workflow` keyword
breadcrumbs:
- doc
- ci
- yaml
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use the [`workflow`](_index.md#workflow) keyword to control when pipelines are created.
The `workflow` keyword is evaluated before jobs. For example, if a job is configured to run
for tags, but the workflow prevents tag pipelines, the job never runs.
## Common `if` clauses for `workflow:rules`
Some example `if` clauses for `workflow: rules`:
| Example rules | Details |
|------------------------------------------------------|---------|
| `if: '$CI_PIPELINE_SOURCE == "merge_request_event"'` | Control when merge request pipelines run. |
| `if: '$CI_PIPELINE_SOURCE == "push"'` | Control when both branch pipelines and tag pipelines run. |
| `if: $CI_COMMIT_TAG` | Control when tag pipelines run. |
| `if: $CI_COMMIT_BRANCH` | Control when branch pipelines run. |
See the [common `if` clauses for `rules`](../jobs/job_rules.md#common-if-clauses-with-predefined-variables) for more examples.
## `workflow: rules` examples
In the following example:
- Pipelines run for all `push` events (changes to branches and new tags).
- Pipelines for push events with commit messages that end with `-draft` don't run, because
they are set to `when: never`.
- Pipelines for schedules or merge requests don't run either, because no rules evaluate to true for them.
```yaml
workflow:
rules:
- if: $CI_COMMIT_MESSAGE =~ /-draft$/
when: never
- if: $CI_PIPELINE_SOURCE == "push"
```
This example has strict rules, and pipelines do **not** run in any other case.
Alternatively, all of the rules can be `when: never`, with a final
`when: always` rule. Pipelines that match the `when: never` rules do not run.
All other pipeline types run. For example:
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: $CI_PIPELINE_SOURCE == "push"
when: never
- when: always
```
This example prevents pipelines for schedules or `push` (branches and tags) pipelines.
The final `when: always` rule runs all other pipeline types, **including** merge
request pipelines.
### Switch between branch pipelines and merge request pipelines
To make the pipeline switch from branch pipelines to merge request pipelines after
a merge request is created, add a `workflow: rules` section to your `.gitlab-ci.yml` file.
If you use both pipeline types at the same time, [duplicate pipelines](../jobs/job_rules.md#avoid-duplicate-pipelines)
might run at the same time. To prevent duplicate pipelines, use the
[`CI_OPEN_MERGE_REQUESTS` variable](../variables/predefined_variables.md).
The following example is for a project that runs branch and merge request pipelines only,
but does not run pipelines for any other case. It runs:
- Branch pipelines when a merge request is not open for the branch.
- Merge request pipelines when a merge request is open for the branch.
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
when: never
- if: $CI_COMMIT_BRANCH
```
If GitLab attempts to trigger:
- A merge request pipeline, start the pipeline. For example, a merge request pipeline
can be triggered by a push to a branch with an associated open merge request.
- A branch pipeline, but a merge request is open for that branch, do not run the branch pipeline.
For example, a branch pipeline can be triggered by a change to a branch, an API call,
a scheduled pipeline, and so on.
- A branch pipeline, but there is no merge request open for the branch, run the branch pipeline.
You can also add a rule to an existing `workflow` section to switch from branch pipelines
to merge request pipelines when a merge request is created.
Add this rule to the top of the `workflow` section, followed by the other rules that
were already present:
```yaml
workflow:
rules:
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS && $CI_PIPELINE_SOURCE == "push"
when: never
- # Previously defined workflow rules here
```
[Triggered pipelines](../triggers/_index.md) that run on a branch have a `$CI_COMMIT_BRANCH`
set and could be blocked by a similar rule. Triggered pipelines have a pipeline source
of `trigger` or `pipeline`, so `&& $CI_PIPELINE_SOURCE == "push"` ensures the rule
does not block triggered pipelines.
### Git Flow with merge request pipelines
You can use `workflow: rules` with merge request pipelines. With these rules,
you can use [merge request pipeline features](../pipelines/merge_request_pipelines.md)
with feature branches, while keeping long-lived branches to support multiple versions
of your software.
For example, to only run pipelines for your merge requests, tags, and protected branches:
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_TAG
- if: $CI_COMMIT_REF_PROTECTED == "true"
```
This example assumes that your long-lived branches are [protected](../../user/project/repository/branches/protected.md).
### Skip pipelines for draft merge requests
You can use `workflow: rules` to skip pipelines for draft merge requests. With these rules, you can avoid using compute minutes until development is complete.
For example, the following rules will disable CI builds for merge requests with `[Draft]`, `(Draft)`, or `Draft:` in the title:
```yaml
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TITLE =~ /^(\[Draft\]|\(Draft\)|Draft:)/
when: never
stages:
- build
build-job:
stage: build
script:
- echo "Testing"
```
## Troubleshooting
### Merge request stuck with `Checking pipeline status.` message
If a merge request displays `Checking pipeline status.`, but the message never goes
away (the "spinner" never stops spinning), it might be due to `workflow:rules`.
This issue can happen if a project has [**Pipelines must succeed**](../../user/project/merge_requests/auto_merge.md#require-a-successful-pipeline-for-merge)
enabled, but the `workflow:rules` prevent a pipeline from running for the merge request.
For example, with this workflow, merge requests cannot be merged, because no
pipeline can run:
```yaml
workflow:
rules:
- changes:
- .gitlab/**/**.md
when: never
```
|
https://docs.gitlab.com/ci/signing_examples
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/signing_examples.md
|
2025-08-13
|
doc/ci/yaml
|
[
"doc",
"ci",
"yaml"
] |
signing_examples.md
|
Software Supply Chain Security
|
Pipeline Security
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Use Sigstore for keyless signing and verification
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
The [Sigstore](https://www.sigstore.dev/) project provides a CLI called
[Cosign](https://docs.sigstore.dev/quickstart/quickstart-cosign/) which can be used for keyless signing of container images built
with GitLab CI/CD. Keyless signing has many advantages, including eliminating the need to manage, safeguard, and rotate a private
key. Cosign requests a short-lived key pair to use for signing, records it on a certificate transparency log, and
then discards it. The key is generated through a token obtained from the GitLab server using the OIDC identity of the user who
ran the pipeline. This token includes unique claims that certify the token was generated by a CI/CD pipeline. To learn more,
see Cosign [documentation](https://docs.sigstore.dev/quickstart/quickstart-cosign/#example-working-with-containers) on keyless signatures.
For details on the mapping between GitLab OIDC claims and Fulcio certificate extensions, see the GitLab column of
[Mapping OIDC token claims to Fulcio OIDs](https://github.com/sigstore/fulcio/blob/main/docs/oid-info.md#mapping-oidc-token-claims-to-fulcio-oids).
Prerequisites:
- You must be using GitLab.com.
- Your project's CI/CD configuration must be located in the project.
## Sign or verify container images and build artifacts by using Cosign
You can use Cosign to sign and verify container images and build artifacts.
Prerequisites:
- You must use a version of Cosign that is `>= 2.0.1`.
**Known issues**
- The `id_tokens` portion of the CI/CD configuration file must be located in the project that is being built and signed. AutoDevOps, CI files included from another repository, and child pipelines are not supported. Work to remove this limitation is being tracked in [epic 11637](https://gitlab.com/groups/gitlab-org/-/epics/11637).
**Best practices**:
- Build and sign an image/artifact in the same job to prevent it from being tampered with before it is signed.
- When signing container images, sign the digest (which is immutable) instead of the tag.
GitLab [ID tokens](../secrets/id_token_authentication.md#id-tokens) can be used by Cosign for
[keyless signing](https://docs.sigstore.dev/quickstart/quickstart-cosign/#keyless-signing-of-a-container). The token must have
`sigstore` set as the [`aud`](../secrets/id_token_authentication.md#token-payload) claim. The token can be used by Cosign automatically when it is set in the
`SIGSTORE_ID_TOKEN` environment variable.
To learn more about how to install Cosign, see [Cosign Installation documentation](https://docs.sigstore.dev/cosign/system_config/installation/).
### Signing
#### Container images
The [`Cosign.gitlab-ci.yml`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Cosign.gitlab-ci.yml)
template can be used to build and sign a container image in GitLab CI. The signature is automatically stored in the same
container repository as the image.
```yaml
include:
- template: Cosign.gitlab-ci.yml
```
To learn more about signing containers, see [Cosign Signing Containers documentation](https://docs.sigstore.dev/cosign/signing/signing_with_containers/).
#### Build artifacts
The following example demonstrates how to sign a build artifact in GitLab CI. You should save the `cosign.bundle` file
produced by `cosign sign-blob`, which is used for signature verification.
To learn more about signing artifacts, see [Cosign Signing Blobs documentation](https://docs.sigstore.dev/cosign/signing/signing_with_blobs/).
```yaml
build_and_sign_artifact:
stage: build
image: alpine:latest
variables:
COSIGN_YES: "true"
id_tokens:
SIGSTORE_ID_TOKEN:
aud: sigstore
before_script:
- apk add --update cosign
script:
- echo "This is a build artifact" > artifact.txt
- cosign sign-blob artifact.txt --bundle cosign.bundle
artifacts:
paths:
- artifact.txt
- cosign.bundle
```
### Verification
**Command-line arguments**
| Name | Value |
|-----------------------------|-------|
| `--certificate-identity` | The SAN of the signing certificate issued by Fulcio. Can be constructed with the following information from the project where the image/artifact was signed: GitLab instance URL + project path + `//` + CI config path + `@` + ref path. |
| `--certificate-oidc-issuer` | The GitLab instance URL where the image/artifact was signed. For example, `https://gitlab.com`. |
| `--bundle` | The `bundle` file produced by `cosign sign-blob`. Only used for verifying build artifacts. |
To learn more about verifying signed images/artifacts, see [Cosign Verifying documentation](https://docs.sigstore.dev/cosign/verifying/verify/).
#### Container images
The following example demonstrates how to verify a signed container image in GitLab CI. Use the previously described [command-line arguments](#verification).
```yaml
verify_image:
image: alpine:3.20
stage: verify
before_script:
- apk add --update cosign docker
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
script:
- cosign verify "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG" --certificate-identity "https://gitlab.com/my-group/my-project//path/to/.gitlab-ci.yml@refs/heads/main" --certificate-oidc-issuer "https://gitlab.com"
```
**Additional details**:
- The double backslash between the project path and the `.gitlab-ci.yml` path is not an error and is required for verification to succeed. A typical error when a single slash is used is `Error: none of the expected identities matched what was in the certificate, got subjects` followed by the signed URL which has two slashes between the project path and the `.gitlab-ci.yml` path.
- If the verification is happening in the same pipeline as the signing, then this path can be used: `"${CI_PROJECT_URL}//.gitlab-ci.yml@refs/heads/${CI_COMMIT_REF_NAME}"`
#### Build artifacts
The following example demonstrates how to verify a signed build artifact in GitLab CI. Verifying an artifact requires both
the artifact itself and the `cosign.bundle` file produced by `cosign sign-blob`. Use the previously described [command-line arguments](#verification).
```yaml
verify_artifact:
stage: verify
image: alpine:latest
before_script:
- apk add --update cosign
script:
- cosign verify-blob artifact.txt --bundle cosign.bundle --certificate-identity "https://gitlab.com/my-group/my-project//path/to/.gitlab-ci.yml@refs/heads/main" --certificate-oidc-issuer "https://gitlab.com"
```
**Additional details**:
- The double backslash between the project path and the `.gitlab-ci.yml` path is not an error and is required for verification to succeed. A typical error when a single slash is used is `Error: none of the expected identities matched what was in the certificate, got subjects` followed by the signed URL which has two slashes between the project path and the `.gitlab-ci.yml` path.
- If the verification is happening in the same pipeline as the signing, then this path can be used: `"${CI_PROJECT_URL}//.gitlab-ci.yml@refs/heads/${CI_COMMIT_REF_NAME}"`
## Use Sigstore and npm to generate keyless provenance
You can use Sigstore and npm, together with GitLab CI/CD, to digitally sign build artifacts without the overhead of key management.
### About npm provenance
[npm CLI](https://docs.npmjs.com/cli/) allows package maintainers to provide users with provenance attestations. Using npm
CLI provenance generation allows users to trust and verify that the package they are downloading and using is from you and the
build system that built it.
For more information on how to publish npm packages, see [GitLab npm package registry](../../user/packages/npm_registry/_index.md).
### Sigstore
[Sigstore](https://www.sigstore.dev/) is a set of tools that package managers and security experts can use to secure their software
supply chains against attacks. Bringing together free-to-use open source technologies like Fulcio, Cosign, and Rekor, it
handles digital signing, verification, and checks for provenance
needed to make it safer to distribute and use open source software.
**Related topics**:
- [SLSA Provenance definition](https://slsa.dev/provenance/v1)
- [npm documentation](https://docs.npmjs.com/generating-provenance-statements/)
- [npm Provenance RFC](https://github.com/npm/rfcs/blob/main/accepted/0049-link-packages-to-source-and-build.md#detailed-steps-to-publish)
### Generating provenance in GitLab CI/CD
Now that Sigstore supports GitLab OIDC as previously described, you can use npm provenance together with GitLab CI/CD and Sigstore to
generate and sign provenance for your npm packages in a GitLab CI/CD pipeline.
#### Prerequisites
1. Set your GitLab [ID token](../secrets/id_token_authentication.md) `aud` to `sigstore`.
1. Add the `--provenance` flag to have npm publish.
Example content to be added to `.gitlab-ci.yml` file:
```yaml
build:
image: node:latest
id_tokens:
SIGSTORE_ID_TOKEN:
aud: sigstore
script:
- npm publish --provenance --access public
```
The npm GitLab template provides this functionality as well, the example is in
the [templates documentation](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/npm.gitlab-ci.yml).
## Verifying npm provenance
npm CLI also provides functionality for end users to verify the provenance of packages.
```plaintext
npm audit signatures
audited 1 package in 0s
1 package has a verified registry signature
```
### Inspecting the provenance metadata
The Rekor transparency log stores certificates and attestations for every package that is published with provenance.
For example, here is the [entry for the following example](https://search.sigstore.dev/?logIndex=21076013).
An example provenance document generated by npm:
```yaml
_type: https://in-toto.io/Statement/v0.1
subject:
- name: pkg:npm/%40strongjz/strongcoin@0.0.13
digest:
sha512: >-
924a134a0fd4fe6a7c87b4687bf0ac898b9153218ce9ad75798cc27ab2cddbeff77541f3847049bd5e3dfd74cea0a83754e7686852f34b185c3621d3932bc3c8
predicateType: https://slsa.dev/provenance/v0.2
predicate:
buildType: https://github.com/npm/CLI/gitlab/v0alpha1
builder:
id: https://gitlab.com/strongjz/npm-provenance-example/-/runners/12270835
invocation:
configSource:
uri: git+https://gitlab.com/strongjz/npm-provenance-example
digest:
sha1: 6e02e901e936bfac3d4691984dff8c505410cbc3
entryPoint: deploy
parameters:
CI: 'true'
CI_API_GRAPHQL_URL: https://gitlab.com/api/graphql
CI_API_V4_URL: https://gitlab.com/api/v4
CI_COMMIT_BEFORE_SHA: 7d3e913e5375f68700e0c34aa90b0be7843edf6c
CI_COMMIT_BRANCH: main
CI_COMMIT_REF_NAME: main
CI_COMMIT_REF_PROTECTED: 'true'
CI_COMMIT_REF_SLUG: main
CI_COMMIT_SHA: 6e02e901e936bfac3d4691984dff8c505410cbc3
CI_COMMIT_SHORT_SHA: 6e02e901
CI_COMMIT_TIMESTAMP: '2023-05-19T10:17:12-04:00'
CI_COMMIT_TITLE: trying to publish to gitlab reg
CI_CONFIG_PATH: .gitlab-ci.yml
CI_DEFAULT_BRANCH: main
CI_DEPENDENCY_PROXY_DIRECT_GROUP_IMAGE_PREFIX: gitlab.com:443/strongjz/dependency_proxy/containers
CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX: gitlab.com:443/strongjz/dependency_proxy/containers
CI_DEPENDENCY_PROXY_SERVER: gitlab.com:443
CI_DEPENDENCY_PROXY_USER: gitlab-ci-token
CI_JOB_ID: '4316132595'
CI_JOB_NAME: deploy
CI_JOB_NAME_SLUG: deploy
CI_JOB_STAGE: deploy
CI_JOB_STARTED_AT: '2023-05-19T14:17:23Z'
CI_JOB_URL: https://gitlab.com/strongjz/npm-provenance-example/-/jobs/4316132595
CI_NODE_TOTAL: '1'
CI_PAGES_DOMAIN: gitlab.io
CI_PAGES_URL: https://strongjz.gitlab.io/npm-provenance-example
CI_PIPELINE_CREATED_AT: '2023-05-19T14:17:21Z'
CI_PIPELINE_ID: '872773336'
CI_PIPELINE_IID: '40'
CI_PIPELINE_SOURCE: push
CI_PIPELINE_URL: https://gitlab.com/strongjz/npm-provenance-example/-/pipelines/872773336
CI_PROJECT_CLASSIFICATION_LABEL: ''
CI_PROJECT_DESCRIPTION: ''
CI_PROJECT_ID: '45821955'
CI_PROJECT_NAME: npm-provenance-example
CI_PROJECT_NAMESPACE: strongjz
CI_PROJECT_NAMESPACE_SLUG: strongjz
CI_PROJECT_NAMESPACE_ID: '36018'
CI_PROJECT_PATH: strongjz/npm-provenance-example
CI_PROJECT_PATH_SLUG: strongjz-npm-provenance-example
CI_PROJECT_REPOSITORY_LANGUAGES: javascript,dockerfile
CI_PROJECT_ROOT_NAMESPACE: strongjz
CI_PROJECT_TITLE: npm-provenance-example
CI_PROJECT_URL: https://gitlab.com/strongjz/npm-provenance-example
CI_PROJECT_VISIBILITY: public
CI_REGISTRY: registry.gitlab.com
CI_REGISTRY_IMAGE: registry.gitlab.com/strongjz/npm-provenance-example
CI_REGISTRY_USER: gitlab-ci-token
CI_RUNNER_DESCRIPTION: 3-blue.shared.runners-manager.gitlab.com/default
CI_RUNNER_ID: '12270835'
CI_RUNNER_TAGS: >-
["gce", "east-c", "linux", "ruby", "mysql", "postgres", "mongo",
"git-annex", "shared", "docker", "saas-linux-small-amd64"]
CI_SERVER_HOST: gitlab.com
CI_SERVER_NAME: GitLab
CI_SERVER_PORT: '443'
CI_SERVER_PROTOCOL: https
CI_SERVER_REVISION: 9d4873fd3c5
CI_SERVER_SHELL_SSH_HOST: gitlab.com
CI_SERVER_SHELL_SSH_PORT: '22'
CI_SERVER_URL: https://gitlab.com
CI_SERVER_VERSION: 16.1.0-pre
CI_SERVER_VERSION_MAJOR: '16'
CI_SERVER_VERSION_MINOR: '1'
CI_SERVER_VERSION_PATCH: '0'
CI_TEMPLATE_REGISTRY_HOST: registry.gitlab.com
GITLAB_CI: 'true'
GITLAB_FEATURES: >-
elastic_search,ldap_group_sync,multiple_ldap_servers,seat_link,usage_quotas,zoekt_code_search,repository_size_limit,admin_audit_log,auditor_user,custom_file_templates,custom_project_templates,db_load_balancing,default_branch_protection_restriction_in_groups,extended_audit_events,external_authorization_service_api_management,geo,instance_level_scim,ldap_group_sync_filter,object_storage,pages_size_limit,project_aliases,password_complexity,enterprise_templates,git_abuse_rate_limit,required_ci_templates,runner_maintenance_note,runner_performance_insights,runner_upgrade_management,runner_jobs_statistics
GITLAB_USER_ID: '31705'
GITLAB_USER_LOGIN: strongjz
environment:
name: 3-blue.shared.runners-manager.gitlab.com/default
architecture: linux/amd64
server: https://gitlab.com
project: strongjz/npm-provenance-example
job:
id: '4316132595'
pipeline:
id: '872773336'
ref: .gitlab-ci.yml
metadata:
buildInvocationId: https://gitlab.com/strongjz/npm-provenance-example/-/jobs/4316132595
completeness:
parameters: true
environment: true
materials: false
reproducible: false
materials:
- uri: git+https://gitlab.com/strongjz/npm-provenance-example
digest:
sha1: 6e02e901e936bfac3d4691984dff8c505410cbc3
```
|
---
stage: Software Supply Chain Security
group: Pipeline Security
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Use Sigstore for keyless signing and verification
breadcrumbs:
- doc
- ci
- yaml
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
The [Sigstore](https://www.sigstore.dev/) project provides a CLI called
[Cosign](https://docs.sigstore.dev/quickstart/quickstart-cosign/) which can be used for keyless signing of container images built
with GitLab CI/CD. Keyless signing has many advantages, including eliminating the need to manage, safeguard, and rotate a private
key. Cosign requests a short-lived key pair to use for signing, records it on a certificate transparency log, and
then discards it. The key is generated through a token obtained from the GitLab server using the OIDC identity of the user who
ran the pipeline. This token includes unique claims that certify the token was generated by a CI/CD pipeline. To learn more,
see Cosign [documentation](https://docs.sigstore.dev/quickstart/quickstart-cosign/#example-working-with-containers) on keyless signatures.
For details on the mapping between GitLab OIDC claims and Fulcio certificate extensions, see the GitLab column of
[Mapping OIDC token claims to Fulcio OIDs](https://github.com/sigstore/fulcio/blob/main/docs/oid-info.md#mapping-oidc-token-claims-to-fulcio-oids).
Prerequisites:
- You must be using GitLab.com.
- Your project's CI/CD configuration must be located in the project.
## Sign or verify container images and build artifacts by using Cosign
You can use Cosign to sign and verify container images and build artifacts.
Prerequisites:
- You must use a version of Cosign that is `>= 2.0.1`.
**Known issues**
- The `id_tokens` portion of the CI/CD configuration file must be located in the project that is being built and signed. AutoDevOps, CI files included from another repository, and child pipelines are not supported. Work to remove this limitation is being tracked in [epic 11637](https://gitlab.com/groups/gitlab-org/-/epics/11637).
**Best practices**:
- Build and sign an image/artifact in the same job to prevent it from being tampered with before it is signed.
- When signing container images, sign the digest (which is immutable) instead of the tag.
GitLab [ID tokens](../secrets/id_token_authentication.md#id-tokens) can be used by Cosign for
[keyless signing](https://docs.sigstore.dev/quickstart/quickstart-cosign/#keyless-signing-of-a-container). The token must have
`sigstore` set as the [`aud`](../secrets/id_token_authentication.md#token-payload) claim. The token can be used by Cosign automatically when it is set in the
`SIGSTORE_ID_TOKEN` environment variable.
To learn more about how to install Cosign, see [Cosign Installation documentation](https://docs.sigstore.dev/cosign/system_config/installation/).
### Signing
#### Container images
The [`Cosign.gitlab-ci.yml`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Cosign.gitlab-ci.yml)
template can be used to build and sign a container image in GitLab CI. The signature is automatically stored in the same
container repository as the image.
```yaml
include:
- template: Cosign.gitlab-ci.yml
```
To learn more about signing containers, see [Cosign Signing Containers documentation](https://docs.sigstore.dev/cosign/signing/signing_with_containers/).
#### Build artifacts
The following example demonstrates how to sign a build artifact in GitLab CI. You should save the `cosign.bundle` file
produced by `cosign sign-blob`, which is used for signature verification.
To learn more about signing artifacts, see [Cosign Signing Blobs documentation](https://docs.sigstore.dev/cosign/signing/signing_with_blobs/).
```yaml
build_and_sign_artifact:
stage: build
image: alpine:latest
variables:
COSIGN_YES: "true"
id_tokens:
SIGSTORE_ID_TOKEN:
aud: sigstore
before_script:
- apk add --update cosign
script:
- echo "This is a build artifact" > artifact.txt
- cosign sign-blob artifact.txt --bundle cosign.bundle
artifacts:
paths:
- artifact.txt
- cosign.bundle
```
### Verification
**Command-line arguments**
| Name | Value |
|-----------------------------|-------|
| `--certificate-identity` | The SAN of the signing certificate issued by Fulcio. Can be constructed with the following information from the project where the image/artifact was signed: GitLab instance URL + project path + `//` + CI config path + `@` + ref path. |
| `--certificate-oidc-issuer` | The GitLab instance URL where the image/artifact was signed. For example, `https://gitlab.com`. |
| `--bundle` | The `bundle` file produced by `cosign sign-blob`. Only used for verifying build artifacts. |
To learn more about verifying signed images/artifacts, see [Cosign Verifying documentation](https://docs.sigstore.dev/cosign/verifying/verify/).
#### Container images
The following example demonstrates how to verify a signed container image in GitLab CI. Use the previously described [command-line arguments](#verification).
```yaml
verify_image:
image: alpine:3.20
stage: verify
before_script:
- apk add --update cosign docker
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
script:
- cosign verify "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG" --certificate-identity "https://gitlab.com/my-group/my-project//path/to/.gitlab-ci.yml@refs/heads/main" --certificate-oidc-issuer "https://gitlab.com"
```
**Additional details**:
- The double backslash between the project path and the `.gitlab-ci.yml` path is not an error and is required for verification to succeed. A typical error when a single slash is used is `Error: none of the expected identities matched what was in the certificate, got subjects` followed by the signed URL which has two slashes between the project path and the `.gitlab-ci.yml` path.
- If the verification is happening in the same pipeline as the signing, then this path can be used: `"${CI_PROJECT_URL}//.gitlab-ci.yml@refs/heads/${CI_COMMIT_REF_NAME}"`
#### Build artifacts
The following example demonstrates how to verify a signed build artifact in GitLab CI. Verifying an artifact requires both
the artifact itself and the `cosign.bundle` file produced by `cosign sign-blob`. Use the previously described [command-line arguments](#verification).
```yaml
verify_artifact:
stage: verify
image: alpine:latest
before_script:
- apk add --update cosign
script:
- cosign verify-blob artifact.txt --bundle cosign.bundle --certificate-identity "https://gitlab.com/my-group/my-project//path/to/.gitlab-ci.yml@refs/heads/main" --certificate-oidc-issuer "https://gitlab.com"
```
**Additional details**:
- The double backslash between the project path and the `.gitlab-ci.yml` path is not an error and is required for verification to succeed. A typical error when a single slash is used is `Error: none of the expected identities matched what was in the certificate, got subjects` followed by the signed URL which has two slashes between the project path and the `.gitlab-ci.yml` path.
- If the verification is happening in the same pipeline as the signing, then this path can be used: `"${CI_PROJECT_URL}//.gitlab-ci.yml@refs/heads/${CI_COMMIT_REF_NAME}"`
## Use Sigstore and npm to generate keyless provenance
You can use Sigstore and npm, together with GitLab CI/CD, to digitally sign build artifacts without the overhead of key management.
### About npm provenance
[npm CLI](https://docs.npmjs.com/cli/) allows package maintainers to provide users with provenance attestations. Using npm
CLI provenance generation allows users to trust and verify that the package they are downloading and using is from you and the
build system that built it.
For more information on how to publish npm packages, see [GitLab npm package registry](../../user/packages/npm_registry/_index.md).
### Sigstore
[Sigstore](https://www.sigstore.dev/) is a set of tools that package managers and security experts can use to secure their software
supply chains against attacks. Bringing together free-to-use open source technologies like Fulcio, Cosign, and Rekor, it
handles digital signing, verification, and checks for provenance
needed to make it safer to distribute and use open source software.
**Related topics**:
- [SLSA Provenance definition](https://slsa.dev/provenance/v1)
- [npm documentation](https://docs.npmjs.com/generating-provenance-statements/)
- [npm Provenance RFC](https://github.com/npm/rfcs/blob/main/accepted/0049-link-packages-to-source-and-build.md#detailed-steps-to-publish)
### Generating provenance in GitLab CI/CD
Now that Sigstore supports GitLab OIDC as previously described, you can use npm provenance together with GitLab CI/CD and Sigstore to
generate and sign provenance for your npm packages in a GitLab CI/CD pipeline.
#### Prerequisites
1. Set your GitLab [ID token](../secrets/id_token_authentication.md) `aud` to `sigstore`.
1. Add the `--provenance` flag to have npm publish.
Example content to be added to `.gitlab-ci.yml` file:
```yaml
build:
image: node:latest
id_tokens:
SIGSTORE_ID_TOKEN:
aud: sigstore
script:
- npm publish --provenance --access public
```
The npm GitLab template provides this functionality as well, the example is in
the [templates documentation](https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/npm.gitlab-ci.yml).
## Verifying npm provenance
npm CLI also provides functionality for end users to verify the provenance of packages.
```plaintext
npm audit signatures
audited 1 package in 0s
1 package has a verified registry signature
```
### Inspecting the provenance metadata
The Rekor transparency log stores certificates and attestations for every package that is published with provenance.
For example, here is the [entry for the following example](https://search.sigstore.dev/?logIndex=21076013).
An example provenance document generated by npm:
```yaml
_type: https://in-toto.io/Statement/v0.1
subject:
- name: pkg:npm/%40strongjz/strongcoin@0.0.13
digest:
sha512: >-
924a134a0fd4fe6a7c87b4687bf0ac898b9153218ce9ad75798cc27ab2cddbeff77541f3847049bd5e3dfd74cea0a83754e7686852f34b185c3621d3932bc3c8
predicateType: https://slsa.dev/provenance/v0.2
predicate:
buildType: https://github.com/npm/CLI/gitlab/v0alpha1
builder:
id: https://gitlab.com/strongjz/npm-provenance-example/-/runners/12270835
invocation:
configSource:
uri: git+https://gitlab.com/strongjz/npm-provenance-example
digest:
sha1: 6e02e901e936bfac3d4691984dff8c505410cbc3
entryPoint: deploy
parameters:
CI: 'true'
CI_API_GRAPHQL_URL: https://gitlab.com/api/graphql
CI_API_V4_URL: https://gitlab.com/api/v4
CI_COMMIT_BEFORE_SHA: 7d3e913e5375f68700e0c34aa90b0be7843edf6c
CI_COMMIT_BRANCH: main
CI_COMMIT_REF_NAME: main
CI_COMMIT_REF_PROTECTED: 'true'
CI_COMMIT_REF_SLUG: main
CI_COMMIT_SHA: 6e02e901e936bfac3d4691984dff8c505410cbc3
CI_COMMIT_SHORT_SHA: 6e02e901
CI_COMMIT_TIMESTAMP: '2023-05-19T10:17:12-04:00'
CI_COMMIT_TITLE: trying to publish to gitlab reg
CI_CONFIG_PATH: .gitlab-ci.yml
CI_DEFAULT_BRANCH: main
CI_DEPENDENCY_PROXY_DIRECT_GROUP_IMAGE_PREFIX: gitlab.com:443/strongjz/dependency_proxy/containers
CI_DEPENDENCY_PROXY_GROUP_IMAGE_PREFIX: gitlab.com:443/strongjz/dependency_proxy/containers
CI_DEPENDENCY_PROXY_SERVER: gitlab.com:443
CI_DEPENDENCY_PROXY_USER: gitlab-ci-token
CI_JOB_ID: '4316132595'
CI_JOB_NAME: deploy
CI_JOB_NAME_SLUG: deploy
CI_JOB_STAGE: deploy
CI_JOB_STARTED_AT: '2023-05-19T14:17:23Z'
CI_JOB_URL: https://gitlab.com/strongjz/npm-provenance-example/-/jobs/4316132595
CI_NODE_TOTAL: '1'
CI_PAGES_DOMAIN: gitlab.io
CI_PAGES_URL: https://strongjz.gitlab.io/npm-provenance-example
CI_PIPELINE_CREATED_AT: '2023-05-19T14:17:21Z'
CI_PIPELINE_ID: '872773336'
CI_PIPELINE_IID: '40'
CI_PIPELINE_SOURCE: push
CI_PIPELINE_URL: https://gitlab.com/strongjz/npm-provenance-example/-/pipelines/872773336
CI_PROJECT_CLASSIFICATION_LABEL: ''
CI_PROJECT_DESCRIPTION: ''
CI_PROJECT_ID: '45821955'
CI_PROJECT_NAME: npm-provenance-example
CI_PROJECT_NAMESPACE: strongjz
CI_PROJECT_NAMESPACE_SLUG: strongjz
CI_PROJECT_NAMESPACE_ID: '36018'
CI_PROJECT_PATH: strongjz/npm-provenance-example
CI_PROJECT_PATH_SLUG: strongjz-npm-provenance-example
CI_PROJECT_REPOSITORY_LANGUAGES: javascript,dockerfile
CI_PROJECT_ROOT_NAMESPACE: strongjz
CI_PROJECT_TITLE: npm-provenance-example
CI_PROJECT_URL: https://gitlab.com/strongjz/npm-provenance-example
CI_PROJECT_VISIBILITY: public
CI_REGISTRY: registry.gitlab.com
CI_REGISTRY_IMAGE: registry.gitlab.com/strongjz/npm-provenance-example
CI_REGISTRY_USER: gitlab-ci-token
CI_RUNNER_DESCRIPTION: 3-blue.shared.runners-manager.gitlab.com/default
CI_RUNNER_ID: '12270835'
CI_RUNNER_TAGS: >-
["gce", "east-c", "linux", "ruby", "mysql", "postgres", "mongo",
"git-annex", "shared", "docker", "saas-linux-small-amd64"]
CI_SERVER_HOST: gitlab.com
CI_SERVER_NAME: GitLab
CI_SERVER_PORT: '443'
CI_SERVER_PROTOCOL: https
CI_SERVER_REVISION: 9d4873fd3c5
CI_SERVER_SHELL_SSH_HOST: gitlab.com
CI_SERVER_SHELL_SSH_PORT: '22'
CI_SERVER_URL: https://gitlab.com
CI_SERVER_VERSION: 16.1.0-pre
CI_SERVER_VERSION_MAJOR: '16'
CI_SERVER_VERSION_MINOR: '1'
CI_SERVER_VERSION_PATCH: '0'
CI_TEMPLATE_REGISTRY_HOST: registry.gitlab.com
GITLAB_CI: 'true'
GITLAB_FEATURES: >-
elastic_search,ldap_group_sync,multiple_ldap_servers,seat_link,usage_quotas,zoekt_code_search,repository_size_limit,admin_audit_log,auditor_user,custom_file_templates,custom_project_templates,db_load_balancing,default_branch_protection_restriction_in_groups,extended_audit_events,external_authorization_service_api_management,geo,instance_level_scim,ldap_group_sync_filter,object_storage,pages_size_limit,project_aliases,password_complexity,enterprise_templates,git_abuse_rate_limit,required_ci_templates,runner_maintenance_note,runner_performance_insights,runner_upgrade_management,runner_jobs_statistics
GITLAB_USER_ID: '31705'
GITLAB_USER_LOGIN: strongjz
environment:
name: 3-blue.shared.runners-manager.gitlab.com/default
architecture: linux/amd64
server: https://gitlab.com
project: strongjz/npm-provenance-example
job:
id: '4316132595'
pipeline:
id: '872773336'
ref: .gitlab-ci.yml
metadata:
buildInvocationId: https://gitlab.com/strongjz/npm-provenance-example/-/jobs/4316132595
completeness:
parameters: true
environment: true
materials: false
reproducible: false
materials:
- uri: git+https://gitlab.com/strongjz/npm-provenance-example
digest:
sha1: 6e02e901e936bfac3d4691984dff8c505410cbc3
```
|
https://docs.gitlab.com/ci/lint
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/lint.md
|
2025-08-13
|
doc/ci/yaml
|
[
"doc",
"ci",
"yaml"
] |
lint.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Validate GitLab CI/CD configuration
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use the CI Lint tool to check the validity of GitLab CI/CD configuration.
You can validate the syntax from a `.gitlab-ci.yml` file or any other sample CI/CD configuration.
This tool checks for syntax and logic errors, and can simulate pipeline
creation to try to find more complicated configuration problems.
If you use the [pipeline editor](../pipeline_editor/_index.md), it verifies configuration
syntax automatically.
If you use VS Code, you can validate your CI/CD configuration with the
[GitLab Workflow extension for VS Code](../../editor_extensions/visual_studio_code/_index.md).
## Check CI/CD syntax
The CI lint tool checks the syntax of GitLab CI/CD configuration, including
configuration added with the [`includes` keyword](_index.md#include).
To check CI/CD configuration with the CI lint tool:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline editor**.
1. Select the **Validate** tab.
1. Select **Lint CI/CD sample**.
1. Paste a copy of the CI/CD configuration you want to check into the text box.
1. Select **Validate**.
## Simulate a pipeline
You can simulate the creation of a GitLab CI/CD pipeline to find more complicated issues,
including problems with [`needs`](_index.md#needs) and [`rules`](_index.md#rules)
configuration. A simulation runs as a Git `push` event on the default branch.
Prerequisites:
- You must have [permissions](../../user/permissions.md#project-members-permissions)
to create pipelines on this branch to validate with a simulation.
To simulate a pipeline:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline editor**.
1. Select the **Validate** tab.
1. Select **Lint CI/CD sample**.
1. Paste a copy of the CI/CD configuration you want to check into the text box.
1. Select **Simulate pipeline creation for the default branch**.
1. Select **Validate**.
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Validate GitLab CI/CD configuration
breadcrumbs:
- doc
- ci
- yaml
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use the CI Lint tool to check the validity of GitLab CI/CD configuration.
You can validate the syntax from a `.gitlab-ci.yml` file or any other sample CI/CD configuration.
This tool checks for syntax and logic errors, and can simulate pipeline
creation to try to find more complicated configuration problems.
If you use the [pipeline editor](../pipeline_editor/_index.md), it verifies configuration
syntax automatically.
If you use VS Code, you can validate your CI/CD configuration with the
[GitLab Workflow extension for VS Code](../../editor_extensions/visual_studio_code/_index.md).
## Check CI/CD syntax
The CI lint tool checks the syntax of GitLab CI/CD configuration, including
configuration added with the [`includes` keyword](_index.md#include).
To check CI/CD configuration with the CI lint tool:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline editor**.
1. Select the **Validate** tab.
1. Select **Lint CI/CD sample**.
1. Paste a copy of the CI/CD configuration you want to check into the text box.
1. Select **Validate**.
## Simulate a pipeline
You can simulate the creation of a GitLab CI/CD pipeline to find more complicated issues,
including problems with [`needs`](_index.md#needs) and [`rules`](_index.md#rules)
configuration. A simulation runs as a Git `push` event on the default branch.
Prerequisites:
- You must have [permissions](../../user/permissions.md#project-members-permissions)
to create pipelines on this branch to validate with a simulation.
To simulate a pipeline:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline editor**.
1. Select the **Validate** tab.
1. Select **Lint CI/CD sample**.
1. Paste a copy of the CI/CD configuration you want to check into the text box.
1. Select **Simulate pipeline creation for the default branch**.
1. Select **Validate**.
|
https://docs.gitlab.com/ci/script
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/script.md
|
2025-08-13
|
doc/ci/yaml
|
[
"doc",
"ci",
"yaml"
] |
script.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Scripts and job logs
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can use special syntax in [`script`](_index.md#script) sections to:
- [Split long commands](#split-long-commands) into multiline commands.
- [Use color codes](#add-color-codes-to-script-output) to make job logs easier to review.
- [Create custom collapsible sections](../jobs/job_logs.md#custom-collapsible-sections)
to simplify job log output.
## Use special characters with `script`
Sometimes, `script` commands must be wrapped in single or double quotes.
For example, commands that contain a colon (`:`) must be wrapped in single quotes (`'`).
The YAML parser needs to interpret the text as a string rather than
a "key: value" pair.
For example, this script uses a colon:
```yaml
job:
script:
- curl --request POST --header 'Content-Type: application/json' "https://gitlab.example.com/api/v4/projects"
```
To be considered valid YAML, you must wrap the entire command in single quotes. If
the command already uses single quotes, you should change them to double quotes (`"`)
if possible:
```yaml
job:
script:
- 'curl --request POST --header "Content-Type: application/json" "https://gitlab.example.com/api/v4/projects"'
```
You can verify the syntax is valid with the [CI Lint](lint.md) tool.
Be careful when using these characters as well:
- `{`, `}`, `[`, `]`, `,`, `&`, `*`, `#`, `?`, `|`, `-`, `<`, `>`, `=`, `!`, `%`, `@`, `` ` ``.
## Ignore non-zero exit codes
When script commands return an exit code other than zero, the job fails and further
commands do not execute.
Store the exit code in a variable to avoid this behavior:
```yaml
job:
script:
- exit_code=0
- false || exit_code=$?
- if [ $exit_code -ne 0 ]; then echo "Previous command failed"; fi;
```
## Set a default `before_script` or `after_script` for all jobs
You can use [`before_script`](_index.md#before_script) and [`after_script`](_index.md#after_script)
with [`default`](_index.md#default):
- Use `before_script` with `default` to define a default array of commands that
should run before the `script` commands in all jobs.
- Use `after_script` with default to define a default array of commands
that should run after any job completes or is canceled.
You can overwrite a default by defining a different one in a job. To ignore the default
use `before_script: []` or `after_script: []`:
```yaml
default:
before_script:
- echo "Execute this `before_script` in all jobs by default."
after_script:
- echo "Execute this `after_script` in all jobs by default."
job1:
script:
- echo "These script commands execute after the default `before_script`,"
- echo "and before the default `after_script`."
job2:
before_script:
- echo "Execute this script instead of the default `before_script`."
script:
- echo "This script executes after the job's `before_script`,"
- echo "but the job does not use the default `after_script`."
after_script: []
```
## Skip `after_script` commands if a job is canceled
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/10158) in GitLab 17.0 [with a flag](../../administration/feature_flags/_index.md) named `ci_canceling_status`. Enabled by default. Requires GitLab Runner version 16.11.1.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/460285) in GitLab 17.3. Feature flag `ci_canceling_status` removed.
{{< /history >}}
[`after_script`](_index.md) commands run if a job is canceled while the `before_script`
or `script` section of that job are running.
The job's status in the UI is `canceling` while the `after_script` are executing,
and changes to `canceled` after the `after_script` commands complete. The `$CI_JOB_STATUS`
predefined variable has a value of `canceled` while the `after_script` commands are running.
To prevent `after_script` commands running after canceling a job, configure the `after_script`
section to:
1. Check the `$CI_JOB_STATUS` predefined variable at the start of the `after_script` section.
1. End execution early if the value is `canceled`.
For example:
```yaml
job1:
script:
- my-script.sh
after_script:
- if [ "$CI_JOB_STATUS" == "canceled" ]; then exit 0; fi
- my-after-script.sh
```
## Split long commands
You can split long commands into multiline commands to improve readability with
`|` (literal) and `>` (folded) [YAML multiline block scalar indicators](https://yaml-multiline.info/).
{{< alert type="warning" >}}
If multiple commands are combined into one command string, only the last command's
failure or success is reported.
[Failures from earlier commands are ignored due to a bug](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/25394).
To work around this, run each command as a separate `script` item, or add an `exit 1`
command to each command string.
{{< /alert >}}
You can use the `|` (literal) YAML multiline block scalar indicator to write
commands over multiple lines in the `script` section of a job description.
Each line is treated as a separate command.
Only the first command is repeated in the job log, but additional
commands are still executed:
```yaml
job:
script:
- |
echo "First command line."
echo "Second command line."
echo "Third command line."
```
The previous example renders in the job log as:
```shell
$ echo First command line # collapsed multiline command
First command line
Second command line.
Third command line.
```
The `>` (folded) YAML multiline block scalar indicator treats empty lines between
sections as the start of a new command:
```yaml
job:
script:
- >
echo "First command line
is split over two lines."
echo "Second command line."
```
This behaves similarly to multiline commands without the `>` or `|` block
scalar indicators:
```yaml
job:
script:
- echo "First command line
is split over two lines."
echo "Second command line."
```
The previous two examples render in the job log as:
```shell
$ echo First command line is split over two lines. # collapsed multiline command
First command line is split over two lines.
Second command line.
```
When you omit the `>` or `|` block scalar indicators, GitLab concatenates non-empty
lines to form the command. Make sure the lines can run when concatenated.
<!-- vale gitlab_base.MeaningfulLinkWords = NO -->
[Shell here documents](https://en.wikipedia.org/wiki/Here_document) work with the
`|` and `>` operators as well. The following example transliterates lowercase letters
to upper case:
<!-- vale gitlab_base.MeaningfulLinkWords = YES -->
```yaml
job:
script:
- |
tr a-z A-Z << END_TEXT
one two three
four five six
END_TEXT
```
Results in:
```shell
$ tr a-z A-Z << END_TEXT # collapsed multiline command
ONE TWO THREE
FOUR FIVE SIX
```
## Add color codes to script output
Script output can be colored using [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors),
or by running commands or programs that output ANSI escape codes.
For example, using [Bash with color codes](https://misc.flogisoft.com/bash/tip_colors_and_formatting):
```yaml
job:
script:
- echo -e "\e[31mThis text is red,\e[0m but this text isn't\e[31m however this text is red again."
```
You can define the color codes in Shell environment variables, or even [CI/CD variables](../variables/_index.md#define-a-cicd-variable-in-the-gitlab-ciyml-file),
which makes the commands easier to read and reusable.
For example, using the previous example and environment variables defined in a `before_script`:
```yaml
job:
before_script:
- TXT_RED="\e[31m" && TXT_CLEAR="\e[0m"
script:
- echo -e "${TXT_RED}This text is red,${TXT_CLEAR} but this part isn't${TXT_RED} however this part is again."
- echo "This text is not colored"
```
Or with [PowerShell color codes](https://superuser.com/a/1259916):
```yaml
job:
before_script:
- $esc="$([char]27)"; $TXT_RED="$esc[31m"; $TXT_CLEAR="$esc[0m"
script:
- Write-Host $TXT_RED"This text is red,"$TXT_CLEAR" but this text isn't"$TXT_RED" however this text is red again."
- Write-Host "This text is not colored"
```
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Scripts and job logs
breadcrumbs:
- doc
- ci
- yaml
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can use special syntax in [`script`](_index.md#script) sections to:
- [Split long commands](#split-long-commands) into multiline commands.
- [Use color codes](#add-color-codes-to-script-output) to make job logs easier to review.
- [Create custom collapsible sections](../jobs/job_logs.md#custom-collapsible-sections)
to simplify job log output.
## Use special characters with `script`
Sometimes, `script` commands must be wrapped in single or double quotes.
For example, commands that contain a colon (`:`) must be wrapped in single quotes (`'`).
The YAML parser needs to interpret the text as a string rather than
a "key: value" pair.
For example, this script uses a colon:
```yaml
job:
script:
- curl --request POST --header 'Content-Type: application/json' "https://gitlab.example.com/api/v4/projects"
```
To be considered valid YAML, you must wrap the entire command in single quotes. If
the command already uses single quotes, you should change them to double quotes (`"`)
if possible:
```yaml
job:
script:
- 'curl --request POST --header "Content-Type: application/json" "https://gitlab.example.com/api/v4/projects"'
```
You can verify the syntax is valid with the [CI Lint](lint.md) tool.
Be careful when using these characters as well:
- `{`, `}`, `[`, `]`, `,`, `&`, `*`, `#`, `?`, `|`, `-`, `<`, `>`, `=`, `!`, `%`, `@`, `` ` ``.
## Ignore non-zero exit codes
When script commands return an exit code other than zero, the job fails and further
commands do not execute.
Store the exit code in a variable to avoid this behavior:
```yaml
job:
script:
- exit_code=0
- false || exit_code=$?
- if [ $exit_code -ne 0 ]; then echo "Previous command failed"; fi;
```
## Set a default `before_script` or `after_script` for all jobs
You can use [`before_script`](_index.md#before_script) and [`after_script`](_index.md#after_script)
with [`default`](_index.md#default):
- Use `before_script` with `default` to define a default array of commands that
should run before the `script` commands in all jobs.
- Use `after_script` with default to define a default array of commands
that should run after any job completes or is canceled.
You can overwrite a default by defining a different one in a job. To ignore the default
use `before_script: []` or `after_script: []`:
```yaml
default:
before_script:
- echo "Execute this `before_script` in all jobs by default."
after_script:
- echo "Execute this `after_script` in all jobs by default."
job1:
script:
- echo "These script commands execute after the default `before_script`,"
- echo "and before the default `after_script`."
job2:
before_script:
- echo "Execute this script instead of the default `before_script`."
script:
- echo "This script executes after the job's `before_script`,"
- echo "but the job does not use the default `after_script`."
after_script: []
```
## Skip `after_script` commands if a job is canceled
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/10158) in GitLab 17.0 [with a flag](../../administration/feature_flags/_index.md) named `ci_canceling_status`. Enabled by default. Requires GitLab Runner version 16.11.1.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/460285) in GitLab 17.3. Feature flag `ci_canceling_status` removed.
{{< /history >}}
[`after_script`](_index.md) commands run if a job is canceled while the `before_script`
or `script` section of that job are running.
The job's status in the UI is `canceling` while the `after_script` are executing,
and changes to `canceled` after the `after_script` commands complete. The `$CI_JOB_STATUS`
predefined variable has a value of `canceled` while the `after_script` commands are running.
To prevent `after_script` commands running after canceling a job, configure the `after_script`
section to:
1. Check the `$CI_JOB_STATUS` predefined variable at the start of the `after_script` section.
1. End execution early if the value is `canceled`.
For example:
```yaml
job1:
script:
- my-script.sh
after_script:
- if [ "$CI_JOB_STATUS" == "canceled" ]; then exit 0; fi
- my-after-script.sh
```
## Split long commands
You can split long commands into multiline commands to improve readability with
`|` (literal) and `>` (folded) [YAML multiline block scalar indicators](https://yaml-multiline.info/).
{{< alert type="warning" >}}
If multiple commands are combined into one command string, only the last command's
failure or success is reported.
[Failures from earlier commands are ignored due to a bug](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/25394).
To work around this, run each command as a separate `script` item, or add an `exit 1`
command to each command string.
{{< /alert >}}
You can use the `|` (literal) YAML multiline block scalar indicator to write
commands over multiple lines in the `script` section of a job description.
Each line is treated as a separate command.
Only the first command is repeated in the job log, but additional
commands are still executed:
```yaml
job:
script:
- |
echo "First command line."
echo "Second command line."
echo "Third command line."
```
The previous example renders in the job log as:
```shell
$ echo First command line # collapsed multiline command
First command line
Second command line.
Third command line.
```
The `>` (folded) YAML multiline block scalar indicator treats empty lines between
sections as the start of a new command:
```yaml
job:
script:
- >
echo "First command line
is split over two lines."
echo "Second command line."
```
This behaves similarly to multiline commands without the `>` or `|` block
scalar indicators:
```yaml
job:
script:
- echo "First command line
is split over two lines."
echo "Second command line."
```
The previous two examples render in the job log as:
```shell
$ echo First command line is split over two lines. # collapsed multiline command
First command line is split over two lines.
Second command line.
```
When you omit the `>` or `|` block scalar indicators, GitLab concatenates non-empty
lines to form the command. Make sure the lines can run when concatenated.
<!-- vale gitlab_base.MeaningfulLinkWords = NO -->
[Shell here documents](https://en.wikipedia.org/wiki/Here_document) work with the
`|` and `>` operators as well. The following example transliterates lowercase letters
to upper case:
<!-- vale gitlab_base.MeaningfulLinkWords = YES -->
```yaml
job:
script:
- |
tr a-z A-Z << END_TEXT
one two three
four five six
END_TEXT
```
Results in:
```shell
$ tr a-z A-Z << END_TEXT # collapsed multiline command
ONE TWO THREE
FOUR FIVE SIX
```
## Add color codes to script output
Script output can be colored using [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors),
or by running commands or programs that output ANSI escape codes.
For example, using [Bash with color codes](https://misc.flogisoft.com/bash/tip_colors_and_formatting):
```yaml
job:
script:
- echo -e "\e[31mThis text is red,\e[0m but this text isn't\e[31m however this text is red again."
```
You can define the color codes in Shell environment variables, or even [CI/CD variables](../variables/_index.md#define-a-cicd-variable-in-the-gitlab-ciyml-file),
which makes the commands easier to read and reusable.
For example, using the previous example and environment variables defined in a `before_script`:
```yaml
job:
before_script:
- TXT_RED="\e[31m" && TXT_CLEAR="\e[0m"
script:
- echo -e "${TXT_RED}This text is red,${TXT_CLEAR} but this part isn't${TXT_RED} however this part is again."
- echo "This text is not colored"
```
Or with [PowerShell color codes](https://superuser.com/a/1259916):
```yaml
job:
before_script:
- $esc="$([char]27)"; $TXT_RED="$esc[31m"; $TXT_CLEAR="$esc[0m"
script:
- Write-Host $TXT_RED"This text is red,"$TXT_CLEAR" but this text isn't"$TXT_RED" however this text is red again."
- Write-Host "This text is not colored"
```
|
https://docs.gitlab.com/ci/deprecated_keywords
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/deprecated_keywords.md
|
2025-08-13
|
doc/ci/yaml
|
[
"doc",
"ci",
"yaml"
] |
deprecated_keywords.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Deprecated keywords
| null |
Some CI/CD keywords are deprecated and no longer recommended for use.
{{< alert type="warning" >}}
These keywords are still usable to ensure backwards compatibility,
but could be scheduled for removal in a future major milestone.
{{< /alert >}}
### Globally-defined `image`, `services`, `cache`, `before_script`, `after_script`
Defining `image`, `services`, `cache`, `before_script`, and `after_script` globally is deprecated.
Use [`default`](_index.md#default) instead.
For example:
```yaml
default:
image: ruby:3.0
services:
- docker:dind
cache:
paths: [vendor/]
before_script:
- bundle config set path vendor/bundle
- bundle install
after_script:
- rm -rf tmp/
```
### `only` / `except`
{{< alert type="note" >}}
`only` and `except` are deprecated. To control when to add jobs to pipelines, use [`rules`](_index.md#rules) instead.
{{< /alert >}}
You can use `only` and `except` to control when to add jobs to pipelines.
- Use `only` to define when a job runs.
- Use `except` to define when a job **does not** run.
#### `only:refs` / `except:refs`
{{< alert type="note" >}}
`only:refs` and `except:refs` are deprecated. To use refs, regular expressions, or variables
to control when to add jobs to pipelines, use [`rules:if`](_index.md#rulesif) instead.
{{< /alert >}}
You can use the `only:refs` and `except:refs` keywords to control when to add jobs to a
pipeline based on branch names or pipeline types.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: An array including any number of:
- Branch names, for example `main` or `my-feature-branch`.
- Regular expressions that match against branch names, for example `/^feature-.*/`.
- The following keywords:
| **Value** | **Description** |
| -------------------------|-----------------|
| `api` | For pipelines triggered by the [pipelines API](../../api/pipelines.md#create-a-new-pipeline). |
| `branches` | When the Git reference for a pipeline is a branch. |
| `chat` | For pipelines created by using a [GitLab ChatOps](../chatops/_index.md) command. |
| `external` | When you use CI services other than GitLab. |
| `external_pull_requests` | When an external pull request on GitHub is created or updated (See [Pipelines for external pull requests](../ci_cd_for_external_repos/_index.md#pipelines-for-external-pull-requests)). |
| `merge_requests` | For pipelines created when a merge request is created or updated. Enables [merge request pipelines](../pipelines/merge_request_pipelines.md), [merged results pipelines](../pipelines/merged_results_pipelines.md), and [merge trains](../pipelines/merge_trains.md). |
| `pipelines` | For [multi-project pipelines](../pipelines/downstream_pipelines.md#multi-project-pipelines) created by [using the API with `CI_JOB_TOKEN`](../pipelines/downstream_pipelines.md#trigger-a-multi-project-pipeline-by-using-the-api), or the [`trigger`](_index.md#trigger) keyword. |
| `pushes` | For pipelines triggered by a `git push` event, including for branches and tags. |
| `schedules` | For [scheduled pipelines](../pipelines/schedules.md). |
| `tags` | When the Git reference for a pipeline is a tag. |
| `triggers` | For pipelines created by using a [trigger token](../triggers/_index.md#configure-cicd-jobs-to-run-in-triggered-pipelines). |
| `web` | For pipelines created by selecting **New pipeline** in the GitLab UI, from the project's **Build > Pipelines** section. |
**Example of `only:refs` and `except:refs`**:
```yaml
job1:
script: echo
only:
- main
- /^issue-.*$/
- merge_requests
job2:
script: echo
except:
- main
- /^stable-branch.*$/
- schedules
```
**Additional details**:
- Scheduled pipelines run on specific branches, so jobs configured with `only: branches`
run on scheduled pipelines too. Add `except: schedules` to prevent jobs with `only: branches`
from running on scheduled pipelines.
- `only` or `except` used without any other keywords are equivalent to `only: refs`
or `except: refs`. For example, the following two jobs configurations have the same
behavior:
```yaml
job1:
script: echo
only:
- branches
job2:
script: echo
only:
refs:
- branches
```
- If a job does not use `only`, `except`, or [`rules`](_index.md#rules), then `only` is set to `branches`
and `tags` by default.
For example, `job1` and `job2` are equivalent:
```yaml
job1:
script: echo "test"
job2:
script: echo "test"
only:
- branches
- tags
```
#### `only:variables` / `except:variables`
{{< alert type="note" >}}
`only:variables` and `except:variables` are deprecated. To use refs, regular expressions, or variables
to control when to add jobs to pipelines, use [`rules:if`](_index.md#rulesif) instead.
{{< /alert >}}
You can use the `only:variables` or `except:variables` keywords to control when to add jobs
to a pipeline, based on the status of [CI/CD variables](../variables/_index.md).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- An array of [CI/CD variable expressions](../jobs/job_rules.md#cicd-variable-expressions).
**Example of `only:variables`**:
```yaml
deploy:
script: cap staging deploy
only:
variables:
- $RELEASE == "staging"
- $STAGING
```
#### `only:changes` / `except:changes`
{{< alert type="note" >}}
`only:changes` and `except:changes` are deprecated. To use changed files to control
when to add a job to a pipeline, use [`rules:changes`](_index.md#ruleschanges) instead.
{{< /alert >}}
Use the `changes` keyword with `only` to run a job, or with `except` to skip a job,
when a Git push event modifies a file.
Use `changes` in pipelines with the following refs:
- `branches`
- `external_pull_requests`
- `merge_requests`
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: An array including any number of:
- Paths to files.
- Wildcard paths for:
- Single directories, for example `path/to/directory/*`.
- A directory and all its subdirectories, for example `path/to/directory/**/*`.
- Wildcard [glob](https://en.wikipedia.org/wiki/Glob_(programming)) paths for all files
with the same extension or multiple extensions, for example `*.md` or `path/to/directory/*.{rb,py,sh}`.
- Wildcard paths to files in the root directory, or all directories, wrapped in double quotes.
For example `"*.json"` or `"**/*.json"`.
**Example of `only:changes`**:
```yaml
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
only:
refs:
- branches
changes:
- Dockerfile
- docker/scripts/*
- dockerfiles/**/*
- more_scripts/*.{rb,py,sh}
- "**/*.json"
```
**Additional details**:
- `changes` resolves to `true` if any of the matching files are changed (an `OR` operation).
- Glob patterns are interpreted with Ruby's [`File.fnmatch`](https://docs.ruby-lang.org/en/master/File.html#method-c-fnmatch)
with the [flags](https://docs.ruby-lang.org/en/master/File/Constants.html#module-File::Constants-label-Filename+Globbing+Constants+-28File-3A-3AFNM_-2A-29)
`File::FNM_PATHNAME | File::FNM_DOTMATCH | File::FNM_EXTGLOB`.
- If you use refs other than `branches`, `external_pull_requests`, or `merge_requests`,
`changes` can't determine if a given file is new or old and always returns `true`.
- If you use `only: changes` with other refs, jobs ignore the changes and always run.
- If you use `except: changes` with other refs, jobs ignore the changes and never run.
**Related topics**:
- [Jobs or pipelines can run unexpectedly when using `only: changes`](../jobs/job_troubleshooting.md#jobs-or-pipelines-run-unexpectedly-when-using-changes).
#### `only:kubernetes` / `except:kubernetes`
{{< alert type="note" >}}
`only:kubernetes` and `except:kubernetes` are deprecated. To control if jobs are added to the pipeline
when the Kubernetes service is active in the project, use [`rules:if`](_index.md#rulesif) with the
[`CI_KUBERNETES_ACTIVE`](../variables/predefined_variables.md) predefined CI/CD variable instead.
{{< /alert >}}
Use `only:kubernetes` or `except:kubernetes` to control if jobs are added to the pipeline
when the Kubernetes service is active in the project.
**Keyword type**: Job-specific. You can use it only as part of a job.
**Supported values**:
- The `kubernetes` strategy accepts only the `active` keyword.
**Example of `only:kubernetes`**:
```yaml
deploy:
only:
kubernetes: active
```
In this example, the `deploy` job runs only when the Kubernetes service is active
in the project.
### `publish` keyword and `pages` job name for GitLab Pages
The job-level `publish` keyword and the `pages` job name for GitLab Pages deployment jobs are deprecated.
To control the pages deployment, use the [`pages`](_index.md#pages) and [`pages.publish`](_index.md#pagespublish)
keywords instead.
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Deprecated keywords
breadcrumbs:
- doc
- ci
- yaml
---
Some CI/CD keywords are deprecated and no longer recommended for use.
{{< alert type="warning" >}}
These keywords are still usable to ensure backwards compatibility,
but could be scheduled for removal in a future major milestone.
{{< /alert >}}
### Globally-defined `image`, `services`, `cache`, `before_script`, `after_script`
Defining `image`, `services`, `cache`, `before_script`, and `after_script` globally is deprecated.
Use [`default`](_index.md#default) instead.
For example:
```yaml
default:
image: ruby:3.0
services:
- docker:dind
cache:
paths: [vendor/]
before_script:
- bundle config set path vendor/bundle
- bundle install
after_script:
- rm -rf tmp/
```
### `only` / `except`
{{< alert type="note" >}}
`only` and `except` are deprecated. To control when to add jobs to pipelines, use [`rules`](_index.md#rules) instead.
{{< /alert >}}
You can use `only` and `except` to control when to add jobs to pipelines.
- Use `only` to define when a job runs.
- Use `except` to define when a job **does not** run.
#### `only:refs` / `except:refs`
{{< alert type="note" >}}
`only:refs` and `except:refs` are deprecated. To use refs, regular expressions, or variables
to control when to add jobs to pipelines, use [`rules:if`](_index.md#rulesif) instead.
{{< /alert >}}
You can use the `only:refs` and `except:refs` keywords to control when to add jobs to a
pipeline based on branch names or pipeline types.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: An array including any number of:
- Branch names, for example `main` or `my-feature-branch`.
- Regular expressions that match against branch names, for example `/^feature-.*/`.
- The following keywords:
| **Value** | **Description** |
| -------------------------|-----------------|
| `api` | For pipelines triggered by the [pipelines API](../../api/pipelines.md#create-a-new-pipeline). |
| `branches` | When the Git reference for a pipeline is a branch. |
| `chat` | For pipelines created by using a [GitLab ChatOps](../chatops/_index.md) command. |
| `external` | When you use CI services other than GitLab. |
| `external_pull_requests` | When an external pull request on GitHub is created or updated (See [Pipelines for external pull requests](../ci_cd_for_external_repos/_index.md#pipelines-for-external-pull-requests)). |
| `merge_requests` | For pipelines created when a merge request is created or updated. Enables [merge request pipelines](../pipelines/merge_request_pipelines.md), [merged results pipelines](../pipelines/merged_results_pipelines.md), and [merge trains](../pipelines/merge_trains.md). |
| `pipelines` | For [multi-project pipelines](../pipelines/downstream_pipelines.md#multi-project-pipelines) created by [using the API with `CI_JOB_TOKEN`](../pipelines/downstream_pipelines.md#trigger-a-multi-project-pipeline-by-using-the-api), or the [`trigger`](_index.md#trigger) keyword. |
| `pushes` | For pipelines triggered by a `git push` event, including for branches and tags. |
| `schedules` | For [scheduled pipelines](../pipelines/schedules.md). |
| `tags` | When the Git reference for a pipeline is a tag. |
| `triggers` | For pipelines created by using a [trigger token](../triggers/_index.md#configure-cicd-jobs-to-run-in-triggered-pipelines). |
| `web` | For pipelines created by selecting **New pipeline** in the GitLab UI, from the project's **Build > Pipelines** section. |
**Example of `only:refs` and `except:refs`**:
```yaml
job1:
script: echo
only:
- main
- /^issue-.*$/
- merge_requests
job2:
script: echo
except:
- main
- /^stable-branch.*$/
- schedules
```
**Additional details**:
- Scheduled pipelines run on specific branches, so jobs configured with `only: branches`
run on scheduled pipelines too. Add `except: schedules` to prevent jobs with `only: branches`
from running on scheduled pipelines.
- `only` or `except` used without any other keywords are equivalent to `only: refs`
or `except: refs`. For example, the following two jobs configurations have the same
behavior:
```yaml
job1:
script: echo
only:
- branches
job2:
script: echo
only:
refs:
- branches
```
- If a job does not use `only`, `except`, or [`rules`](_index.md#rules), then `only` is set to `branches`
and `tags` by default.
For example, `job1` and `job2` are equivalent:
```yaml
job1:
script: echo "test"
job2:
script: echo "test"
only:
- branches
- tags
```
#### `only:variables` / `except:variables`
{{< alert type="note" >}}
`only:variables` and `except:variables` are deprecated. To use refs, regular expressions, or variables
to control when to add jobs to pipelines, use [`rules:if`](_index.md#rulesif) instead.
{{< /alert >}}
You can use the `only:variables` or `except:variables` keywords to control when to add jobs
to a pipeline, based on the status of [CI/CD variables](../variables/_index.md).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- An array of [CI/CD variable expressions](../jobs/job_rules.md#cicd-variable-expressions).
**Example of `only:variables`**:
```yaml
deploy:
script: cap staging deploy
only:
variables:
- $RELEASE == "staging"
- $STAGING
```
#### `only:changes` / `except:changes`
{{< alert type="note" >}}
`only:changes` and `except:changes` are deprecated. To use changed files to control
when to add a job to a pipeline, use [`rules:changes`](_index.md#ruleschanges) instead.
{{< /alert >}}
Use the `changes` keyword with `only` to run a job, or with `except` to skip a job,
when a Git push event modifies a file.
Use `changes` in pipelines with the following refs:
- `branches`
- `external_pull_requests`
- `merge_requests`
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: An array including any number of:
- Paths to files.
- Wildcard paths for:
- Single directories, for example `path/to/directory/*`.
- A directory and all its subdirectories, for example `path/to/directory/**/*`.
- Wildcard [glob](https://en.wikipedia.org/wiki/Glob_(programming)) paths for all files
with the same extension or multiple extensions, for example `*.md` or `path/to/directory/*.{rb,py,sh}`.
- Wildcard paths to files in the root directory, or all directories, wrapped in double quotes.
For example `"*.json"` or `"**/*.json"`.
**Example of `only:changes`**:
```yaml
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
only:
refs:
- branches
changes:
- Dockerfile
- docker/scripts/*
- dockerfiles/**/*
- more_scripts/*.{rb,py,sh}
- "**/*.json"
```
**Additional details**:
- `changes` resolves to `true` if any of the matching files are changed (an `OR` operation).
- Glob patterns are interpreted with Ruby's [`File.fnmatch`](https://docs.ruby-lang.org/en/master/File.html#method-c-fnmatch)
with the [flags](https://docs.ruby-lang.org/en/master/File/Constants.html#module-File::Constants-label-Filename+Globbing+Constants+-28File-3A-3AFNM_-2A-29)
`File::FNM_PATHNAME | File::FNM_DOTMATCH | File::FNM_EXTGLOB`.
- If you use refs other than `branches`, `external_pull_requests`, or `merge_requests`,
`changes` can't determine if a given file is new or old and always returns `true`.
- If you use `only: changes` with other refs, jobs ignore the changes and always run.
- If you use `except: changes` with other refs, jobs ignore the changes and never run.
**Related topics**:
- [Jobs or pipelines can run unexpectedly when using `only: changes`](../jobs/job_troubleshooting.md#jobs-or-pipelines-run-unexpectedly-when-using-changes).
#### `only:kubernetes` / `except:kubernetes`
{{< alert type="note" >}}
`only:kubernetes` and `except:kubernetes` are deprecated. To control if jobs are added to the pipeline
when the Kubernetes service is active in the project, use [`rules:if`](_index.md#rulesif) with the
[`CI_KUBERNETES_ACTIVE`](../variables/predefined_variables.md) predefined CI/CD variable instead.
{{< /alert >}}
Use `only:kubernetes` or `except:kubernetes` to control if jobs are added to the pipeline
when the Kubernetes service is active in the project.
**Keyword type**: Job-specific. You can use it only as part of a job.
**Supported values**:
- The `kubernetes` strategy accepts only the `active` keyword.
**Example of `only:kubernetes`**:
```yaml
deploy:
only:
kubernetes: active
```
In this example, the `deploy` job runs only when the Kubernetes service is active
in the project.
### `publish` keyword and `pages` job name for GitLab Pages
The job-level `publish` keyword and the `pages` job name for GitLab Pages deployment jobs are deprecated.
To control the pages deployment, use the [`pages`](_index.md#pages) and [`pages.publish`](_index.md#pagespublish)
keywords instead.
|
https://docs.gitlab.com/ci/script_troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/script_troubleshooting.md
|
2025-08-13
|
doc/ci/yaml
|
[
"doc",
"ci",
"yaml"
] |
script_troubleshooting.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting scripts and job logs
| null |
## `Syntax is incorrect` in scripts that use `:`
If you use a colon (`:`) in a script, GitLab might output:
- `Syntax is incorrect`
- `script config should be a string or a nested array of strings up to 10 levels deep`
For example, if you use `"PRIVATE-TOKEN: ${PRIVATE_TOKEN}"` as part of a cURL command:
```yaml
pages-job:
stage: deploy
script:
- curl --header 'PRIVATE-TOKEN: ${PRIVATE_TOKEN}' "https://gitlab.example.com/api/v4/projects"
environment: production
```
The YAML parser thinks the `:` defines a YAML keyword, and outputs the
`Syntax is incorrect` error.
To use commands that contain a colon, you should wrap the whole command
in single quotes. You might need to change existing single quotes (`'`) into double quotes (`"`):
```yaml
pages-job:
stage: deploy
script:
- 'curl --header "PRIVATE-TOKEN: ${PRIVATE_TOKEN}" "https://gitlab.example.com/api/v4/projects"'
environment: production
```
## Job does not fail when using `&&` in a script
If you use `&&` to combine two commands together in a single script line, the job
might return as successful, even if one of the commands failed. For example:
```yaml
job-does-not-fail:
script:
- invalid-command xyz && invalid-command abc
- echo $?
- echo "The job should have failed already, but this is executed unexpectedly."
```
The `&&` operator returns an exit code of `0` even though the two commands failed,
and the job continues to run. To force the script to exit when either command fails,
enclose the entire line in parentheses:
```yaml
job-fails:
script:
- (invalid-command xyz && invalid-command abc)
- echo "The job failed already, and this is not executed."
```
## Multiline commands not preserved by folded YAML multiline block scalar
If you use the `- >` folded YAML multiline block scalar to split long commands,
additional indentation causes the lines to be processed as individual commands.
For example:
```yaml
script:
- >
RESULT=$(curl --silent
--header
"Authorization: Bearer $CI_JOB_TOKEN"
"${CI_API_V4_URL}/job"
)
```
This fails as the indentation causes the line breaks to be preserved:
```plaintext
$ RESULT=$(curl --silent # collapsed multi-line command
curl: no URL specified!
curl: try 'curl --help' or 'curl --manual' for more information
/bin/bash: line 149: --header: command not found
/bin/bash: line 150: https://gitlab.example.com/api/v4/job: No such file or directory
```
Resolve this by either:
- Removing the extra indentation:
```yaml
script:
- >
RESULT=$(curl --silent
--header
"Authorization: Bearer $CI_JOB_TOKEN"
"${CI_API_V4_URL}/job"
)
```
- Modifying the script so the extra line breaks are handled, for example using shell line continuation:
```yaml
script:
- >
RESULT=$(curl --silent \
--header \
"Authorization: Bearer $CI_JOB_TOKEN" \
"${CI_API_V4_URL}/job")
```
## Job log output is not formatted as expected or contains unexpected characters
Sometimes the formatting in the job log displays incorrectly with tools that rely
on the `TERM` environment variable for coloring or formatting. For example, with the `mypy` command:

GitLab Runner runs the container's shell in non-interactive mode, so the shell's `TERM`
environment variable is set to `dumb`. To fix the formatting for these tools, you can:
- Add an additional script line to set `TERM=ansi` in the shell's environment before running the command.
- Add a `TERM` [CI/CD variable](../variables/_index.md) with a value of `ansi`.
## `after_script` section execution stops early and incorrect `$CI_JOB_STATUS` values
In GitLab Runner 16.9.0 to 16.11.0:
- The `after_script` section execution sometimes stops too early.
- The status of the `$CI_JOB_STATUS` predefined variable is
[incorrectly set as `failed` while the job is canceling](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/37485).
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting scripts and job logs
breadcrumbs:
- doc
- ci
- yaml
---
## `Syntax is incorrect` in scripts that use `:`
If you use a colon (`:`) in a script, GitLab might output:
- `Syntax is incorrect`
- `script config should be a string or a nested array of strings up to 10 levels deep`
For example, if you use `"PRIVATE-TOKEN: ${PRIVATE_TOKEN}"` as part of a cURL command:
```yaml
pages-job:
stage: deploy
script:
- curl --header 'PRIVATE-TOKEN: ${PRIVATE_TOKEN}' "https://gitlab.example.com/api/v4/projects"
environment: production
```
The YAML parser thinks the `:` defines a YAML keyword, and outputs the
`Syntax is incorrect` error.
To use commands that contain a colon, you should wrap the whole command
in single quotes. You might need to change existing single quotes (`'`) into double quotes (`"`):
```yaml
pages-job:
stage: deploy
script:
- 'curl --header "PRIVATE-TOKEN: ${PRIVATE_TOKEN}" "https://gitlab.example.com/api/v4/projects"'
environment: production
```
## Job does not fail when using `&&` in a script
If you use `&&` to combine two commands together in a single script line, the job
might return as successful, even if one of the commands failed. For example:
```yaml
job-does-not-fail:
script:
- invalid-command xyz && invalid-command abc
- echo $?
- echo "The job should have failed already, but this is executed unexpectedly."
```
The `&&` operator returns an exit code of `0` even though the two commands failed,
and the job continues to run. To force the script to exit when either command fails,
enclose the entire line in parentheses:
```yaml
job-fails:
script:
- (invalid-command xyz && invalid-command abc)
- echo "The job failed already, and this is not executed."
```
## Multiline commands not preserved by folded YAML multiline block scalar
If you use the `- >` folded YAML multiline block scalar to split long commands,
additional indentation causes the lines to be processed as individual commands.
For example:
```yaml
script:
- >
RESULT=$(curl --silent
--header
"Authorization: Bearer $CI_JOB_TOKEN"
"${CI_API_V4_URL}/job"
)
```
This fails as the indentation causes the line breaks to be preserved:
```plaintext
$ RESULT=$(curl --silent # collapsed multi-line command
curl: no URL specified!
curl: try 'curl --help' or 'curl --manual' for more information
/bin/bash: line 149: --header: command not found
/bin/bash: line 150: https://gitlab.example.com/api/v4/job: No such file or directory
```
Resolve this by either:
- Removing the extra indentation:
```yaml
script:
- >
RESULT=$(curl --silent
--header
"Authorization: Bearer $CI_JOB_TOKEN"
"${CI_API_V4_URL}/job"
)
```
- Modifying the script so the extra line breaks are handled, for example using shell line continuation:
```yaml
script:
- >
RESULT=$(curl --silent \
--header \
"Authorization: Bearer $CI_JOB_TOKEN" \
"${CI_API_V4_URL}/job")
```
## Job log output is not formatted as expected or contains unexpected characters
Sometimes the formatting in the job log displays incorrectly with tools that rely
on the `TERM` environment variable for coloring or formatting. For example, with the `mypy` command:

GitLab Runner runs the container's shell in non-interactive mode, so the shell's `TERM`
environment variable is set to `dumb`. To fix the formatting for these tools, you can:
- Add an additional script line to set `TERM=ansi` in the shell's environment before running the command.
- Add a `TERM` [CI/CD variable](../variables/_index.md) with a value of `ansi`.
## `after_script` section execution stops early and incorrect `$CI_JOB_STATUS` values
In GitLab Runner 16.9.0 to 16.11.0:
- The `after_script` section execution sometimes stops too early.
- The status of the `$CI_JOB_STATUS` predefined variable is
[incorrectly set as `failed` while the job is canceling](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/37485).
|
https://docs.gitlab.com/ci/yaml
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/_index.md
|
2025-08-13
|
doc/ci/yaml
|
[
"doc",
"ci",
"yaml"
] |
_index.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
CI/CD YAML syntax reference
|
Pipeline configuration keywords, syntax, examples, and inputs.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
This document lists the configuration options for the GitLab `.gitlab-ci.yml` file.
This file is where you define the CI/CD jobs that make up your pipeline.
- If you are already familiar with [basic CI/CD concepts](../_index.md), try creating
your own `.gitlab-ci.yml` file by following a tutorial that demonstrates a [simple](../quick_start/_index.md)
or [complex](../quick_start/tutorial.md) pipeline.
- For a collection of examples, see [GitLab CI/CD examples](../examples/_index.md).
- To view a large `.gitlab-ci.yml` file used in an enterprise, see the
[`.gitlab-ci.yml` file for `gitlab`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab-ci.yml).
When you are editing your `.gitlab-ci.yml` file, you can validate it with the
[CI Lint](lint.md) tool.
<!--
If you are editing content on this page, follow the instructions for documenting keywords:
https://docs.gitlab.com/development/cicd/cicd_reference_documentation_guide/
-->
## Keywords
A GitLab CI/CD pipeline configuration includes:
- [Global keywords](#global-keywords) that configure pipeline behavior:
| Keyword | Description |
|-------------------------|:------------|
| [`default`](#default) | Custom default values for job keywords. |
| [`include`](#include) | Import configuration from other YAML files. |
| [`stages`](#stages) | The names and order of the pipeline stages. |
| [`workflow`](#workflow) | Control what types of pipeline run. |
- [Header keywords](#header-keywords)
| Keyword | Description |
|-----------------|:------------|
| [`spec`](#spec) | Define specifications for external configuration files. |
- [Jobs](../jobs/_index.md) configured with [job keywords](#job-keywords):
| Keyword | Description |
|:----------------------------------------------|:------------|
| [`after_script`](#after_script) | Override a set of commands that are executed after job. |
| [`allow_failure`](#allow_failure) | Allow job to fail. A failed job does not cause the pipeline to fail. |
| [`artifacts`](#artifacts) | List of files and directories to attach to a job on success. |
| [`before_script`](#before_script) | Override a set of commands that are executed before job. |
| [`cache`](#cache) | List of files that should be cached between subsequent runs. |
| [`coverage`](#coverage) | Code coverage settings for a given job. |
| [`dast_configuration`](#dast_configuration) | Use configuration from DAST profiles on a job level. |
| [`dependencies`](#dependencies) | Restrict which artifacts are passed to a specific job by providing a list of jobs to fetch artifacts from. |
| [`environment`](#environment) | Name of an environment to which the job deploys. |
| [`extends`](#extends) | Configuration entries that this job inherits from. |
| [`identity`](#identity) | Authenticate with third party services using identity federation. |
| [`image`](#image) | Use Docker images. |
| [`inherit`](#inherit) | Select which global defaults all jobs inherit. |
| [`interruptible`](#interruptible) | Defines if a job can be canceled when made redundant by a newer run. |
| [`manual_confirmation`](#manual_confirmation) | Define a custom confirmation message for a manual job. |
| [`needs`](#needs) | Execute jobs earlier than the stage ordering. |
| [`pages`](#pages) | Upload the result of a job to use with GitLab Pages. |
| [`parallel`](#parallel) | How many instances of a job should be run in parallel. |
| [`release`](#release) | Instructs the runner to generate a [release](../../user/project/releases/_index.md) object. |
| [`resource_group`](#resource_group) | Limit job concurrency. |
| [`retry`](#retry) | When and how many times a job can be auto-retried in case of a failure. |
| [`rules`](#rules) | List of conditions to evaluate and determine selected attributes of a job, and whether or not it's created. |
| [`script`](#script) | Shell script that is executed by a runner. |
| [`run`](#run) | Run configuration that is executed by a runner. |
| [`secrets`](#secrets) | The CI/CD secrets the job needs. |
| [`services`](#services) | Use Docker services images. |
| [`stage`](#stage) | Defines a job stage. |
| [`tags`](#tags) | List of tags that are used to select a runner. |
| [`timeout`](#timeout) | Define a custom job-level timeout that takes precedence over the project-wide setting. |
| [`trigger`](#trigger) | Defines a downstream pipeline trigger. |
| [`when`](#when) | When to run job. |
- [CI/CD variables](#variables)
| Keyword | Description |
|:------------------------------------------|:------------|
| [Default `variables`](#default-variables) | Define default CI/CD variables for all jobs in the pipeline. |
| [Job `variables`](#job-variables) | Define CI/CD variables for individual jobs. |
- [Deprecated keywords](deprecated_keywords.md) that are no longer recommended for use.
---
## Global keywords
Some keywords are not defined in a job. These keywords control pipeline behavior
or import additional pipeline configuration.
---
### `default`
{{< history >}}
- Support for `id_tokens` [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/419750) in GitLab 16.4.
{{< /history >}}
You can set global defaults for some keywords. Each default keyword is copied to every job
that doesn't already have it defined. If the job already has a keyword defined, that default
is not used.
**Keyword type**: Global keyword.
**Supported values**: These keywords can have custom defaults:
- [`after_script`](#after_script)
- [`artifacts`](#artifacts)
- [`before_script`](#before_script)
- [`cache`](#cache)
- [`hooks`](#hooks)
- [`id_tokens`](#id_tokens)
- [`image`](#image)
- [`interruptible`](#interruptible)
- [`retry`](#retry)
- [`services`](#services)
- [`tags`](#tags)
- [`timeout`](#timeout), though due to [issue 213634](https://gitlab.com/gitlab-org/gitlab/-/issues/213634)
this keyword has no effect.
**Example of `default`**:
```yaml
default:
image: ruby:3.0
retry: 2
rspec:
script: bundle exec rspec
rspec 2.7:
image: ruby:2.7
script: bundle exec rspec
```
In this example:
- `image: ruby:3.0` and `retry: 2` are the default keywords for all jobs in the pipeline.
- The `rspec` job does not have `image` or `retry` defined, so it uses the defaults of
`image: ruby:3.0` and `retry: 2`.
- The `rspec 2.7` job does not have `retry` defined, but it does have `image` explicitly defined.
It uses the default `retry: 2`, but ignores the default `image` and uses the `image: ruby:2.7`
defined in the job.
**Additional details**:
- Control inheritance of default keywords in jobs with [`inherit:default`](#inheritdefault).
- Global defaults are not passed to [downstream pipelines](../pipelines/downstream_pipelines.md),
which run independently of the upstream pipeline that triggered the downstream pipeline.
---
### `include`
Use `include` to include external YAML files in your CI/CD configuration.
You can split one long `.gitlab-ci.yml` file into multiple files to increase readability,
or reduce duplication of the same configuration in multiple places.
You can also store template files in a central repository and include them in projects.
The `include` files are:
- Merged with those in the `.gitlab-ci.yml` file.
- Always evaluated first and then merged with the content of the `.gitlab-ci.yml` file,
regardless of the position of the `include` keyword.
The time limit to resolve all files is 30 seconds.
**Keyword type**: Global keyword.
**Supported values**: The `include` subkeys:
- [`include:component`](#includecomponent)
- [`include:local`](#includelocal)
- [`include:project`](#includeproject)
- [`include:remote`](#includeremote)
- [`include:template`](#includetemplate)
And optionally:
- [`include:inputs`](#includeinputs)
- [`include:rules`](#includerules)
- [`include:integrity`](#includeintegrity)
**Additional details**:
- Only [certain CI/CD variables](includes.md#use-variables-with-include) can be used
with `include` keywords.
- Use merging to customize and override included CI/CD configurations with local
- You can override included configuration by having the same job name or global keyword
in the `.gitlab-ci.yml` file. The two configurations are merged together, and the
configuration in the `.gitlab-ci.yml` file takes precedence over the included configuration.
- If you rerun a:
- Job, the `include` files are not fetched again. All jobs in a pipeline use the configuration
fetched when the pipeline was created. Any changes to the source `include` files
do not affect job reruns.
- Pipeline, the `include` files are fetched again. If they changed after the last
pipeline run, the new pipeline uses the changed configuration.
- You can have up to 150 includes per pipeline by default, including [nested](includes.md#use-nested-includes). Additionally:
- In [GitLab 16.0 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/207270) users on GitLab Self-Managed can
change the [maximum includes](../../administration/settings/continuous_integration.md#set-maximum-includes) value.
- In [GitLab 15.10 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/367150) you can have up to 150 includes.
In nested includes, the same file can be included multiple times, but duplicated includes
count towards the limit.
- From [GitLab 14.9 to GitLab 15.9](https://gitlab.com/gitlab-org/gitlab/-/issues/28987), you can have up to 100 includes.
The same file can be included multiple times in nested includes, but duplicates are ignored.
---
#### `include:component`
Use `include:component` to add a [CI/CD component](../components/_index.md) to the
pipeline configuration.
**Keyword type**: Global keyword.
**Supported values**: The full address of the CI/CD component, formatted as
`<fully-qualified-domain-name>/<project-path>/<component-name>@<specific-version>`.
**Example of `include:component`**:
```yaml
include:
- component: $CI_SERVER_FQDN/my-org/security-components/secret-detection@1.0
```
**Related topics**:
- [Use a CI/CD component](../components/_index.md#use-a-component).
---
#### `include:local`
Use `include:local` to include a file that is in the same repository and branch as the configuration file containing the `include` keyword.
Use `include:local` instead of symbolic links.
**Keyword type**: Global keyword.
**Supported values**:
A full path relative to the root directory (`/`):
- The YAML file must have the extension `.yml` or `.yaml`.
- You can [use `*` and `**` wildcards in the file path](includes.md#use-includelocal-with-wildcard-file-paths).
- You can use [certain CI/CD variables](includes.md#use-variables-with-include).
**Example of `include:local`**:
```yaml
include:
- local: '/templates/.gitlab-ci-template.yml'
```
You can also use shorter syntax to define the path:
```yaml
include: '.gitlab-ci-production.yml'
```
**Additional details**:
- The `.gitlab-ci.yml` file and the local file must be on the same branch.
- You can't include local files through Git submodules paths.
- `include` configuration is always evaluated based on the location of the file
containing the `include` keyword, not the project running the pipeline. If a
[nested `include`](includes.md#use-nested-includes) is in a configuration file
in a different project, `include: local` checks that other project for the file.
---
#### `include:project`
To include files from another private project on the same GitLab instance,
use `include:project` and `include:file`.
**Keyword type**: Global keyword.
**Supported values**:
- `include:project`: The full GitLab project path.
- `include:file` A full file path, or array of file paths, relative to the root directory (`/`).
The YAML files must have the `.yml` or `.yaml` extension.
- `include:ref`: Optional. The ref to retrieve the file from. Defaults to the `HEAD` of the project
when not specified.
- You can use [certain CI/CD variables](includes.md#use-variables-with-include).
**Example of `include:project`**:
```yaml
include:
- project: 'my-group/my-project'
file: '/templates/.gitlab-ci-template.yml'
- project: 'my-group/my-subgroup/my-project-2'
file:
- '/templates/.builds.yml'
- '/templates/.tests.yml'
```
You can also specify a `ref`:
```yaml
include:
- project: 'my-group/my-project'
ref: main # Git branch
file: '/templates/.gitlab-ci-template.yml'
- project: 'my-group/my-project'
ref: v1.0.0 # Git Tag
file: '/templates/.gitlab-ci-template.yml'
- project: 'my-group/my-project'
ref: 787123b47f14b552955ca2786bc9542ae66fee5b # Git SHA
file: '/templates/.gitlab-ci-template.yml'
```
**Additional details**:
- `include` configuration is always evaluated based on the location of the file
containing the `include` keyword, not the project running the pipeline. If a
[nested `include`](includes.md#use-nested-includes) is in a configuration file
in a different project, `include: local` checks that other project for the file.
- When the pipeline starts, the `.gitlab-ci.yml` file configuration included by all methods is evaluated.
The configuration is a snapshot in time and persists in the database. GitLab does not reflect any changes to
the referenced `.gitlab-ci.yml` file configuration until the next pipeline starts.
- When you include a YAML file from another private project, the user running the pipeline
must be a member of both projects and have the appropriate permissions to run pipelines.
A `not found or access denied` error may be displayed if the user does not have access to any of the included files.
- Be careful when including another project's CI/CD configuration file. No pipelines or notifications trigger when CI/CD configuration files change.
From a security perspective, this is similar to pulling a third-party dependency. For the `ref`, consider:
- Using a specific SHA hash, which should be the most stable option. Use the
full 40-character SHA hash to ensure the desired commit is referenced, because
using a short SHA hash for the `ref` might be ambiguous.
- Applying both [protected branch](../../user/project/repository/branches/protected.md) and [protected tag](../../user/project/protected_tags.md#prevent-tag-creation-with-the-same-name-as-branches) rules to
the `ref` in the other project. Protected tags and branches are more likely to pass through change management before changing.
---
#### `include:remote`
Use `include:remote` with a full URL to include a file from a different location.
**Keyword type**: Global keyword.
**Supported values**:
A public URL accessible by an HTTP/HTTPS `GET` request:
- Authentication with the remote URL is not supported.
- The YAML file must have the extension `.yml` or `.yaml`.
- You can use [certain CI/CD variables](includes.md#use-variables-with-include).
**Example of `include:remote`**:
```yaml
include:
- remote: 'https://gitlab.com/example-project/-/raw/main/.gitlab-ci.yml'
```
**Additional details**:
- All [nested includes](includes.md#use-nested-includes) are executed without context as a public user,
so you can only include public projects or templates. No variables are available in the `include` section of nested includes.
- Be careful when including another project's CI/CD configuration file. No pipelines or notifications trigger
when the other project's files change. From a security perspective, this is similar to
pulling a third-party dependency. To verify the integrity of the included file, consider using the [`integrity`](#includeintegrity) keyword.
If you link to another GitLab project you own, consider the use of both
[protected branches](../../user/project/repository/branches/protected.md) and [protected tags](../../user/project/protected_tags.md#prevent-tag-creation-with-the-same-name-as-branches)
to enforce change management rules.
---
#### `include:template`
Use `include:template` to include [`.gitlab-ci.yml` templates](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates).
**Keyword type**: Global keyword.
**Supported values**:
A [CI/CD template](../examples/_index.md#cicd-templates):
- All templates can be viewed in [`lib/gitlab/ci/templates`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates).
Not all templates are designed to be used with `include:template`, so check template
comments before using one.
- You can use [certain CI/CD variables](includes.md#use-variables-with-include).
**Example of `include:template`**:
```yaml
# File sourced from the GitLab template collection
include:
- template: Auto-DevOps.gitlab-ci.yml
```
Multiple `include:template` files:
```yaml
include:
- template: Android-Fastlane.gitlab-ci.yml
- template: Auto-DevOps.gitlab-ci.yml
```
**Additional details**:
- All [nested includes](includes.md#use-nested-includes) are executed without context as a public user,
so you can only include public projects or templates. No variables are available in the `include` section of nested includes.
---
#### `include:inputs`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/391331) in GitLab 15.11 as a beta feature.
- [Made generally available](https://gitlab.com/gitlab-com/www-gitlab-com/-/merge_requests/134062) in GitLab 17.0.
{{< /history >}}
Use `include:inputs` to set the values for input parameters when the included configuration
uses [`spec:inputs`](#specinputs) and is added to the pipeline.
**Keyword type**: Global keyword.
**Supported values**: A string, numeric value, or boolean.
**Example of `include:inputs`**:
```yaml
include:
- local: 'custom_configuration.yml'
inputs:
website: "My website"
```
In this example:
- The configuration contained in `custom_configuration.yml` is added to the pipeline,
with a `website` input set to a value of `My website` for the included configuration.
**Additional details**:
- If the included configuration file uses [`spec:inputs:type`](#specinputstype),
the input value must match the defined type.
- If the included configuration file uses [`spec:inputs:options`](#specinputsoptions),
the input value must match one of the listed options.
**Related topics**:
- [Set input values when using `include`](../inputs/_index.md#for-configuration-added-with-include).
---
#### `include:rules`
You can use [`rules`](#rules) with `include` to conditionally include other configuration files.
**Keyword type**: Global keyword.
**Supported values**: These `rules` subkeys:
- [`rules:if`](#rulesif).
- [`rules:exists`](#rulesexists).
- [`rules:changes`](#ruleschanges).
Some [CI/CD variables are supported](includes.md#use-variables-with-include).
**Example of `include:rules`**:
```yaml
include:
- local: build_jobs.yml
rules:
- if: $INCLUDE_BUILDS == "true"
test-job:
stage: test
script: echo "This is a test job"
```
In this example, if the `INCLUDE_BUILDS` variable is:
- `true`, the `build_jobs.yml` configuration is included in the pipeline.
- Not `true` or does not exist, the `build_jobs.yml` configuration is not included in the pipeline.
**Related topics**:
- Examples of using `include` with:
- [`rules:if`](includes.md#include-with-rulesif).
- [`rules:changes`](includes.md#include-with-ruleschanges).
- [`rules:exists`](includes.md#include-with-rulesexists).
---
#### `include:integrity`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/178593) in GitLab 17.9.
{{< /history >}}
Use `integrity` with `include:remote` to specifiy a SHA256 hash of the included remote file.
If `integrity` does not match the actual content, the remote file is not processed
and the pipeline fails.
**Keyword type**: Global keyword.
**Supported values**: Base64-encoded SHA256 hash of the included content.
**Example of `include:integrity`**:
```yaml
include:
- remote: 'https://gitlab.com/example-project/-/raw/main/.gitlab-ci.yml'
integrity: 'sha256-L3/GAoKaw0Arw6hDCKeKQlV1QPEgHYxGBHsH4zG1IY8='
```
---
### `stages`
{{< history >}}
- Support for nested array of strings [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/439451) in GitLab 16.9.
{{< /history >}}
Use `stages` to define stages that contain groups of jobs. Use [`stage`](#stage)
in a job to configure the job to run in a specific stage.
If `stages` is not defined in the `.gitlab-ci.yml` file, the default pipeline stages are:
- [`.pre`](#stage-pre)
- `build`
- `test`
- `deploy`
- [`.post`](#stage-post)
The order of the items in `stages` defines the execution order for jobs:
- Jobs in the same stage run in parallel.
- Jobs in the next stage run after the jobs from the previous stage complete successfully.
If a pipeline contains only jobs in the `.pre` or `.post` stages, it does not run.
There must be at least one other job in a different stage.
**Keyword type**: Global keyword.
**Example of `stages`**:
```yaml
stages:
- build
- test
- deploy
```
In this example:
1. All jobs in `build` execute in parallel.
1. If all jobs in `build` succeed, the `test` jobs execute in parallel.
1. If all jobs in `test` succeed, the `deploy` jobs execute in parallel.
1. If all jobs in `deploy` succeed, the pipeline is marked as `passed`.
If any job fails, the pipeline is marked as `failed` and jobs in later stages do not
start. Jobs in the current stage are not stopped and continue to run.
**Additional details**:
- If a job does not specify a [`stage`](#stage), the job is assigned the `test` stage.
- If a stage is defined but no jobs use it, the stage is not visible in the pipeline,
which can help [compliance pipeline configurations](../../user/compliance/compliance_pipelines.md):
- Stages can be defined in the compliance configuration but remain hidden if not used.
- The defined stages become visible when developers use them in job definitions.
**Related topics**:
- To make a job start earlier and ignore the stage order, use the [`needs`](#needs) keyword.
---
### `workflow`
Use [`workflow`](workflow.md) to control pipeline behavior.
You can use some [predefined CI/CD variables](../variables/predefined_variables.md) in
`workflow` configuration, but not variables that are only defined when jobs start.
**Related topics**:
- [`workflow: rules` examples](workflow.md#workflow-rules-examples)
- [Switch between branch pipelines and merge request pipelines](workflow.md#switch-between-branch-pipelines-and-merge-request-pipelines)
---
#### `workflow:auto_cancel:on_new_commit`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/412473) in GitLab 16.8 [with a flag](../../administration/feature_flags/_index.md) named `ci_workflow_auto_cancel_on_new_commit`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/434676) in GitLab 16.9.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/434676) in GitLab 16.10. Feature flag `ci_workflow_auto_cancel_on_new_commit` removed.
{{< /history >}}
Use `workflow:auto_cancel:on_new_commit` to configure the behavior of
the [auto-cancel redundant pipelines](../pipelines/settings.md#auto-cancel-redundant-pipelines) feature.
**Supported values**:
- `conservative`: Cancel the pipeline, but only if no jobs with `interruptible: false` have started yet. Default when not defined.
- `interruptible`: Cancel only jobs with `interruptible: true`.
- `none`: Do not auto-cancel any jobs.
**Example of `workflow:auto_cancel:on_new_commit`**:
```yaml
workflow:
auto_cancel:
on_new_commit: interruptible
job1:
interruptible: true
script: sleep 60
job2:
interruptible: false # Default when not defined.
script: sleep 60
```
In this example:
- When a new commit is pushed to a branch, GitLab creates a new pipeline and `job1` and `job2` start.
- If a new commit is pushed to the branch before the jobs complete, only `job1` is canceled.
---
#### `workflow:auto_cancel:on_job_failure`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/23605) in GitLab 16.10 [with a flag](../../administration/feature_flags/_index.md) named `auto_cancel_pipeline_on_job_failure`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/433163) in GitLab 16.11. Feature flag `auto_cancel_pipeline_on_job_failure` removed.
{{< /history >}}
Use `workflow:auto_cancel:on_job_failure` to configure which jobs should be canceled as soon as one job fails.
**Supported values**:
- `all`: Cancel the pipeline and all running jobs as soon as one job fails.
- `none`: Do not auto-cancel any jobs.
**Example of `workflow:auto_cancel:on_job_failure`**:
```yaml
stages: [stage_a, stage_b]
workflow:
auto_cancel:
on_job_failure: all
job1:
stage: stage_a
script: sleep 60
job2:
stage: stage_a
script:
- sleep 30
- exit 1
job3:
stage: stage_b
script:
- sleep 30
```
In this example, if `job2` fails, `job1` is canceled if it is still running and `job3` does not start.
**Related topics**:
- [Auto-cancel the parent pipeline from a downstream pipeline](../pipelines/downstream_pipelines.md#auto-cancel-the-parent-pipeline-from-a-downstream-pipeline)
---
#### `workflow:name`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/372538) in GitLab 15.5 [with a flag](../../administration/feature_flags/_index.md) named `pipeline_name`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/376095) in GitLab 15.7.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/376095) in GitLab 15.8. Feature flag `pipeline_name` removed.
{{< /history >}}
You can use `name` in `workflow:` to define a name for pipelines.
All pipelines are assigned the defined name. Any leading or trailing spaces in the name are removed.
**Supported values**:
- A string.
- [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
- A combination of both.
**Examples of `workflow:name`**:
A simple pipeline name with a predefined variable:
```yaml
workflow:
name: 'Pipeline for branch: $CI_COMMIT_BRANCH'
```
A configuration with different pipeline names depending on the pipeline conditions:
```yaml
variables:
PROJECT1_PIPELINE_NAME: 'Default pipeline name' # A default is not required
workflow:
name: '$PROJECT1_PIPELINE_NAME'
rules:
- if: '$CI_MERGE_REQUEST_LABELS =~ /pipeline:run-in-ruby3/'
variables:
PROJECT1_PIPELINE_NAME: 'Ruby 3 pipeline'
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
variables:
PROJECT1_PIPELINE_NAME: 'MR pipeline: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME'
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # For default branch pipelines, use the default name
```
**Additional details**:
- If the name is an empty string, the pipeline is not assigned a name. A name consisting
of only CI/CD variables could evaluate to an empty string if all the variables are also empty.
- `workflow:rules:variables` become [default variables](#default-variables) available in all jobs,
including [`trigger`](#trigger) jobs which forward variables to downstream pipelines by default.
If the downstream pipeline uses the same variable, the [variable is overwritten](../variables/_index.md#cicd-variable-precedence)
by the upstream variable value. Be sure to either:
- Use a unique variable name in every project's pipeline configuration, like `PROJECT1_PIPELINE_NAME`.
- Use [`inherit:variables`](#inheritvariables) in the trigger job and list the
exact variables you want to forward to the downstream pipeline.
---
#### `workflow:rules`
The `rules` keyword in `workflow` is similar to [`rules` defined in jobs](#rules),
but controls whether or not a whole pipeline is created.
When no rules evaluate to true, the pipeline does not run.
**Supported values**: You can use some of the same keywords as job-level [`rules`](#rules):
- [`rules: if`](#rulesif).
- [`rules: changes`](#ruleschanges).
- [`rules: exists`](#rulesexists).
- [`when`](#when), can only be `always` or `never` when used with `workflow`.
- [`variables`](#workflowrulesvariables).
**Example of `workflow:rules`**:
```yaml
workflow:
rules:
- if: $CI_COMMIT_TITLE =~ /-draft$/
when: never
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
In this example, pipelines run if the commit title (first line of the commit message) does not end with `-draft`
and the pipeline is for either:
- A merge request
- The default branch.
**Additional details**:
- If your rules match both branch pipelines (other than the default branch) and merge request pipelines,
[duplicate pipelines](../jobs/job_rules.md#avoid-duplicate-pipelines) can occur.
- `start_in`, `allow_failure`, and `needs` are not supported in `workflow:rules`,
but do not cause a syntax violation. Though they have no effect, do not use them
in `workflow:rules` as it could cause syntax failures in the future. See
[issue 436473](https://gitlab.com/gitlab-org/gitlab/-/issues/436473) for more details.
**Related topics**:
- [Common `if` clauses for `workflow:rules`](workflow.md#common-if-clauses-for-workflowrules).
- [Use `rules` to run merge request pipelines](../pipelines/merge_request_pipelines.md#add-jobs-to-merge-request-pipelines).
---
#### `workflow:rules:variables`
You can use [`variables`](#variables) in `workflow:rules` to define variables for
specific pipeline conditions.
When the condition matches, the variable is created and can be used by all jobs
in the pipeline. If the variable is already defined at the top level as a default variable,
the `workflow` variable takes precedence and overrides the default variable.
**Keyword type**: Global keyword.
**Supported values**: Variable name and value pairs:
- The name can use only numbers, letters, and underscores (`_`).
- The value must be a string.
**Example of `workflow:rules:variables`**:
```yaml
variables:
DEPLOY_VARIABLE: "default-deploy"
workflow:
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
variables:
DEPLOY_VARIABLE: "deploy-production" # Override globally-defined DEPLOY_VARIABLE
- if: $CI_COMMIT_BRANCH =~ /feature/
variables:
IS_A_FEATURE: "true" # Define a new variable.
- if: $CI_COMMIT_BRANCH # Run the pipeline in other cases
job1:
variables:
DEPLOY_VARIABLE: "job1-default-deploy"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
variables: # Override DEPLOY_VARIABLE defined
DEPLOY_VARIABLE: "job1-deploy-production" # at the job level.
- when: on_success # Run the job in other cases
script:
- echo "Run script with $DEPLOY_VARIABLE as an argument"
- echo "Run another script if $IS_A_FEATURE exists"
job2:
script:
- echo "Run script with $DEPLOY_VARIABLE as an argument"
- echo "Run another script if $IS_A_FEATURE exists"
```
When the branch is the default branch:
- job1's `DEPLOY_VARIABLE` is `job1-deploy-production`.
- job2's `DEPLOY_VARIABLE` is `deploy-production`.
When the branch is `feature`:
- job1's `DEPLOY_VARIABLE` is `job1-default-deploy`, and `IS_A_FEATURE` is `true`.
- job2's `DEPLOY_VARIABLE` is `default-deploy`, and `IS_A_FEATURE` is `true`.
When the branch is something else:
- job1's `DEPLOY_VARIABLE` is `job1-default-deploy`.
- job2's `DEPLOY_VARIABLE` is `default-deploy`.
**Additional details**:
- `workflow:rules:variables` become [default variables](#variables) available in all jobs,
including [`trigger`](#trigger) jobs which forward variables to downstream pipelines by default.
If the downstream pipeline uses the same variable, the [variable is overwritten](../variables/_index.md#cicd-variable-precedence)
by the upstream variable value. Be sure to either:
- Use unique variable names in every project's pipeline configuration, like `PROJECT1_VARIABLE_NAME`.
- Use [`inherit:variables`](#inheritvariables) in the trigger job and list the
exact variables you want to forward to the downstream pipeline.
---
#### `workflow:rules:auto_cancel`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/436467) in GitLab 16.8 [with a flag](../../administration/feature_flags/_index.md) named `ci_workflow_auto_cancel_on_new_commit`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/434676) in GitLab 16.9.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/434676) in GitLab 16.10. Feature flag `ci_workflow_auto_cancel_on_new_commit` removed.
- `on_job_failure` option for `workflow:rules` [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/23605) in GitLab 16.10 [with a flag](../../administration/feature_flags/_index.md) named `auto_cancel_pipeline_on_job_failure`. Disabled by default.
- `on_job_failure` option for `workflow:rules` [generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/433163) in GitLab 16.11. Feature flag `auto_cancel_pipeline_on_job_failure` removed.
{{< /history >}}
Use `workflow:rules:auto_cancel` to configure the behavior of
the [`workflow:auto_cancel:on_new_commit`](#workflowauto_cancelon_new_commit) or
the [`workflow:auto_cancel:on_job_failure`](#workflowauto_cancelon_job_failure) features.
**Supported values**:
- `on_new_commit`: [`workflow:auto_cancel:on_new_commit`](#workflowauto_cancelon_new_commit)
- `on_job_failure`: [`workflow:auto_cancel:on_job_failure`](#workflowauto_cancelon_job_failure)
**Example of `workflow:rules:auto_cancel`**:
```yaml
workflow:
auto_cancel:
on_new_commit: interruptible
on_job_failure: all
rules:
- if: $CI_COMMIT_REF_PROTECTED == 'true'
auto_cancel:
on_new_commit: none
on_job_failure: none
- when: always # Run the pipeline in other cases
test-job1:
script: sleep 10
interruptible: false
test-job2:
script: sleep 10
interruptible: true
```
In this example, [`workflow:auto_cancel:on_new_commit`](#workflowauto_cancelon_new_commit)
is set to `interruptible` and [`workflow:auto_cancel:on_job_failure`](#workflowauto_cancelon_job_failure)
is set to `all` for all jobs by default. But if a pipeline runs for a protected branch,
the rule overrides the default with `on_new_commit: none` and `on_job_failure: none`. For example, if a pipeline
is running for:
- A non-protected branch and a new commit is pushed, `test-job1` continues to run and `test-job2` is canceled.
- A protected branch and a new commit is pushed, both `test-job1` and `test-job2` continue to run.
---
## Header keywords
Some keywords must be defined in a header section of a YAML configuration file.
The header must be at the top of the file, separated from the rest of the configuration
with `---`.
---
### `spec`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/391331) in GitLab 15.11 as a beta feature.
{{< /history >}}
Add a `spec` section to the header of a YAML file to configure the behavior of a pipeline
when a configuration is added to the pipeline with the `include` keyword.
Specs must be declared at the top of a configuration file, in a header section separated
from the rest of the configuration with `---`.
---
#### `spec:inputs`
You can use `spec:inputs` to define [inputs](../inputs/_index.md) for the CI/CD configuration.
Use the interpolation format `$[[ inputs.input-id ]]` to reference the values outside of the header section.
Inputs are evaluated and interpolated when the configuration is fetched during pipeline creation.
When using `inputs`, interpolation completes before the configuration is merged
with the contents of the `.gitlab-ci.yml` file.
**Keyword type**: Header keyword. `spec` must be declared at the top of the configuration file,
in a header section.
**Supported values**: A hash of strings representing the expected inputs.
**Example of `spec:inputs`**:
```yaml
spec:
inputs:
environment:
job-stage:
---
scan-website:
stage: $[[ inputs.job-stage ]]
script: ./scan-website $[[ inputs.environment ]]
```
**Additional details**:
- Inputs are mandatory unless you use [`spec:inputs:default`](#specinputsdefault)
to set a default value. Avoid mandatory inputs unless you only use inputs with
[`include:inputs`](#includeinputs).
- Inputs expect strings unless you use [`spec:inputs:type`](#specinputstype) to set a
different input type.
- A string containing an interpolation block must not exceed 1 MB.
- The string inside an interpolation block must not exceed 1 KB.
- You can define input values [when running a new pipeline](../inputs/_index.md#for-a-pipeline).
**Related topics**:
- [Define input parameters with `spec:inputs`](../inputs/_index.md#define-input-parameters-with-specinputs).
---
##### `spec:inputs:default`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/391331) in GitLab 15.11 as a beta feature.
{{< /history >}}
Inputs are mandatory when included, unless you set a default value with `spec:inputs:default`.
Use `default: ''` to have no default value.
**Keyword type**: Header keyword. `spec` must be declared at the top of the configuration file,
in a header section.
**Supported values**: A string representing the default value, or `''`.
**Example of `spec:inputs:default`**:
```yaml
spec:
inputs:
website:
user:
default: 'test-user'
flags:
default: ''
title: The pipeline configuration would follow...
---
```
In this example:
- `website` is mandatory and must be defined.
- `user` is optional. If not defined, the value is `test-user`.
- `flags` is optional. If not defined, it has no value.
**Additional details**:
- The pipeline fails with a validation error when the input:
- Uses both `default` and [`options`](#specinputsoptions), but the default value
is not one of the listed options.
- Uses both `default` and `regex`, but the default value does not match the regular expression.
- Value does not match the [`type`](#specinputstype).
---
##### `spec:inputs:description`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/415637) in GitLab 16.5.
{{< /history >}}
Use `description` to give a description to a specific input. The description does
not affect the behavior of the input and is only used to help users of the file
understand the input.
**Keyword type**: Header keyword. `spec` must be declared at the top of the configuration file,
in a header section.
**Supported values**: A string representing the description.
**Example of `spec:inputs:description`**:
```yaml
spec:
inputs:
flags:
description: 'Sample description of the `flags` input details.'
title: The pipeline configuration would follow...
---
```
---
##### `spec:inputs:options`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/393401) in GitLab 16.6.
{{< /history >}}
Inputs can use `options` to specify a list of allowed values for an input.
The limit is 50 options per input.
**Keyword type**: Header keyword. `spec` must be declared at the top of the configuration file,
in a header section.
**Supported values**: An array of input options.
**Example of `spec:inputs:options`**:
```yaml
spec:
inputs:
environment:
options:
- development
- staging
- production
title: The pipeline configuration would follow...
---
```
In this example:
- `environment` is mandatory and must be defined with one of the values in the list.
**Additional details**:
- The pipeline fails with a validation error when:
- The input uses both `options` and [`default`](#specinputsdefault), but the default value
is not one of the listed options.
- Any of the input options do not match the [`type`](#specinputstype), which can
be either `string` or `number`, but not `boolean` when using `options`.
---
##### `spec:inputs:regex`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/410836) in GitLab 16.5.
{{< /history >}}
Use `spec:inputs:regex` to specify a regular expression that the input must match.
**Keyword type**: Header keyword. `spec` must be declared at the top of the configuration file,
in a header section.
**Supported values**: Must be a regular expression.
**Example of `spec:inputs:regex`**:
```yaml
spec:
inputs:
version:
regex: ^v\d\.\d+(\.\d+)?$
title: The pipeline configuration would follow...
---
```
In this example, inputs of `v1.0` or `v1.2.3` match the regular expression and pass validation.
An input of `v1.A.B` does not match the regular expression and fails validation.
**Additional details**:
- `inputs:regex` can only be used with a [`type`](#specinputstype) of `string`,
not `number` or `boolean`.
- Do not enclose the regular expression with the `/` character. For example, use `regex.*`,
not `/regex.*/`.
- `inputs:regex` uses [RE2](https://github.com/google/re2/wiki/Syntax) to parse regular expressions.
---
##### `spec:inputs:type`
By default, inputs expect strings. Use `spec:inputs:type` to set a different required
type for inputs.
**Keyword type**: Header keyword. `spec` must be declared at the top of the configuration file,
in a header section.
**Supported values**: Can be one of:
- `array`, to accept an [array](../inputs/_index.md#array-type) of inputs.
- `string`, to accept string inputs (default when not defined).
- `number`, to only accept numeric inputs.
- `boolean`, to only accept `true` or `false` inputs.
**Example of `spec:inputs:type`**:
```yaml
spec:
inputs:
job_name:
website:
type: string
port:
type: number
available:
type: boolean
array_input:
type: array
title: The pipeline configuration would follow...
---
```
---
## Job keywords
The following topics explain how to use keywords to configure CI/CD pipelines.
---
### `after_script`
{{< history >}}
- Running `after_script` commands for canceled jobs [introduced](https://gitlab.com/groups/gitlab-org/-/epics/10158) in GitLab 17.0.
{{< /history >}}
Use `after_script` to define an array of commands to run last, after a job's `before_script` and
`script` sections complete. `after_script` commands also run when:
- The job is canceled while the `before_script` or `script` sections are still running.
- The job fails with failure type of `script_failure`, but not [other failure types](#retrywhen).
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: An array including:
- Single line commands.
- Long commands [split over multiple lines](script.md#split-long-commands).
- [YAML anchors](yaml_optimization.md#yaml-anchors-for-scripts).
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `after_script`**:
```yaml
job:
script:
- echo "An example script section."
after_script:
- echo "Execute this command after the `script` section completes."
```
**Additional details**:
Scripts you specify in `after_script` execute in a new shell, separate from any
`before_script` or `script` commands. As a result, they:
- Have the current working directory set back to the default (according to the [variables which define how the runner processes Git requests](../runners/configure_runners.md#configure-runner-behavior-with-variables)).
- Don't have access to changes done by commands defined in the `before_script` or `script`,
including:
- Command aliases and variables exported in `script` scripts.
- Changes outside of the working tree (depending on the runner executor), like
software installed by a `before_script` or `script` script.
- Have a separate timeout. For GitLab Runner 16.4 and later, this defaults to 5 minutes, and can be configured with the
[`RUNNER_AFTER_SCRIPT_TIMEOUT`](../runners/configure_runners.md#set-script-and-after_script-timeouts) variable.
In GitLab 16.3 and earlier, the timeout is hard-coded to 5 minutes.
- Don't affect the job's exit code. If the `script` section succeeds and the
`after_script` times out or fails, the job exits with code `0` (`Job Succeeded`).
- There is a known issue with using [CI/CD job tokens](../jobs/ci_job_token.md) with `after_script`.
You can use a job token for authentication in `after_script` commands, but the token
immediately becomes invalid if the job is canceled. See [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/473376)
for more details.
For jobs that time out:
- `after_script` commands do not execute by default.
- You can [configure timeout values](../runners/configure_runners.md#ensuring-after_script-execution) to ensure `after_script` runs by setting appropriate `RUNNER_SCRIPT_TIMEOUT` and `RUNNER_AFTER_SCRIPT_TIMEOUT` values that don't exceed the job's timeout.
**Related topics**:
- [Use `after_script` with `default`](script.md#set-a-default-before_script-or-after_script-for-all-jobs)
to define a default array of commands that should run after all jobs.
- You can configure a job to [skip `after_script` commands if the job is canceled](script.md#skip-after_script-commands-if-a-job-is-canceled).
- You can [ignore non-zero exit codes](script.md#ignore-non-zero-exit-codes).
- [Use color codes with `after_script`](script.md#add-color-codes-to-script-output)
to make job logs easier to review.
- [Create custom collapsible sections](../jobs/job_logs.md#custom-collapsible-sections)
to simplify job log output.
- You can [ignore errors in `after_script`](../runners/configure_runners.md#ignore-errors-in-after_script).
---
### `allow_failure`
Use `allow_failure` to determine whether a pipeline should continue running when a job fails.
- To let the pipeline continue running subsequent jobs, use `allow_failure: true`.
- To stop the pipeline from running subsequent jobs, use `allow_failure: false`.
When jobs are allowed to fail (`allow_failure: true`) an orange warning ({{< icon name="status_warning" >}})
indicates that a job failed. However, the pipeline is successful and the associated commit
is marked as passed with no warnings.
This same warning is displayed when:
- All other jobs in the stage are successful.
- All other jobs in the pipeline are successful.
The default value for `allow_failure` is:
- `true` for [manual jobs](../jobs/job_control.md#create-a-job-that-must-be-run-manually).
- `false` for jobs that use `when: manual` inside [`rules`](#rules).
- `false` in all other cases.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `true` or `false`.
**Example of `allow_failure`**:
```yaml
job1:
stage: test
script:
- execute_script_1
job2:
stage: test
script:
- execute_script_2
allow_failure: true
job3:
stage: deploy
script:
- deploy_to_staging
environment: staging
```
In this example, `job1` and `job2` run in parallel:
- If `job1` fails, jobs in the `deploy` stage do not start.
- If `job2` fails, jobs in the `deploy` stage can still start.
**Additional details**:
- You can use `allow_failure` as a subkey of [`rules`](#rulesallow_failure).
- If `allow_failure: true` is set, the job is always considered successful, and later jobs with [`when: on_failure`](#when) don't start if this job fails.
- You can use `allow_failure: false` with a manual job to create a [blocking manual job](../jobs/job_control.md#types-of-manual-jobs).
A blocked pipeline does not run any jobs in later stages until the manual job
is started and completes successfully.
---
#### `allow_failure:exit_codes`
Use `allow_failure:exit_codes` to control when a job should be
allowed to fail. The job is `allow_failure: true` for any of the listed exit codes,
and `allow_failure` false for any other exit code.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A single exit code.
- An array of exit codes.
**Example of `allow_failure`**:
```yaml
test_job_1:
script:
- echo "Run a script that results in exit code 1. This job fails."
- exit 1
allow_failure:
exit_codes: 137
test_job_2:
script:
- echo "Run a script that results in exit code 137. This job is allowed to fail."
- exit 137
allow_failure:
exit_codes:
- 137
- 255
```
---
### `artifacts`
{{< history >}}
- [Updated](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/5543) in GitLab Runner 18.1. During the caching process,
`symlinks` are no longer followed, which happened in some edge cases with previous GitLab Runner versions.
{{< /history >}}
Use `artifacts` to specify which files to save as [job artifacts](../jobs/job_artifacts.md).
Job artifacts are a list of files and directories that are
attached to the job when it [succeeds, fails, or always](#artifactswhen).
The artifacts are sent to GitLab after the job finishes. They are
available for download in the GitLab UI if the size is smaller than the
[maximum artifact size](../../user/gitlab_com/_index.md#cicd).
By default, jobs in later stages automatically download all the artifacts created
by jobs in earlier stages. You can control artifact download behavior in jobs with
[`dependencies`](#dependencies).
When using the [`needs`](#needs) keyword, jobs can only download
artifacts from the jobs defined in the `needs` configuration.
Job artifacts are only collected for successful jobs by default, and
artifacts are restored after [caches](#cache).
[Read more about artifacts](../jobs/job_artifacts.md).
---
#### `artifacts:paths`
Paths are relative to the project directory (`$CI_PROJECT_DIR`) and can't directly
link outside it.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- An array of file paths, relative to the project directory.
- You can use Wildcards that use [glob](https://en.wikipedia.org/wiki/Glob_(programming)) patterns and [`doublestar.Glob`](https://pkg.go.dev/github.com/bmatcuk/doublestar@v1.2.2?tab=doc#Match) patterns.
- For [GitLab Pages job](#pages):
- In [GitLab 17.10 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/428018),
the [`pages.publish`](#pagespublish) path is automatically appended to `artifacts:paths`,
so you don't need to specify it again.
- In [GitLab 17.10 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/428018),
when the [`pages.publish`](#pagespublish) path is not specified,
the `public` directory is automatically appended to `artifacts:paths`.
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `artifacts:paths`**:
```yaml
job:
artifacts:
paths:
- binaries/
- .config
```
This example creates an artifact with `.config` and all the files in the `binaries` directory.
**Additional details**:
- If not used with [`artifacts:name`](#artifactsname), the artifacts file
is named `artifacts`, which becomes `artifacts.zip` when downloaded.
**Related topics**:
- To restrict which jobs a specific job fetches artifacts from, see [`dependencies`](#dependencies).
- [Create job artifacts](../jobs/job_artifacts.md#create-job-artifacts).
---
#### `artifacts:exclude`
Use `artifacts:exclude` to prevent files from being added to an artifacts archive.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- An array of file paths, relative to the project directory.
- You can use Wildcards that use [glob](https://en.wikipedia.org/wiki/Glob_(programming)) or
[`doublestar.PathMatch`](https://pkg.go.dev/github.com/bmatcuk/doublestar@v1.2.2?tab=doc#PathMatch) patterns.
**Example of `artifacts:exclude`**:
```yaml
artifacts:
paths:
- binaries/
exclude:
- binaries/**/*.o
```
This example stores all files in `binaries/`, but not `*.o` files located in
subdirectories of `binaries/`.
**Additional details**:
- `artifacts:exclude` paths are not searched recursively.
- Files matched by [`artifacts:untracked`](#artifactsuntracked) can be excluded using
`artifacts:exclude` too.
**Related topics**:
- [Exclude files from job artifacts](../jobs/job_artifacts.md#without-excluded-files).
---
#### `artifacts:expire_in`
Use `expire_in` to specify how long [job artifacts](../jobs/job_artifacts.md) are stored before
they expire and are deleted. The `expire_in` setting does not affect:
- Artifacts from the latest job, unless keeping the latest job artifacts is disabled
[at the project level](../jobs/job_artifacts.md#keep-artifacts-from-most-recent-successful-jobs)
or [instance-wide](../../administration/settings/continuous_integration.md#keep-artifacts-from-latest-successful-pipelines).
After their expiry, artifacts are deleted hourly by default (using a cron job), and are not
accessible anymore.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: The expiry time. If no unit is provided, the time is in seconds.
Valid values include:
- `'42'`
- `42 seconds`
- `3 mins 4 sec`
- `2 hrs 20 min`
- `2h20min`
- `6 mos 1 day`
- `47 yrs 6 mos and 4d`
- `3 weeks and 2 days`
- `never`
**Example of `artifacts:expire_in`**:
```yaml
job:
artifacts:
expire_in: 1 week
```
**Additional details**:
- The expiration time period begins when the artifact is uploaded and stored on GitLab.
If the expiry time is not defined, it defaults to the [instance wide setting](../../administration/settings/continuous_integration.md#set-default-artifacts-expiration).
- To override the expiration date and protect artifacts from being automatically deleted:
- Select **Keep** on the job page.
- Set the value of `expire_in` to `never`.
- If the expiry time is too short, jobs in later stages of a long pipeline might try to fetch
expired artifacts from earlier jobs. If the artifacts are expired, jobs that try to fetch
them fail with a [`could not retrieve the needed artifacts` error](../jobs/job_artifacts_troubleshooting.md#error-message-this-job-could-not-start-because-it-could-not-retrieve-the-needed-artifacts).
Set the expiry time to be longer, or use [`dependencies`](#dependencies) in later jobs
to ensure they don't try to fetch expired artifacts.
- `artifacts:expire_in` doesn't affect GitLab Pages deployments. To configure Pages deployments' expiry, use [`pages.expire_in`](#pagesexpire_in).
---
#### `artifacts:expose_as`
Use the `artifacts:expose_as` keyword to
[expose job artifacts in the merge request UI](../jobs/job_artifacts.md#link-to-job-artifacts-in-the-merge-request-ui).
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- The name to display in the merge request UI for the artifacts download link.
Must be combined with [`artifacts:paths`](#artifactspaths).
**Example of `artifacts:expose_as`**:
```yaml
test:
script: ["echo 'test' > file.txt"]
artifacts:
expose_as: 'artifact 1'
paths: ['file.txt']
```
**Additional details**:
- Artifacts are saved, but do not display in the UI if the `artifacts:paths` values:
- Use [CI/CD variables](../variables/_index.md).
- Define a directory, but do not end with `/`. For example, `directory/` works with `artifacts:expose_as`,
but `directory` does not.
- Start with `./`. For example, `file` works with `artifacts:expose_as`, but `./file` does not.
- A maximum of 10 job artifacts per merge request can be exposed.
- Glob patterns are unsupported.
- If a directory is specified and there is more than one file in the directory,
the link is to the job [artifacts browser](../jobs/job_artifacts.md#download-job-artifacts).
- If [GitLab Pages](../../administration/pages/_index.md) is enabled, GitLab automatically
renders the artifacts when the artifacts is a single file with one of these extensions:
- `.html` or `.htm`
- `.txt`
- `.json`
- `.xml`
- `.log`
**Related topics**:
- [Expose job artifacts in the merge request UI](../jobs/job_artifacts.md#link-to-job-artifacts-in-the-merge-request-ui).
---
#### `artifacts:name`
Use the `artifacts:name` keyword to define the name of the created artifacts
archive. You can specify a unique name for every archive.
If not defined, the default name is `artifacts`, which becomes `artifacts.zip` when downloaded.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- The name of the artifacts archive. CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
Must be combined with [`artifacts:paths`](#artifactspaths).
**Example of `artifacts:name`**:
To create an archive with a name of the current job:
```yaml
job:
artifacts:
name: "job1-artifacts-file"
paths:
- binaries/
```
**Related topics**:
- [Use CI/CD variables to define the artifacts configuration](../jobs/job_artifacts.md#with-variable-expansion)
---
#### `artifacts:public`
{{< history >}}
- [Updated](https://gitlab.com/gitlab-org/gitlab/-/issues/322454) in GitLab 15.10. Artifacts created with `artifacts:public` before 15.10 are not guaranteed to remain private after this update.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/294503) in GitLab 16.7. Feature flag `non_public_artifacts` removed.
{{< /history >}}
{{< alert type="note" >}}
`artifacts:public` is now superseded by [`artifacts:access`](#artifactsaccess) which
has more options.
{{< /alert >}}
Use `artifacts:public` to determine whether the job artifacts should be
publicly available.
When `artifacts:public` is `true` (default), the artifacts in
public pipelines are available for download by anonymous, guest, and reporter users.
To deny read access to artifacts in public
pipelines for anonymous, guest, and reporter users, set `artifacts:public` to `false`:
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `true` (default if not defined) or `false`.
**Example of `artifacts:public`**:
```yaml
job:
artifacts:
public: false
```
---
#### `artifacts:access`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/145206) in GitLab 16.11.
{{< /history >}}
Use `artifacts:access` to determine who can access the job artifacts from the GitLab UI
or API. This option does not prevent you from forwarding artifacts to downstream pipelines.
You cannot use [`artifacts:public`](#artifactspublic) and `artifacts:access` in the same job.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `all` (default): Artifacts in a job in public pipelines are available for download by anyone,
including anonymous, guest, and reporter users.
- `developer`: Artifacts in the job are only available for download by users with the Developer role or higher.
- `none`: Artifacts in the job are not available for download by anyone.
**Example of `artifacts:access`**:
```yaml
job:
artifacts:
access: 'developer'
```
**Additional details**:
- `artifacts:access` affects all [`artifacts:reports`](#artifactsreports) too,
so you can also restrict access to [artifacts for reports](artifacts_reports.md).
---
#### `artifacts:reports`
Use [`artifacts:reports`](artifacts_reports.md) to collect artifacts generated by
included templates in jobs.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- See list of available [artifacts reports types](artifacts_reports.md).
**Example of `artifacts:reports`**:
```yaml
rspec:
stage: test
script:
- bundle install
- rspec --format RspecJunitFormatter --out rspec.xml
artifacts:
reports:
junit: rspec.xml
```
**Additional details**:
- Combining reports in parent pipelines using [artifacts from child pipelines](#needspipelinejob) is
not supported. Track progress on adding support in [this issue](https://gitlab.com/gitlab-org/gitlab/-/issues/215725).
- To be able to browse and download the report output files, include the [`artifacts:paths`](#artifactspaths) keyword. This uploads and stores the artifact twice.
- Artifacts created for `artifacts: reports` are always uploaded, regardless of the job results (success or failure).
You can use [`artifacts:expire_in`](#artifactsexpire_in) to set an expiration
date for the artifacts.
---
#### `artifacts:untracked`
Use `artifacts:untracked` to add all Git untracked files as artifacts (along
with the paths defined in `artifacts:paths`). `artifacts:untracked` ignores configuration
in the repository's `.gitignore`, so matching artifacts in `.gitignore` are included.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `true` or `false` (default if not defined).
**Example of `artifacts:untracked`**:
Save all Git untracked files:
```yaml
job:
artifacts:
untracked: true
```
**Related topics**:
- [Add untracked files to artifacts](../jobs/job_artifacts.md#with-untracked-files).
---
#### `artifacts:when`
Use `artifacts:when` to upload artifacts on job failure or despite the
failure.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `on_success` (default): Upload artifacts only when the job succeeds.
- `on_failure`: Upload artifacts only when the job fails.
- `always`: Always upload artifacts (except when jobs time out). For example, when
[uploading artifacts](../testing/unit_test_reports.md#add-screenshots-to-test-reports)
required to troubleshoot failing tests.
**Example of `artifacts:when`**:
```yaml
job:
artifacts:
when: on_failure
```
**Additional details**:
- The artifacts created for [`artifacts:reports`](#artifactsreports) are always uploaded,
regardless of the job results (success or failure). `artifacts:when` does not change this behavior.
---
### `before_script`
Use `before_script` to define an array of commands that should run before each job's
`script` commands, but after [artifacts](#artifacts) are restored.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: An array including:
- Single line commands.
- Long commands [split over multiple lines](script.md#split-long-commands).
- [YAML anchors](yaml_optimization.md#yaml-anchors-for-scripts).
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `before_script`**:
```yaml
job:
before_script:
- echo "Execute this command before any 'script:' commands."
script:
- echo "This command executes after the job's 'before_script' commands."
```
**Additional details**:
- Scripts you specify in `before_script` are concatenated with any scripts you specify
in the main [`script`](#script). The combined scripts execute together in a single shell.
- Using `before_script` at the top level, but not in the `default` section, [is deprecated](deprecated_keywords.md#globally-defined-image-services-cache-before_script-after_script).
**Related topics**:
- [Use `before_script` with `default`](script.md#set-a-default-before_script-or-after_script-for-all-jobs)
to define a default array of commands that should run before the `script` commands in all jobs.
- You can [ignore non-zero exit codes](script.md#ignore-non-zero-exit-codes).
- [Use color codes with `before_script`](script.md#add-color-codes-to-script-output)
to make job logs easier to review.
- [Create custom collapsible sections](../jobs/job_logs.md#custom-collapsible-sections)
to simplify job log output.
---
### `cache`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/330047) in GitLab 15.0, caches are not shared between protected and unprotected branches.
- [Updated](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/5543) in GitLab Runner 18.1. During the caching process,
`symlinks` are no longer followed, which happened in some edge cases with previous GitLab Runner versions.
{{< /history >}}
Use `cache` to specify a list of files and directories to
cache between jobs. You can only use paths that are in the local working copy.
Caches are:
- Shared between pipelines and jobs.
- By default, not shared between [protected](../../user/project/repository/branches/protected.md) and unprotected branches.
- Restored before [artifacts](#artifacts).
- Limited to a maximum of four [different caches](../caching/_index.md#use-multiple-caches).
You can [disable caching for specific jobs](../caching/_index.md#disable-cache-for-specific-jobs),
for example to override:
- A default cache defined with [`default`](#default).
- The configuration for a job added with [`include`](#include).
For more information about caches, see [Caching in GitLab CI/CD](../caching/_index.md).
---
#### `cache:paths`
Use the `cache:paths` keyword to choose which files or directories to cache.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- An array of paths relative to the project directory (`$CI_PROJECT_DIR`).
You can use wildcards that use [glob](https://en.wikipedia.org/wiki/Glob_(programming)) and
[`doublestar.Glob`](https://pkg.go.dev/github.com/bmatcuk/doublestar@v1.2.2?tab=doc#Match) patterns.
[CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file) are supported.
**Example of `cache:paths`**:
Cache all files in `binaries` that end in `.apk` and the `.config` file:
```yaml
rspec:
script:
- echo "This job uses a cache."
cache:
key: binaries-cache
paths:
- binaries/*.apk
- .config
```
**Additional details**:
- The `cache:paths` keyword includes files even if they are untracked or in your `.gitignore` file.
**Related topics**:
- See the [common `cache` use cases](../caching/_index.md#common-use-cases-for-caches) for more
`cache:paths` examples.
---
#### `cache:key`
Use the `cache:key` keyword to give each cache a unique identifying key. All jobs
that use the same cache key use the same cache, including in different pipelines.
If not set, the default key is `default`. All jobs with the `cache` keyword but
no `cache:key` share the `default` cache.
Must be used with `cache: paths`, or nothing is cached.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- A string.
- A predefined [CI/CD variable](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
- A combination of both.
**Example of `cache:key`**:
```yaml
cache-job:
script:
- echo "This job uses a cache."
cache:
key: binaries-cache-$CI_COMMIT_REF_SLUG
paths:
- binaries/
```
**Additional details**:
- If you use **Windows Batch** to run your shell scripts you must replace
`$` with `%`. For example: `key: %CI_COMMIT_REF_SLUG%`
- The `cache:key` value can't contain:
- The `/` character, or the equivalent URI-encoded `%2F`.
- Only the `.` character (any number), or the equivalent URI-encoded `%2E`.
- The cache is shared between jobs, so if you're using different
paths for different jobs, you should also set a different `cache:key`.
Otherwise cache content can be overwritten.
**Related topics**:
- You can specify a [fallback cache key](../caching/_index.md#use-a-fallback-cache-key)
to use if the specified `cache:key` is not found.
- You can [use multiple cache keys](../caching/_index.md#use-multiple-caches) in a single job.
- See the [common `cache` use cases](../caching/_index.md#common-use-cases-for-caches) for more
`cache:key` examples.
---
##### `cache:key:files`
Use the `cache:key:files` keyword to generate a new key when files matching either of the defined paths or patterns
change. `cache:key:files` lets you reuse some caches, and rebuild them less often,
which speeds up subsequent pipeline runs.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- An array of up to two file paths or patterns.
CI/CD variables are not supported.
**Example of `cache:key:files`**:
```yaml
cache-job:
script:
- echo "This job uses a cache."
cache:
key:
files:
- Gemfile.lock
- package.json
paths:
- vendor/ruby
- node_modules
```
This example creates a cache for Ruby and Node.js dependencies. The cache
is tied to the current versions of the `Gemfile.lock` and `package.json` files. When one of
these files changes, a new cache key is computed and a new cache is created. Any future
job runs that use the same `Gemfile.lock` and `package.json` with `cache:key:files`
use the new cache, instead of rebuilding the dependencies.
**Additional details**:
- The cache `key` is a SHA computed from the most recent commits
that changed each listed file.
If neither file is changed in any commits, the fallback key is `default`.
- Wildcard patterns like `**/package.json` can be used. An [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/301161)
exists to increase the number of paths or patterns allowed for a cache key.
---
##### `cache:key:prefix`
Use `cache:key:prefix` to combine a prefix with the SHA computed for [`cache:key:files`](#cachekeyfiles).
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- A string.
- A predefined [CI/CD variable](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
- A combination of both.
**Example of `cache:key:prefix`**:
```yaml
rspec:
script:
- echo "This rspec job uses a cache."
cache:
key:
files:
- Gemfile.lock
prefix: $CI_JOB_NAME
paths:
- vendor/ruby
```
For example, adding a `prefix` of `$CI_JOB_NAME` causes the key to look like `rspec-feef9576d21ee9b6a32e30c5c79d0a0ceb68d1e5`.
If a branch changes `Gemfile.lock`, that branch has a new SHA checksum for `cache:key:files`.
A new cache key is generated, and a new cache is created for that key. If `Gemfile.lock`
is not found, the prefix is added to `default`, so the key in the example would be `rspec-default`.
**Additional details**:
- If no file in `cache:key:files` is changed in any commits, the prefix is added to the `default` key.
---
#### `cache:untracked`
Use `untracked: true` to cache all files that are untracked in your Git repository.
Untracked files include files that are:
- Ignored due to [`.gitignore` configuration](https://git-scm.com/docs/gitignore).
- Created, but not added to the checkout with [`git add`](https://git-scm.com/docs/git-add).
Caching untracked files can create unexpectedly large caches if the job downloads:
- Dependencies, like gems or node modules, which are usually untracked.
- [Artifacts](#artifacts) from a different job. Files extracted from the artifacts are untracked by default.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `true` or `false` (default).
**Example of `cache:untracked`**:
```yaml
rspec:
script: test
cache:
untracked: true
```
**Additional details**:
- You can combine `cache:untracked` with `cache:paths` to cache all untracked files, as well as files in the configured paths.
Use `cache:paths` to cache any specific files, including tracked files, or files that are outside of the working directory,
and use `cache: untracked` to also cache all untracked files. For example:
```yaml
rspec:
script: test
cache:
untracked: true
paths:
- binaries/
```
In this example, the job caches all untracked files in the repository, as well as all the files in `binaries/`.
If there are untracked files in `binaries/`, they are covered by both keywords.
---
#### `cache:unprotect`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/362114) in GitLab 15.8.
{{< /history >}}
Use `cache:unprotect` to set a cache to be shared between [protected](../../user/project/repository/branches/protected.md)
and unprotected branches.
{{< alert type="warning" >}}
When set to `true`, users without access to protected branches can read and write to
cache keys used by protected branches.
{{< /alert >}}
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `true` or `false` (default).
**Example of `cache:unprotect`**:
```yaml
rspec:
script: test
cache:
unprotect: true
```
---
#### `cache:when`
Use `cache:when` to define when to save the cache, based on the status of the job.
Must be used with `cache: paths`, or nothing is cached.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `on_success` (default): Save the cache only when the job succeeds.
- `on_failure`: Save the cache only when the job fails.
- `always`: Always save the cache.
**Example of `cache:when`**:
```yaml
rspec:
script: rspec
cache:
paths:
- rspec/
when: 'always'
```
This example stores the cache whether or not the job fails or succeeds.
---
#### `cache:policy`
To change the upload and download behavior of a cache, use the `cache:policy` keyword.
By default, the job downloads the cache when the job starts, and uploads changes
to the cache when the job ends. This caching style is the `pull-push` policy (default).
To set a job to only download the cache when the job starts, but never upload changes
when the job finishes, use `cache:policy:pull`.
To set a job to only upload a cache when the job finishes, but never download the
cache when the job starts, use `cache:policy:push`.
Use the `pull` policy when you have many jobs executing in parallel that use the same cache.
This policy speeds up job execution and reduces load on the cache server. You can
use a job with the `push` policy to build the cache.
Must be used with `cache: paths`, or nothing is cached.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `pull`
- `push`
- `pull-push` (default)
- [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `cache:policy`**:
```yaml
prepare-dependencies-job:
stage: build
cache:
key: gems
paths:
- vendor/bundle
policy: push
script:
- echo "This job only downloads dependencies and builds the cache."
- echo "Downloading dependencies..."
faster-test-job:
stage: test
cache:
key: gems
paths:
- vendor/bundle
policy: pull
script:
- echo "This job script uses the cache, but does not update it."
- echo "Running tests..."
```
**Related topics**:
- You can [use a variable to control a job's cache policy](../caching/_index.md#use-a-variable-to-control-a-jobs-cache-policy).
---
#### `cache:fallback_keys`
Use `cache:fallback_keys` to specify a list of keys to try to restore cache from
if there is no cache found for the `cache:key`. Caches are retrieved in the order specified
in the `fallback_keys` section.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- An array of cache keys
**Example of `cache:fallback_keys`**:
```yaml
rspec:
script: rspec
cache:
key: gems-$CI_COMMIT_REF_SLUG
paths:
- rspec/
fallback_keys:
- gems
when: 'always'
```
---
### `coverage`
Use `coverage` with a custom regular expression to configure how code coverage
is extracted from the job output. The coverage is shown in the UI if at least one
line in the job output matches the regular expression.
To extract the code coverage value from the match, GitLab uses
this smaller regular expression: `\d+(?:\.\d+)?`.
**Supported values**:
- An RE2 regular expression. Must start and end with `/`. Must match the coverage number.
May match surrounding text as well, so you don't need to use a regular expression character group
to capture the exact number.
Because it uses RE2 syntax, all groups must be non-capturing.
**Example of `coverage`**:
```yaml
job1:
script: rspec
coverage: '/Code coverage: \d+(?:\.\d+)?/'
```
In this example:
1. GitLab checks the job log for a match with the regular expression. A line
like `Code coverage: 67.89% of lines covered` would match.
1. GitLab then checks the matched fragment to find a match to the regular expression: `\d+(?:\.\d+)?`.
The sample regex can match a code coverage of `67.89`.
**Additional details**:
- You can find regex examples in [Code Coverage](../testing/code_coverage/_index.md#coverage-regex-patterns).
- If there is more than one matched line in the job output, the last line is used
(the first result of reverse search).
- If there are multiple matches in a single line, the last match is searched
for the coverage number.
- If there are multiple coverage numbers found in the matched fragment, the first number is used.
- Leading zeros are removed.
- Coverage output from [child pipelines](../pipelines/downstream_pipelines.md#parent-child-pipelines)
is not recorded or displayed. Check [the related issue](https://gitlab.com/gitlab-org/gitlab/-/issues/280818)
for more details.
---
### `dast_configuration`
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use the `dast_configuration` keyword to specify a site profile and scanner profile to be used in a
CI/CD configuration. Both profiles must first have been created in the project. The job's stage must
be `dast`.
**Keyword type**: Job keyword. You can use only as part of a job.
**Supported values**: One each of `site_profile` and `scanner_profile`.
- Use `site_profile` to specify the site profile to be used in the job.
- Use `scanner_profile` to specify the scanner profile to be used in the job.
**Example of `dast_configuration`**:
```yaml
stages:
- build
- dast
include:
- template: DAST.gitlab-ci.yml
dast:
dast_configuration:
site_profile: "Example Co"
scanner_profile: "Quick Passive Test"
```
In this example, the `dast` job extends the `dast` configuration added with the `include` keyword
to select a specific site profile and scanner profile.
**Additional details**:
- Settings contained in either a site profile or scanner profile take precedence over those
contained in the DAST template.
**Related topics**:
- [Site profile](../../user/application_security/dast/profiles.md#site-profile).
- [Scanner profile](../../user/application_security/dast/profiles.md#scanner-profile).
---
### `dependencies`
Use the `dependencies` keyword to define a list of specific jobs to fetch [artifacts](#artifacts)
from. The specified jobs must all be in earlier stages. You can also set a job to download no artifacts at all.
When `dependencies` is not defined in a job, all jobs in earlier stages are considered dependent
and the job fetches all artifacts from those jobs.
To fetch artifacts from a job in the same stage, you must use [`needs:artifacts`](#needsartifacts).
You should not combine `dependencies` with `needs` in the same job.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- The names of jobs to fetch artifacts from.
- An empty array (`[]`), to configure the job to not download any artifacts.
**Example of `dependencies`**:
```yaml
build osx:
stage: build
script: make build:osx
artifacts:
paths:
- binaries/
build linux:
stage: build
script: make build:linux
artifacts:
paths:
- binaries/
test osx:
stage: test
script: make test:osx
dependencies:
- build osx
test linux:
stage: test
script: make test:linux
dependencies:
- build linux
deploy:
stage: deploy
script: make deploy
environment: production
```
In this example, two jobs have artifacts: `build osx` and `build linux`. When `test osx` is executed,
the artifacts from `build osx` are downloaded and extracted in the context of the build.
The same thing happens for `test linux` and artifacts from `build linux`.
The `deploy` job downloads artifacts from all previous jobs because of
the [stage](#stages) precedence.
**Additional details**:
- The job status does not matter. If a job fails or it's a manual job that isn't triggered, no error occurs.
- If the artifacts of a dependent job are [expired](#artifactsexpire_in) or
[deleted](../jobs/job_artifacts.md#delete-job-log-and-artifacts), then the job fails.
---
### `environment`
Use `environment` to define the [environment](../environments/_index.md) that a job deploys to.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: The name of the environment the job deploys to, in one of these
formats:
- Plain text, including letters, digits, spaces, and these characters: `-`, `_`, `/`, `$`, `{`, `}`.
- CI/CD variables, including predefined, project, group, instance, or variables defined in the
`.gitlab-ci.yml` file. You can't use variables defined in a `script` section.
**Example of `environment`**:
```yaml
deploy to production:
stage: deploy
script: git push production HEAD:main
environment: production
```
**Additional details**:
- If you specify an `environment` and no environment with that name exists, an environment is
created.
---
#### `environment:name`
Set a name for an [environment](../environments/_index.md).
Common environment names are `qa`, `staging`, and `production`, but you can use any name.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: The name of the environment the job deploys to, in one of these
formats:
- Plain text, including letters, digits, spaces, and these characters: `-`, `_`, `/`, `$`, `{`, `}`.
- [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file),
including predefined, project, group, instance, or variables defined in the
`.gitlab-ci.yml` file. You can't use variables defined in a `script` section.
**Example of `environment:name`**:
```yaml
deploy to production:
stage: deploy
script: git push production HEAD:main
environment:
name: production
```
---
#### `environment:url`
Set a URL for an [environment](../environments/_index.md).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: A single URL, in one of these formats:
- Plain text, like `https://prod.example.com`.
- [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file),
including predefined, project, group, instance, or variables defined in the
`.gitlab-ci.yml` file. You can't use variables defined in a `script` section.
**Example of `environment:url`**:
```yaml
deploy to production:
stage: deploy
script: git push production HEAD:main
environment:
name: production
url: https://prod.example.com
```
**Additional details**:
- After the job completes, you can access the URL by selecting a button in the merge request,
environment, or deployment pages.
---
#### `environment:on_stop`
Closing (stopping) environments can be achieved with the `on_stop` keyword
defined under `environment`. It declares a different job that runs to close the
environment.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Additional details**:
- See [`environment:action`](#environmentaction) for more details and an example.
---
#### `environment:action`
Use the `action` keyword to specify how the job interacts with the environment.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: One of the following keywords:
| **Value** | **Description** |
|:----------|:----------------|
| `start` | Default value. Indicates that the job starts the environment. The deployment is created after the job starts. |
| `prepare` | Indicates that the job is only preparing the environment. It does not trigger deployments. [Read more about preparing environments](../environments/_index.md#access-an-environment-for-preparation-or-verification-purposes). |
| `stop` | Indicates that the job stops an environment. [Read more about stopping an environment](../environments/_index.md#stopping-an-environment). |
| `verify` | Indicates that the job is only verifying the environment. It does not trigger deployments. [Read more about verifying environments](../environments/_index.md#access-an-environment-for-preparation-or-verification-purposes). |
| `access` | Indicates that the job is only accessing the environment. It does not trigger deployments. [Read more about accessing environments](../environments/_index.md#access-an-environment-for-preparation-or-verification-purposes). |
**Example of `environment:action`**:
```yaml
stop_review_app:
stage: deploy
variables:
GIT_STRATEGY: none
script: make delete-app
when: manual
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
```
---
#### `environment:auto_stop_in`
{{< history >}}
- CI/CD variable support [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/365140) in GitLab 15.4.
- [Updated](https://gitlab.com/gitlab-org/gitlab/-/issues/437133) to support `prepare`, `access` and `verify` environment actions in GitLab 17.7.
{{< /history >}}
The `auto_stop_in` keyword specifies the lifetime of the environment. When an environment expires, GitLab
automatically stops it.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: A period of time written in natural language. For example,
these are all equivalent:
- `168 hours`
- `7 days`
- `one week`
- `never`
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `environment:auto_stop_in`**:
```yaml
review_app:
script: deploy-review-app
environment:
name: review/$CI_COMMIT_REF_SLUG
auto_stop_in: 1 day
```
When the environment for `review_app` is created, the environment's lifetime is set to `1 day`.
Every time the review app is deployed, that lifetime is also reset to `1 day`.
The `auto_stop_in` keyword can be used for all [environment actions](#environmentaction) except `stop`.
Some actions can be used to reset the scheduled stop time for the environment. For more information, see
[Access an environment for preparation or verification purposes](../environments/_index.md#access-an-environment-for-preparation-or-verification-purposes).
**Related topics**:
- [Environments auto-stop documentation](../environments/_index.md#stop-an-environment-after-a-certain-time-period).
---
#### `environment:kubernetes`
{{< history >}}
- `agent` keyword [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/467912) in GitLab 17.6.
- `namespace` and `flux_resource_path` keywords [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/500164) in GitLab 17.7.
{{< /history >}}
Use the `kubernetes` keyword to configure the [dashboard for Kubernetes](../environments/kubernetes_dashboard.md)
for an environment.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `agent`: A string specifying the [GitLab agent for Kubernetes](../../user/clusters/agent/_index.md). The format is `path/to/agent/project:agent-name`. If the agent is connected to the project running the pipeline, use `$CI_PROJECT_PATH:agent-name`.
- `namespace`: A string representing the Kubernetes namespace where the environment is deployed. The namespace must be set together with the `agent` keyword.
- `flux_resource_path`: A string representing the full path to the Flux resource, such as a HelmRelease. The Flux resource must be set together with the
`agent` and `namespace` keywords.
**Example of `environment:kubernetes`**:
```yaml
deploy:
stage: deploy
script: make deploy-app
environment:
name: production
kubernetes:
agent: path/to/agent/project:agent-name
namespace: my-namespace
flux_resource_path: helm.toolkit.fluxcd.io/v2/namespaces/flux-system/helmreleases/helm-release-resource
```
This configuration:
- Sets up the `deploy` job to deploy to the `production`
environment
- Associates the [agent](../../user/clusters/agent/_index.md) named `agent-name` with the environment
- Configures the [dashboard for Kubernetes](../environments/kubernetes_dashboard.md) for an environment with
the namespace `my-namespace` and the `flux_resource_path` set to
`helm.toolkit.fluxcd.io/v2/namespaces/flux-system/helmreleases/helm-release-resource`.
**Additional details**:
- To use the dashboard, you must
[install the GitLab agent for Kubernetes](../../user/clusters/agent/install/_index.md) and
[configure `user_access`](../../user/clusters/agent/user_access.md)
for the environment's project or its parent group.
- The user running the job must be authorized to access the cluster agent.
Otherwise, the dashboard ignores the `agent`, `namespace`, and `flux_resource_path` attributes.
- If you only want to set the `agent`, you do not have to set the `namespace`, and cannot set `flux_resource_path`. However, this configuration lists all namespaces in a cluster in the dashboard for Kubernetes.
---
#### `environment:deployment_tier`
Use the `deployment_tier` keyword to specify the tier of the deployment environment.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: One of the following:
- `production`
- `staging`
- `testing`
- `development`
- `other`
**Example of `environment:deployment_tier`**:
```yaml
deploy:
script: echo
environment:
name: customer-portal
deployment_tier: production
```
**Additional details**:
- Environments created from this job definition are assigned a [tier](../environments/_index.md#deployment-tier-of-environments) based on this value.
- Existing environments don't have their tier updated if this value is added later. Existing environments must have their tier updated via the [Environments API](../../api/environments.md#update-an-existing-environment).
**Related topics**:
- [Deployment tier of environments](../environments/_index.md#deployment-tier-of-environments).
---
#### Dynamic environments
Use CI/CD [variables](../variables/_index.md) to dynamically name environments.
For example:
```yaml
deploy as review app:
stage: deploy
script: make deploy
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com/
```
The `deploy as review app` job is marked as a deployment to dynamically
create the `review/$CI_COMMIT_REF_SLUG` environment. `$CI_COMMIT_REF_SLUG`
is a [CI/CD variable](../variables/_index.md) set by the runner. The
`$CI_ENVIRONMENT_SLUG` variable is based on the environment name, but suitable
for inclusion in URLs. If the `deploy as review app` job runs in a branch named
`pow`, this environment would be accessible with a URL like `https://review-pow.example.com/`.
The common use case is to create dynamic environments for branches and use them
as review apps. You can see an example that uses review apps at
<https://gitlab.com/gitlab-examples/review-apps-nginx/>.
---
### `extends`
Use `extends` to reuse configuration sections. It's an alternative to [YAML anchors](yaml_optimization.md#anchors)
and is a little more flexible and readable.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- The name of another job in the pipeline.
- A list (array) of names of other jobs in the pipeline.
**Example of `extends`**:
```yaml
.tests:
stage: test
image: ruby:3.0
rspec:
extends: .tests
script: rake rspec
rubocop:
extends: .tests
script: bundle exec rubocop
```
In this example, the `rspec` job uses the configuration from the `.tests` template job.
When creating the pipeline, GitLab:
- Performs a reverse deep merge based on the keys.
- Merges the `.tests` content with the `rspec` job.
- Doesn't merge the values of the keys.
The combined configuration is equivalent to these jobs:
```yaml
rspec:
stage: test
image: ruby:3.0
script: rake rspec
rubocop:
stage: test
image: ruby:3.0
script: bundle exec rubocop
```
**Additional details**:
- You can use multiple parents for `extends`.
- The `extends` keyword supports up to eleven levels of inheritance, but you should
avoid using more than three levels.
- In the previous example, `.tests` is a [hidden job](../jobs/_index.md#hide-a-job),
but you can extend configuration from regular jobs as well.
**Related topics**:
- [Reuse configuration sections by using `extends`](yaml_optimization.md#use-extends-to-reuse-configuration-sections).
- Use `extends` to reuse configuration from [included configuration files](yaml_optimization.md#use-extends-and-include-together).
---
### `hooks`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/356850) in GitLab 15.6 [with a flag](../../administration/feature_flags/_index.md) named `ci_hooks_pre_get_sources_script`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/381840) in GitLab 15.10. Feature flag `ci_hooks_pre_get_sources_script` removed.
{{< /history >}}
Use `hooks` to specify lists of commands to execute on the runner
at certain stages of job execution, like before retrieving the Git repository.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- A hash of hooks and their commands. Available hooks: `pre_get_sources_script`.
---
#### `hooks:pre_get_sources_script`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/356850) in GitLab 15.6 [with a flag](../../administration/feature_flags/_index.md) named `ci_hooks_pre_get_sources_script`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/381840) in GitLab 15.10. Feature flag `ci_hooks_pre_get_sources_script` removed.
{{< /history >}}
Use `hooks:pre_get_sources_script` to specify a list of commands to execute on the runner
before cloning the Git repository and any submodules.
You can use it for example to:
- Adjust the [Git configuration](../jobs/job_troubleshooting.md#get_sources-job-section-fails-because-of-an-http2-problem).
- Export [tracing variables](../../topics/git/troubleshooting_git.md#debug-git-with-traces).
**Supported values**: An array including:
- Single line commands.
- Long commands [split over multiple lines](script.md#split-long-commands).
- [YAML anchors](yaml_optimization.md#yaml-anchors-for-scripts).
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `hooks:pre_get_sources_script`**:
```yaml
job1:
hooks:
pre_get_sources_script:
- echo 'hello job1 pre_get_sources_script'
script: echo 'hello job1 script'
```
**Related topics**:
- [GitLab Runner configuration](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runners-section)
---
### `identity`
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
- Status: Beta
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/142054) in GitLab 16.9 [with a flag](../../administration/feature_flags/_index.md) named `google_cloud_support_feature_flag`. This feature is in [beta](../../policy/development_stages_support.md).
- [Enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/150472) in GitLab 17.1. Feature flag `google_cloud_support_feature_flag` removed.
{{< /history >}}
This feature is in [beta](../../policy/development_stages_support.md).
Use `identity` to authenticate with third party services using identity federation.
**Keyword type**: Job keyword. You can use it only as part of a job or in the [`default:` section](#default).
**Supported values**: An identifier. Supported providers:
- `google_cloud`: Google Cloud. Must be configured with the [Google Cloud IAM integration](../../integration/google_cloud_iam.md).
**Example of `identity`**:
```yaml
job_with_workload_identity:
identity: google_cloud
script:
- gcloud compute instances list
```
**Related topics**:
- [Workload Identity Federation](https://cloud.google.com/iam/docs/workload-identity-federation).
- [Google Cloud IAM integration](../../integration/google_cloud_iam.md).
---
### `id_tokens`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/356986) in GitLab 15.7.
{{< /history >}}
Use `id_tokens` to create [JSON web tokens (JWT)](https://www.rfc-editor.org/rfc/rfc7519) to authenticate with third party services. All
JWTs created this way support OIDC authentication. The required `aud` sub-keyword is used to configure the `aud` claim for the JWT.
**Supported values**:
- Token names with their `aud` claims. `aud` supports:
- A single string.
- An array of strings.
- [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `id_tokens`**:
```yaml
job_with_id_tokens:
id_tokens:
ID_TOKEN_1:
aud: https://vault.example.com
ID_TOKEN_2:
aud:
- https://gcp.com
- https://aws.com
SIGSTORE_ID_TOKEN:
aud: sigstore
script:
- command_to_authenticate_with_vault $ID_TOKEN_1
- command_to_authenticate_with_aws $ID_TOKEN_2
- command_to_authenticate_with_gcp $ID_TOKEN_2
```
**Related topics**:
- [ID token authentication](../secrets/id_token_authentication.md).
- [Connect to cloud services](../cloud_services/_index.md).
- [Keyless signing with Sigstore](signing_examples.md).
---
### `image`
Use `image` to specify a Docker image that the job runs in.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: The name of the image, including the registry path if needed, in one of these formats:
- `<image-name>` (Same as using `<image-name>` with the `latest` tag)
- `<image-name>:<tag>`
- `<image-name>@<digest>`
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `image`**:
```yaml
default:
image: ruby:3.0
rspec:
script: bundle exec rspec
rspec 2.7:
image: registry.example.com/my-group/my-project/ruby:2.7
script: bundle exec rspec
```
In this example, the `ruby:3.0` image is the default for all jobs in the pipeline.
The `rspec 2.7` job does not use the default, because it overrides the default with
a job-specific `image` section.
**Related topics**:
- [Run your CI/CD jobs in Docker containers](../docker/using_docker_images.md).
---
#### `image:name`
The name of the Docker image that the job runs in. Similar to [`image`](#image) used by itself.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: The name of the image, including the registry path if needed, in one of these formats:
- `<image-name>` (Same as using `<image-name>` with the `latest` tag)
- `<image-name>:<tag>`
- `<image-name>@<digest>`
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `image:name`**:
```yaml
test-job:
image:
name: "registry.example.com/my/image:latest"
script: echo "Hello world"
```
**Related topics**:
- [Run your CI/CD jobs in Docker containers](../docker/using_docker_images.md).
---
#### `image:entrypoint`
Command or script to execute as the container's entry point.
When the Docker container is created, the `entrypoint` is translated to the Docker `--entrypoint` option.
The syntax is similar to the [Dockerfile `ENTRYPOINT` directive](https://docs.docker.com/reference/dockerfile/#entrypoint),
where each shell token is a separate string in the array.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- A string.
**Example of `image:entrypoint`**:
```yaml
test-job:
image:
name: super/sql:experimental
entrypoint: [""]
script: echo "Hello world"
```
**Related topics**:
- [Override the entrypoint of an image](../docker/using_docker_images.md#override-the-entrypoint-of-an-image).
---
#### `image:docker`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/27919) in GitLab 16.7. Requires GitLab Runner 16.7 or later.
- `user` input option [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/137907) in GitLab 16.8.
{{< /history >}}
Use `image:docker` to pass options to runners using the [Docker executor](https://docs.gitlab.com/runner/executors/docker.html)
or the [Kubernetes executor](https://docs.gitlab.com/runner/executors/kubernetes/).
This keyword does not work with other executor types.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
A hash of options for the Docker executor, which can include:
- `platform`: Selects the architecture of the image to pull. When not specified,
the default is the same platform as the host runner.
- `user`: Specify the username or UID to use when running the container.
**Example of `image:docker`**:
```yaml
arm-sql-job:
script: echo "Run sql tests"
image:
name: super/sql:experimental
docker:
platform: arm64/v8
user: dave
```
**Additional details**:
- `image:docker:platform` maps to the [`docker pull --platform` option](https://docs.docker.com/reference/cli/docker/image/pull/#options).
- `image:docker:user` maps to the [`docker run --user` option](https://docs.docker.com/reference/cli/docker/container/run/#options).
---
#### `image:kubernetes`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/38451) in GitLab 18.0. Requires GitLab Runner 17.11 or later.
- `user` input option [introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/5469) in GitLab Runner 17.11.
- `user` input option [extended to support `uid:gid` format](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/5540) in GitLab 18.0.
{{< /history >}}
Use `image:kubernetes` to pass options to the GitLab Runner [Kubernetes executor](https://docs.gitlab.com/runner/executors/kubernetes/).
This keyword does not work with other executor types.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
A hash of options for the Kubernetes executor, which can include:
- `user`: Specify the username or UID to use when the container runs. You can also use it to set GID by using the `UID:GID` format.
**Example of `image:kubernetes` with only UID**:
```yaml
arm-sql-job:
script: echo "Run sql tests"
image:
name: super/sql:experimental
kubernetes:
user: "1001"
```
**Example of `image:kubernetes` with both UID and GID**:
```yaml
arm-sql-job:
script: echo "Run sql tests"
image:
name: super/sql:experimental
kubernetes:
user: "1001:1001"
```
---
#### `image:pull_policy`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/21619) in GitLab 15.1 [with a flag](../../administration/feature_flags/_index.md) named `ci_docker_image_pull_policy`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/363186) in GitLab 15.2.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/363186) in GitLab 15.4. [Feature flag `ci_docker_image_pull_policy`](https://gitlab.com/gitlab-org/gitlab/-/issues/363186) removed.
- Requires GitLab Runner 15.1 or later.
{{< /history >}}
The pull policy that the runner uses to fetch the Docker image.
**Keyword type**: Job keyword. You can use it only as part of a job or in the [`default` section](#default).
**Supported values**:
- A single pull policy, or multiple pull policies in an array.
Can be `always`, `if-not-present`, or `never`.
**Examples of `image:pull_policy`**:
```yaml
job1:
script: echo "A single pull policy."
image:
name: ruby:3.0
pull_policy: if-not-present
job2:
script: echo "Multiple pull policies."
image:
name: ruby:3.0
pull_policy: [always, if-not-present]
```
**Additional details**:
- If the runner does not support the defined pull policy, the job fails with an error similar to:
`ERROR: Job failed (system failure): the configured PullPolicies ([always]) are not allowed by AllowedPullPolicies ([never])`.
**Related topics**:
- [Run your CI/CD jobs in Docker containers](../docker/using_docker_images.md).
- [Configure how runners pull images](https://docs.gitlab.com/runner/executors/docker.html#configure-how-runners-pull-images).
- [Set multiple pull policies](https://docs.gitlab.com/runner/executors/docker.html#set-multiple-pull-policies).
---
### `inherit`
Use `inherit` to [control inheritance of default keywords and variables](../jobs/_index.md#control-the-inheritance-of-default-keywords-and-variables).
---
#### `inherit:default`
Use `inherit:default` to control the inheritance of [default keywords](#default).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `true` (default) or `false` to enable or disable the inheritance of all default keywords.
- A list of specific default keywords to inherit.
**Example of `inherit:default`**:
```yaml
default:
retry: 2
image: ruby:3.0
interruptible: true
job1:
script: echo "This job does not inherit any default keywords."
inherit:
default: false
job2:
script: echo "This job inherits only the two listed default keywords. It does not inherit 'interruptible'."
inherit:
default:
- retry
- image
```
**Additional details**:
- You can also list default keywords to inherit on one line: `default: [keyword1, keyword2]`
---
#### `inherit:variables`
Use `inherit:variables` to control the inheritance of [default variables](#default-variables) keywords.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `true` (default) or `false` to enable or disable the inheritance of all default variables.
- A list of specific variables to inherit.
**Example of `inherit:variables`**:
```yaml
variables:
VARIABLE1: "This is default variable 1"
VARIABLE2: "This is default variable 2"
VARIABLE3: "This is default variable 3"
job1:
script: echo "This job does not inherit any default variables."
inherit:
variables: false
job2:
script: echo "This job inherits only the two listed default variables. It does not inherit 'VARIABLE3'."
inherit:
variables:
- VARIABLE1
- VARIABLE2
```
**Additional details**:
- You can also list default variables to inherit on one line: `variables: [VARIABLE1, VARIABLE2]`
---
### `interruptible`
{{< history >}}
- Support for `trigger` jobs [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/138508) in GitLab 16.8.
{{< /history >}}
Use `interruptible` to configure the [auto-cancel redundant pipelines](../pipelines/settings.md#auto-cancel-redundant-pipelines)
feature to cancel a job before it completes if a new pipeline on the same ref starts for a newer commit. If the feature
is disabled, the keyword has no effect. The new pipeline must be for a commit with new changes. For example,
the **Auto-cancel redundant pipelines** feature has no effect
if you select **New pipeline** in the UI to run a pipeline for the same commit.
The behavior of the **Auto-cancel redundant pipelines** feature can be controlled by
the [`workflow:auto_cancel:on_new_commit`](#workflowauto_cancelon_new_commit) setting.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `true` or `false` (default).
**Example of `interruptible` with the default behavior**:
```yaml
workflow:
auto_cancel:
on_new_commit: conservative # the default behavior
stages:
- stage1
- stage2
- stage3
step-1:
stage: stage1
script:
- echo "Can be canceled."
interruptible: true
step-2:
stage: stage2
script:
- echo "Can not be canceled."
step-3:
stage: stage3
script:
- echo "Because step-2 can not be canceled, this step can never be canceled, even though it's set as interruptible."
interruptible: true
```
In this example, a new pipeline causes a running pipeline to be:
- Canceled, if only `step-1` is running or pending.
- Not canceled, after `step-2` starts.
**Example of `interruptible` with the `auto_cancel:on_new_commit:interruptible` setting**:
```yaml
workflow:
auto_cancel:
on_new_commit: interruptible
stages:
- stage1
- stage2
- stage3
step-1:
stage: stage1
script:
- echo "Can be canceled."
interruptible: true
step-2:
stage: stage2
script:
- echo "Can not be canceled."
step-3:
stage: stage3
script:
- echo "Can be canceled."
interruptible: true
```
In this example, a new pipeline causes a running pipeline to cancel `step-1` and `step-3` if they are running or pending.
**Additional details**:
- Only set `interruptible: true` if the job can be safely canceled after it has started,
like a build job. Deployment jobs usually shouldn't be canceled, to prevent partial deployments.
- When using the default behavior or `workflow:auto_cancel:on_new_commit: conservative`:
- A job that has not started yet is always considered `interruptible: true`, regardless of the job's configuration.
The `interruptible` configuration is only considered after the job starts.
- **Running** pipelines are only canceled if all running jobs are configured with `interruptible: true` or
no jobs configured with `interruptible: false` have started at any time.
After a job with `interruptible: false` starts, the entire pipeline is no longer
considered interruptible.
- If the pipeline triggered a downstream pipeline, but no job with `interruptible: false`
in the downstream pipeline has started yet, the downstream pipeline is also canceled.
- You can add an optional manual job with `interruptible: false` in the first stage of
a pipeline to allow users to manually prevent a pipeline from being automatically
canceled. After a user starts the job, the pipeline cannot be canceled by the
**Auto-cancel redundant pipelines** feature.
- When using `interruptible` with a [trigger job](#trigger):
- The triggered downstream pipeline is never affected by the trigger job's `interruptible` configuration.
- If [`workflow:auto_cancel`](#workflowauto_cancelon_new_commit) is set to `conservative`,
the trigger job's `interruptible` configuration has no effect.
- If [`workflow:auto_cancel`](#workflowauto_cancelon_new_commit) is set to `interruptible`,
a trigger job with `interruptible: true` can be automatically canceled.
---
### `needs`
Use `needs` to execute jobs out-of-order. Relationships between jobs
that use `needs` can be visualized as a [directed acyclic graph](needs.md).
You can ignore stage ordering and run some jobs without waiting for others to complete.
Jobs in multiple stages can run concurrently.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- An array of jobs (maximum of 50 jobs).
- An empty array (`[]`), to set the job to start as soon as the pipeline is created.
**Example of `needs`**:
```yaml
linux:build:
stage: build
script: echo "Building linux..."
mac:build:
stage: build
script: echo "Building mac..."
lint:
stage: test
needs: []
script: echo "Linting..."
linux:rspec:
stage: test
needs: ["linux:build"]
script: echo "Running rspec on linux..."
mac:rspec:
stage: test
needs: ["mac:build"]
script: echo "Running rspec on mac..."
production:
stage: deploy
script: echo "Running production..."
environment: production
```
This example creates four paths of execution:
- Linter: The `lint` job runs immediately without waiting for the `build` stage
to complete because it has no needs (`needs: []`).
- Linux path: The `linux:rspec` job runs as soon as the `linux:build`
job finishes, without waiting for `mac:build` to finish.
- macOS path: The `mac:rspec` jobs runs as soon as the `mac:build`
job finishes, without waiting for `linux:build` to finish.
- The `production` job runs as soon as all previous jobs finish:
`lint`, `linux:build`, `linux:rspec`, `mac:build`, `mac:rspec`.
**Additional details**:
- The maximum number of jobs that a single job can have in the `needs` array is limited:
- For GitLab.com, the limit is 50. For more information, see
[issue 350398](https://gitlab.com/gitlab-org/gitlab/-/issues/350398).
- For GitLab Self-Managed and GitLab Dedicated, the default limit is 50. This limit can be changed by [updating the CI/CD limits in the Admin area](../../administration/settings/continuous_integration.md#set-cicd-limits).
- If `needs` refers to a job that uses the [`parallel`](#parallel) keyword,
it depends on all jobs created in parallel, not just one job. It also downloads
artifacts from all the parallel jobs by default. If the artifacts have the same
name, they overwrite each other and only the last one downloaded is saved.
- To have `needs` refer to a subset of parallelized jobs (and not all of the parallelized jobs),
use the [`needs:parallel:matrix`](#needsparallelmatrix) keyword.
- You can refer to jobs in the same stage as the job you are configuring.
- If `needs` refers to a job that might not be added to
a pipeline because of `only`, `except`, or `rules`, the pipeline might fail to create. Use the [`needs:optional`](#needsoptional) keyword to resolve a failed pipeline creation.
- If a pipeline has jobs with `needs: []` and jobs in the [`.pre`](#stage-pre) stage, they will
all start as soon as the pipeline is created. Jobs with `needs: []` start immediately,
and jobs in the `.pre` stage also start immediately.
---
#### `needs:artifacts`
When a job uses `needs`, it no longer downloads all artifacts from previous stages
by default, because jobs with `needs` can start before earlier stages complete. With
`needs` you can only download artifacts from the jobs listed in the `needs` configuration.
Use `artifacts: true` (default) or `artifacts: false` to control when artifacts are
downloaded in jobs that use `needs`.
**Keyword type**: Job keyword. You can use it only as part of a job. Must be used with `needs:job`.
**Supported values**:
- `true` (default) or `false`.
**Example of `needs:artifacts`**:
```yaml
test-job1:
stage: test
needs:
- job: build_job1
artifacts: true
test-job2:
stage: test
needs:
- job: build_job2
artifacts: false
test-job3:
needs:
- job: build_job1
artifacts: true
- job: build_job2
- build_job3
```
In this example:
- The `test-job1` job downloads the `build_job1` artifacts
- The `test-job2` job does not download the `build_job2` artifacts.
- The `test-job3` job downloads the artifacts from all three `build_jobs`, because
`artifacts` is `true`, or defaults to `true`, for all three needed jobs.
**Additional details**:
- You should not combine `needs` with [`dependencies`](#dependencies) in the same job.
---
#### `needs:project`
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use `needs:project` to download artifacts from up to five jobs in other pipelines.
The artifacts are downloaded from the latest successful specified job for the specified ref.
To specify multiple jobs, add each as separate array items under the `needs` keyword.
If there is a pipeline running for the ref, a job with `needs:project`
does not wait for the pipeline to complete. Instead, the artifacts are downloaded
from the latest successful run of the specified job.
`needs:project` must be used with `job`, `ref`, and `artifacts`.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `needs:project`: A full project path, including namespace and group.
- `job`: The job to download artifacts from.
- `ref`: The ref to download artifacts from.
- `artifacts`: Must be `true` to download artifacts.
**Examples of `needs:project`**:
```yaml
build_job:
stage: build
script:
- ls -lhR
needs:
- project: namespace/group/project-name
job: build-1
ref: main
artifacts: true
- project: namespace/group/project-name-2
job: build-2
ref: main
artifacts: true
```
In this example, `build_job` downloads the artifacts from the latest successful `build-1` and `build-2` jobs
on the `main` branches in the `group/project-name` and `group/project-name-2` projects.
You can use [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file) in `needs:project`, for example:
```yaml
build_job:
stage: build
script:
- ls -lhR
needs:
- project: $CI_PROJECT_PATH
job: $DEPENDENCY_JOB_NAME
ref: $ARTIFACTS_DOWNLOAD_REF
artifacts: true
```
**Additional details**:
- To download artifacts from a different pipeline in the current project, set `project`
to be the same as the current project, but use a different ref than the current pipeline.
Concurrent pipelines running on the same ref could override the artifacts.
- The user running the pipeline must have at least the Reporter role for the group or project,
or the group/project must have public visibility.
- You can't use `needs:project` in the same job as [`trigger`](#trigger).
- When using `needs:project` to download artifacts from another pipeline, the job does not wait for
the needed job to complete. [Using `needs` to wait for jobs to complete](needs.md)
is limited to jobs in the same pipeline. Make sure that the needed job in the other
pipeline completes before the job that needs it tries to download the artifacts.
- You can't download artifacts from jobs that run in [`parallel`](#parallel).
- Support [CI/CD variables](../variables/_index.md) in `project`, `job`, and `ref`.
**Related topics**:
- To download artifacts between [parent-child pipelines](../pipelines/downstream_pipelines.md#parent-child-pipelines),
use [`needs:pipeline:job`](#needspipelinejob).
---
#### `needs:pipeline:job`
A [child pipeline](../pipelines/downstream_pipelines.md#parent-child-pipelines) can download artifacts from a
successfully finished job in its parent pipeline or another child pipeline in the same parent-child pipeline hierarchy.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `needs:pipeline`: A pipeline ID. Must be a pipeline present in the same parent-child pipeline hierarchy.
- `job`: The job to download artifacts from.
**Example of `needs:pipeline:job`**:
- Parent pipeline (`.gitlab-ci.yml`):
```yaml
stages:
- build
- test
create-artifact:
stage: build
script: echo "sample artifact" > artifact.txt
artifacts:
paths: [artifact.txt]
child-pipeline:
stage: test
trigger:
include: child.yml
strategy: mirror
variables:
PARENT_PIPELINE_ID: $CI_PIPELINE_ID
```
- Child pipeline (`child.yml`):
```yaml
use-artifact:
script: cat artifact.txt
needs:
- pipeline: $PARENT_PIPELINE_ID
job: create-artifact
```
In this example, the `create-artifact` job in the parent pipeline creates some artifacts.
The `child-pipeline` job triggers a child pipeline, and passes the `CI_PIPELINE_ID`
variable to the child pipeline as a new `PARENT_PIPELINE_ID` variable. The child pipeline
can use that variable in `needs:pipeline` to download artifacts from the parent pipeline.
Having the `create-artifact` and `child-pipeline` jobs in subsequent stages ensures that
the `use-artifact` job only executes when `create-artifact` has successfully finished.
**Additional details**:
- The `pipeline` attribute does not accept the current pipeline ID (`$CI_PIPELINE_ID`).
To download artifacts from a job in the current pipeline, use [`needs:artifacts`](#needsartifacts).
- You cannot use `needs:pipeline:job` in a [trigger job](#trigger), or to fetch artifacts
from a [multi-project pipeline](../pipelines/downstream_pipelines.md#multi-project-pipelines).
To fetch artifacts from a multi-project pipeline use [`needs:project`](#needsproject).
- The job listed in `needs:pipeline:job` must complete with a status of `success`
or the artifacts can't be fetched. [Issue 367229](https://gitlab.com/gitlab-org/gitlab/-/issues/367229)
proposes to allow fetching artifacts from any job with artifacts.
---
#### `needs:optional`
To need a job that sometimes does not exist in the pipeline, add `optional: true`
to the `needs` configuration. If not defined, `optional: false` is the default.
Jobs that use [`rules`](#rules), [`only`, or `except`](deprecated_keywords.md#only--except) and that are added with [`include`](#include)
might not always be added to a pipeline. GitLab checks the `needs` relationships before starting a pipeline:
- If the `needs` entry has `optional: true` and the needed job is present in the pipeline,
the job waits for it to complete before starting.
- If the needed job is not present, the job can start when all other needs requirements are met.
- If the `needs` section contains only optional jobs, and none are added to the pipeline,
the job starts immediately (the same as an empty `needs` entry: `needs: []`).
- If a needed job has `optional: false`, but it was not added to the pipeline, the
pipeline fails to start with an error similar to: `'job1' job needs 'job2' job, but it was not added to the pipeline`.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Example of `needs:optional`**:
```yaml
build-job:
stage: build
test-job1:
stage: test
test-job2:
stage: test
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
deploy-job:
stage: deploy
needs:
- job: test-job2
optional: true
- job: test-job1
environment: production
review-job:
stage: deploy
needs:
- job: test-job2
optional: true
environment: review
```
In this example:
- `build-job`, `test-job1`, and `test-job2` start in stage order.
- When the branch is the default branch, `test-job2` is added to the pipeline, so:
- `deploy-job` waits for both `test-job1` and `test-job2` to complete.
- `review-job` waits for `test-job2` to complete.
- When the branch is not the default branch, `test-job2` is not added to the pipeline, so:
- `deploy-job` waits for only `test-job1` to complete, and does not wait for the missing `test-job2`.
- `review-job` has no other needed jobs and starts immediately (at the same time as `build-job`),
like `needs: []`.
---
#### `needs:pipeline`
You can mirror the pipeline status from an upstream pipeline to a job by
using the `needs:pipeline` keyword. The latest pipeline status from the default branch is
replicated to the job.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A full project path, including namespace and group. If the
project is in the same group or namespace, you can omit them from the `project`
keyword. For example: `project: group/project-name` or `project: project-name`.
**Example of `needs:pipeline`**:
```yaml
upstream_status:
stage: test
needs:
pipeline: other/project
```
**Additional details**:
- If you add the `job` keyword to `needs:pipeline`, the job no longer mirrors the
pipeline status. The behavior changes to [`needs:pipeline:job`](#needspipelinejob).
---
#### `needs:parallel:matrix`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/254821) in GitLab 16.3.
{{< /history >}}
Jobs can use [`parallel:matrix`](#parallelmatrix) to run a job multiple times in parallel in a single pipeline,
but with different variable values for each instance of the job.
Use `needs:parallel:matrix` to execute jobs out-of-order depending on parallelized jobs.
**Keyword type**: Job keyword. You can use it only as part of a job. Must be used with `needs:job`.
**Supported values**: An array of hashes of variables:
- The variables and values must be selected from the variables and values defined in the `parallel:matrix` job.
**Example of `needs:parallel:matrix`**:
```yaml
linux:build:
stage: build
script: echo "Building linux..."
parallel:
matrix:
- PROVIDER: aws
STACK:
- monitoring
- app1
- app2
linux:rspec:
stage: test
needs:
- job: linux:build
parallel:
matrix:
- PROVIDER: aws
STACK: app1
script: echo "Running rspec on linux..."
```
The previous example generates the following jobs:
```plaintext
linux:build: [aws, monitoring]
linux:build: [aws, app1]
linux:build: [aws, app2]
linux:rspec
```
The `linux:rspec` job runs as soon as the `linux:build: [aws, app1]` job finishes.
**Related topics**:
- [Specify a parallelized job using needs with multiple parallelized jobs](../jobs/job_control.md#specify-a-parallelized-job-using-needs-with-multiple-parallelized-jobs).
**Additional details**:
- The order of the matrix variables in `needs:parallel:matrix` must match the order
of the matrix variables in the needed job. For example, reversing the order of
the variables in the `linux:rspec` job in the previous example would be invalid:
```yaml
linux:rspec:
stage: test
needs:
- job: linux:build
parallel:
matrix:
- STACK: app1 # The variable order does not match `linux:build` and is invalid.
PROVIDER: aws
script: echo "Running rspec on linux..."
```
---
### `pages`
Use `pages` to define a [GitLab Pages](../../user/project/pages/_index.md) job that
uploads static content to GitLab. The content is then published as a website.
You must:
- Define `pages: true` to publish a directory named `public`
- Alternatively, define [`pages.publish`](#pagespublish) if want to use a different content directory.
- Have a non-empty `index.html` file in the root of the content directory.
**Keyword type**: Job keyword or Job name (deprecated). You can use it only as part of a job.
**Supported Values**:
- A boolean. Uses the default configuration when set to `true`
- A hash of configuration options, see the following sections for details.
**Example of `pages`**:
```yaml
create-pages:
stage: deploy
script:
- mv my-html-content public
pages: true # specifies that this is a Pages job and publishes the default public directory
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
environment: production
```
This example renames the `my-html-content/` directory to `public/`.
This directory is exported as an artifact and published with GitLab Pages.
**Example using a configuration hash**:
```yaml
create-pages:
stage: deploy
script:
- echo "nothing to do here"
pages: # specifies that this is a Pages job and publishes the default public directory
publish: my-html-content
expire_in: "1 week"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
environment: production
```
This example does not move the directory, but uses the `publish` property directly.
It also configures the pages deployment to be unpublished after a week.
**Additional details**:
- Using `pages` as a job name [is deprecated](deprecated_keywords.md#publish-keyword-and-pages-job-name-for-gitlab-pages).
- To use `pages` as a job name without triggering a Pages deployment, set the `pages` property to false
---
#### `pages.publish`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/415821) in GitLab 16.1.
- [Changed](https://gitlab.com/gitlab-org/gitlab/-/issues/500000) to allow variables when passed to `publish` property in GitLab 17.9.
- [Moved](https://gitlab.com/gitlab-org/gitlab/-/issues/428018) the `publish` property under the `pages` keyword in GitLab 17.9.
- [Appended](https://gitlab.com/gitlab-org/gitlab/-/issues/428018) the `pages.publish` path automatically to `artifacts:paths` in GitLab 17.10.
{{< /history >}}
Use `pages.publish` to configure the content directory of a [`pages` job](#pages).
**Keyword type**: Job keyword. You can use it only as part of a `pages` job.
**Supported values**: A path to a directory containing the Pages content.
In [GitLab 17.10 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/428018),
if not specified, the default `public` directory is used and if specified,
this path is automatically appended to [`artifacts:paths`](#artifactspaths).
**Example of `pages.publish`**:
```yaml
create-pages:
stage: deploy
script:
- npx @11ty/eleventy --input=path/to/eleventy/root --output=dist
pages:
publish: dist # this path is automatically appended to artifacts:paths
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
environment: production
```
This example uses [Eleventy](https://www.11ty.dev) to generate a static website and
output the generated HTML files into a the `dist/` directory. This directory is exported
as an artifact and published with GitLab Pages.
It is also possible to use variables in the `pages.publish` field. For example:
```yaml
create-pages:
stage: deploy
script:
- mkdir -p $CUSTOM_FOLDER/$CUSTOM_PATH
- cp -r public $CUSTOM_FOLDER/$CUSTOM_SUBFOLDER
pages:
publish: $CUSTOM_FOLDER/$CUSTOM_SUBFOLDER # this path is automatically appended to artifacts:paths
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
variables:
CUSTOM_FOLDER: "custom_folder"
CUSTOM_SUBFOLDER: "custom_subfolder"
```
The publish path specified must be relative to the build root.
**Additional details**:
- The top-level `publish` keyword [is deprecated](deprecated_keywords.md#publish-keyword-and-pages-job-name-for-gitlab-pages) and must now be nested under the `pages` keyword
---
#### `pages.path_prefix`
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
- Status: Beta
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/129534) in GitLab 16.7 as an [experiment](../../policy/development_stages_support.md) [with a flag](../../administration/feature_flags/_index.md) named `pages_multiple_versions_setting`, disabled by default.
- [Enabled on GitLab.com, GitLab Self-Managed, and GitLab Dedicated](https://gitlab.com/gitlab-org/gitlab/-/issues/422145) in GitLab 17.4.
- [Changed](https://gitlab.com/gitlab-org/gitlab/-/issues/507423) to allow periods in GitLab 17.8.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/487161) in GitLab 17.9. Feature flag `pages_multiple_versions_setting` removed.
{{< /history >}}
Use `pages.path_prefix` to configure a path prefix for [parallel deployments](../../user/project/pages/_index.md#parallel-deployments) of GitLab Pages.
**Keyword type**: Job keyword. You can use it only as part of a `pages` job.
**Supported values**:
- A string
- [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file)
- A combination of both
The given value is converted to lowercase and shortened to 63 bytes.
Everything except alphanumeric characters or periods is replaced with a hyphen.
Leading and trailing hyphens or periods are not permitted.
**Example of `pages.path_prefix`**:
```yaml
create-pages:
stage: deploy
script:
- echo "Pages accessible through ${CI_PAGES_URL}/${CI_COMMIT_BRANCH}"
pages: # specifies that this is a Pages job and publishes the default public directory
path_prefix: "$CI_COMMIT_BRANCH"
```
In this example, a different pages deployment is created for each branch.
---
#### `pages.expire_in`
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/456478) in GitLab 17.4.
- Support for variables [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/492289) in GitLab 17.11.
{{< /history >}}
Use `expire_in` to specify how long a deployment should be available before
it expires. After the deployment is expired, it's deactivated by a cron
job running every 10 minutes.
By default, [parallel deployments](../../user/project/pages/_index.md#parallel-deployments) expire
automatically after 24 hours.
To disable this behavior, set the value to `never`.
**Keyword type**: Job keyword. You can use it only as part of a `pages` job.
**Supported values**: The expiry time. If no unit is provided, the time is in seconds.
Variables are also supported. Valid values include:
- `'42'`
- `42 seconds`
- `3 mins 4 sec`
- `2 hrs 20 min`
- `2h20min`
- `6 mos 1 day`
- `47 yrs 6 mos and 4d`
- `3 weeks and 2 days`
- `never`
- `$DURATION`
**Example of `pages.expire_in`**:
```yaml
create-pages:
stage: deploy
script:
- echo "Pages accessible through ${CI_PAGES_URL}"
pages: # specifies that this is a Pages job and publishes the default public directory
expire_in: 1 week
```
---
### `parallel`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/336576) in GitLab 15.9, the maximum value for `parallel` is increased from 50 to 200.
{{< /history >}}
Use `parallel` to run a job multiple times in parallel in a single pipeline.
Multiple runners must exist, or a single runner must be configured to run multiple jobs concurrently.
Parallel jobs are named sequentially from `job_name 1/N` to `job_name N/N`.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A numeric value from `1` to `200`.
**Example of `parallel`**:
```yaml
test:
script: rspec
parallel: 5
```
This example creates 5 jobs that run in parallel, named `test 1/5` to `test 5/5`.
**Additional details**:
- Every parallel job has a `CI_NODE_INDEX` and `CI_NODE_TOTAL`
[predefined CI/CD variable](../variables/_index.md#predefined-cicd-variables) set.
- A pipeline with jobs that use `parallel` might:
- Create more jobs running in parallel than available runners. Excess jobs are queued
and marked `pending` while waiting for an available runner.
- Create too many jobs, and the pipeline fails with a `job_activity_limit_exceeded` error.
The maximum number of jobs that can exist in active pipelines is [limited at the instance-level](../../administration/instance_limits.md#number-of-jobs-in-active-pipelines).
**Related topics**:
- [Parallelize large jobs](../jobs/job_control.md#parallelize-large-jobs).
---
#### `parallel:matrix`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/336576) in GitLab 15.9, the maximum number of permutations is increased from 50 to 200.
{{< /history >}}
Use `parallel:matrix` to run a job multiple times in parallel in a single pipeline,
but with different variable values for each instance of the job.
Multiple runners must exist, or a single runner must be configured to run multiple jobs concurrently.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: An array of hashes of variables:
- The variable names can use only numbers, letters, and underscores (`_`).
- The values must be either a string, or an array of strings.
- The number of permutations cannot exceed 200.
**Example of `parallel:matrix`**:
```yaml
deploystacks:
stage: deploy
script:
- bin/deploy
parallel:
matrix:
- PROVIDER: aws
STACK:
- monitoring
- app1
- app2
- PROVIDER: ovh
STACK: [monitoring, backup, app]
- PROVIDER: [gcp, vultr]
STACK: [data, processing]
environment: $PROVIDER/$STACK
```
The example generates 10 parallel `deploystacks` jobs, each with different values
for `PROVIDER` and `STACK`:
```plaintext
deploystacks: [aws, monitoring]
deploystacks: [aws, app1]
deploystacks: [aws, app2]
deploystacks: [ovh, monitoring]
deploystacks: [ovh, backup]
deploystacks: [ovh, app]
deploystacks: [gcp, data]
deploystacks: [gcp, processing]
deploystacks: [vultr, data]
deploystacks: [vultr, processing]
```
**Additional details**:
- `parallel:matrix` jobs add the variable values to the job names to differentiate
the jobs from each other, but [large values can cause names to exceed limits](https://gitlab.com/gitlab-org/gitlab/-/issues/362262):
- [Job names](../jobs/_index.md#job-names) must be 255 characters or fewer.
- When using [`needs`](#needs), job names must be 128 characters or fewer.
- You cannot create multiple matrix configurations with the same variable values but different variable names.
Job names are generated from the variable values, not the variable names, so matrix entries
with identical values generate identical job names that overwrite each other.
For example, this `test` configuration would try to create two series of identical jobs,
but the `OS2` versions overwrite the `OS` versions:
```yaml
test:
parallel:
matrix:
- OS: [ubuntu]
PROVIDER: [aws, gcp]
- OS2: [ubuntu]
PROVIDER: [aws, gcp]
```
- There's a [known issue](../debugging.md#config-should-be-an-array-of-hashes-error-message) when using [`!reference` tags](yaml_optimization.md#reference-tags) with `parallel:matrix`.
**Related topics**:
- [Run a one-dimensional matrix of parallel jobs](../jobs/job_control.md#run-a-one-dimensional-matrix-of-parallel-jobs).
- [Run a matrix of triggered parallel jobs](../jobs/job_control.md#run-a-matrix-of-parallel-trigger-jobs).
- [Select different runner tags for each parallel matrix job](../jobs/job_control.md#select-different-runner-tags-for-each-parallel-matrix-job).
---
### `release`
Use `release` to create a [release](../../user/project/releases/_index.md).
The release job must have access to the [`release-cli`](https://gitlab.com/gitlab-org/release-cli/-/tree/master/docs),
which must be in the `$PATH`.
If you use the [Docker executor](https://docs.gitlab.com/runner/executors/docker.html),
you can use this image from the GitLab container registry: `registry.gitlab.com/gitlab-org/release-cli:latest`
If you use the [Shell executor](https://docs.gitlab.com/runner/executors/shell.html) or similar,
[install `release-cli`](../../user/project/releases/release_cli.md) on the server where the runner is registered.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: The `release` subkeys:
- [`tag_name`](#releasetag_name)
- [`tag_message`](#releasetag_message) (optional)
- [`name`](#releasename) (optional)
- [`description`](#releasedescription)
- [`ref`](#releaseref) (optional)
- [`milestones`](#releasemilestones) (optional)
- [`released_at`](#releasereleased_at) (optional)
- [`assets:links`](#releaseassetslinks) (optional)
**Example of `release` keyword**:
```yaml
release_job:
stage: release
image: registry.gitlab.com/gitlab-org/release-cli:latest
rules:
- if: $CI_COMMIT_TAG # Run this job when a tag is created manually
script:
- echo "Running the release job."
release:
tag_name: $CI_COMMIT_TAG
name: 'Release $CI_COMMIT_TAG'
description: 'Release created using the release-cli.'
```
This example creates a release:
- When you push a Git tag.
- When you add a Git tag in the UI at **Code > Tags**.
**Additional details**:
- All release jobs, except [trigger](#trigger) jobs, must include the `script` keyword. A release
job can use the output from script commands. If you don't need the script, you can use a placeholder:
```yaml
script:
- echo "release job"
```
An [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/223856) exists to remove this requirement.
- The `release` section executes after the `script` keyword and before the `after_script`.
- A release is created only if the job's main script succeeds.
- If the release already exists, it is not updated and the job with the `release` keyword fails.
**Related topics**:
- [CI/CD example of the `release` keyword](../../user/project/releases/_index.md#creating-a-release-by-using-a-cicd-job).
- [Create multiple releases in a single pipeline](../../user/project/releases/_index.md#create-multiple-releases-in-a-single-pipeline).
- [Use a custom SSL CA certificate authority](../../user/project/releases/_index.md#use-a-custom-ssl-ca-certificate-authority).
---
#### `release:tag_name`
Required. The Git tag for the release.
If the tag does not exist in the project yet, it is created at the same time as the release.
New tags use the SHA associated with the pipeline.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A tag name.
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `release:tag_name`**:
To create a release when a new tag is added to the project:
- Use the `$CI_COMMIT_TAG` CI/CD variable as the `tag_name`.
- Use [`rules:if`](#rulesif) to configure the job to run only for new tags.
```yaml
job:
script: echo "Running the release job for the new tag."
release:
tag_name: $CI_COMMIT_TAG
description: 'Release description'
rules:
- if: $CI_COMMIT_TAG
```
To create a release and a new tag at the same time, your [`rules`](#rules)
should **not** configure the job to run only for new tags. A semantic versioning example:
```yaml
job:
script: echo "Running the release job and creating a new tag."
release:
tag_name: ${MAJOR}_${MINOR}_${REVISION}
description: 'Release description'
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
```
---
#### `release:tag_message`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/363024) in GitLab 15.3. Supported by `release-cli` v0.12.0 or later.
{{< /history >}}
If the tag does not exist, the newly created tag is annotated with the message specified by `tag_message`.
If omitted, a lightweight tag is created.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A text string.
**Example of `release:tag_message`**:
```yaml
release_job:
stage: release
release:
tag_name: $CI_COMMIT_TAG
description: 'Release description'
tag_message: 'Annotated tag message'
```
---
#### `release:name`
The release name. If omitted, it is populated with the value of `release: tag_name`.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A text string.
**Example of `release:name`**:
```yaml
release_job:
stage: release
release:
name: 'Release $CI_COMMIT_TAG'
```
---
#### `release:description`
The long description of the release.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A string with the long description.
- The path to a file that contains the description.
- The file location must be relative to the project directory (`$CI_PROJECT_DIR`).
- If the file is a symbolic link, it must be in the `$CI_PROJECT_DIR`.
- The `./path/to/file` and filename can't contain spaces.
**Example of `release:description`**:
```yaml
job:
release:
tag_name: ${MAJOR}_${MINOR}_${REVISION}
description: './path/to/CHANGELOG.md'
```
**Additional details**:
- The `description` is evaluated by the shell that runs `release-cli`.
You can use CI/CD variables to define the description, but some shells
[use different syntax](../variables/job_scripts.md)
to reference variables. Similarly, some shells might require special characters
to be escaped. For example, backticks (`` ` ``) might need to be escaped with a backslash (` \ `).
---
#### `release:ref`
The `ref` for the release, if the `release: tag_name` doesn't exist yet.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A commit SHA, another tag name, or a branch name.
---
#### `release:milestones`
The title of each milestone the release is associated with.
---
#### `release:released_at`
The date and time when the release is ready.
**Supported values**:
- A date enclosed in quotes and expressed in ISO 8601 format.
**Example of `release:released_at`**:
```yaml
released_at: '2021-03-15T08:00:00Z'
```
**Additional details**:
- If it is not defined, the current date and time is used.
---
#### `release:assets:links`
Use `release:assets:links` to include [asset links](../../user/project/releases/release_fields.md#release-assets) in the release.
Requires `release-cli` version v0.4.0 or later.
**Example of `release:assets:links`**:
```yaml
assets:
links:
- name: 'asset1'
url: 'https://example.com/assets/1'
- name: 'asset2'
url: 'https://example.com/assets/2'
filepath: '/pretty/url/1' # optional
link_type: 'other' # optional
```
---
### `resource_group`
Use `resource_group` to create a [resource group](../resource_groups/_index.md) that
ensures a job is mutually exclusive across different pipelines for the same project.
For example, if multiple jobs that belong to the same resource group are queued simultaneously,
only one of the jobs starts. The other jobs wait until the `resource_group` is free.
Resource groups behave similar to semaphores in other programming languages.
You can choose a [process mode](../resource_groups/_index.md#process-modes) to strategically control the job concurrency for your deployment preferences. The default process mode is `unordered`. To change the process mode of a resource group, use the [API](../../api/resource_groups.md#edit-an-existing-resource-group) to send a request to edit an existing resource group.
You can define multiple resource groups per environment. For example,
when deploying to physical devices, you might have multiple physical devices. Each device
can be deployed to, but only one deployment can occur per device at any given time.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- Only letters, digits, `-`, `_`, `/`, `$`, `{`, `}`, `.`, and spaces.
It can't start or end with `/`. CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `resource_group`**:
```yaml
deploy-to-production:
script: deploy
resource_group: production
```
In this example, two `deploy-to-production` jobs in two separate pipelines can never run at the same time. As a result,
you can ensure that concurrent deployments never happen to the production environment.
**Related topics**:
- [Pipeline-level concurrency control with cross-project/parent-child pipelines](../resource_groups/_index.md#pipeline-level-concurrency-control-with-cross-projectparent-child-pipelines).
---
### `retry`
Use `retry` to configure how many times a job is retried if it fails.
If not defined, defaults to `0` and jobs do not retry.
When a job fails, the job is processed up to two more times, until it succeeds or
reaches the maximum number of retries.
By default, all failure types cause the job to be retried. Use [`retry:when`](#retrywhen) or [`retry:exit_codes`](#retryexit_codes)
to select which failures to retry on.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `0` (default), `1`, or `2`.
**Example of `retry`**:
```yaml
test:
script: rspec
retry: 2
test_advanced:
script:
- echo "Run a script that results in exit code 137."
- exit 137
retry:
max: 2
when: runner_system_failure
exit_codes: 137
```
`test_advanced` will be retried up to 2 times if the exit code is `137` or if it had
a runner system failure.
---
#### `retry:when`
Use `retry:when` with `retry:max` to retry jobs for only specific failure cases.
`retry:max` is the maximum number of retries, like [`retry`](#retry), and can be
`0`, `1`, or `2`.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- A single failure type, or an array of one or more failure types:
<!--
If you change any of the following values, make sure to update the `RETRY_WHEN_IN_DOCUMENTATION`
array in `spec/lib/gitlab/ci/config/entry/retry_spec.rb`.
The test there makes sure that all documented
values are valid as a configuration option and therefore should always
stay in sync with this documentation.
-->
- `always`: Retry on any failure (default).
- `unknown_failure`: Retry when the failure reason is unknown.
- `script_failure`: Retry when:
- The script failed.
- The runner failed to pull the Docker image. For `docker`, `docker+machine`, `kubernetes` [executors](https://docs.gitlab.com/runner/executors/).
- `api_failure`: Retry on API failure.
- `stuck_or_timeout_failure`: Retry when the job got stuck or timed out.
- `runner_system_failure`: Retry if there is a runner system failure (for example, job setup failed).
- `runner_unsupported`: Retry if the runner is unsupported.
- `stale_schedule`: Retry if a delayed job could not be executed.
- `job_execution_timeout`: Retry if the script exceeded the maximum execution time set for the job.
- `archived_failure`: Retry if the job is archived and can't be run.
- `unmet_prerequisites`: Retry if the job failed to complete prerequisite tasks.
- `scheduler_failure`: Retry if the scheduler failed to assign the job to a runner.
- `data_integrity_failure`: Retry if there is an unknown job problem.
**Example of `retry:when`** (single failure type):
```yaml
test:
script: rspec
retry:
max: 2
when: runner_system_failure
```
If there is a failure other than a runner system failure, the job is not retried.
**Example of `retry:when`** (array of failure types):
```yaml
test:
script: rspec
retry:
max: 2
when:
- runner_system_failure
- stuck_or_timeout_failure
```
---
#### `retry:exit_codes`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/430037) in GitLab 16.10 [with a flag](../../administration/feature_flags/_index.md) named `ci_retry_on_exit_codes`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/430037) in GitLab 16.11.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/452412) in GitLab 17.5. Feature flag `ci_retry_on_exit_codes` removed.
{{< /history >}}
Use `retry:exit_codes` with `retry:max` to retry jobs for only specific failure cases.
`retry:max` is the maximum number of retries, like [`retry`](#retry), and can be
`0`, `1`, or `2`.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- A single exit code.
- An array of exit codes.
**Example of `retry:exit_codes`**:
```yaml
test_job_1:
script:
- echo "Run a script that results in exit code 1. This job isn't retried."
- exit 1
retry:
max: 2
exit_codes: 137
test_job_2:
script:
- echo "Run a script that results in exit code 137. This job will be retried."
- exit 137
retry:
max: 1
exit_codes:
- 255
- 137
```
**Related topics**:
You can specify the number of [retry attempts for certain stages of job execution](../runners/configure_runners.md#job-stages-attempts)
using variables.
---
### `rules`
Use `rules` to include or exclude jobs in pipelines.
Rules are evaluated when the pipeline is created, and evaluated in order. When a match is found,
no more rules are checked and the job is either included or excluded from the pipeline
depending on the configuration. If no rules match, the job is not added to the pipeline.
`rules` accepts an array of rules. Each rules must have at least one of:
- `if`
- `changes`
- `exists`
- `when`
Rules can also optionally be combined with:
- `allow_failure`
- `needs`
- `variables`
- `interruptible`
You can combine multiple keywords together for [complex rules](../jobs/job_rules.md#complex-rules).
The job is added to the pipeline:
- If an `if`, `changes`, or `exists` rule matches, and is configured with `when: on_success` (default if not defined),
`when: delayed`, or `when: always`.
- If a rule is reached that is only `when: on_success`, `when: delayed`, or `when: always`.
The job is not added to the pipeline:
- If no rules match.
- If a rule matches and has `when: never`.
For additional examples, see [Specify when jobs run with `rules`](../jobs/job_rules.md).
---
#### `rules:if`
Use `rules:if` clauses to specify when to add a job to a pipeline:
- If an `if` statement is true, add the job to the pipeline.
- If an `if` statement is true, but it's combined with `when: never`, do not add the job to the pipeline.
- If an `if` statement is false, check the next `rules` item (if any more exist).
`if` clauses are evaluated:
- Based on the values of [CI/CD variables](../variables/_index.md) or [predefined CI/CD variables](../variables/predefined_variables.md),
with [some exceptions](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
- In order, following [`rules` execution flow](#rules).
**Keyword type**: Job-specific and pipeline-specific. You can use it as part of a job
to configure the job behavior, or with [`workflow`](#workflow) to configure the pipeline behavior.
**Supported values**:
- A [CI/CD variable expression](../jobs/job_rules.md#cicd-variable-expressions).
**Example of `rules:if`**:
```yaml
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/ && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME != $CI_DEFAULT_BRANCH
when: never
- if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/
when: manual
allow_failure: true
- if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME
```
**Additional details**:
- You cannot use [nested variables](../variables/where_variables_can_be_used.md#nested-variable-expansion)
with `if`. See [issue 327780](https://gitlab.com/gitlab-org/gitlab/-/issues/327780) for more details.
- If a rule matches and has no `when` defined, the rule uses the `when`
defined for the job, which defaults to `on_success` if not defined.
- You can [mix `when` at the job-level with `when` in rules](https://gitlab.com/gitlab-org/gitlab/-/issues/219437).
`when` configuration in `rules` takes precedence over `when` at the job-level.
- Unlike variables in [`script`](../variables/job_scripts.md)
sections, variables in rules expressions are always formatted as `$VARIABLE`.
- You can use `rules:if` with `include` to [conditionally include other configuration files](includes.md#use-rules-with-include).
- CI/CD variables on the right side of `=~` and `!~` expressions are [evaluated as regular expressions](../jobs/job_rules.md#store-a-regular-expression-in-a-variable).
**Related topics**:
- [Common `if` expressions for `rules`](../jobs/job_rules.md#common-if-clauses-with-predefined-variables).
- [Avoid duplicate pipelines](../jobs/job_rules.md#avoid-duplicate-pipelines).
- [Use `rules` to run merge request pipelines](../pipelines/merge_request_pipelines.md#add-jobs-to-merge-request-pipelines).
---
#### `rules:changes`
Use `rules:changes` to specify when to add a job to a pipeline by checking for changes
to specific files.
For new branch pipelines or when there is no Git `push` event, `rules: changes` always evaluates to true
and the job always runs. Pipelines like tag pipelines, scheduled pipelines,
and manual pipelines, all do **not** have a Git `push` event associated with them.
To cover these cases, use [`rules: changes: compare_to`](#ruleschangescompare_to) to specify
the branch to compare against the pipeline ref.
If you do not use `compare_to`, you should use `rules: changes` only with [branch pipelines](../pipelines/pipeline_types.md#branch-pipeline)
or [merge request pipelines](../pipelines/merge_request_pipelines.md), though
`rules: changes` still evaluates to true when creating a new branch. With:
- Merge request pipelines, `rules:changes` compares the changes with the target MR branch.
- Branch pipelines, `rules:changes` compares the changes with the previous commit on the branch.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
An array including any number of:
- Paths to files. The file paths can include [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
- Wildcard paths for:
- Single directories, for example `path/to/directory/*`.
- A directory and all its subdirectories, for example `path/to/directory/**/*`.
- Wildcard [glob](https://en.wikipedia.org/wiki/Glob_(programming)) paths for all files
with the same extension or multiple extensions, for example `*.md` or `path/to/directory/*.{rb,py,sh}`.
- Wildcard paths to files in the root directory, or all directories, wrapped in double quotes.
For example `"*.json"` or `"**/*.json"`.
**Example of `rules:changes`**:
```yaml
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
- Dockerfile
when: manual
allow_failure: true
docker build alternative:
variables:
DOCKERFILES_DIR: 'path/to/dockerfiles'
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
- $DOCKERFILES_DIR/**/*
```
In this example:
- If the pipeline is a merge request pipeline, check `Dockerfile` and the files in
`$DOCKERFILES_DIR/**/*` for changes.
- If `Dockerfile` has changed, add the job to the pipeline as a manual job, and the pipeline
continues running even if the job is not triggered (`allow_failure: true`).
- If a file in `$DOCKERFILES_DIR/**/*` has changed, add the job to the pipeline.
- If no listed files have changed, do not add either job to any pipeline (same as `when: never`).
**Additional details**:
- Glob patterns are interpreted with Ruby's [`File.fnmatch`](https://docs.ruby-lang.org/en/master/File.html#method-c-fnmatch)
with the [flags](https://docs.ruby-lang.org/en/master/File/Constants.html#module-File::Constants-label-Filename+Globbing+Constants+-28File-3A-3AFNM_-2A-29)
`File::FNM_PATHNAME | File::FNM_DOTMATCH | File::FNM_EXTGLOB`.
- A maximum of 50 patterns or file paths can be defined per `rules:changes` section.
- `changes` resolves to `true` if any of the matching files are changed (an `OR` operation).
- For additional examples, see [Specify when jobs run with `rules`](../jobs/job_rules.md).
- You can use the `$` character for both variables and paths. For example, if the
`$VAR` variable exists, its value is used. If it does not exist, the `$` is interpreted
as being part of a path.
**Related topics**:
- [Jobs or pipelines can run unexpectedly when using `rules: changes`](../jobs/job_troubleshooting.md#jobs-or-pipelines-run-unexpectedly-when-using-changes).
---
##### `rules:changes:paths`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/90171) in GitLab 15.2.
{{< /history >}}
Use `rules:changes` to specify that a job only be added to a pipeline when specific
files are changed, and use `rules:changes:paths` to specify the files.
`rules:changes:paths` is the same as using [`rules:changes`](#ruleschanges) without
any subkeys. All additional details and related topics are the same.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- Same as `rules:changes`.
**Example of `rules:changes:paths`**:
```yaml
docker-build-1:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
- Dockerfile
docker-build-2:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
paths:
- Dockerfile
```
In this example, both jobs have the same behavior.
---
##### `rules:changes:compare_to`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/293645) in GitLab 15.3 [with a flag](../../administration/feature_flags/_index.md) named `ci_rules_changes_compare`. Enabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/366412) in GitLab 15.5. Feature flag `ci_rules_changes_compare` removed.
- Support for CI/CD variables [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/369916) in GitLab 17.2.
{{< /history >}}
Use `rules:changes:compare_to` to specify which ref to compare against for changes to the files
listed under [`rules:changes:paths`](#ruleschangespaths).
**Keyword type**: Job keyword. You can use it only as part of a job, and it must be combined with `rules:changes:paths`.
**Supported values**:
- A branch name, like `main`, `branch1`, or `refs/heads/branch1`.
- A tag name, like `tag1` or `refs/tags/tag1`.
- A commit SHA, like `2fg31ga14b`.
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `rules:changes:compare_to`**:
```yaml
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
paths:
- Dockerfile
compare_to: 'refs/heads/branch1'
```
In this example, the `docker build` job is only included when the `Dockerfile` has changed
relative to `refs/heads/branch1` and the pipeline source is a merge request event.
**Additional details**:
- Using `compare_to` with [merged results pipelines](../pipelines/merged_results_pipelines.md#troubleshooting) can cause unexpected results, because the comparison base is an internal commit that GitLab creates.
**Related topics**:
- You can use `rules:changes:compare_to` to [skip a job if the branch is empty](../jobs/job_rules.md#skip-jobs-if-the-branch-is-empty).
---
#### `rules:exists`
{{< history >}}
- CI/CD variable support [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/283881) in GitLab 15.6.
- Maximum number of checks against `exists` patterns or file paths [increased](https://gitlab.com/gitlab-org/gitlab/-/issues/227632) from 10,000 to 50,000 in GitLab 17.7.
- Support for directory paths [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/327485) in GitLab 18.2.
{{< /history >}}
Use `exists` to run a job when certain files or directories exist in the repository.
**Keyword type**: Job keyword. You can use it as part of a job or an [`include`](#include).
**Supported values**:
- An array of file or directory paths. Paths are relative to the project directory (`$CI_PROJECT_DIR`)
and can't directly link outside it. File paths can use glob patterns and
[CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `rules:exists`**:
```yaml
job:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- exists:
- Dockerfile
job2:
variables:
DOCKERPATH: "**/Dockerfile"
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- exists:
- $DOCKERPATH
```
In this example:
- `job1` runs if a `Dockerfile` exists in the root directory of the repository.
- `job2` runs if a `Dockerfile` exists anywhere in the repository.
**Additional details**:
- Glob patterns are interpreted with Ruby's [`File.fnmatch`](https://docs.ruby-lang.org/en/master/File.html#method-c-fnmatch)
with the [flags](https://docs.ruby-lang.org/en/master/File/Constants.html#module-File::Constants-label-Filename+Globbing+Constants+-28File-3A-3AFNM_-2A-29)
`File::FNM_PATHNAME | File::FNM_DOTMATCH | File::FNM_EXTGLOB`.
- For performance reasons, GitLab performs a maximum of 50,000 checks against
`exists` patterns or file paths. After the 50,000th check, rules with patterned
globs always match. In other words, the `exists` rule always assumes a match in
projects with more than 50,000 files, or if there are fewer than 50,000 files but
the `exists` rules are checked more than 50,000 times.
- If there are multiple patterned globs, the limit is 50,000 divided by the number
of globs. For example, a rule with 5 patterned globs has file limit of 10,000.
- A maximum of 50 patterns or file paths can be defined per `rules:exists` section.
- `exists` resolves to `true` if any of the listed files are found (an `OR` operation).
- With job-level `rules:exists`, GitLab searches for the files in the project and
ref that runs the pipeline. When using [`include` with `rules:exists`](includes.md#include-with-rulesexists),
GitLab searches for the files or directories in the project and ref of the file that contains the `include`
section. The project containing the `include` section can be different than the project
running the pipeline when using:
- [Nested includes](includes.md#use-nested-includes).
- [Compliance pipelines](../../user/compliance/compliance_pipelines.md).
- `rules:exists` cannot search for the presence of [artifacts](../jobs/job_artifacts.md),
because `rules` evaluation happens before jobs run and artifacts are fetched.
- To test the existence of a directory, the path must end with a forward slash (/)
---
##### `rules:exists:paths`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/386040) in GitLab 16.11 [with a flag](../../administration/feature_flags/_index.md) named `ci_support_rules_exists_paths_and_project`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/386040) in GitLab 17.0. Feature flag `ci_support_rules_exists_paths_and_project` removed.
{{< /history >}}
`rules:exists:paths` is the same as using [`rules:exists`](#rulesexists) without
any subkeys. All additional details are the same.
**Keyword type**: Job keyword. You can use it as part of a job or an [`include`](#include).
**Supported values**:
- An array of file paths.
**Example of `rules:exists:paths`**:
```yaml
docker-build-1:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
exists:
- Dockerfile
docker-build-2:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
exists:
paths:
- Dockerfile
```
In this example, both jobs have the same behavior.
**Additional details**:
- In some cases you cannot use `/` or `./` in a CI/CD variable with `exists`.
See [issue 386595](https://gitlab.com/gitlab-org/gitlab/-/issues/386595) for more details.
---
##### `rules:exists:project`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/386040) in GitLab 16.11 [with a flag](../../administration/feature_flags/_index.md) named `ci_support_rules_exists_paths_and_project`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/386040) in GitLab 17.0. Feature flag `ci_support_rules_exists_paths_and_project` removed.
{{< /history >}}
Use `rules:exists:project` to specify the location in which to search for the files
listed under [`rules:exists:paths`](#rulesexistspaths). Must be used with `rules:exists:paths`.
**Keyword type**: Job keyword. You can use it as part of a job or an [`include`](#include), and it must be combined with `rules:exists:paths`.
**Supported values**:
- `exists:project`: A full project path, including namespace and group.
- `exists:ref`: Optional. The commit ref to use to search for the file. The ref can be a tag, branch name, or SHA. Defaults to the `HEAD` of the project when not specified.
**Example of `rules:exists:project`**:
```yaml
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- exists:
paths:
- Dockerfile
project: my-group/my-project
ref: v1.0.0
```
In this example, the `docker build` job is only included when the `Dockerfile` exists in
the project `my-group/my-project` on the commit tagged with `v1.0.0`.
---
#### `rules:when`
Use `rules:when` alone or as part of another rule to control conditions for adding
a job to a pipeline. `rules:when` is similar to [`when`](#when), but with slightly
different input options.
If a `rules:when` rule is not combined with `if`, `changes`, or `exists`, it always matches
if reached when evaluating a job's rules.
**Keyword type**: Job-specific. You can use it only as part of a job.
**Supported values**:
- `on_success` (default): Run the job only when no jobs in earlier stages fail.
- `on_failure`: Run the job only when at least one job in an earlier stage fails.
- `never`: Don't run the job regardless of the status of jobs in earlier stages.
- `always`: Run the job regardless of the status of jobs in earlier stages.
- `manual`: Add the job to the pipeline as a [manual job](../jobs/job_control.md#create-a-job-that-must-be-run-manually).
The default value for [`allow_failure`](#allow_failure) changes to `false`.
- `delayed`: Add the job to the pipeline as a [delayed job](../jobs/job_control.md#run-a-job-after-a-delay).
**Example of `rules:when`**:
```yaml
job1:
rules:
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
- if: $CI_COMMIT_REF_NAME =~ /feature/
when: delayed
- when: manual
script:
- echo
```
In this example, `job1` is added to pipelines:
- For the default branch, with `when: on_success` which is the default behavior
when `when` is not defined.
- For feature branches as a delayed job.
- In all other cases as a manual job.
**Additional details**:
- When evaluating the status of jobs for `on_success` and `on_failure`:
- Jobs with [`allow_failure: true`](#allow_failure) in earlier stages are considered successful, even if they failed.
- Skipped jobs in earlier stages, for example [manual jobs that have not been started](../jobs/job_control.md#create-a-job-that-must-be-run-manually),
are considered successful.
- When using `rules:when: manual` to [add a manual job](../jobs/job_control.md#create-a-job-that-must-be-run-manually):
- [`allow_failure`](#allow_failure) becomes `false` by default. This default is the opposite of
using [`when: manual`](#when) to add a manual job.
- To achieve the same behavior as `when: manual` defined outside of `rules`, set [`rules: allow_failure`](#rulesallow_failure) to `true`.
---
#### `rules:allow_failure`
Use [`allow_failure: true`](#allow_failure) in `rules` to allow a job to fail
without stopping the pipeline.
You can also use `allow_failure: true` with a manual job. The pipeline continues
running without waiting for the result of the manual job. `allow_failure: false`
combined with `when: manual` in rules causes the pipeline to wait for the manual
job to run before continuing.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `true` or `false`. Defaults to `false` if not defined.
**Example of `rules:allow_failure`**:
```yaml
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH
when: manual
allow_failure: true
```
If the rule matches, then the job is a manual job with `allow_failure: true`.
**Additional details**:
- The rule-level `rules:allow_failure` overrides the job-level [`allow_failure`](#allow_failure),
and only applies when the specific rule triggers the job.
---
#### `rules:needs`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/31581) in GitLab 16.0 [with a flag](../../administration/feature_flags/_index.md) named `introduce_rules_with_needs`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/408871) in GitLab 16.2. Feature flag `introduce_rules_with_needs` removed.
{{< /history >}}
Use `needs` in rules to update a job's [`needs`](#needs) for specific conditions. When a condition matches a rule, the job's `needs` configuration is completely replaced with the `needs` in the rule.
**Keyword type**: Job-specific. You can use it only as part of a job.
**Supported values**:
- An array of job names as strings.
- A hash with a job name, optionally with additional attributes.
- An empty array (`[]`), to set the job needs to none when the specific condition is met.
**Example of `rules:needs`**:
```yaml
build-dev:
stage: build
rules:
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
script: echo "Feature branch, so building dev version..."
build-prod:
stage: build
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
script: echo "Default branch, so building prod version..."
tests:
stage: test
rules:
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
needs: ['build-dev']
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
needs: ['build-prod']
script: echo "Running dev specs by default, or prod specs when default branch..."
```
In this example:
- If the pipeline runs on a branch that is not the default branch, and therefore the rule matches the first condition, the `specs` job needs the `build-dev` job.
- If the pipeline runs on the default branch, and therefore the rule matches the second condition, the `specs` job needs the `build-prod` job.
**Additional details**:
- `needs` in rules override any `needs` defined at the job-level. When overridden, the behavior is same as [job-level `needs`](#needs).
- `needs` in rules can accept [`artifacts`](#needsartifacts) and [`optional`](#needsoptional).
---
#### `rules:variables`
Use [`variables`](#variables) in `rules` to define variables for specific conditions.
**Keyword type**: Job-specific. You can use it only as part of a job.
**Supported values**:
- A hash of variables in the format `VARIABLE-NAME: value`.
**Example of `rules:variables`**:
```yaml
job:
variables:
DEPLOY_VARIABLE: "default-deploy"
rules:
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
variables: # Override DEPLOY_VARIABLE defined
DEPLOY_VARIABLE: "deploy-production" # at the job level.
- if: $CI_COMMIT_REF_NAME =~ /feature/
variables:
IS_A_FEATURE: "true" # Define a new variable.
script:
- echo "Run script with $DEPLOY_VARIABLE as an argument"
- echo "Run another script if $IS_A_FEATURE exists"
```
---
#### `rules:interruptible`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/194023) in GitLab 16.10.
{{< /history >}}
Use `interruptible` in rules to update a job's [`interruptible`](#interruptible) value for specific conditions.
**Keyword type**: Job-specific. You can use it only as part of a job.
**Supported values**:
- `true` or `false`.
**Example of `rules:interruptible`**:
```yaml
job:
script: echo "Hello, Rules!"
interruptible: true
rules:
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
interruptible: false # Override interruptible defined at the job level.
- when: on_success
```
**Additional details**:
- The rule-level `rules:interruptible` overrides the job-level [`interruptible`](#interruptible),
and only applies when the specific rule triggers the job.
---
### `run`
{{< details >}}
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/440487) in GitLab 17.3 [with a flag](../../administration/feature_flags/_index.md) named `pipeline_run_keyword`. Disabled by default. Requires GitLab Runner 17.1.
- Feature flag `pipeline_run_keyword` [removed](https://gitlab.com/gitlab-org/gitlab/-/issues/471925) in GitLab 17.5.
{{< /history >}}
{{< alert type="note" >}}
This feature is available for testing, but not ready for production use.
{{< /alert >}}
Use `run` to define a series of [steps](../steps/_index.md) to be executed in a job. Each step can be either a script or a predefined step.
You can also provide optional environment variables and inputs.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- An array of hashes, where each hash represents a step with the following possible keys:
- `name`: A string representing the name of the step.
- `script`: A string or array of strings containing shell commands to execute.
- `step`: A string identifying a predefined step to run.
- `env`: Optional. A hash of environment variables specific to this step.
- `inputs`: Optional. A hash of input parameters for predefined steps.
Each array entry must have a `name`, and one `script` or `step` (but not both).
**Example of `run`**:
``` yaml
job:
run:
- name: 'hello_steps'
script: 'echo "hello from step1"'
- name: 'bye_steps'
step: gitlab.com/gitlab-org/ci-cd/runner-tools/echo-step@main
inputs:
echo: 'bye steps!'
env:
var1: 'value 1'
```
In this example, the job has two steps:
- `hello_steps` runs the `echo` shell command.
- `bye_steps` uses a predefined step with an environment variable and an input parameter.
**Additional details**:
- A step can have either a `script` or a `step` key, but not both.
- A `run` configuration cannot be used together with existing [`script`](#script), [`after_script`](#after_script) or [`before_script`](#before_script) keywords.
- Multi-line scripts can be defined using [YAML block scalar syntax](script.md#split-long-commands).
---
### `script`
Use `script` to specify commands for the runner to execute.
All jobs except [trigger jobs](#trigger) require a `script` keyword.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: An array including:
- Single line commands.
- Long commands [split over multiple lines](script.md#split-long-commands).
- [YAML anchors](yaml_optimization.md#yaml-anchors-for-scripts).
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `script`**:
```yaml
job1:
script: "bundle exec rspec"
job2:
script:
- uname -a
- bundle exec rspec
```
**Additional details**:
- When you use [these special characters in `script`](script.md#use-special-characters-with-script), you must use single quotes (`'`) or double quotes (`"`).
**Related topics**:
- You can [ignore non-zero exit codes](script.md#ignore-non-zero-exit-codes).
- [Use color codes with `script`](script.md#add-color-codes-to-script-output)
to make job logs easier to review.
- [Create custom collapsible sections](../jobs/job_logs.md#custom-collapsible-sections)
to simplify job log output.
---
### `secrets`
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use `secrets` to specify [CI/CD secrets](../secrets/_index.md) to:
- Retrieve from an external secrets provider.
- Make available in the job as [CI/CD variables](../variables/_index.md)
([`file` type](../variables/_index.md#use-file-type-cicd-variables) by default).
---
#### `secrets:vault`
{{< history >}}
- `generic` engine option [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/366492) in GitLab Runner 16.11.
{{< /history >}}
Use `secrets:vault` to specify secrets provided by a [HashiCorp Vault](https://www.vaultproject.io/).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `engine:name`: Name of the secrets engine. Can be one of `kv-v2` (default), `kv-v1`, or `generic`.
- `engine:path`: Path to the secrets engine.
- `path`: Path to the secret.
- `field`: Name of the field where the password is stored.
**Example of `secrets:vault`**:
To specify all details explicitly and use the [KV-V2](https://developer.hashicorp.com/vault/docs/secrets/kv/kv-v2) secrets engine:
```yaml
job:
secrets:
DATABASE_PASSWORD: # Store the path to the secret in this CI/CD variable
vault: # Translates to secret: `ops/data/production/db`, field: `password`
engine:
name: kv-v2
path: ops
path: production/db
field: password
```
You can shorten this syntax. With the short syntax, `engine:name` and `engine:path`
both default to `kv-v2`:
```yaml
job:
secrets:
DATABASE_PASSWORD: # Store the path to the secret in this CI/CD variable
vault: production/db/password # Translates to secret: `kv-v2/data/production/db`, field: `password`
```
To specify a custom secrets engine path in the short syntax, add a suffix that starts with `@`:
```yaml
job:
secrets:
DATABASE_PASSWORD: # Store the path to the secret in this CI/CD variable
vault: production/db/password@ops # Translates to secret: `ops/data/production/db`, field: `password`
```
---
#### `secrets:gcp_secret_manager`
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/11739) in GitLab 16.8 and GitLab Runner 16.8.
{{< /history >}}
Use `secrets:gcp_secret_manager` to specify secrets provided by [GCP Secret Manager](https://cloud.google.com/security/products/secret-manager).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `name`: Name of the secret.
- `version`: Version of the secret.
**Example of `secrets:gcp_secret_manager`**:
```yaml
job:
secrets:
DATABASE_PASSWORD:
gcp_secret_manager:
name: 'test'
version: 2
```
**Related topics**:
- [Use GCP Secret Manager secrets in GitLab CI/CD](../secrets/gcp_secret_manager.md).
---
#### `secrets:azure_key_vault`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/271271) in GitLab 16.3 and GitLab Runner 16.3.
{{< /history >}}
Use `secrets:azure_key_vault` to specify secrets provided by a [Azure Key Vault](https://azure.microsoft.com/en-us/products/key-vault/).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `name`: Name of the secret.
- `version`: Version of the secret.
**Example of `secrets:azure_key_vault`**:
```yaml
job:
secrets:
DATABASE_PASSWORD:
azure_key_vault:
name: 'test'
version: 'test'
```
**Related topics**:
- [Use Azure Key Vault secrets in GitLab CI/CD](../secrets/azure_key_vault.md).
---
#### `secrets:file`
Use `secrets:file` to configure the secret to be stored as either a
[`file` or `variable` type CI/CD variable](../variables/_index.md#use-file-type-cicd-variables)
By default, the secret is passed to the job as a `file` type CI/CD variable. The value
of the secret is stored in the file and the variable contains the path to the file.
If your software can't use `file` type CI/CD variables, set `file: false` to store
the secret value directly in the variable.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `true` (default) or `false`.
**Example of `secrets:file`**:
```yaml
job:
secrets:
DATABASE_PASSWORD:
vault: production/db/password@ops
file: false
```
**Additional details**:
- The `file` keyword is a setting for the CI/CD variable and must be nested under
the CI/CD variable name, not in the `vault` section.
---
#### `secrets:token`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/356986) in GitLab 15.8, controlled by the **Limit JSON Web Token (JWT) access** setting.
- [Made always available and **Limit JSON Web Token (JWT) access** setting removed](https://gitlab.com/gitlab-org/gitlab/-/issues/366798) in GitLab 16.0.
{{< /history >}}
Use `secrets:token` to explicitly select a token to use when authenticating with the external secrets provider by referencing the token's CI/CD variable.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- The name of an ID token
**Example of `secrets:token`**:
```yaml
job:
id_tokens:
AWS_TOKEN:
aud: https://aws.example.com
VAULT_TOKEN:
aud: https://vault.example.com
secrets:
DB_PASSWORD:
vault: gitlab/production/db
token: $VAULT_TOKEN
```
**Additional details**:
- When the `token` keyword is not set and there is only one token defined, the defined token will automatically be used.
- If there is more than one token defined, you should specify which token to use by setting the `token` keyword.
If you do not specify which token to use, it is not possible to predict which token is used each time the job runs.
---
### `services`
Use `services` to specify any additional Docker images that your scripts require to run successfully. The [`services` image](../services/_index.md) is linked
to the image specified in the [`image`](#image) keyword.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: The name of the services image, including the registry path if needed, in one of these formats:
- `<image-name>` (Same as using `<image-name>` with the `latest` tag)
- `<image-name>:<tag>`
- `<image-name>@<digest>`
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file), but [not for `alias`](https://gitlab.com/gitlab-org/gitlab/-/issues/19561).
**Example of `services`**:
```yaml
default:
image:
name: ruby:2.6
entrypoint: ["/bin/bash"]
services:
- name: my-postgres:11.7
alias: db-postgres
entrypoint: ["/usr/local/bin/db-postgres"]
command: ["start"]
before_script:
- bundle install
test:
script:
- bundle exec rake spec
```
In this example, GitLab launches two containers for the job:
- A Ruby container that runs the `script` commands.
- A PostgreSQL container. The `script` commands in the Ruby container can connect to
the PostgreSQL database at the `db-postgres` hostname.
**Related topics**:
- [Available settings for `services`](../services/_index.md#available-settings-for-services).
- [Define `services` in the `.gitlab-ci.yml` file](../services/_index.md#define-services-in-the-gitlab-ciyml-file).
- [Run your CI/CD jobs in Docker containers](../docker/using_docker_images.md).
- [Use Docker to build Docker images](../docker/using_docker_build.md).
---
#### `services:docker`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/27919) in GitLab 16.7. Requires GitLab Runner 16.7 or later.
- `user` input option [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/137907) in GitLab 16.8.
{{< /history >}}
Use `services:docker` to pass options to the Docker executor of a GitLab Runner.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
A hash of options for the Docker executor, which can include:
- `platform`: Selects the architecture of the image to pull. When not specified,
the default is the same platform as the host runner.
- `user`: Specify the username or UID to use when running the container.
**Example of `services:docker`**:
```yaml
arm-sql-job:
script: echo "Run sql tests in service container"
image: ruby:2.6
services:
- name: super/sql:experimental
docker:
platform: arm64/v8
user: dave
```
**Additional details**:
- `services:docker:platform` maps to the [`docker pull --platform` option](https://docs.docker.com/reference/cli/docker/image/pull/#options).
- `services:docker:user` maps to the [`docker run --user` option](https://docs.docker.com/reference/cli/docker/container/run/#options).
---
#### `services:kubernetes`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/38451) in GitLab 18.0. Requires GitLab Runner 17.11 or later.
- `user` input option [introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/5469) in GitLab Runner 17.11.
- `user` input option [extended to support `uid:gid` format](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/5540) in GitLab 18.0.
{{< /history >}}
Use `services:kubernetes` to pass options to the GitLab Runner [Kubernetes executor](https://docs.gitlab.com/runner/executors/kubernetes/).
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
A hash of options for the Kubernetes executor, which can include:
- `user`: Specify the username or UID to use when the container runs. You can also use it to set GID by using the `UID:GID` format.
**Example of `services:kubernetes` with only UID**:
```yaml
arm-sql-job:
script: echo "Run sql tests"
image: ruby:2.6
services:
- name: super/sql:experimental
kubernetes:
user: "1001"
```
**Example of `services:kubernetes` with both UID and GID**:
```yaml
arm-sql-job:
script: echo "Run sql tests"
image: ruby:2.6
services:
- name: super/sql:experimental
kubernetes:
user: "1001:1001"
```
---
#### `services:pull_policy`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/21619) in GitLab 15.1 [with a flag](../../administration/feature_flags/_index.md) named `ci_docker_image_pull_policy`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/363186) in GitLab 15.2.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/363186) in GitLab 15.4. [Feature flag `ci_docker_image_pull_policy`](https://gitlab.com/gitlab-org/gitlab/-/issues/363186) removed.
{{< /history >}}
The pull policy that the runner uses to fetch the Docker image. Requires GitLab Runner 15.1 or later.
**Keyword type**: Job keyword. You can use it only as part of a job or in the [`default` section](#default).
**Supported values**:
- A single pull policy, or multiple pull policies in an array.
Can be `always`, `if-not-present`, or `never`.
**Examples of `services:pull_policy`**:
```yaml
job1:
script: echo "A single pull policy."
services:
- name: postgres:11.6
pull_policy: if-not-present
job2:
script: echo "Multiple pull policies."
services:
- name: postgres:11.6
pull_policy: [always, if-not-present]
```
**Additional details**:
- If the runner does not support the defined pull policy, the job fails with an error similar to:
`ERROR: Job failed (system failure): the configured PullPolicies ([always]) are not allowed by AllowedPullPolicies ([never])`.
**Related topics**:
- [Run your CI/CD jobs in Docker containers](../docker/using_docker_images.md).
- [Configure how runners pull images](https://docs.gitlab.com/runner/executors/docker.html#configure-how-runners-pull-images).
- [Set multiple pull policies](https://docs.gitlab.com/runner/executors/docker.html#set-multiple-pull-policies).
---
### `stage`
Use `stage` to define which [stage](#stages) a job runs in. Jobs in the same
`stage` can execute in parallel (see **Additional details**).
If `stage` is not defined, the job uses the `test` stage by default.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: A string, which can be a:
- [Default stage](#stages).
- User-defined stages.
**Example of `stage`**:
```yaml
stages:
- build
- test
- deploy
job1:
stage: build
script:
- echo "This job compiles code."
job2:
stage: test
script:
- echo "This job tests the compiled code. It runs when the build stage completes."
job3:
script:
- echo "This job also runs in the test stage."
job4:
stage: deploy
script:
- echo "This job deploys the code. It runs when the test stage completes."
environment: production
```
**Additional details**:
- The stage name must be 255 characters or fewer.
- Jobs can run in parallel if they run on different runners.
- If you have only one runner, jobs can run in parallel if the runner's
[`concurrent` setting](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-global-section)
is greater than `1`.
---
#### `stage: .pre`
Use the `.pre` stage to make a job run at the start of a pipeline. By default, `.pre` is
the first stage in a pipeline. User-defined stages execute after `.pre`.
You do not have to define `.pre` in [`stages`](#stages).
If a pipeline contains only jobs in the `.pre` or `.post` stages, it does not run.
There must be at least one other job in a different stage.
**Keyword type**: You can only use it with a job's `stage` keyword.
**Example of `stage: .pre`**:
```yaml
stages:
- build
- test
job1:
stage: build
script:
- echo "This job runs in the build stage."
first-job:
stage: .pre
script:
- echo "This job runs in the .pre stage, before all other stages."
job2:
stage: test
script:
- echo "This job runs in the test stage."
```
**Additional details**:
- If a pipeline has jobs with [`needs: []`](#needs) and jobs in the `.pre` stage, they will
all start as soon as the pipeline is created. Jobs with `needs: []` start immediately,
ignoring any stage configuration.
- A [pipeline execution policy](../../user/application_security/policies/pipeline_execution_policies.md) can define a `.pipeline-policy-pre` stage which runs before `.pre`.
---
#### `stage: .post`
Use the `.post` stage to make a job run at the end of a pipeline. By default, `.post`
is the last stage in a pipeline. User-defined stages execute before `.post`.
You do not have to define `.post` in [`stages`](#stages).
If a pipeline contains only jobs in the `.pre` or `.post` stages, it does not run.
There must be at least one other job in a different stage.
**Keyword type**: You can only use it with a job's `stage` keyword.
**Example of `stage: .post`**:
```yaml
stages:
- build
- test
job1:
stage: build
script:
- echo "This job runs in the build stage."
last-job:
stage: .post
script:
- echo "This job runs in the .post stage, after all other stages."
job2:
stage: test
script:
- echo "This job runs in the test stage."
```
**Additional details**:
- A [pipeline execution policy](../../user/application_security/policies/pipeline_execution_policies.md) can define a `.pipeline-policy-post` stage which runs after `.post`.
---
### `tags`
Use `tags` to select a specific runner from the list of all runners that are
available for the project.
When you register a runner, you can specify the runner's tags, for
example `ruby`, `postgres`, or `development`. To pick up and run a job, a runner must
be assigned every tag listed in the job.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- An array of tag names, which are case-sensitive.
- CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `tags`**:
```yaml
job:
tags:
- ruby
- postgres
```
In this example, only runners with both the `ruby` and `postgres` tags can run the job.
**Additional details**:
- The number of tags must be less than `50`.
**Related topics**:
- [Use tags to control which jobs a runner can run](../runners/configure_runners.md#control-jobs-that-a-runner-can-run)
- [Select different runner tags for each parallel matrix job](../jobs/job_control.md#select-different-runner-tags-for-each-parallel-matrix-job)
- Runner tags for hosted runners:
- [Hosted runners on Linux](../runners/hosted_runners/linux.md)
- [GPU-enabled hosted runners](../runners/hosted_runners/gpu_enabled.md)
- [Hosted runners on macOS](../runners/hosted_runners/macos.md)
- [Hosted runners on Windows](../runners/hosted_runners/windows.md)
---
### `timeout`
Use `timeout` to configure a timeout for a specific job. If the job runs for longer
than the timeout, the job fails.
The job-level timeout can be longer than the [project-level timeout](../pipelines/settings.md#set-a-limit-for-how-long-jobs-can-run),
but can't be longer than the [runner's timeout](../runners/configure_runners.md#set-the-maximum-job-timeout).
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: A period of time written in natural language. For example, these are all equivalent:
- `3600 seconds`
- `60 minutes`
- `one hour`
**Example of `timeout`**:
```yaml
build:
script: build.sh
timeout: 3 hours 30 minutes
test:
script: rspec
timeout: 3h 30m
```
---
### `trigger`
{{< history >}}
- Support for `environment` [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/369061) in GitLab 16.4.
{{< /history >}}
Use `trigger` to declare that a job is a "trigger job" which starts a
[downstream pipeline](../pipelines/downstream_pipelines.md) that is either:
- [A multi-project pipeline](../pipelines/downstream_pipelines.md#multi-project-pipelines).
- [A child pipeline](../pipelines/downstream_pipelines.md#parent-child-pipelines).
Trigger jobs can use only a limited set of GitLab CI/CD configuration keywords.
The keywords available for use in trigger jobs are:
- [`allow_failure`](#allow_failure).
- [`extends`](#extends).
- [`needs`](#needs), but not [`needs:project`](#needsproject).
- [`only` and `except`](deprecated_keywords.md#only--except).
- [`parallel`](#parallel).
- [`rules`](#rules).
- [`stage`](#stage).
- [`trigger`](#trigger).
- [`variables`](#variables).
- [`when`](#when) (only with a value of `on_success`, `on_failure`, or `always`).
- [`resource_group`](#resource_group).
- [`environment`](#environment).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- For multi-project pipelines, the path to the downstream project. CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file)
in GitLab 15.3 and later, but not [job-only variables](../variables/predefined_variables.md#variable-availability).
Alternatively, use [`trigger:project`](#triggerproject).
- For child pipelines, use [`trigger:include`](#triggerinclude).
**Example of `trigger`**:
```yaml
trigger-multi-project-pipeline:
trigger: my-group/my-project
```
**Additional details**:
- You can use [`when:manual`](#when) in the same job as `trigger`, but you cannot
use the API to start `when:manual` trigger jobs. See [issue 284086](https://gitlab.com/gitlab-org/gitlab/-/issues/284086)
for more details.
- You cannot [manually specify CI/CD variables](../jobs/job_control.md#specify-variables-when-running-manual-jobs)
before running a manual trigger job.
- [CI/CD variables](#variables) defined in a top-level `variables` section (globally) or in the trigger job are forwarded
to the downstream pipeline as [trigger variables](../pipelines/downstream_pipelines.md#pass-cicd-variables-to-a-downstream-pipeline).
- [Pipeline variables](../variables/_index.md#cicd-variable-precedence) are not passed
to downstream pipelines by default. Use [trigger:forward](#triggerforward) to forward
these variables to downstream pipelines.
- [Job-only variables](../variables/predefined_variables.md#variable-availability)
are not available in trigger jobs.
- Environment variables [defined in the runner's `config.toml`](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runners-section) are not available to trigger jobs and are not passed to downstream pipelines.
- You cannot use [`needs:pipeline:job`](#needspipelinejob) in a trigger job.
**Related topics**:
- [Multi-project pipeline configuration examples](../pipelines/downstream_pipelines.md#trigger-a-downstream-pipeline-from-a-job-in-the-gitlab-ciyml-file).
- To run a pipeline for a specific branch, tag, or commit, you can use a [trigger token](../triggers/_index.md)
to authenticate with the [pipeline triggers API](../../api/pipeline_triggers.md).
The trigger token is different than the `trigger` keyword.
---
#### `trigger:inputs`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/519963) in GitLab 17.11.
{{</history >}}
Use `trigger:inputs` to set the [inputs](../inputs/_index.md) for a multi-project pipeline
when the downstream pipeline configuration uses [`spec:inputs`](#specinputs).
**Example of `trigger:inputs`**:
```yaml
trigger:
- project: 'my-group/my-project'
inputs:
website: "My website"
```
---
#### `trigger:include`
Use `trigger:include` to declare that a job is a "trigger job" which starts a
[child pipeline](../pipelines/downstream_pipelines.md#parent-child-pipelines).
Additionally, use:
- `trigger:include:artifact` to trigger a [dynamic child pipeline](../pipelines/downstream_pipelines.md#dynamic-child-pipelines).
- `trigger:include:inputs` to set the [inputs](../inputs/_index.md) when the downstream pipeline configuration
uses [`spec:inputs`](#specinputs).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- The path to the child pipeline's configuration file.
**Example of `trigger:include`**:
```yaml
trigger-child-pipeline:
trigger:
include: path/to/child-pipeline.gitlab-ci.yml
```
**Related topics**:
- [Child pipeline configuration examples](../pipelines/downstream_pipelines.md#trigger-a-downstream-pipeline-from-a-job-in-the-gitlab-ciyml-file).
---
#### `trigger:include:inputs`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/519963) in GitLab 17.11.
{{</history >}}
Use `trigger:include:inputs` to set the [inputs](../inputs/_index.md) for a child pipeline
when the downstream pipeline configuration uses [`spec:inputs`](#specinputs).
**Example of `trigger:inputs`**:
```yaml
trigger-job:
trigger:
include:
- local: path/to/child-pipeline.yml
inputs:
website: "My website"
```
---
#### `trigger:project`
Use `trigger:project` to declare that a job is a "trigger job" which starts a
[multi-project pipeline](../pipelines/downstream_pipelines.md#multi-project-pipelines).
By default, the multi-project pipeline triggers for the default branch. Use `trigger:branch`
to specify a different branch.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- The path to the downstream project. CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file)
in GitLab 15.3 and later, but not [job-only variables](../variables/predefined_variables.md#variable-availability).
**Example of `trigger:project`**:
```yaml
trigger-multi-project-pipeline:
trigger:
project: my-group/my-project
```
**Example of `trigger:project` for a different branch**:
```yaml
trigger-multi-project-pipeline:
trigger:
project: my-group/my-project
branch: development
```
**Related topics**:
- [Multi-project pipeline configuration examples](../pipelines/downstream_pipelines.md#trigger-a-downstream-pipeline-from-a-job-in-the-gitlab-ciyml-file).
- To run a pipeline for a specific branch, tag, or commit, you can also use a [trigger token](../triggers/_index.md)
to authenticate with the [pipeline triggers API](../../api/pipeline_triggers.md).
The trigger token is different than the `trigger` keyword.
---
#### `trigger:strategy`
{{< history >}}
- `strategy:mirror` option [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/431882) in GitLab 18.2.
{{< /history >}}
Use `trigger:strategy` to force the `trigger` job to wait for the downstream pipeline to complete
before it is marked as **success**.
This behavior is different than the default, which is for the `trigger` job to be marked as
**success** as soon as the downstream pipeline is created.
This setting makes your pipeline execution linear rather than parallel.
**Supported values**:
- `mirror`: Mirrors the status of the downstream pipeline exactly.
- `depend`: The trigger job status shows **failed**, **success** or **running**,
depending on the downstream pipeline status. See additional details.
**Example of `trigger:strategy`**:
```yaml
trigger_job:
trigger:
include: path/to/child-pipeline.yml
strategy: mirror
```
In this example, jobs from subsequent stages wait for the triggered pipeline to
successfully complete before starting.
**Additional details**:
- [Optional manual jobs](../jobs/job_control.md#types-of-manual-jobs) in the downstream pipeline
do not affect the status of the downstream pipeline or the upstream trigger job.
The downstream pipeline can complete successfully without running any optional manual jobs.
- By default, jobs in later stages do not start until the trigger job completes.
- [Blocking manual jobs](../jobs/job_control.md#types-of-manual-jobs) in the downstream pipeline
must run before the trigger job is marked as successful or failed.
- When using `stratgy:depend`:
- The trigger job shows **running** ({{< icon name="status_running" >}}) if the downstream pipeline status is
**waiting for manual action** ({{< icon name="status_manual" >}}) due to manual jobs.
- If the downstream pipeline has a failed job, but the job uses [`allow_failure: true`](#allow_failure),
the downstream pipeline is considered successful and the trigger job shows **success**.
---
#### `trigger:forward`
{{< history >}}
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/355572) in GitLab 15.1. [Feature flag `ci_trigger_forward_variables`](https://gitlab.com/gitlab-org/gitlab/-/issues/355572) removed.
{{< /history >}}
Use `trigger:forward` to specify what to forward to the downstream pipeline. You can control
what is forwarded to both [parent-child pipelines](../pipelines/downstream_pipelines.md#parent-child-pipelines)
and [multi-project pipelines](../pipelines/downstream_pipelines.md#multi-project-pipelines).
Forwarded variables do not get forwarded again in nested downstream pipelines by default,
unless the nested downstream trigger job also uses `trigger:forward`.
**Supported values**:
- `yaml_variables`: `true` (default), or `false`. When `true`, variables defined
in the trigger job are passed to downstream pipelines.
- `pipeline_variables`: `true` or `false` (default). When `true`, [pipeline variables](../variables/_index.md#cicd-variable-precedence)
are passed to the downstream pipeline.
**Example of `trigger:forward`**:
[Run this pipeline manually](../pipelines/_index.md#run-a-pipeline-manually), with
the CI/CD variable `MYVAR = my value`:
```yaml
variables: # default variables for each job
VAR: value
---
# Default behavior:
---
# - VAR is passed to the child
---
# - MYVAR is not passed to the child
child1:
trigger:
include: .child-pipeline.yml
---
# Forward pipeline variables:
---
# - VAR is passed to the child
---
# - MYVAR is passed to the child
child2:
trigger:
include: .child-pipeline.yml
forward:
pipeline_variables: true
---
# Do not forward YAML variables:
---
# - VAR is not passed to the child
---
# - MYVAR is not passed to the child
child3:
trigger:
include: .child-pipeline.yml
forward:
yaml_variables: false
```
**Additional details**:
- CI/CD variables forwarded to downstream pipelines with `trigger:forward` are [pipeline variables](../variables/_index.md#cicd-variable-precedence),
which have high precedence. If a variable with the same name is defined in the downstream pipeline,
that variable is usually overwritten by the forwarded variable.
---
### `when`
Use `when` to configure the conditions for when jobs run. If not defined in a job,
the default value is `when: on_success`.
**Keyword type**: Job keyword. You can use it as part of a job. `when: always` and `when: never` can also be used in [`workflow:rules`](#workflow).
**Supported values**:
- `on_success` (default): Run the job only when no jobs in earlier stages fail.
- `on_failure`: Run the job only when at least one job in an earlier stage fails.
- `never`: Don't run the job regardless of the status of jobs in earlier stages.
Can only be used in a [`rules`](#ruleswhen) section or [`workflow: rules`](#workflowrules).
- `always`: Run the job regardless of the status of jobs in earlier stages.
- `manual`: Add the job to the pipeline as a [manual job](../jobs/job_control.md#create-a-job-that-must-be-run-manually).
- `delayed`: Add the job to the pipeline as a [delayed job](../jobs/job_control.md#run-a-job-after-a-delay).
**Example of `when`**:
```yaml
stages:
- build
- cleanup_build
- test
- deploy
- cleanup
build_job:
stage: build
script:
- make build
cleanup_build_job:
stage: cleanup_build
script:
- cleanup build when failed
when: on_failure
test_job:
stage: test
script:
- make test
deploy_job:
stage: deploy
script:
- make deploy
when: manual
environment: production
cleanup_job:
stage: cleanup
script:
- cleanup after jobs
when: always
```
In this example, the script:
1. Executes `cleanup_build_job` only when `build_job` fails.
1. Always executes `cleanup_job` as the last step in pipeline regardless of
success or failure.
1. Executes `deploy_job` when you run it manually in the GitLab UI.
**Additional details**:
- When evaluating the status of jobs for `on_success` and `on_failure`:
- Jobs with [`allow_failure: true`](#allow_failure) in earlier stages are considered successful, even if they failed.
- Skipped jobs in earlier stages, for example [manual jobs that have not been started](../jobs/job_control.md#create-a-job-that-must-be-run-manually),
are considered successful.
- The default value for [`allow_failure`](#allow_failure) is `true` with `when: manual`. The default value
changes to `false` with [`rules:when: manual`](#ruleswhen).
**Related topics**:
- `when` can be used with [`rules`](#rules) for more dynamic job control.
- `when` can be used with [`workflow`](#workflow) to control when a pipeline can start.
---
#### `manual_confirmation`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/18906) in GitLab 17.1.
{{< /history >}}
Use `manual_confirmation` with [`when: manual`](#when) to define a custom confirmation message for manual jobs.
If no manual job is defined with `when: manual`, this keyword has no effect.
Manual confirmation works with all manual jobs, including environment stop jobs that use
[`environment:action: stop`](#environmentaction).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A string with the confirmation message.
**Example of `manual_confirmation`**:
```yaml
delete_job:
stage: post-deployment
script:
- make delete
when: manual
manual_confirmation: 'Are you sure you want to delete this environment?'
stop_production:
stage: cleanup
script:
- echo "Stopping production environment"
environment:
name: production
action: stop
when: manual
manual_confirmation: "Are you sure you want to stop the production environment?"
```
---
## `variables`
Use `variables` to define [CI/CD variables](../variables/_index.md#define-a-cicd-variable-in-the-gitlab-ciyml-file).
Variables can be [defined in a CI/CD job](#job-variables), or as a top-level (global) keyword to define
[default CI/CD variables](#default-variables) for all jobs.
**Additional details**:
- All YAML-defined variables are also set to any linked [Docker service containers](../services/_index.md).
- YAML-defined variables are meant for non-sensitive project configuration. Store sensitive information
in [protected variables](../variables/_index.md#protect-a-cicd-variable) or [CI/CD secrets](../secrets/_index.md).
- [Manual pipeline variables](../variables/_index.md#use-pipeline-variables)
and [scheduled pipeline variables](../pipelines/schedules.md#add-a-pipeline-schedule)
are not passed to downstream pipelines by default. Use [trigger:forward](#triggerforward)
to forward these variables to downstream pipelines.
**Related topics**:
- [Predefined variables](../variables/predefined_variables.md) are variables the runner
automatically creates and makes available in the job.
- You can [configure runner behavior with variables](../runners/configure_runners.md#configure-runner-behavior-with-variables).
---
### Job `variables`
You can use job variables in commands in the job's `script`, `before_script`, or `after_script` sections,
and also with some [job keywords](#job-keywords). Check the **Supported values** section of each job keyword
to see if it supports variables.
You cannot use job variables as values for [global keywords](#global-keywords) like
[`include`](includes.md#use-variables-with-include).
**Supported values**: Variable name and value pairs:
- The name can use only numbers, letters, and underscores (`_`). In some shells,
the first character must be a letter.
- The value must be a string.
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of job `variables`**:
```yaml
review_job:
variables:
DEPLOY_SITE: "https://dev.example.com/"
REVIEW_PATH: "/review"
script:
- deploy-review-script --url $DEPLOY_SITE --path $REVIEW_PATH
```
In this example:
- `review_job` has `DEPLOY_SITE` and `REVIEW_PATH` job variables defined.
Both job variables can be used in the `script` section.
---
### Default `variables`
Variables defined in a top-level `variables` section act as default variables
for all jobs.
Each default variable is made available to every job in the pipeline, except when
the job already has a variable defined with the same name. The variable defined in the job
[takes precedence](../variables/_index.md#cicd-variable-precedence), so the value of
the default variable with the same name cannot be used in the job.
Like job variables, you cannot use default variables as values for other global keywords,
like [`include`](includes.md#use-variables-with-include).
**Supported values**: Variable name and value pairs:
- The name can use only numbers, letters, and underscores (`_`). In some shells,
the first character must be a letter.
- The value must be a string.
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Examples of `variables`**:
```yaml
variables:
DEPLOY_SITE: "https://example.com/"
deploy_job:
stage: deploy
script:
- deploy-script --url $DEPLOY_SITE --path "/"
environment: production
deploy_review_job:
stage: deploy
variables:
DEPLOY_SITE: "https://dev.example.com/"
REVIEW_PATH: "/review"
script:
- deploy-review-script --url $DEPLOY_SITE --path $REVIEW_PATH
environment: production
```
In this example:
- `deploy_job` has no variables defined. The default `DEPLOY_SITE` variable is copied to the job
and can be used in the `script` section.
- `deploy_review_job` already has a `DEPLOY_SITE` variable defined, so the default `DEPLOY_SITE`
is not copied to the job. The job also has a `REVIEW_PATH` job variable defined.
Both job variables can be used in the `script` section.
---
#### `variables:description`
Use the `description` keyword to define a description for a default variable.
The description displays with [the prefilled variable name when running a pipeline manually](../pipelines/_index.md#prefill-variables-in-manual-pipelines).
**Keyword type**: You can only use this keyword with default `variables`, not job `variables`.
**Supported values**:
- A string. You can use Markdown.
**Example of `variables:description`**:
```yaml
variables:
DEPLOY_NOTE:
description: "The deployment note. Explain the reason for this deployment."
```
**Additional details**:
- When used without `value`, the variable exists in pipelines that were not triggered manually,
and the default value is an empty string (`''`).
---
#### `variables:value`
Use the `value` keyword to define a pipeline-level (default) variable's value. When used with
[`variables: description`](#variablesdescription), the variable value is [prefilled when running a pipeline manually](../pipelines/_index.md#prefill-variables-in-manual-pipelines).
**Keyword type**: You can only use this keyword with default `variables`, not job `variables`.
**Supported values**:
- A string.
**Example of `variables:value`**:
```yaml
variables:
DEPLOY_ENVIRONMENT:
value: "staging"
description: "The deployment target. Change this variable to 'canary' or 'production' if needed."
```
**Additional details**:
- If used without [`variables: description`](#variablesdescription), the behavior is
the same as [`variables`](#variables).
---
#### `variables:options`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/105502) in GitLab 15.7.
{{< /history >}}
Use `variables:options` to define an array of values that are [selectable in the UI when running a pipeline manually](../pipelines/_index.md#configure-a-list-of-selectable-prefilled-variable-values).
Must be used with `variables: value`, and the string defined for `value`:
- Must also be one of the strings in the `options` array.
- Is the default selection.
If there is no [`description`](#variablesdescription),
this keyword has no effect.
**Keyword type**: You can only use this keyword with default `variables`, not job `variables`.
**Supported values**:
- An array of strings.
**Example of `variables:options`**:
```yaml
variables:
DEPLOY_ENVIRONMENT:
value: "staging"
options:
- "production"
- "staging"
- "canary"
description: "The deployment target. Set to 'staging' by default."
```
---
### `variables:expand`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/353991) in GitLab 15.6 [with a flag](../../administration/feature_flags/_index.md) named `ci_raw_variables_in_yaml_config`. Disabled by default.
- [Enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/issues/375034) in GitLab 15.6.
- [Enabled on GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/375034) in GitLab 15.7.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/375034) in GitLab 15.8. Feature flag `ci_raw_variables_in_yaml_config` removed.
{{< /history >}}
Use the `expand` keyword to configure a variable to be expandable or not.
**Keyword type**: You can use this keyword with both default and job `variables`.
**Supported values**:
- `true` (default): The variable is expandable.
- `false`: The variable is not expandable.
**Example of `variables:expand`**:
```yaml
variables:
VAR1: value1
VAR2: value2 $VAR1
VAR3:
value: value3 $VAR1
expand: false
```
- The result of `VAR2` is `value2 value1`.
- The result of `VAR3` is `value3 $VAR1`.
**Additional details**:
- The `expand` keyword can only be used with default and job `variables` keywords.
You can't use it with [`rules:variables`](#rulesvariables) or [`workflow:rules:variables`](#workflowrulesvariables).
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: CI/CD YAML syntax reference
description: Pipeline configuration keywords, syntax, examples, and inputs.
breadcrumbs:
- doc
- ci
- yaml
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
This document lists the configuration options for the GitLab `.gitlab-ci.yml` file.
This file is where you define the CI/CD jobs that make up your pipeline.
- If you are already familiar with [basic CI/CD concepts](../_index.md), try creating
your own `.gitlab-ci.yml` file by following a tutorial that demonstrates a [simple](../quick_start/_index.md)
or [complex](../quick_start/tutorial.md) pipeline.
- For a collection of examples, see [GitLab CI/CD examples](../examples/_index.md).
- To view a large `.gitlab-ci.yml` file used in an enterprise, see the
[`.gitlab-ci.yml` file for `gitlab`](https://gitlab.com/gitlab-org/gitlab/-/blob/master/.gitlab-ci.yml).
When you are editing your `.gitlab-ci.yml` file, you can validate it with the
[CI Lint](lint.md) tool.
<!--
If you are editing content on this page, follow the instructions for documenting keywords:
https://docs.gitlab.com/development/cicd/cicd_reference_documentation_guide/
-->
## Keywords
A GitLab CI/CD pipeline configuration includes:
- [Global keywords](#global-keywords) that configure pipeline behavior:
| Keyword | Description |
|-------------------------|:------------|
| [`default`](#default) | Custom default values for job keywords. |
| [`include`](#include) | Import configuration from other YAML files. |
| [`stages`](#stages) | The names and order of the pipeline stages. |
| [`workflow`](#workflow) | Control what types of pipeline run. |
- [Header keywords](#header-keywords)
| Keyword | Description |
|-----------------|:------------|
| [`spec`](#spec) | Define specifications for external configuration files. |
- [Jobs](../jobs/_index.md) configured with [job keywords](#job-keywords):
| Keyword | Description |
|:----------------------------------------------|:------------|
| [`after_script`](#after_script) | Override a set of commands that are executed after job. |
| [`allow_failure`](#allow_failure) | Allow job to fail. A failed job does not cause the pipeline to fail. |
| [`artifacts`](#artifacts) | List of files and directories to attach to a job on success. |
| [`before_script`](#before_script) | Override a set of commands that are executed before job. |
| [`cache`](#cache) | List of files that should be cached between subsequent runs. |
| [`coverage`](#coverage) | Code coverage settings for a given job. |
| [`dast_configuration`](#dast_configuration) | Use configuration from DAST profiles on a job level. |
| [`dependencies`](#dependencies) | Restrict which artifacts are passed to a specific job by providing a list of jobs to fetch artifacts from. |
| [`environment`](#environment) | Name of an environment to which the job deploys. |
| [`extends`](#extends) | Configuration entries that this job inherits from. |
| [`identity`](#identity) | Authenticate with third party services using identity federation. |
| [`image`](#image) | Use Docker images. |
| [`inherit`](#inherit) | Select which global defaults all jobs inherit. |
| [`interruptible`](#interruptible) | Defines if a job can be canceled when made redundant by a newer run. |
| [`manual_confirmation`](#manual_confirmation) | Define a custom confirmation message for a manual job. |
| [`needs`](#needs) | Execute jobs earlier than the stage ordering. |
| [`pages`](#pages) | Upload the result of a job to use with GitLab Pages. |
| [`parallel`](#parallel) | How many instances of a job should be run in parallel. |
| [`release`](#release) | Instructs the runner to generate a [release](../../user/project/releases/_index.md) object. |
| [`resource_group`](#resource_group) | Limit job concurrency. |
| [`retry`](#retry) | When and how many times a job can be auto-retried in case of a failure. |
| [`rules`](#rules) | List of conditions to evaluate and determine selected attributes of a job, and whether or not it's created. |
| [`script`](#script) | Shell script that is executed by a runner. |
| [`run`](#run) | Run configuration that is executed by a runner. |
| [`secrets`](#secrets) | The CI/CD secrets the job needs. |
| [`services`](#services) | Use Docker services images. |
| [`stage`](#stage) | Defines a job stage. |
| [`tags`](#tags) | List of tags that are used to select a runner. |
| [`timeout`](#timeout) | Define a custom job-level timeout that takes precedence over the project-wide setting. |
| [`trigger`](#trigger) | Defines a downstream pipeline trigger. |
| [`when`](#when) | When to run job. |
- [CI/CD variables](#variables)
| Keyword | Description |
|:------------------------------------------|:------------|
| [Default `variables`](#default-variables) | Define default CI/CD variables for all jobs in the pipeline. |
| [Job `variables`](#job-variables) | Define CI/CD variables for individual jobs. |
- [Deprecated keywords](deprecated_keywords.md) that are no longer recommended for use.
---
## Global keywords
Some keywords are not defined in a job. These keywords control pipeline behavior
or import additional pipeline configuration.
---
### `default`
{{< history >}}
- Support for `id_tokens` [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/419750) in GitLab 16.4.
{{< /history >}}
You can set global defaults for some keywords. Each default keyword is copied to every job
that doesn't already have it defined. If the job already has a keyword defined, that default
is not used.
**Keyword type**: Global keyword.
**Supported values**: These keywords can have custom defaults:
- [`after_script`](#after_script)
- [`artifacts`](#artifacts)
- [`before_script`](#before_script)
- [`cache`](#cache)
- [`hooks`](#hooks)
- [`id_tokens`](#id_tokens)
- [`image`](#image)
- [`interruptible`](#interruptible)
- [`retry`](#retry)
- [`services`](#services)
- [`tags`](#tags)
- [`timeout`](#timeout), though due to [issue 213634](https://gitlab.com/gitlab-org/gitlab/-/issues/213634)
this keyword has no effect.
**Example of `default`**:
```yaml
default:
image: ruby:3.0
retry: 2
rspec:
script: bundle exec rspec
rspec 2.7:
image: ruby:2.7
script: bundle exec rspec
```
In this example:
- `image: ruby:3.0` and `retry: 2` are the default keywords for all jobs in the pipeline.
- The `rspec` job does not have `image` or `retry` defined, so it uses the defaults of
`image: ruby:3.0` and `retry: 2`.
- The `rspec 2.7` job does not have `retry` defined, but it does have `image` explicitly defined.
It uses the default `retry: 2`, but ignores the default `image` and uses the `image: ruby:2.7`
defined in the job.
**Additional details**:
- Control inheritance of default keywords in jobs with [`inherit:default`](#inheritdefault).
- Global defaults are not passed to [downstream pipelines](../pipelines/downstream_pipelines.md),
which run independently of the upstream pipeline that triggered the downstream pipeline.
---
### `include`
Use `include` to include external YAML files in your CI/CD configuration.
You can split one long `.gitlab-ci.yml` file into multiple files to increase readability,
or reduce duplication of the same configuration in multiple places.
You can also store template files in a central repository and include them in projects.
The `include` files are:
- Merged with those in the `.gitlab-ci.yml` file.
- Always evaluated first and then merged with the content of the `.gitlab-ci.yml` file,
regardless of the position of the `include` keyword.
The time limit to resolve all files is 30 seconds.
**Keyword type**: Global keyword.
**Supported values**: The `include` subkeys:
- [`include:component`](#includecomponent)
- [`include:local`](#includelocal)
- [`include:project`](#includeproject)
- [`include:remote`](#includeremote)
- [`include:template`](#includetemplate)
And optionally:
- [`include:inputs`](#includeinputs)
- [`include:rules`](#includerules)
- [`include:integrity`](#includeintegrity)
**Additional details**:
- Only [certain CI/CD variables](includes.md#use-variables-with-include) can be used
with `include` keywords.
- Use merging to customize and override included CI/CD configurations with local
- You can override included configuration by having the same job name or global keyword
in the `.gitlab-ci.yml` file. The two configurations are merged together, and the
configuration in the `.gitlab-ci.yml` file takes precedence over the included configuration.
- If you rerun a:
- Job, the `include` files are not fetched again. All jobs in a pipeline use the configuration
fetched when the pipeline was created. Any changes to the source `include` files
do not affect job reruns.
- Pipeline, the `include` files are fetched again. If they changed after the last
pipeline run, the new pipeline uses the changed configuration.
- You can have up to 150 includes per pipeline by default, including [nested](includes.md#use-nested-includes). Additionally:
- In [GitLab 16.0 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/207270) users on GitLab Self-Managed can
change the [maximum includes](../../administration/settings/continuous_integration.md#set-maximum-includes) value.
- In [GitLab 15.10 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/367150) you can have up to 150 includes.
In nested includes, the same file can be included multiple times, but duplicated includes
count towards the limit.
- From [GitLab 14.9 to GitLab 15.9](https://gitlab.com/gitlab-org/gitlab/-/issues/28987), you can have up to 100 includes.
The same file can be included multiple times in nested includes, but duplicates are ignored.
---
#### `include:component`
Use `include:component` to add a [CI/CD component](../components/_index.md) to the
pipeline configuration.
**Keyword type**: Global keyword.
**Supported values**: The full address of the CI/CD component, formatted as
`<fully-qualified-domain-name>/<project-path>/<component-name>@<specific-version>`.
**Example of `include:component`**:
```yaml
include:
- component: $CI_SERVER_FQDN/my-org/security-components/secret-detection@1.0
```
**Related topics**:
- [Use a CI/CD component](../components/_index.md#use-a-component).
---
#### `include:local`
Use `include:local` to include a file that is in the same repository and branch as the configuration file containing the `include` keyword.
Use `include:local` instead of symbolic links.
**Keyword type**: Global keyword.
**Supported values**:
A full path relative to the root directory (`/`):
- The YAML file must have the extension `.yml` or `.yaml`.
- You can [use `*` and `**` wildcards in the file path](includes.md#use-includelocal-with-wildcard-file-paths).
- You can use [certain CI/CD variables](includes.md#use-variables-with-include).
**Example of `include:local`**:
```yaml
include:
- local: '/templates/.gitlab-ci-template.yml'
```
You can also use shorter syntax to define the path:
```yaml
include: '.gitlab-ci-production.yml'
```
**Additional details**:
- The `.gitlab-ci.yml` file and the local file must be on the same branch.
- You can't include local files through Git submodules paths.
- `include` configuration is always evaluated based on the location of the file
containing the `include` keyword, not the project running the pipeline. If a
[nested `include`](includes.md#use-nested-includes) is in a configuration file
in a different project, `include: local` checks that other project for the file.
---
#### `include:project`
To include files from another private project on the same GitLab instance,
use `include:project` and `include:file`.
**Keyword type**: Global keyword.
**Supported values**:
- `include:project`: The full GitLab project path.
- `include:file` A full file path, or array of file paths, relative to the root directory (`/`).
The YAML files must have the `.yml` or `.yaml` extension.
- `include:ref`: Optional. The ref to retrieve the file from. Defaults to the `HEAD` of the project
when not specified.
- You can use [certain CI/CD variables](includes.md#use-variables-with-include).
**Example of `include:project`**:
```yaml
include:
- project: 'my-group/my-project'
file: '/templates/.gitlab-ci-template.yml'
- project: 'my-group/my-subgroup/my-project-2'
file:
- '/templates/.builds.yml'
- '/templates/.tests.yml'
```
You can also specify a `ref`:
```yaml
include:
- project: 'my-group/my-project'
ref: main # Git branch
file: '/templates/.gitlab-ci-template.yml'
- project: 'my-group/my-project'
ref: v1.0.0 # Git Tag
file: '/templates/.gitlab-ci-template.yml'
- project: 'my-group/my-project'
ref: 787123b47f14b552955ca2786bc9542ae66fee5b # Git SHA
file: '/templates/.gitlab-ci-template.yml'
```
**Additional details**:
- `include` configuration is always evaluated based on the location of the file
containing the `include` keyword, not the project running the pipeline. If a
[nested `include`](includes.md#use-nested-includes) is in a configuration file
in a different project, `include: local` checks that other project for the file.
- When the pipeline starts, the `.gitlab-ci.yml` file configuration included by all methods is evaluated.
The configuration is a snapshot in time and persists in the database. GitLab does not reflect any changes to
the referenced `.gitlab-ci.yml` file configuration until the next pipeline starts.
- When you include a YAML file from another private project, the user running the pipeline
must be a member of both projects and have the appropriate permissions to run pipelines.
A `not found or access denied` error may be displayed if the user does not have access to any of the included files.
- Be careful when including another project's CI/CD configuration file. No pipelines or notifications trigger when CI/CD configuration files change.
From a security perspective, this is similar to pulling a third-party dependency. For the `ref`, consider:
- Using a specific SHA hash, which should be the most stable option. Use the
full 40-character SHA hash to ensure the desired commit is referenced, because
using a short SHA hash for the `ref` might be ambiguous.
- Applying both [protected branch](../../user/project/repository/branches/protected.md) and [protected tag](../../user/project/protected_tags.md#prevent-tag-creation-with-the-same-name-as-branches) rules to
the `ref` in the other project. Protected tags and branches are more likely to pass through change management before changing.
---
#### `include:remote`
Use `include:remote` with a full URL to include a file from a different location.
**Keyword type**: Global keyword.
**Supported values**:
A public URL accessible by an HTTP/HTTPS `GET` request:
- Authentication with the remote URL is not supported.
- The YAML file must have the extension `.yml` or `.yaml`.
- You can use [certain CI/CD variables](includes.md#use-variables-with-include).
**Example of `include:remote`**:
```yaml
include:
- remote: 'https://gitlab.com/example-project/-/raw/main/.gitlab-ci.yml'
```
**Additional details**:
- All [nested includes](includes.md#use-nested-includes) are executed without context as a public user,
so you can only include public projects or templates. No variables are available in the `include` section of nested includes.
- Be careful when including another project's CI/CD configuration file. No pipelines or notifications trigger
when the other project's files change. From a security perspective, this is similar to
pulling a third-party dependency. To verify the integrity of the included file, consider using the [`integrity`](#includeintegrity) keyword.
If you link to another GitLab project you own, consider the use of both
[protected branches](../../user/project/repository/branches/protected.md) and [protected tags](../../user/project/protected_tags.md#prevent-tag-creation-with-the-same-name-as-branches)
to enforce change management rules.
---
#### `include:template`
Use `include:template` to include [`.gitlab-ci.yml` templates](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates).
**Keyword type**: Global keyword.
**Supported values**:
A [CI/CD template](../examples/_index.md#cicd-templates):
- All templates can be viewed in [`lib/gitlab/ci/templates`](https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates).
Not all templates are designed to be used with `include:template`, so check template
comments before using one.
- You can use [certain CI/CD variables](includes.md#use-variables-with-include).
**Example of `include:template`**:
```yaml
# File sourced from the GitLab template collection
include:
- template: Auto-DevOps.gitlab-ci.yml
```
Multiple `include:template` files:
```yaml
include:
- template: Android-Fastlane.gitlab-ci.yml
- template: Auto-DevOps.gitlab-ci.yml
```
**Additional details**:
- All [nested includes](includes.md#use-nested-includes) are executed without context as a public user,
so you can only include public projects or templates. No variables are available in the `include` section of nested includes.
---
#### `include:inputs`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/391331) in GitLab 15.11 as a beta feature.
- [Made generally available](https://gitlab.com/gitlab-com/www-gitlab-com/-/merge_requests/134062) in GitLab 17.0.
{{< /history >}}
Use `include:inputs` to set the values for input parameters when the included configuration
uses [`spec:inputs`](#specinputs) and is added to the pipeline.
**Keyword type**: Global keyword.
**Supported values**: A string, numeric value, or boolean.
**Example of `include:inputs`**:
```yaml
include:
- local: 'custom_configuration.yml'
inputs:
website: "My website"
```
In this example:
- The configuration contained in `custom_configuration.yml` is added to the pipeline,
with a `website` input set to a value of `My website` for the included configuration.
**Additional details**:
- If the included configuration file uses [`spec:inputs:type`](#specinputstype),
the input value must match the defined type.
- If the included configuration file uses [`spec:inputs:options`](#specinputsoptions),
the input value must match one of the listed options.
**Related topics**:
- [Set input values when using `include`](../inputs/_index.md#for-configuration-added-with-include).
---
#### `include:rules`
You can use [`rules`](#rules) with `include` to conditionally include other configuration files.
**Keyword type**: Global keyword.
**Supported values**: These `rules` subkeys:
- [`rules:if`](#rulesif).
- [`rules:exists`](#rulesexists).
- [`rules:changes`](#ruleschanges).
Some [CI/CD variables are supported](includes.md#use-variables-with-include).
**Example of `include:rules`**:
```yaml
include:
- local: build_jobs.yml
rules:
- if: $INCLUDE_BUILDS == "true"
test-job:
stage: test
script: echo "This is a test job"
```
In this example, if the `INCLUDE_BUILDS` variable is:
- `true`, the `build_jobs.yml` configuration is included in the pipeline.
- Not `true` or does not exist, the `build_jobs.yml` configuration is not included in the pipeline.
**Related topics**:
- Examples of using `include` with:
- [`rules:if`](includes.md#include-with-rulesif).
- [`rules:changes`](includes.md#include-with-ruleschanges).
- [`rules:exists`](includes.md#include-with-rulesexists).
---
#### `include:integrity`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/178593) in GitLab 17.9.
{{< /history >}}
Use `integrity` with `include:remote` to specifiy a SHA256 hash of the included remote file.
If `integrity` does not match the actual content, the remote file is not processed
and the pipeline fails.
**Keyword type**: Global keyword.
**Supported values**: Base64-encoded SHA256 hash of the included content.
**Example of `include:integrity`**:
```yaml
include:
- remote: 'https://gitlab.com/example-project/-/raw/main/.gitlab-ci.yml'
integrity: 'sha256-L3/GAoKaw0Arw6hDCKeKQlV1QPEgHYxGBHsH4zG1IY8='
```
---
### `stages`
{{< history >}}
- Support for nested array of strings [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/439451) in GitLab 16.9.
{{< /history >}}
Use `stages` to define stages that contain groups of jobs. Use [`stage`](#stage)
in a job to configure the job to run in a specific stage.
If `stages` is not defined in the `.gitlab-ci.yml` file, the default pipeline stages are:
- [`.pre`](#stage-pre)
- `build`
- `test`
- `deploy`
- [`.post`](#stage-post)
The order of the items in `stages` defines the execution order for jobs:
- Jobs in the same stage run in parallel.
- Jobs in the next stage run after the jobs from the previous stage complete successfully.
If a pipeline contains only jobs in the `.pre` or `.post` stages, it does not run.
There must be at least one other job in a different stage.
**Keyword type**: Global keyword.
**Example of `stages`**:
```yaml
stages:
- build
- test
- deploy
```
In this example:
1. All jobs in `build` execute in parallel.
1. If all jobs in `build` succeed, the `test` jobs execute in parallel.
1. If all jobs in `test` succeed, the `deploy` jobs execute in parallel.
1. If all jobs in `deploy` succeed, the pipeline is marked as `passed`.
If any job fails, the pipeline is marked as `failed` and jobs in later stages do not
start. Jobs in the current stage are not stopped and continue to run.
**Additional details**:
- If a job does not specify a [`stage`](#stage), the job is assigned the `test` stage.
- If a stage is defined but no jobs use it, the stage is not visible in the pipeline,
which can help [compliance pipeline configurations](../../user/compliance/compliance_pipelines.md):
- Stages can be defined in the compliance configuration but remain hidden if not used.
- The defined stages become visible when developers use them in job definitions.
**Related topics**:
- To make a job start earlier and ignore the stage order, use the [`needs`](#needs) keyword.
---
### `workflow`
Use [`workflow`](workflow.md) to control pipeline behavior.
You can use some [predefined CI/CD variables](../variables/predefined_variables.md) in
`workflow` configuration, but not variables that are only defined when jobs start.
**Related topics**:
- [`workflow: rules` examples](workflow.md#workflow-rules-examples)
- [Switch between branch pipelines and merge request pipelines](workflow.md#switch-between-branch-pipelines-and-merge-request-pipelines)
---
#### `workflow:auto_cancel:on_new_commit`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/412473) in GitLab 16.8 [with a flag](../../administration/feature_flags/_index.md) named `ci_workflow_auto_cancel_on_new_commit`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/434676) in GitLab 16.9.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/434676) in GitLab 16.10. Feature flag `ci_workflow_auto_cancel_on_new_commit` removed.
{{< /history >}}
Use `workflow:auto_cancel:on_new_commit` to configure the behavior of
the [auto-cancel redundant pipelines](../pipelines/settings.md#auto-cancel-redundant-pipelines) feature.
**Supported values**:
- `conservative`: Cancel the pipeline, but only if no jobs with `interruptible: false` have started yet. Default when not defined.
- `interruptible`: Cancel only jobs with `interruptible: true`.
- `none`: Do not auto-cancel any jobs.
**Example of `workflow:auto_cancel:on_new_commit`**:
```yaml
workflow:
auto_cancel:
on_new_commit: interruptible
job1:
interruptible: true
script: sleep 60
job2:
interruptible: false # Default when not defined.
script: sleep 60
```
In this example:
- When a new commit is pushed to a branch, GitLab creates a new pipeline and `job1` and `job2` start.
- If a new commit is pushed to the branch before the jobs complete, only `job1` is canceled.
---
#### `workflow:auto_cancel:on_job_failure`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/23605) in GitLab 16.10 [with a flag](../../administration/feature_flags/_index.md) named `auto_cancel_pipeline_on_job_failure`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/433163) in GitLab 16.11. Feature flag `auto_cancel_pipeline_on_job_failure` removed.
{{< /history >}}
Use `workflow:auto_cancel:on_job_failure` to configure which jobs should be canceled as soon as one job fails.
**Supported values**:
- `all`: Cancel the pipeline and all running jobs as soon as one job fails.
- `none`: Do not auto-cancel any jobs.
**Example of `workflow:auto_cancel:on_job_failure`**:
```yaml
stages: [stage_a, stage_b]
workflow:
auto_cancel:
on_job_failure: all
job1:
stage: stage_a
script: sleep 60
job2:
stage: stage_a
script:
- sleep 30
- exit 1
job3:
stage: stage_b
script:
- sleep 30
```
In this example, if `job2` fails, `job1` is canceled if it is still running and `job3` does not start.
**Related topics**:
- [Auto-cancel the parent pipeline from a downstream pipeline](../pipelines/downstream_pipelines.md#auto-cancel-the-parent-pipeline-from-a-downstream-pipeline)
---
#### `workflow:name`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/372538) in GitLab 15.5 [with a flag](../../administration/feature_flags/_index.md) named `pipeline_name`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/376095) in GitLab 15.7.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/376095) in GitLab 15.8. Feature flag `pipeline_name` removed.
{{< /history >}}
You can use `name` in `workflow:` to define a name for pipelines.
All pipelines are assigned the defined name. Any leading or trailing spaces in the name are removed.
**Supported values**:
- A string.
- [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
- A combination of both.
**Examples of `workflow:name`**:
A simple pipeline name with a predefined variable:
```yaml
workflow:
name: 'Pipeline for branch: $CI_COMMIT_BRANCH'
```
A configuration with different pipeline names depending on the pipeline conditions:
```yaml
variables:
PROJECT1_PIPELINE_NAME: 'Default pipeline name' # A default is not required
workflow:
name: '$PROJECT1_PIPELINE_NAME'
rules:
- if: '$CI_MERGE_REQUEST_LABELS =~ /pipeline:run-in-ruby3/'
variables:
PROJECT1_PIPELINE_NAME: 'Ruby 3 pipeline'
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
variables:
PROJECT1_PIPELINE_NAME: 'MR pipeline: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME'
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # For default branch pipelines, use the default name
```
**Additional details**:
- If the name is an empty string, the pipeline is not assigned a name. A name consisting
of only CI/CD variables could evaluate to an empty string if all the variables are also empty.
- `workflow:rules:variables` become [default variables](#default-variables) available in all jobs,
including [`trigger`](#trigger) jobs which forward variables to downstream pipelines by default.
If the downstream pipeline uses the same variable, the [variable is overwritten](../variables/_index.md#cicd-variable-precedence)
by the upstream variable value. Be sure to either:
- Use a unique variable name in every project's pipeline configuration, like `PROJECT1_PIPELINE_NAME`.
- Use [`inherit:variables`](#inheritvariables) in the trigger job and list the
exact variables you want to forward to the downstream pipeline.
---
#### `workflow:rules`
The `rules` keyword in `workflow` is similar to [`rules` defined in jobs](#rules),
but controls whether or not a whole pipeline is created.
When no rules evaluate to true, the pipeline does not run.
**Supported values**: You can use some of the same keywords as job-level [`rules`](#rules):
- [`rules: if`](#rulesif).
- [`rules: changes`](#ruleschanges).
- [`rules: exists`](#rulesexists).
- [`when`](#when), can only be `always` or `never` when used with `workflow`.
- [`variables`](#workflowrulesvariables).
**Example of `workflow:rules`**:
```yaml
workflow:
rules:
- if: $CI_COMMIT_TITLE =~ /-draft$/
when: never
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
In this example, pipelines run if the commit title (first line of the commit message) does not end with `-draft`
and the pipeline is for either:
- A merge request
- The default branch.
**Additional details**:
- If your rules match both branch pipelines (other than the default branch) and merge request pipelines,
[duplicate pipelines](../jobs/job_rules.md#avoid-duplicate-pipelines) can occur.
- `start_in`, `allow_failure`, and `needs` are not supported in `workflow:rules`,
but do not cause a syntax violation. Though they have no effect, do not use them
in `workflow:rules` as it could cause syntax failures in the future. See
[issue 436473](https://gitlab.com/gitlab-org/gitlab/-/issues/436473) for more details.
**Related topics**:
- [Common `if` clauses for `workflow:rules`](workflow.md#common-if-clauses-for-workflowrules).
- [Use `rules` to run merge request pipelines](../pipelines/merge_request_pipelines.md#add-jobs-to-merge-request-pipelines).
---
#### `workflow:rules:variables`
You can use [`variables`](#variables) in `workflow:rules` to define variables for
specific pipeline conditions.
When the condition matches, the variable is created and can be used by all jobs
in the pipeline. If the variable is already defined at the top level as a default variable,
the `workflow` variable takes precedence and overrides the default variable.
**Keyword type**: Global keyword.
**Supported values**: Variable name and value pairs:
- The name can use only numbers, letters, and underscores (`_`).
- The value must be a string.
**Example of `workflow:rules:variables`**:
```yaml
variables:
DEPLOY_VARIABLE: "default-deploy"
workflow:
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
variables:
DEPLOY_VARIABLE: "deploy-production" # Override globally-defined DEPLOY_VARIABLE
- if: $CI_COMMIT_BRANCH =~ /feature/
variables:
IS_A_FEATURE: "true" # Define a new variable.
- if: $CI_COMMIT_BRANCH # Run the pipeline in other cases
job1:
variables:
DEPLOY_VARIABLE: "job1-default-deploy"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
variables: # Override DEPLOY_VARIABLE defined
DEPLOY_VARIABLE: "job1-deploy-production" # at the job level.
- when: on_success # Run the job in other cases
script:
- echo "Run script with $DEPLOY_VARIABLE as an argument"
- echo "Run another script if $IS_A_FEATURE exists"
job2:
script:
- echo "Run script with $DEPLOY_VARIABLE as an argument"
- echo "Run another script if $IS_A_FEATURE exists"
```
When the branch is the default branch:
- job1's `DEPLOY_VARIABLE` is `job1-deploy-production`.
- job2's `DEPLOY_VARIABLE` is `deploy-production`.
When the branch is `feature`:
- job1's `DEPLOY_VARIABLE` is `job1-default-deploy`, and `IS_A_FEATURE` is `true`.
- job2's `DEPLOY_VARIABLE` is `default-deploy`, and `IS_A_FEATURE` is `true`.
When the branch is something else:
- job1's `DEPLOY_VARIABLE` is `job1-default-deploy`.
- job2's `DEPLOY_VARIABLE` is `default-deploy`.
**Additional details**:
- `workflow:rules:variables` become [default variables](#variables) available in all jobs,
including [`trigger`](#trigger) jobs which forward variables to downstream pipelines by default.
If the downstream pipeline uses the same variable, the [variable is overwritten](../variables/_index.md#cicd-variable-precedence)
by the upstream variable value. Be sure to either:
- Use unique variable names in every project's pipeline configuration, like `PROJECT1_VARIABLE_NAME`.
- Use [`inherit:variables`](#inheritvariables) in the trigger job and list the
exact variables you want to forward to the downstream pipeline.
---
#### `workflow:rules:auto_cancel`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/436467) in GitLab 16.8 [with a flag](../../administration/feature_flags/_index.md) named `ci_workflow_auto_cancel_on_new_commit`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/434676) in GitLab 16.9.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/434676) in GitLab 16.10. Feature flag `ci_workflow_auto_cancel_on_new_commit` removed.
- `on_job_failure` option for `workflow:rules` [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/23605) in GitLab 16.10 [with a flag](../../administration/feature_flags/_index.md) named `auto_cancel_pipeline_on_job_failure`. Disabled by default.
- `on_job_failure` option for `workflow:rules` [generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/433163) in GitLab 16.11. Feature flag `auto_cancel_pipeline_on_job_failure` removed.
{{< /history >}}
Use `workflow:rules:auto_cancel` to configure the behavior of
the [`workflow:auto_cancel:on_new_commit`](#workflowauto_cancelon_new_commit) or
the [`workflow:auto_cancel:on_job_failure`](#workflowauto_cancelon_job_failure) features.
**Supported values**:
- `on_new_commit`: [`workflow:auto_cancel:on_new_commit`](#workflowauto_cancelon_new_commit)
- `on_job_failure`: [`workflow:auto_cancel:on_job_failure`](#workflowauto_cancelon_job_failure)
**Example of `workflow:rules:auto_cancel`**:
```yaml
workflow:
auto_cancel:
on_new_commit: interruptible
on_job_failure: all
rules:
- if: $CI_COMMIT_REF_PROTECTED == 'true'
auto_cancel:
on_new_commit: none
on_job_failure: none
- when: always # Run the pipeline in other cases
test-job1:
script: sleep 10
interruptible: false
test-job2:
script: sleep 10
interruptible: true
```
In this example, [`workflow:auto_cancel:on_new_commit`](#workflowauto_cancelon_new_commit)
is set to `interruptible` and [`workflow:auto_cancel:on_job_failure`](#workflowauto_cancelon_job_failure)
is set to `all` for all jobs by default. But if a pipeline runs for a protected branch,
the rule overrides the default with `on_new_commit: none` and `on_job_failure: none`. For example, if a pipeline
is running for:
- A non-protected branch and a new commit is pushed, `test-job1` continues to run and `test-job2` is canceled.
- A protected branch and a new commit is pushed, both `test-job1` and `test-job2` continue to run.
---
## Header keywords
Some keywords must be defined in a header section of a YAML configuration file.
The header must be at the top of the file, separated from the rest of the configuration
with `---`.
---
### `spec`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/391331) in GitLab 15.11 as a beta feature.
{{< /history >}}
Add a `spec` section to the header of a YAML file to configure the behavior of a pipeline
when a configuration is added to the pipeline with the `include` keyword.
Specs must be declared at the top of a configuration file, in a header section separated
from the rest of the configuration with `---`.
---
#### `spec:inputs`
You can use `spec:inputs` to define [inputs](../inputs/_index.md) for the CI/CD configuration.
Use the interpolation format `$[[ inputs.input-id ]]` to reference the values outside of the header section.
Inputs are evaluated and interpolated when the configuration is fetched during pipeline creation.
When using `inputs`, interpolation completes before the configuration is merged
with the contents of the `.gitlab-ci.yml` file.
**Keyword type**: Header keyword. `spec` must be declared at the top of the configuration file,
in a header section.
**Supported values**: A hash of strings representing the expected inputs.
**Example of `spec:inputs`**:
```yaml
spec:
inputs:
environment:
job-stage:
---
scan-website:
stage: $[[ inputs.job-stage ]]
script: ./scan-website $[[ inputs.environment ]]
```
**Additional details**:
- Inputs are mandatory unless you use [`spec:inputs:default`](#specinputsdefault)
to set a default value. Avoid mandatory inputs unless you only use inputs with
[`include:inputs`](#includeinputs).
- Inputs expect strings unless you use [`spec:inputs:type`](#specinputstype) to set a
different input type.
- A string containing an interpolation block must not exceed 1 MB.
- The string inside an interpolation block must not exceed 1 KB.
- You can define input values [when running a new pipeline](../inputs/_index.md#for-a-pipeline).
**Related topics**:
- [Define input parameters with `spec:inputs`](../inputs/_index.md#define-input-parameters-with-specinputs).
---
##### `spec:inputs:default`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/391331) in GitLab 15.11 as a beta feature.
{{< /history >}}
Inputs are mandatory when included, unless you set a default value with `spec:inputs:default`.
Use `default: ''` to have no default value.
**Keyword type**: Header keyword. `spec` must be declared at the top of the configuration file,
in a header section.
**Supported values**: A string representing the default value, or `''`.
**Example of `spec:inputs:default`**:
```yaml
spec:
inputs:
website:
user:
default: 'test-user'
flags:
default: ''
title: The pipeline configuration would follow...
---
```
In this example:
- `website` is mandatory and must be defined.
- `user` is optional. If not defined, the value is `test-user`.
- `flags` is optional. If not defined, it has no value.
**Additional details**:
- The pipeline fails with a validation error when the input:
- Uses both `default` and [`options`](#specinputsoptions), but the default value
is not one of the listed options.
- Uses both `default` and `regex`, but the default value does not match the regular expression.
- Value does not match the [`type`](#specinputstype).
---
##### `spec:inputs:description`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/415637) in GitLab 16.5.
{{< /history >}}
Use `description` to give a description to a specific input. The description does
not affect the behavior of the input and is only used to help users of the file
understand the input.
**Keyword type**: Header keyword. `spec` must be declared at the top of the configuration file,
in a header section.
**Supported values**: A string representing the description.
**Example of `spec:inputs:description`**:
```yaml
spec:
inputs:
flags:
description: 'Sample description of the `flags` input details.'
title: The pipeline configuration would follow...
---
```
---
##### `spec:inputs:options`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/393401) in GitLab 16.6.
{{< /history >}}
Inputs can use `options` to specify a list of allowed values for an input.
The limit is 50 options per input.
**Keyword type**: Header keyword. `spec` must be declared at the top of the configuration file,
in a header section.
**Supported values**: An array of input options.
**Example of `spec:inputs:options`**:
```yaml
spec:
inputs:
environment:
options:
- development
- staging
- production
title: The pipeline configuration would follow...
---
```
In this example:
- `environment` is mandatory and must be defined with one of the values in the list.
**Additional details**:
- The pipeline fails with a validation error when:
- The input uses both `options` and [`default`](#specinputsdefault), but the default value
is not one of the listed options.
- Any of the input options do not match the [`type`](#specinputstype), which can
be either `string` or `number`, but not `boolean` when using `options`.
---
##### `spec:inputs:regex`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/410836) in GitLab 16.5.
{{< /history >}}
Use `spec:inputs:regex` to specify a regular expression that the input must match.
**Keyword type**: Header keyword. `spec` must be declared at the top of the configuration file,
in a header section.
**Supported values**: Must be a regular expression.
**Example of `spec:inputs:regex`**:
```yaml
spec:
inputs:
version:
regex: ^v\d\.\d+(\.\d+)?$
title: The pipeline configuration would follow...
---
```
In this example, inputs of `v1.0` or `v1.2.3` match the regular expression and pass validation.
An input of `v1.A.B` does not match the regular expression and fails validation.
**Additional details**:
- `inputs:regex` can only be used with a [`type`](#specinputstype) of `string`,
not `number` or `boolean`.
- Do not enclose the regular expression with the `/` character. For example, use `regex.*`,
not `/regex.*/`.
- `inputs:regex` uses [RE2](https://github.com/google/re2/wiki/Syntax) to parse regular expressions.
---
##### `spec:inputs:type`
By default, inputs expect strings. Use `spec:inputs:type` to set a different required
type for inputs.
**Keyword type**: Header keyword. `spec` must be declared at the top of the configuration file,
in a header section.
**Supported values**: Can be one of:
- `array`, to accept an [array](../inputs/_index.md#array-type) of inputs.
- `string`, to accept string inputs (default when not defined).
- `number`, to only accept numeric inputs.
- `boolean`, to only accept `true` or `false` inputs.
**Example of `spec:inputs:type`**:
```yaml
spec:
inputs:
job_name:
website:
type: string
port:
type: number
available:
type: boolean
array_input:
type: array
title: The pipeline configuration would follow...
---
```
---
## Job keywords
The following topics explain how to use keywords to configure CI/CD pipelines.
---
### `after_script`
{{< history >}}
- Running `after_script` commands for canceled jobs [introduced](https://gitlab.com/groups/gitlab-org/-/epics/10158) in GitLab 17.0.
{{< /history >}}
Use `after_script` to define an array of commands to run last, after a job's `before_script` and
`script` sections complete. `after_script` commands also run when:
- The job is canceled while the `before_script` or `script` sections are still running.
- The job fails with failure type of `script_failure`, but not [other failure types](#retrywhen).
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: An array including:
- Single line commands.
- Long commands [split over multiple lines](script.md#split-long-commands).
- [YAML anchors](yaml_optimization.md#yaml-anchors-for-scripts).
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `after_script`**:
```yaml
job:
script:
- echo "An example script section."
after_script:
- echo "Execute this command after the `script` section completes."
```
**Additional details**:
Scripts you specify in `after_script` execute in a new shell, separate from any
`before_script` or `script` commands. As a result, they:
- Have the current working directory set back to the default (according to the [variables which define how the runner processes Git requests](../runners/configure_runners.md#configure-runner-behavior-with-variables)).
- Don't have access to changes done by commands defined in the `before_script` or `script`,
including:
- Command aliases and variables exported in `script` scripts.
- Changes outside of the working tree (depending on the runner executor), like
software installed by a `before_script` or `script` script.
- Have a separate timeout. For GitLab Runner 16.4 and later, this defaults to 5 minutes, and can be configured with the
[`RUNNER_AFTER_SCRIPT_TIMEOUT`](../runners/configure_runners.md#set-script-and-after_script-timeouts) variable.
In GitLab 16.3 and earlier, the timeout is hard-coded to 5 minutes.
- Don't affect the job's exit code. If the `script` section succeeds and the
`after_script` times out or fails, the job exits with code `0` (`Job Succeeded`).
- There is a known issue with using [CI/CD job tokens](../jobs/ci_job_token.md) with `after_script`.
You can use a job token for authentication in `after_script` commands, but the token
immediately becomes invalid if the job is canceled. See [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/473376)
for more details.
For jobs that time out:
- `after_script` commands do not execute by default.
- You can [configure timeout values](../runners/configure_runners.md#ensuring-after_script-execution) to ensure `after_script` runs by setting appropriate `RUNNER_SCRIPT_TIMEOUT` and `RUNNER_AFTER_SCRIPT_TIMEOUT` values that don't exceed the job's timeout.
**Related topics**:
- [Use `after_script` with `default`](script.md#set-a-default-before_script-or-after_script-for-all-jobs)
to define a default array of commands that should run after all jobs.
- You can configure a job to [skip `after_script` commands if the job is canceled](script.md#skip-after_script-commands-if-a-job-is-canceled).
- You can [ignore non-zero exit codes](script.md#ignore-non-zero-exit-codes).
- [Use color codes with `after_script`](script.md#add-color-codes-to-script-output)
to make job logs easier to review.
- [Create custom collapsible sections](../jobs/job_logs.md#custom-collapsible-sections)
to simplify job log output.
- You can [ignore errors in `after_script`](../runners/configure_runners.md#ignore-errors-in-after_script).
---
### `allow_failure`
Use `allow_failure` to determine whether a pipeline should continue running when a job fails.
- To let the pipeline continue running subsequent jobs, use `allow_failure: true`.
- To stop the pipeline from running subsequent jobs, use `allow_failure: false`.
When jobs are allowed to fail (`allow_failure: true`) an orange warning ({{< icon name="status_warning" >}})
indicates that a job failed. However, the pipeline is successful and the associated commit
is marked as passed with no warnings.
This same warning is displayed when:
- All other jobs in the stage are successful.
- All other jobs in the pipeline are successful.
The default value for `allow_failure` is:
- `true` for [manual jobs](../jobs/job_control.md#create-a-job-that-must-be-run-manually).
- `false` for jobs that use `when: manual` inside [`rules`](#rules).
- `false` in all other cases.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `true` or `false`.
**Example of `allow_failure`**:
```yaml
job1:
stage: test
script:
- execute_script_1
job2:
stage: test
script:
- execute_script_2
allow_failure: true
job3:
stage: deploy
script:
- deploy_to_staging
environment: staging
```
In this example, `job1` and `job2` run in parallel:
- If `job1` fails, jobs in the `deploy` stage do not start.
- If `job2` fails, jobs in the `deploy` stage can still start.
**Additional details**:
- You can use `allow_failure` as a subkey of [`rules`](#rulesallow_failure).
- If `allow_failure: true` is set, the job is always considered successful, and later jobs with [`when: on_failure`](#when) don't start if this job fails.
- You can use `allow_failure: false` with a manual job to create a [blocking manual job](../jobs/job_control.md#types-of-manual-jobs).
A blocked pipeline does not run any jobs in later stages until the manual job
is started and completes successfully.
---
#### `allow_failure:exit_codes`
Use `allow_failure:exit_codes` to control when a job should be
allowed to fail. The job is `allow_failure: true` for any of the listed exit codes,
and `allow_failure` false for any other exit code.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A single exit code.
- An array of exit codes.
**Example of `allow_failure`**:
```yaml
test_job_1:
script:
- echo "Run a script that results in exit code 1. This job fails."
- exit 1
allow_failure:
exit_codes: 137
test_job_2:
script:
- echo "Run a script that results in exit code 137. This job is allowed to fail."
- exit 137
allow_failure:
exit_codes:
- 137
- 255
```
---
### `artifacts`
{{< history >}}
- [Updated](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/5543) in GitLab Runner 18.1. During the caching process,
`symlinks` are no longer followed, which happened in some edge cases with previous GitLab Runner versions.
{{< /history >}}
Use `artifacts` to specify which files to save as [job artifacts](../jobs/job_artifacts.md).
Job artifacts are a list of files and directories that are
attached to the job when it [succeeds, fails, or always](#artifactswhen).
The artifacts are sent to GitLab after the job finishes. They are
available for download in the GitLab UI if the size is smaller than the
[maximum artifact size](../../user/gitlab_com/_index.md#cicd).
By default, jobs in later stages automatically download all the artifacts created
by jobs in earlier stages. You can control artifact download behavior in jobs with
[`dependencies`](#dependencies).
When using the [`needs`](#needs) keyword, jobs can only download
artifacts from the jobs defined in the `needs` configuration.
Job artifacts are only collected for successful jobs by default, and
artifacts are restored after [caches](#cache).
[Read more about artifacts](../jobs/job_artifacts.md).
---
#### `artifacts:paths`
Paths are relative to the project directory (`$CI_PROJECT_DIR`) and can't directly
link outside it.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- An array of file paths, relative to the project directory.
- You can use Wildcards that use [glob](https://en.wikipedia.org/wiki/Glob_(programming)) patterns and [`doublestar.Glob`](https://pkg.go.dev/github.com/bmatcuk/doublestar@v1.2.2?tab=doc#Match) patterns.
- For [GitLab Pages job](#pages):
- In [GitLab 17.10 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/428018),
the [`pages.publish`](#pagespublish) path is automatically appended to `artifacts:paths`,
so you don't need to specify it again.
- In [GitLab 17.10 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/428018),
when the [`pages.publish`](#pagespublish) path is not specified,
the `public` directory is automatically appended to `artifacts:paths`.
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `artifacts:paths`**:
```yaml
job:
artifacts:
paths:
- binaries/
- .config
```
This example creates an artifact with `.config` and all the files in the `binaries` directory.
**Additional details**:
- If not used with [`artifacts:name`](#artifactsname), the artifacts file
is named `artifacts`, which becomes `artifacts.zip` when downloaded.
**Related topics**:
- To restrict which jobs a specific job fetches artifacts from, see [`dependencies`](#dependencies).
- [Create job artifacts](../jobs/job_artifacts.md#create-job-artifacts).
---
#### `artifacts:exclude`
Use `artifacts:exclude` to prevent files from being added to an artifacts archive.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- An array of file paths, relative to the project directory.
- You can use Wildcards that use [glob](https://en.wikipedia.org/wiki/Glob_(programming)) or
[`doublestar.PathMatch`](https://pkg.go.dev/github.com/bmatcuk/doublestar@v1.2.2?tab=doc#PathMatch) patterns.
**Example of `artifacts:exclude`**:
```yaml
artifacts:
paths:
- binaries/
exclude:
- binaries/**/*.o
```
This example stores all files in `binaries/`, but not `*.o` files located in
subdirectories of `binaries/`.
**Additional details**:
- `artifacts:exclude` paths are not searched recursively.
- Files matched by [`artifacts:untracked`](#artifactsuntracked) can be excluded using
`artifacts:exclude` too.
**Related topics**:
- [Exclude files from job artifacts](../jobs/job_artifacts.md#without-excluded-files).
---
#### `artifacts:expire_in`
Use `expire_in` to specify how long [job artifacts](../jobs/job_artifacts.md) are stored before
they expire and are deleted. The `expire_in` setting does not affect:
- Artifacts from the latest job, unless keeping the latest job artifacts is disabled
[at the project level](../jobs/job_artifacts.md#keep-artifacts-from-most-recent-successful-jobs)
or [instance-wide](../../administration/settings/continuous_integration.md#keep-artifacts-from-latest-successful-pipelines).
After their expiry, artifacts are deleted hourly by default (using a cron job), and are not
accessible anymore.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: The expiry time. If no unit is provided, the time is in seconds.
Valid values include:
- `'42'`
- `42 seconds`
- `3 mins 4 sec`
- `2 hrs 20 min`
- `2h20min`
- `6 mos 1 day`
- `47 yrs 6 mos and 4d`
- `3 weeks and 2 days`
- `never`
**Example of `artifacts:expire_in`**:
```yaml
job:
artifacts:
expire_in: 1 week
```
**Additional details**:
- The expiration time period begins when the artifact is uploaded and stored on GitLab.
If the expiry time is not defined, it defaults to the [instance wide setting](../../administration/settings/continuous_integration.md#set-default-artifacts-expiration).
- To override the expiration date and protect artifacts from being automatically deleted:
- Select **Keep** on the job page.
- Set the value of `expire_in` to `never`.
- If the expiry time is too short, jobs in later stages of a long pipeline might try to fetch
expired artifacts from earlier jobs. If the artifacts are expired, jobs that try to fetch
them fail with a [`could not retrieve the needed artifacts` error](../jobs/job_artifacts_troubleshooting.md#error-message-this-job-could-not-start-because-it-could-not-retrieve-the-needed-artifacts).
Set the expiry time to be longer, or use [`dependencies`](#dependencies) in later jobs
to ensure they don't try to fetch expired artifacts.
- `artifacts:expire_in` doesn't affect GitLab Pages deployments. To configure Pages deployments' expiry, use [`pages.expire_in`](#pagesexpire_in).
---
#### `artifacts:expose_as`
Use the `artifacts:expose_as` keyword to
[expose job artifacts in the merge request UI](../jobs/job_artifacts.md#link-to-job-artifacts-in-the-merge-request-ui).
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- The name to display in the merge request UI for the artifacts download link.
Must be combined with [`artifacts:paths`](#artifactspaths).
**Example of `artifacts:expose_as`**:
```yaml
test:
script: ["echo 'test' > file.txt"]
artifacts:
expose_as: 'artifact 1'
paths: ['file.txt']
```
**Additional details**:
- Artifacts are saved, but do not display in the UI if the `artifacts:paths` values:
- Use [CI/CD variables](../variables/_index.md).
- Define a directory, but do not end with `/`. For example, `directory/` works with `artifacts:expose_as`,
but `directory` does not.
- Start with `./`. For example, `file` works with `artifacts:expose_as`, but `./file` does not.
- A maximum of 10 job artifacts per merge request can be exposed.
- Glob patterns are unsupported.
- If a directory is specified and there is more than one file in the directory,
the link is to the job [artifacts browser](../jobs/job_artifacts.md#download-job-artifacts).
- If [GitLab Pages](../../administration/pages/_index.md) is enabled, GitLab automatically
renders the artifacts when the artifacts is a single file with one of these extensions:
- `.html` or `.htm`
- `.txt`
- `.json`
- `.xml`
- `.log`
**Related topics**:
- [Expose job artifacts in the merge request UI](../jobs/job_artifacts.md#link-to-job-artifacts-in-the-merge-request-ui).
---
#### `artifacts:name`
Use the `artifacts:name` keyword to define the name of the created artifacts
archive. You can specify a unique name for every archive.
If not defined, the default name is `artifacts`, which becomes `artifacts.zip` when downloaded.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- The name of the artifacts archive. CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
Must be combined with [`artifacts:paths`](#artifactspaths).
**Example of `artifacts:name`**:
To create an archive with a name of the current job:
```yaml
job:
artifacts:
name: "job1-artifacts-file"
paths:
- binaries/
```
**Related topics**:
- [Use CI/CD variables to define the artifacts configuration](../jobs/job_artifacts.md#with-variable-expansion)
---
#### `artifacts:public`
{{< history >}}
- [Updated](https://gitlab.com/gitlab-org/gitlab/-/issues/322454) in GitLab 15.10. Artifacts created with `artifacts:public` before 15.10 are not guaranteed to remain private after this update.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/294503) in GitLab 16.7. Feature flag `non_public_artifacts` removed.
{{< /history >}}
{{< alert type="note" >}}
`artifacts:public` is now superseded by [`artifacts:access`](#artifactsaccess) which
has more options.
{{< /alert >}}
Use `artifacts:public` to determine whether the job artifacts should be
publicly available.
When `artifacts:public` is `true` (default), the artifacts in
public pipelines are available for download by anonymous, guest, and reporter users.
To deny read access to artifacts in public
pipelines for anonymous, guest, and reporter users, set `artifacts:public` to `false`:
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `true` (default if not defined) or `false`.
**Example of `artifacts:public`**:
```yaml
job:
artifacts:
public: false
```
---
#### `artifacts:access`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/145206) in GitLab 16.11.
{{< /history >}}
Use `artifacts:access` to determine who can access the job artifacts from the GitLab UI
or API. This option does not prevent you from forwarding artifacts to downstream pipelines.
You cannot use [`artifacts:public`](#artifactspublic) and `artifacts:access` in the same job.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `all` (default): Artifacts in a job in public pipelines are available for download by anyone,
including anonymous, guest, and reporter users.
- `developer`: Artifacts in the job are only available for download by users with the Developer role or higher.
- `none`: Artifacts in the job are not available for download by anyone.
**Example of `artifacts:access`**:
```yaml
job:
artifacts:
access: 'developer'
```
**Additional details**:
- `artifacts:access` affects all [`artifacts:reports`](#artifactsreports) too,
so you can also restrict access to [artifacts for reports](artifacts_reports.md).
---
#### `artifacts:reports`
Use [`artifacts:reports`](artifacts_reports.md) to collect artifacts generated by
included templates in jobs.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- See list of available [artifacts reports types](artifacts_reports.md).
**Example of `artifacts:reports`**:
```yaml
rspec:
stage: test
script:
- bundle install
- rspec --format RspecJunitFormatter --out rspec.xml
artifacts:
reports:
junit: rspec.xml
```
**Additional details**:
- Combining reports in parent pipelines using [artifacts from child pipelines](#needspipelinejob) is
not supported. Track progress on adding support in [this issue](https://gitlab.com/gitlab-org/gitlab/-/issues/215725).
- To be able to browse and download the report output files, include the [`artifacts:paths`](#artifactspaths) keyword. This uploads and stores the artifact twice.
- Artifacts created for `artifacts: reports` are always uploaded, regardless of the job results (success or failure).
You can use [`artifacts:expire_in`](#artifactsexpire_in) to set an expiration
date for the artifacts.
---
#### `artifacts:untracked`
Use `artifacts:untracked` to add all Git untracked files as artifacts (along
with the paths defined in `artifacts:paths`). `artifacts:untracked` ignores configuration
in the repository's `.gitignore`, so matching artifacts in `.gitignore` are included.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `true` or `false` (default if not defined).
**Example of `artifacts:untracked`**:
Save all Git untracked files:
```yaml
job:
artifacts:
untracked: true
```
**Related topics**:
- [Add untracked files to artifacts](../jobs/job_artifacts.md#with-untracked-files).
---
#### `artifacts:when`
Use `artifacts:when` to upload artifacts on job failure or despite the
failure.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `on_success` (default): Upload artifacts only when the job succeeds.
- `on_failure`: Upload artifacts only when the job fails.
- `always`: Always upload artifacts (except when jobs time out). For example, when
[uploading artifacts](../testing/unit_test_reports.md#add-screenshots-to-test-reports)
required to troubleshoot failing tests.
**Example of `artifacts:when`**:
```yaml
job:
artifacts:
when: on_failure
```
**Additional details**:
- The artifacts created for [`artifacts:reports`](#artifactsreports) are always uploaded,
regardless of the job results (success or failure). `artifacts:when` does not change this behavior.
---
### `before_script`
Use `before_script` to define an array of commands that should run before each job's
`script` commands, but after [artifacts](#artifacts) are restored.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: An array including:
- Single line commands.
- Long commands [split over multiple lines](script.md#split-long-commands).
- [YAML anchors](yaml_optimization.md#yaml-anchors-for-scripts).
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `before_script`**:
```yaml
job:
before_script:
- echo "Execute this command before any 'script:' commands."
script:
- echo "This command executes after the job's 'before_script' commands."
```
**Additional details**:
- Scripts you specify in `before_script` are concatenated with any scripts you specify
in the main [`script`](#script). The combined scripts execute together in a single shell.
- Using `before_script` at the top level, but not in the `default` section, [is deprecated](deprecated_keywords.md#globally-defined-image-services-cache-before_script-after_script).
**Related topics**:
- [Use `before_script` with `default`](script.md#set-a-default-before_script-or-after_script-for-all-jobs)
to define a default array of commands that should run before the `script` commands in all jobs.
- You can [ignore non-zero exit codes](script.md#ignore-non-zero-exit-codes).
- [Use color codes with `before_script`](script.md#add-color-codes-to-script-output)
to make job logs easier to review.
- [Create custom collapsible sections](../jobs/job_logs.md#custom-collapsible-sections)
to simplify job log output.
---
### `cache`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/330047) in GitLab 15.0, caches are not shared between protected and unprotected branches.
- [Updated](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/5543) in GitLab Runner 18.1. During the caching process,
`symlinks` are no longer followed, which happened in some edge cases with previous GitLab Runner versions.
{{< /history >}}
Use `cache` to specify a list of files and directories to
cache between jobs. You can only use paths that are in the local working copy.
Caches are:
- Shared between pipelines and jobs.
- By default, not shared between [protected](../../user/project/repository/branches/protected.md) and unprotected branches.
- Restored before [artifacts](#artifacts).
- Limited to a maximum of four [different caches](../caching/_index.md#use-multiple-caches).
You can [disable caching for specific jobs](../caching/_index.md#disable-cache-for-specific-jobs),
for example to override:
- A default cache defined with [`default`](#default).
- The configuration for a job added with [`include`](#include).
For more information about caches, see [Caching in GitLab CI/CD](../caching/_index.md).
---
#### `cache:paths`
Use the `cache:paths` keyword to choose which files or directories to cache.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- An array of paths relative to the project directory (`$CI_PROJECT_DIR`).
You can use wildcards that use [glob](https://en.wikipedia.org/wiki/Glob_(programming)) and
[`doublestar.Glob`](https://pkg.go.dev/github.com/bmatcuk/doublestar@v1.2.2?tab=doc#Match) patterns.
[CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file) are supported.
**Example of `cache:paths`**:
Cache all files in `binaries` that end in `.apk` and the `.config` file:
```yaml
rspec:
script:
- echo "This job uses a cache."
cache:
key: binaries-cache
paths:
- binaries/*.apk
- .config
```
**Additional details**:
- The `cache:paths` keyword includes files even if they are untracked or in your `.gitignore` file.
**Related topics**:
- See the [common `cache` use cases](../caching/_index.md#common-use-cases-for-caches) for more
`cache:paths` examples.
---
#### `cache:key`
Use the `cache:key` keyword to give each cache a unique identifying key. All jobs
that use the same cache key use the same cache, including in different pipelines.
If not set, the default key is `default`. All jobs with the `cache` keyword but
no `cache:key` share the `default` cache.
Must be used with `cache: paths`, or nothing is cached.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- A string.
- A predefined [CI/CD variable](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
- A combination of both.
**Example of `cache:key`**:
```yaml
cache-job:
script:
- echo "This job uses a cache."
cache:
key: binaries-cache-$CI_COMMIT_REF_SLUG
paths:
- binaries/
```
**Additional details**:
- If you use **Windows Batch** to run your shell scripts you must replace
`$` with `%`. For example: `key: %CI_COMMIT_REF_SLUG%`
- The `cache:key` value can't contain:
- The `/` character, or the equivalent URI-encoded `%2F`.
- Only the `.` character (any number), or the equivalent URI-encoded `%2E`.
- The cache is shared between jobs, so if you're using different
paths for different jobs, you should also set a different `cache:key`.
Otherwise cache content can be overwritten.
**Related topics**:
- You can specify a [fallback cache key](../caching/_index.md#use-a-fallback-cache-key)
to use if the specified `cache:key` is not found.
- You can [use multiple cache keys](../caching/_index.md#use-multiple-caches) in a single job.
- See the [common `cache` use cases](../caching/_index.md#common-use-cases-for-caches) for more
`cache:key` examples.
---
##### `cache:key:files`
Use the `cache:key:files` keyword to generate a new key when files matching either of the defined paths or patterns
change. `cache:key:files` lets you reuse some caches, and rebuild them less often,
which speeds up subsequent pipeline runs.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- An array of up to two file paths or patterns.
CI/CD variables are not supported.
**Example of `cache:key:files`**:
```yaml
cache-job:
script:
- echo "This job uses a cache."
cache:
key:
files:
- Gemfile.lock
- package.json
paths:
- vendor/ruby
- node_modules
```
This example creates a cache for Ruby and Node.js dependencies. The cache
is tied to the current versions of the `Gemfile.lock` and `package.json` files. When one of
these files changes, a new cache key is computed and a new cache is created. Any future
job runs that use the same `Gemfile.lock` and `package.json` with `cache:key:files`
use the new cache, instead of rebuilding the dependencies.
**Additional details**:
- The cache `key` is a SHA computed from the most recent commits
that changed each listed file.
If neither file is changed in any commits, the fallback key is `default`.
- Wildcard patterns like `**/package.json` can be used. An [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/301161)
exists to increase the number of paths or patterns allowed for a cache key.
---
##### `cache:key:prefix`
Use `cache:key:prefix` to combine a prefix with the SHA computed for [`cache:key:files`](#cachekeyfiles).
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- A string.
- A predefined [CI/CD variable](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
- A combination of both.
**Example of `cache:key:prefix`**:
```yaml
rspec:
script:
- echo "This rspec job uses a cache."
cache:
key:
files:
- Gemfile.lock
prefix: $CI_JOB_NAME
paths:
- vendor/ruby
```
For example, adding a `prefix` of `$CI_JOB_NAME` causes the key to look like `rspec-feef9576d21ee9b6a32e30c5c79d0a0ceb68d1e5`.
If a branch changes `Gemfile.lock`, that branch has a new SHA checksum for `cache:key:files`.
A new cache key is generated, and a new cache is created for that key. If `Gemfile.lock`
is not found, the prefix is added to `default`, so the key in the example would be `rspec-default`.
**Additional details**:
- If no file in `cache:key:files` is changed in any commits, the prefix is added to the `default` key.
---
#### `cache:untracked`
Use `untracked: true` to cache all files that are untracked in your Git repository.
Untracked files include files that are:
- Ignored due to [`.gitignore` configuration](https://git-scm.com/docs/gitignore).
- Created, but not added to the checkout with [`git add`](https://git-scm.com/docs/git-add).
Caching untracked files can create unexpectedly large caches if the job downloads:
- Dependencies, like gems or node modules, which are usually untracked.
- [Artifacts](#artifacts) from a different job. Files extracted from the artifacts are untracked by default.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `true` or `false` (default).
**Example of `cache:untracked`**:
```yaml
rspec:
script: test
cache:
untracked: true
```
**Additional details**:
- You can combine `cache:untracked` with `cache:paths` to cache all untracked files, as well as files in the configured paths.
Use `cache:paths` to cache any specific files, including tracked files, or files that are outside of the working directory,
and use `cache: untracked` to also cache all untracked files. For example:
```yaml
rspec:
script: test
cache:
untracked: true
paths:
- binaries/
```
In this example, the job caches all untracked files in the repository, as well as all the files in `binaries/`.
If there are untracked files in `binaries/`, they are covered by both keywords.
---
#### `cache:unprotect`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/362114) in GitLab 15.8.
{{< /history >}}
Use `cache:unprotect` to set a cache to be shared between [protected](../../user/project/repository/branches/protected.md)
and unprotected branches.
{{< alert type="warning" >}}
When set to `true`, users without access to protected branches can read and write to
cache keys used by protected branches.
{{< /alert >}}
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `true` or `false` (default).
**Example of `cache:unprotect`**:
```yaml
rspec:
script: test
cache:
unprotect: true
```
---
#### `cache:when`
Use `cache:when` to define when to save the cache, based on the status of the job.
Must be used with `cache: paths`, or nothing is cached.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `on_success` (default): Save the cache only when the job succeeds.
- `on_failure`: Save the cache only when the job fails.
- `always`: Always save the cache.
**Example of `cache:when`**:
```yaml
rspec:
script: rspec
cache:
paths:
- rspec/
when: 'always'
```
This example stores the cache whether or not the job fails or succeeds.
---
#### `cache:policy`
To change the upload and download behavior of a cache, use the `cache:policy` keyword.
By default, the job downloads the cache when the job starts, and uploads changes
to the cache when the job ends. This caching style is the `pull-push` policy (default).
To set a job to only download the cache when the job starts, but never upload changes
when the job finishes, use `cache:policy:pull`.
To set a job to only upload a cache when the job finishes, but never download the
cache when the job starts, use `cache:policy:push`.
Use the `pull` policy when you have many jobs executing in parallel that use the same cache.
This policy speeds up job execution and reduces load on the cache server. You can
use a job with the `push` policy to build the cache.
Must be used with `cache: paths`, or nothing is cached.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `pull`
- `push`
- `pull-push` (default)
- [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `cache:policy`**:
```yaml
prepare-dependencies-job:
stage: build
cache:
key: gems
paths:
- vendor/bundle
policy: push
script:
- echo "This job only downloads dependencies and builds the cache."
- echo "Downloading dependencies..."
faster-test-job:
stage: test
cache:
key: gems
paths:
- vendor/bundle
policy: pull
script:
- echo "This job script uses the cache, but does not update it."
- echo "Running tests..."
```
**Related topics**:
- You can [use a variable to control a job's cache policy](../caching/_index.md#use-a-variable-to-control-a-jobs-cache-policy).
---
#### `cache:fallback_keys`
Use `cache:fallback_keys` to specify a list of keys to try to restore cache from
if there is no cache found for the `cache:key`. Caches are retrieved in the order specified
in the `fallback_keys` section.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- An array of cache keys
**Example of `cache:fallback_keys`**:
```yaml
rspec:
script: rspec
cache:
key: gems-$CI_COMMIT_REF_SLUG
paths:
- rspec/
fallback_keys:
- gems
when: 'always'
```
---
### `coverage`
Use `coverage` with a custom regular expression to configure how code coverage
is extracted from the job output. The coverage is shown in the UI if at least one
line in the job output matches the regular expression.
To extract the code coverage value from the match, GitLab uses
this smaller regular expression: `\d+(?:\.\d+)?`.
**Supported values**:
- An RE2 regular expression. Must start and end with `/`. Must match the coverage number.
May match surrounding text as well, so you don't need to use a regular expression character group
to capture the exact number.
Because it uses RE2 syntax, all groups must be non-capturing.
**Example of `coverage`**:
```yaml
job1:
script: rspec
coverage: '/Code coverage: \d+(?:\.\d+)?/'
```
In this example:
1. GitLab checks the job log for a match with the regular expression. A line
like `Code coverage: 67.89% of lines covered` would match.
1. GitLab then checks the matched fragment to find a match to the regular expression: `\d+(?:\.\d+)?`.
The sample regex can match a code coverage of `67.89`.
**Additional details**:
- You can find regex examples in [Code Coverage](../testing/code_coverage/_index.md#coverage-regex-patterns).
- If there is more than one matched line in the job output, the last line is used
(the first result of reverse search).
- If there are multiple matches in a single line, the last match is searched
for the coverage number.
- If there are multiple coverage numbers found in the matched fragment, the first number is used.
- Leading zeros are removed.
- Coverage output from [child pipelines](../pipelines/downstream_pipelines.md#parent-child-pipelines)
is not recorded or displayed. Check [the related issue](https://gitlab.com/gitlab-org/gitlab/-/issues/280818)
for more details.
---
### `dast_configuration`
{{< details >}}
- Tier: Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use the `dast_configuration` keyword to specify a site profile and scanner profile to be used in a
CI/CD configuration. Both profiles must first have been created in the project. The job's stage must
be `dast`.
**Keyword type**: Job keyword. You can use only as part of a job.
**Supported values**: One each of `site_profile` and `scanner_profile`.
- Use `site_profile` to specify the site profile to be used in the job.
- Use `scanner_profile` to specify the scanner profile to be used in the job.
**Example of `dast_configuration`**:
```yaml
stages:
- build
- dast
include:
- template: DAST.gitlab-ci.yml
dast:
dast_configuration:
site_profile: "Example Co"
scanner_profile: "Quick Passive Test"
```
In this example, the `dast` job extends the `dast` configuration added with the `include` keyword
to select a specific site profile and scanner profile.
**Additional details**:
- Settings contained in either a site profile or scanner profile take precedence over those
contained in the DAST template.
**Related topics**:
- [Site profile](../../user/application_security/dast/profiles.md#site-profile).
- [Scanner profile](../../user/application_security/dast/profiles.md#scanner-profile).
---
### `dependencies`
Use the `dependencies` keyword to define a list of specific jobs to fetch [artifacts](#artifacts)
from. The specified jobs must all be in earlier stages. You can also set a job to download no artifacts at all.
When `dependencies` is not defined in a job, all jobs in earlier stages are considered dependent
and the job fetches all artifacts from those jobs.
To fetch artifacts from a job in the same stage, you must use [`needs:artifacts`](#needsartifacts).
You should not combine `dependencies` with `needs` in the same job.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- The names of jobs to fetch artifacts from.
- An empty array (`[]`), to configure the job to not download any artifacts.
**Example of `dependencies`**:
```yaml
build osx:
stage: build
script: make build:osx
artifacts:
paths:
- binaries/
build linux:
stage: build
script: make build:linux
artifacts:
paths:
- binaries/
test osx:
stage: test
script: make test:osx
dependencies:
- build osx
test linux:
stage: test
script: make test:linux
dependencies:
- build linux
deploy:
stage: deploy
script: make deploy
environment: production
```
In this example, two jobs have artifacts: `build osx` and `build linux`. When `test osx` is executed,
the artifacts from `build osx` are downloaded and extracted in the context of the build.
The same thing happens for `test linux` and artifacts from `build linux`.
The `deploy` job downloads artifacts from all previous jobs because of
the [stage](#stages) precedence.
**Additional details**:
- The job status does not matter. If a job fails or it's a manual job that isn't triggered, no error occurs.
- If the artifacts of a dependent job are [expired](#artifactsexpire_in) or
[deleted](../jobs/job_artifacts.md#delete-job-log-and-artifacts), then the job fails.
---
### `environment`
Use `environment` to define the [environment](../environments/_index.md) that a job deploys to.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: The name of the environment the job deploys to, in one of these
formats:
- Plain text, including letters, digits, spaces, and these characters: `-`, `_`, `/`, `$`, `{`, `}`.
- CI/CD variables, including predefined, project, group, instance, or variables defined in the
`.gitlab-ci.yml` file. You can't use variables defined in a `script` section.
**Example of `environment`**:
```yaml
deploy to production:
stage: deploy
script: git push production HEAD:main
environment: production
```
**Additional details**:
- If you specify an `environment` and no environment with that name exists, an environment is
created.
---
#### `environment:name`
Set a name for an [environment](../environments/_index.md).
Common environment names are `qa`, `staging`, and `production`, but you can use any name.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: The name of the environment the job deploys to, in one of these
formats:
- Plain text, including letters, digits, spaces, and these characters: `-`, `_`, `/`, `$`, `{`, `}`.
- [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file),
including predefined, project, group, instance, or variables defined in the
`.gitlab-ci.yml` file. You can't use variables defined in a `script` section.
**Example of `environment:name`**:
```yaml
deploy to production:
stage: deploy
script: git push production HEAD:main
environment:
name: production
```
---
#### `environment:url`
Set a URL for an [environment](../environments/_index.md).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: A single URL, in one of these formats:
- Plain text, like `https://prod.example.com`.
- [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file),
including predefined, project, group, instance, or variables defined in the
`.gitlab-ci.yml` file. You can't use variables defined in a `script` section.
**Example of `environment:url`**:
```yaml
deploy to production:
stage: deploy
script: git push production HEAD:main
environment:
name: production
url: https://prod.example.com
```
**Additional details**:
- After the job completes, you can access the URL by selecting a button in the merge request,
environment, or deployment pages.
---
#### `environment:on_stop`
Closing (stopping) environments can be achieved with the `on_stop` keyword
defined under `environment`. It declares a different job that runs to close the
environment.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Additional details**:
- See [`environment:action`](#environmentaction) for more details and an example.
---
#### `environment:action`
Use the `action` keyword to specify how the job interacts with the environment.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: One of the following keywords:
| **Value** | **Description** |
|:----------|:----------------|
| `start` | Default value. Indicates that the job starts the environment. The deployment is created after the job starts. |
| `prepare` | Indicates that the job is only preparing the environment. It does not trigger deployments. [Read more about preparing environments](../environments/_index.md#access-an-environment-for-preparation-or-verification-purposes). |
| `stop` | Indicates that the job stops an environment. [Read more about stopping an environment](../environments/_index.md#stopping-an-environment). |
| `verify` | Indicates that the job is only verifying the environment. It does not trigger deployments. [Read more about verifying environments](../environments/_index.md#access-an-environment-for-preparation-or-verification-purposes). |
| `access` | Indicates that the job is only accessing the environment. It does not trigger deployments. [Read more about accessing environments](../environments/_index.md#access-an-environment-for-preparation-or-verification-purposes). |
**Example of `environment:action`**:
```yaml
stop_review_app:
stage: deploy
variables:
GIT_STRATEGY: none
script: make delete-app
when: manual
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
```
---
#### `environment:auto_stop_in`
{{< history >}}
- CI/CD variable support [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/365140) in GitLab 15.4.
- [Updated](https://gitlab.com/gitlab-org/gitlab/-/issues/437133) to support `prepare`, `access` and `verify` environment actions in GitLab 17.7.
{{< /history >}}
The `auto_stop_in` keyword specifies the lifetime of the environment. When an environment expires, GitLab
automatically stops it.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: A period of time written in natural language. For example,
these are all equivalent:
- `168 hours`
- `7 days`
- `one week`
- `never`
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `environment:auto_stop_in`**:
```yaml
review_app:
script: deploy-review-app
environment:
name: review/$CI_COMMIT_REF_SLUG
auto_stop_in: 1 day
```
When the environment for `review_app` is created, the environment's lifetime is set to `1 day`.
Every time the review app is deployed, that lifetime is also reset to `1 day`.
The `auto_stop_in` keyword can be used for all [environment actions](#environmentaction) except `stop`.
Some actions can be used to reset the scheduled stop time for the environment. For more information, see
[Access an environment for preparation or verification purposes](../environments/_index.md#access-an-environment-for-preparation-or-verification-purposes).
**Related topics**:
- [Environments auto-stop documentation](../environments/_index.md#stop-an-environment-after-a-certain-time-period).
---
#### `environment:kubernetes`
{{< history >}}
- `agent` keyword [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/467912) in GitLab 17.6.
- `namespace` and `flux_resource_path` keywords [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/500164) in GitLab 17.7.
{{< /history >}}
Use the `kubernetes` keyword to configure the [dashboard for Kubernetes](../environments/kubernetes_dashboard.md)
for an environment.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `agent`: A string specifying the [GitLab agent for Kubernetes](../../user/clusters/agent/_index.md). The format is `path/to/agent/project:agent-name`. If the agent is connected to the project running the pipeline, use `$CI_PROJECT_PATH:agent-name`.
- `namespace`: A string representing the Kubernetes namespace where the environment is deployed. The namespace must be set together with the `agent` keyword.
- `flux_resource_path`: A string representing the full path to the Flux resource, such as a HelmRelease. The Flux resource must be set together with the
`agent` and `namespace` keywords.
**Example of `environment:kubernetes`**:
```yaml
deploy:
stage: deploy
script: make deploy-app
environment:
name: production
kubernetes:
agent: path/to/agent/project:agent-name
namespace: my-namespace
flux_resource_path: helm.toolkit.fluxcd.io/v2/namespaces/flux-system/helmreleases/helm-release-resource
```
This configuration:
- Sets up the `deploy` job to deploy to the `production`
environment
- Associates the [agent](../../user/clusters/agent/_index.md) named `agent-name` with the environment
- Configures the [dashboard for Kubernetes](../environments/kubernetes_dashboard.md) for an environment with
the namespace `my-namespace` and the `flux_resource_path` set to
`helm.toolkit.fluxcd.io/v2/namespaces/flux-system/helmreleases/helm-release-resource`.
**Additional details**:
- To use the dashboard, you must
[install the GitLab agent for Kubernetes](../../user/clusters/agent/install/_index.md) and
[configure `user_access`](../../user/clusters/agent/user_access.md)
for the environment's project or its parent group.
- The user running the job must be authorized to access the cluster agent.
Otherwise, the dashboard ignores the `agent`, `namespace`, and `flux_resource_path` attributes.
- If you only want to set the `agent`, you do not have to set the `namespace`, and cannot set `flux_resource_path`. However, this configuration lists all namespaces in a cluster in the dashboard for Kubernetes.
---
#### `environment:deployment_tier`
Use the `deployment_tier` keyword to specify the tier of the deployment environment.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: One of the following:
- `production`
- `staging`
- `testing`
- `development`
- `other`
**Example of `environment:deployment_tier`**:
```yaml
deploy:
script: echo
environment:
name: customer-portal
deployment_tier: production
```
**Additional details**:
- Environments created from this job definition are assigned a [tier](../environments/_index.md#deployment-tier-of-environments) based on this value.
- Existing environments don't have their tier updated if this value is added later. Existing environments must have their tier updated via the [Environments API](../../api/environments.md#update-an-existing-environment).
**Related topics**:
- [Deployment tier of environments](../environments/_index.md#deployment-tier-of-environments).
---
#### Dynamic environments
Use CI/CD [variables](../variables/_index.md) to dynamically name environments.
For example:
```yaml
deploy as review app:
stage: deploy
script: make deploy
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com/
```
The `deploy as review app` job is marked as a deployment to dynamically
create the `review/$CI_COMMIT_REF_SLUG` environment. `$CI_COMMIT_REF_SLUG`
is a [CI/CD variable](../variables/_index.md) set by the runner. The
`$CI_ENVIRONMENT_SLUG` variable is based on the environment name, but suitable
for inclusion in URLs. If the `deploy as review app` job runs in a branch named
`pow`, this environment would be accessible with a URL like `https://review-pow.example.com/`.
The common use case is to create dynamic environments for branches and use them
as review apps. You can see an example that uses review apps at
<https://gitlab.com/gitlab-examples/review-apps-nginx/>.
---
### `extends`
Use `extends` to reuse configuration sections. It's an alternative to [YAML anchors](yaml_optimization.md#anchors)
and is a little more flexible and readable.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- The name of another job in the pipeline.
- A list (array) of names of other jobs in the pipeline.
**Example of `extends`**:
```yaml
.tests:
stage: test
image: ruby:3.0
rspec:
extends: .tests
script: rake rspec
rubocop:
extends: .tests
script: bundle exec rubocop
```
In this example, the `rspec` job uses the configuration from the `.tests` template job.
When creating the pipeline, GitLab:
- Performs a reverse deep merge based on the keys.
- Merges the `.tests` content with the `rspec` job.
- Doesn't merge the values of the keys.
The combined configuration is equivalent to these jobs:
```yaml
rspec:
stage: test
image: ruby:3.0
script: rake rspec
rubocop:
stage: test
image: ruby:3.0
script: bundle exec rubocop
```
**Additional details**:
- You can use multiple parents for `extends`.
- The `extends` keyword supports up to eleven levels of inheritance, but you should
avoid using more than three levels.
- In the previous example, `.tests` is a [hidden job](../jobs/_index.md#hide-a-job),
but you can extend configuration from regular jobs as well.
**Related topics**:
- [Reuse configuration sections by using `extends`](yaml_optimization.md#use-extends-to-reuse-configuration-sections).
- Use `extends` to reuse configuration from [included configuration files](yaml_optimization.md#use-extends-and-include-together).
---
### `hooks`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/356850) in GitLab 15.6 [with a flag](../../administration/feature_flags/_index.md) named `ci_hooks_pre_get_sources_script`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/381840) in GitLab 15.10. Feature flag `ci_hooks_pre_get_sources_script` removed.
{{< /history >}}
Use `hooks` to specify lists of commands to execute on the runner
at certain stages of job execution, like before retrieving the Git repository.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- A hash of hooks and their commands. Available hooks: `pre_get_sources_script`.
---
#### `hooks:pre_get_sources_script`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/356850) in GitLab 15.6 [with a flag](../../administration/feature_flags/_index.md) named `ci_hooks_pre_get_sources_script`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/381840) in GitLab 15.10. Feature flag `ci_hooks_pre_get_sources_script` removed.
{{< /history >}}
Use `hooks:pre_get_sources_script` to specify a list of commands to execute on the runner
before cloning the Git repository and any submodules.
You can use it for example to:
- Adjust the [Git configuration](../jobs/job_troubleshooting.md#get_sources-job-section-fails-because-of-an-http2-problem).
- Export [tracing variables](../../topics/git/troubleshooting_git.md#debug-git-with-traces).
**Supported values**: An array including:
- Single line commands.
- Long commands [split over multiple lines](script.md#split-long-commands).
- [YAML anchors](yaml_optimization.md#yaml-anchors-for-scripts).
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `hooks:pre_get_sources_script`**:
```yaml
job1:
hooks:
pre_get_sources_script:
- echo 'hello job1 pre_get_sources_script'
script: echo 'hello job1 script'
```
**Related topics**:
- [GitLab Runner configuration](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runners-section)
---
### `identity`
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
- Status: Beta
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/142054) in GitLab 16.9 [with a flag](../../administration/feature_flags/_index.md) named `google_cloud_support_feature_flag`. This feature is in [beta](../../policy/development_stages_support.md).
- [Enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/150472) in GitLab 17.1. Feature flag `google_cloud_support_feature_flag` removed.
{{< /history >}}
This feature is in [beta](../../policy/development_stages_support.md).
Use `identity` to authenticate with third party services using identity federation.
**Keyword type**: Job keyword. You can use it only as part of a job or in the [`default:` section](#default).
**Supported values**: An identifier. Supported providers:
- `google_cloud`: Google Cloud. Must be configured with the [Google Cloud IAM integration](../../integration/google_cloud_iam.md).
**Example of `identity`**:
```yaml
job_with_workload_identity:
identity: google_cloud
script:
- gcloud compute instances list
```
**Related topics**:
- [Workload Identity Federation](https://cloud.google.com/iam/docs/workload-identity-federation).
- [Google Cloud IAM integration](../../integration/google_cloud_iam.md).
---
### `id_tokens`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/356986) in GitLab 15.7.
{{< /history >}}
Use `id_tokens` to create [JSON web tokens (JWT)](https://www.rfc-editor.org/rfc/rfc7519) to authenticate with third party services. All
JWTs created this way support OIDC authentication. The required `aud` sub-keyword is used to configure the `aud` claim for the JWT.
**Supported values**:
- Token names with their `aud` claims. `aud` supports:
- A single string.
- An array of strings.
- [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `id_tokens`**:
```yaml
job_with_id_tokens:
id_tokens:
ID_TOKEN_1:
aud: https://vault.example.com
ID_TOKEN_2:
aud:
- https://gcp.com
- https://aws.com
SIGSTORE_ID_TOKEN:
aud: sigstore
script:
- command_to_authenticate_with_vault $ID_TOKEN_1
- command_to_authenticate_with_aws $ID_TOKEN_2
- command_to_authenticate_with_gcp $ID_TOKEN_2
```
**Related topics**:
- [ID token authentication](../secrets/id_token_authentication.md).
- [Connect to cloud services](../cloud_services/_index.md).
- [Keyless signing with Sigstore](signing_examples.md).
---
### `image`
Use `image` to specify a Docker image that the job runs in.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: The name of the image, including the registry path if needed, in one of these formats:
- `<image-name>` (Same as using `<image-name>` with the `latest` tag)
- `<image-name>:<tag>`
- `<image-name>@<digest>`
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `image`**:
```yaml
default:
image: ruby:3.0
rspec:
script: bundle exec rspec
rspec 2.7:
image: registry.example.com/my-group/my-project/ruby:2.7
script: bundle exec rspec
```
In this example, the `ruby:3.0` image is the default for all jobs in the pipeline.
The `rspec 2.7` job does not use the default, because it overrides the default with
a job-specific `image` section.
**Related topics**:
- [Run your CI/CD jobs in Docker containers](../docker/using_docker_images.md).
---
#### `image:name`
The name of the Docker image that the job runs in. Similar to [`image`](#image) used by itself.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: The name of the image, including the registry path if needed, in one of these formats:
- `<image-name>` (Same as using `<image-name>` with the `latest` tag)
- `<image-name>:<tag>`
- `<image-name>@<digest>`
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `image:name`**:
```yaml
test-job:
image:
name: "registry.example.com/my/image:latest"
script: echo "Hello world"
```
**Related topics**:
- [Run your CI/CD jobs in Docker containers](../docker/using_docker_images.md).
---
#### `image:entrypoint`
Command or script to execute as the container's entry point.
When the Docker container is created, the `entrypoint` is translated to the Docker `--entrypoint` option.
The syntax is similar to the [Dockerfile `ENTRYPOINT` directive](https://docs.docker.com/reference/dockerfile/#entrypoint),
where each shell token is a separate string in the array.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- A string.
**Example of `image:entrypoint`**:
```yaml
test-job:
image:
name: super/sql:experimental
entrypoint: [""]
script: echo "Hello world"
```
**Related topics**:
- [Override the entrypoint of an image](../docker/using_docker_images.md#override-the-entrypoint-of-an-image).
---
#### `image:docker`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/27919) in GitLab 16.7. Requires GitLab Runner 16.7 or later.
- `user` input option [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/137907) in GitLab 16.8.
{{< /history >}}
Use `image:docker` to pass options to runners using the [Docker executor](https://docs.gitlab.com/runner/executors/docker.html)
or the [Kubernetes executor](https://docs.gitlab.com/runner/executors/kubernetes/).
This keyword does not work with other executor types.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
A hash of options for the Docker executor, which can include:
- `platform`: Selects the architecture of the image to pull. When not specified,
the default is the same platform as the host runner.
- `user`: Specify the username or UID to use when running the container.
**Example of `image:docker`**:
```yaml
arm-sql-job:
script: echo "Run sql tests"
image:
name: super/sql:experimental
docker:
platform: arm64/v8
user: dave
```
**Additional details**:
- `image:docker:platform` maps to the [`docker pull --platform` option](https://docs.docker.com/reference/cli/docker/image/pull/#options).
- `image:docker:user` maps to the [`docker run --user` option](https://docs.docker.com/reference/cli/docker/container/run/#options).
---
#### `image:kubernetes`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/38451) in GitLab 18.0. Requires GitLab Runner 17.11 or later.
- `user` input option [introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/5469) in GitLab Runner 17.11.
- `user` input option [extended to support `uid:gid` format](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/5540) in GitLab 18.0.
{{< /history >}}
Use `image:kubernetes` to pass options to the GitLab Runner [Kubernetes executor](https://docs.gitlab.com/runner/executors/kubernetes/).
This keyword does not work with other executor types.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
A hash of options for the Kubernetes executor, which can include:
- `user`: Specify the username or UID to use when the container runs. You can also use it to set GID by using the `UID:GID` format.
**Example of `image:kubernetes` with only UID**:
```yaml
arm-sql-job:
script: echo "Run sql tests"
image:
name: super/sql:experimental
kubernetes:
user: "1001"
```
**Example of `image:kubernetes` with both UID and GID**:
```yaml
arm-sql-job:
script: echo "Run sql tests"
image:
name: super/sql:experimental
kubernetes:
user: "1001:1001"
```
---
#### `image:pull_policy`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/21619) in GitLab 15.1 [with a flag](../../administration/feature_flags/_index.md) named `ci_docker_image_pull_policy`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/363186) in GitLab 15.2.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/363186) in GitLab 15.4. [Feature flag `ci_docker_image_pull_policy`](https://gitlab.com/gitlab-org/gitlab/-/issues/363186) removed.
- Requires GitLab Runner 15.1 or later.
{{< /history >}}
The pull policy that the runner uses to fetch the Docker image.
**Keyword type**: Job keyword. You can use it only as part of a job or in the [`default` section](#default).
**Supported values**:
- A single pull policy, or multiple pull policies in an array.
Can be `always`, `if-not-present`, or `never`.
**Examples of `image:pull_policy`**:
```yaml
job1:
script: echo "A single pull policy."
image:
name: ruby:3.0
pull_policy: if-not-present
job2:
script: echo "Multiple pull policies."
image:
name: ruby:3.0
pull_policy: [always, if-not-present]
```
**Additional details**:
- If the runner does not support the defined pull policy, the job fails with an error similar to:
`ERROR: Job failed (system failure): the configured PullPolicies ([always]) are not allowed by AllowedPullPolicies ([never])`.
**Related topics**:
- [Run your CI/CD jobs in Docker containers](../docker/using_docker_images.md).
- [Configure how runners pull images](https://docs.gitlab.com/runner/executors/docker.html#configure-how-runners-pull-images).
- [Set multiple pull policies](https://docs.gitlab.com/runner/executors/docker.html#set-multiple-pull-policies).
---
### `inherit`
Use `inherit` to [control inheritance of default keywords and variables](../jobs/_index.md#control-the-inheritance-of-default-keywords-and-variables).
---
#### `inherit:default`
Use `inherit:default` to control the inheritance of [default keywords](#default).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `true` (default) or `false` to enable or disable the inheritance of all default keywords.
- A list of specific default keywords to inherit.
**Example of `inherit:default`**:
```yaml
default:
retry: 2
image: ruby:3.0
interruptible: true
job1:
script: echo "This job does not inherit any default keywords."
inherit:
default: false
job2:
script: echo "This job inherits only the two listed default keywords. It does not inherit 'interruptible'."
inherit:
default:
- retry
- image
```
**Additional details**:
- You can also list default keywords to inherit on one line: `default: [keyword1, keyword2]`
---
#### `inherit:variables`
Use `inherit:variables` to control the inheritance of [default variables](#default-variables) keywords.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `true` (default) or `false` to enable or disable the inheritance of all default variables.
- A list of specific variables to inherit.
**Example of `inherit:variables`**:
```yaml
variables:
VARIABLE1: "This is default variable 1"
VARIABLE2: "This is default variable 2"
VARIABLE3: "This is default variable 3"
job1:
script: echo "This job does not inherit any default variables."
inherit:
variables: false
job2:
script: echo "This job inherits only the two listed default variables. It does not inherit 'VARIABLE3'."
inherit:
variables:
- VARIABLE1
- VARIABLE2
```
**Additional details**:
- You can also list default variables to inherit on one line: `variables: [VARIABLE1, VARIABLE2]`
---
### `interruptible`
{{< history >}}
- Support for `trigger` jobs [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/138508) in GitLab 16.8.
{{< /history >}}
Use `interruptible` to configure the [auto-cancel redundant pipelines](../pipelines/settings.md#auto-cancel-redundant-pipelines)
feature to cancel a job before it completes if a new pipeline on the same ref starts for a newer commit. If the feature
is disabled, the keyword has no effect. The new pipeline must be for a commit with new changes. For example,
the **Auto-cancel redundant pipelines** feature has no effect
if you select **New pipeline** in the UI to run a pipeline for the same commit.
The behavior of the **Auto-cancel redundant pipelines** feature can be controlled by
the [`workflow:auto_cancel:on_new_commit`](#workflowauto_cancelon_new_commit) setting.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `true` or `false` (default).
**Example of `interruptible` with the default behavior**:
```yaml
workflow:
auto_cancel:
on_new_commit: conservative # the default behavior
stages:
- stage1
- stage2
- stage3
step-1:
stage: stage1
script:
- echo "Can be canceled."
interruptible: true
step-2:
stage: stage2
script:
- echo "Can not be canceled."
step-3:
stage: stage3
script:
- echo "Because step-2 can not be canceled, this step can never be canceled, even though it's set as interruptible."
interruptible: true
```
In this example, a new pipeline causes a running pipeline to be:
- Canceled, if only `step-1` is running or pending.
- Not canceled, after `step-2` starts.
**Example of `interruptible` with the `auto_cancel:on_new_commit:interruptible` setting**:
```yaml
workflow:
auto_cancel:
on_new_commit: interruptible
stages:
- stage1
- stage2
- stage3
step-1:
stage: stage1
script:
- echo "Can be canceled."
interruptible: true
step-2:
stage: stage2
script:
- echo "Can not be canceled."
step-3:
stage: stage3
script:
- echo "Can be canceled."
interruptible: true
```
In this example, a new pipeline causes a running pipeline to cancel `step-1` and `step-3` if they are running or pending.
**Additional details**:
- Only set `interruptible: true` if the job can be safely canceled after it has started,
like a build job. Deployment jobs usually shouldn't be canceled, to prevent partial deployments.
- When using the default behavior or `workflow:auto_cancel:on_new_commit: conservative`:
- A job that has not started yet is always considered `interruptible: true`, regardless of the job's configuration.
The `interruptible` configuration is only considered after the job starts.
- **Running** pipelines are only canceled if all running jobs are configured with `interruptible: true` or
no jobs configured with `interruptible: false` have started at any time.
After a job with `interruptible: false` starts, the entire pipeline is no longer
considered interruptible.
- If the pipeline triggered a downstream pipeline, but no job with `interruptible: false`
in the downstream pipeline has started yet, the downstream pipeline is also canceled.
- You can add an optional manual job with `interruptible: false` in the first stage of
a pipeline to allow users to manually prevent a pipeline from being automatically
canceled. After a user starts the job, the pipeline cannot be canceled by the
**Auto-cancel redundant pipelines** feature.
- When using `interruptible` with a [trigger job](#trigger):
- The triggered downstream pipeline is never affected by the trigger job's `interruptible` configuration.
- If [`workflow:auto_cancel`](#workflowauto_cancelon_new_commit) is set to `conservative`,
the trigger job's `interruptible` configuration has no effect.
- If [`workflow:auto_cancel`](#workflowauto_cancelon_new_commit) is set to `interruptible`,
a trigger job with `interruptible: true` can be automatically canceled.
---
### `needs`
Use `needs` to execute jobs out-of-order. Relationships between jobs
that use `needs` can be visualized as a [directed acyclic graph](needs.md).
You can ignore stage ordering and run some jobs without waiting for others to complete.
Jobs in multiple stages can run concurrently.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- An array of jobs (maximum of 50 jobs).
- An empty array (`[]`), to set the job to start as soon as the pipeline is created.
**Example of `needs`**:
```yaml
linux:build:
stage: build
script: echo "Building linux..."
mac:build:
stage: build
script: echo "Building mac..."
lint:
stage: test
needs: []
script: echo "Linting..."
linux:rspec:
stage: test
needs: ["linux:build"]
script: echo "Running rspec on linux..."
mac:rspec:
stage: test
needs: ["mac:build"]
script: echo "Running rspec on mac..."
production:
stage: deploy
script: echo "Running production..."
environment: production
```
This example creates four paths of execution:
- Linter: The `lint` job runs immediately without waiting for the `build` stage
to complete because it has no needs (`needs: []`).
- Linux path: The `linux:rspec` job runs as soon as the `linux:build`
job finishes, without waiting for `mac:build` to finish.
- macOS path: The `mac:rspec` jobs runs as soon as the `mac:build`
job finishes, without waiting for `linux:build` to finish.
- The `production` job runs as soon as all previous jobs finish:
`lint`, `linux:build`, `linux:rspec`, `mac:build`, `mac:rspec`.
**Additional details**:
- The maximum number of jobs that a single job can have in the `needs` array is limited:
- For GitLab.com, the limit is 50. For more information, see
[issue 350398](https://gitlab.com/gitlab-org/gitlab/-/issues/350398).
- For GitLab Self-Managed and GitLab Dedicated, the default limit is 50. This limit can be changed by [updating the CI/CD limits in the Admin area](../../administration/settings/continuous_integration.md#set-cicd-limits).
- If `needs` refers to a job that uses the [`parallel`](#parallel) keyword,
it depends on all jobs created in parallel, not just one job. It also downloads
artifacts from all the parallel jobs by default. If the artifacts have the same
name, they overwrite each other and only the last one downloaded is saved.
- To have `needs` refer to a subset of parallelized jobs (and not all of the parallelized jobs),
use the [`needs:parallel:matrix`](#needsparallelmatrix) keyword.
- You can refer to jobs in the same stage as the job you are configuring.
- If `needs` refers to a job that might not be added to
a pipeline because of `only`, `except`, or `rules`, the pipeline might fail to create. Use the [`needs:optional`](#needsoptional) keyword to resolve a failed pipeline creation.
- If a pipeline has jobs with `needs: []` and jobs in the [`.pre`](#stage-pre) stage, they will
all start as soon as the pipeline is created. Jobs with `needs: []` start immediately,
and jobs in the `.pre` stage also start immediately.
---
#### `needs:artifacts`
When a job uses `needs`, it no longer downloads all artifacts from previous stages
by default, because jobs with `needs` can start before earlier stages complete. With
`needs` you can only download artifacts from the jobs listed in the `needs` configuration.
Use `artifacts: true` (default) or `artifacts: false` to control when artifacts are
downloaded in jobs that use `needs`.
**Keyword type**: Job keyword. You can use it only as part of a job. Must be used with `needs:job`.
**Supported values**:
- `true` (default) or `false`.
**Example of `needs:artifacts`**:
```yaml
test-job1:
stage: test
needs:
- job: build_job1
artifacts: true
test-job2:
stage: test
needs:
- job: build_job2
artifacts: false
test-job3:
needs:
- job: build_job1
artifacts: true
- job: build_job2
- build_job3
```
In this example:
- The `test-job1` job downloads the `build_job1` artifacts
- The `test-job2` job does not download the `build_job2` artifacts.
- The `test-job3` job downloads the artifacts from all three `build_jobs`, because
`artifacts` is `true`, or defaults to `true`, for all three needed jobs.
**Additional details**:
- You should not combine `needs` with [`dependencies`](#dependencies) in the same job.
---
#### `needs:project`
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use `needs:project` to download artifacts from up to five jobs in other pipelines.
The artifacts are downloaded from the latest successful specified job for the specified ref.
To specify multiple jobs, add each as separate array items under the `needs` keyword.
If there is a pipeline running for the ref, a job with `needs:project`
does not wait for the pipeline to complete. Instead, the artifacts are downloaded
from the latest successful run of the specified job.
`needs:project` must be used with `job`, `ref`, and `artifacts`.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `needs:project`: A full project path, including namespace and group.
- `job`: The job to download artifacts from.
- `ref`: The ref to download artifacts from.
- `artifacts`: Must be `true` to download artifacts.
**Examples of `needs:project`**:
```yaml
build_job:
stage: build
script:
- ls -lhR
needs:
- project: namespace/group/project-name
job: build-1
ref: main
artifacts: true
- project: namespace/group/project-name-2
job: build-2
ref: main
artifacts: true
```
In this example, `build_job` downloads the artifacts from the latest successful `build-1` and `build-2` jobs
on the `main` branches in the `group/project-name` and `group/project-name-2` projects.
You can use [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file) in `needs:project`, for example:
```yaml
build_job:
stage: build
script:
- ls -lhR
needs:
- project: $CI_PROJECT_PATH
job: $DEPENDENCY_JOB_NAME
ref: $ARTIFACTS_DOWNLOAD_REF
artifacts: true
```
**Additional details**:
- To download artifacts from a different pipeline in the current project, set `project`
to be the same as the current project, but use a different ref than the current pipeline.
Concurrent pipelines running on the same ref could override the artifacts.
- The user running the pipeline must have at least the Reporter role for the group or project,
or the group/project must have public visibility.
- You can't use `needs:project` in the same job as [`trigger`](#trigger).
- When using `needs:project` to download artifacts from another pipeline, the job does not wait for
the needed job to complete. [Using `needs` to wait for jobs to complete](needs.md)
is limited to jobs in the same pipeline. Make sure that the needed job in the other
pipeline completes before the job that needs it tries to download the artifacts.
- You can't download artifacts from jobs that run in [`parallel`](#parallel).
- Support [CI/CD variables](../variables/_index.md) in `project`, `job`, and `ref`.
**Related topics**:
- To download artifacts between [parent-child pipelines](../pipelines/downstream_pipelines.md#parent-child-pipelines),
use [`needs:pipeline:job`](#needspipelinejob).
---
#### `needs:pipeline:job`
A [child pipeline](../pipelines/downstream_pipelines.md#parent-child-pipelines) can download artifacts from a
successfully finished job in its parent pipeline or another child pipeline in the same parent-child pipeline hierarchy.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `needs:pipeline`: A pipeline ID. Must be a pipeline present in the same parent-child pipeline hierarchy.
- `job`: The job to download artifacts from.
**Example of `needs:pipeline:job`**:
- Parent pipeline (`.gitlab-ci.yml`):
```yaml
stages:
- build
- test
create-artifact:
stage: build
script: echo "sample artifact" > artifact.txt
artifacts:
paths: [artifact.txt]
child-pipeline:
stage: test
trigger:
include: child.yml
strategy: mirror
variables:
PARENT_PIPELINE_ID: $CI_PIPELINE_ID
```
- Child pipeline (`child.yml`):
```yaml
use-artifact:
script: cat artifact.txt
needs:
- pipeline: $PARENT_PIPELINE_ID
job: create-artifact
```
In this example, the `create-artifact` job in the parent pipeline creates some artifacts.
The `child-pipeline` job triggers a child pipeline, and passes the `CI_PIPELINE_ID`
variable to the child pipeline as a new `PARENT_PIPELINE_ID` variable. The child pipeline
can use that variable in `needs:pipeline` to download artifacts from the parent pipeline.
Having the `create-artifact` and `child-pipeline` jobs in subsequent stages ensures that
the `use-artifact` job only executes when `create-artifact` has successfully finished.
**Additional details**:
- The `pipeline` attribute does not accept the current pipeline ID (`$CI_PIPELINE_ID`).
To download artifacts from a job in the current pipeline, use [`needs:artifacts`](#needsartifacts).
- You cannot use `needs:pipeline:job` in a [trigger job](#trigger), or to fetch artifacts
from a [multi-project pipeline](../pipelines/downstream_pipelines.md#multi-project-pipelines).
To fetch artifacts from a multi-project pipeline use [`needs:project`](#needsproject).
- The job listed in `needs:pipeline:job` must complete with a status of `success`
or the artifacts can't be fetched. [Issue 367229](https://gitlab.com/gitlab-org/gitlab/-/issues/367229)
proposes to allow fetching artifacts from any job with artifacts.
---
#### `needs:optional`
To need a job that sometimes does not exist in the pipeline, add `optional: true`
to the `needs` configuration. If not defined, `optional: false` is the default.
Jobs that use [`rules`](#rules), [`only`, or `except`](deprecated_keywords.md#only--except) and that are added with [`include`](#include)
might not always be added to a pipeline. GitLab checks the `needs` relationships before starting a pipeline:
- If the `needs` entry has `optional: true` and the needed job is present in the pipeline,
the job waits for it to complete before starting.
- If the needed job is not present, the job can start when all other needs requirements are met.
- If the `needs` section contains only optional jobs, and none are added to the pipeline,
the job starts immediately (the same as an empty `needs` entry: `needs: []`).
- If a needed job has `optional: false`, but it was not added to the pipeline, the
pipeline fails to start with an error similar to: `'job1' job needs 'job2' job, but it was not added to the pipeline`.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Example of `needs:optional`**:
```yaml
build-job:
stage: build
test-job1:
stage: test
test-job2:
stage: test
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
deploy-job:
stage: deploy
needs:
- job: test-job2
optional: true
- job: test-job1
environment: production
review-job:
stage: deploy
needs:
- job: test-job2
optional: true
environment: review
```
In this example:
- `build-job`, `test-job1`, and `test-job2` start in stage order.
- When the branch is the default branch, `test-job2` is added to the pipeline, so:
- `deploy-job` waits for both `test-job1` and `test-job2` to complete.
- `review-job` waits for `test-job2` to complete.
- When the branch is not the default branch, `test-job2` is not added to the pipeline, so:
- `deploy-job` waits for only `test-job1` to complete, and does not wait for the missing `test-job2`.
- `review-job` has no other needed jobs and starts immediately (at the same time as `build-job`),
like `needs: []`.
---
#### `needs:pipeline`
You can mirror the pipeline status from an upstream pipeline to a job by
using the `needs:pipeline` keyword. The latest pipeline status from the default branch is
replicated to the job.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A full project path, including namespace and group. If the
project is in the same group or namespace, you can omit them from the `project`
keyword. For example: `project: group/project-name` or `project: project-name`.
**Example of `needs:pipeline`**:
```yaml
upstream_status:
stage: test
needs:
pipeline: other/project
```
**Additional details**:
- If you add the `job` keyword to `needs:pipeline`, the job no longer mirrors the
pipeline status. The behavior changes to [`needs:pipeline:job`](#needspipelinejob).
---
#### `needs:parallel:matrix`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/254821) in GitLab 16.3.
{{< /history >}}
Jobs can use [`parallel:matrix`](#parallelmatrix) to run a job multiple times in parallel in a single pipeline,
but with different variable values for each instance of the job.
Use `needs:parallel:matrix` to execute jobs out-of-order depending on parallelized jobs.
**Keyword type**: Job keyword. You can use it only as part of a job. Must be used with `needs:job`.
**Supported values**: An array of hashes of variables:
- The variables and values must be selected from the variables and values defined in the `parallel:matrix` job.
**Example of `needs:parallel:matrix`**:
```yaml
linux:build:
stage: build
script: echo "Building linux..."
parallel:
matrix:
- PROVIDER: aws
STACK:
- monitoring
- app1
- app2
linux:rspec:
stage: test
needs:
- job: linux:build
parallel:
matrix:
- PROVIDER: aws
STACK: app1
script: echo "Running rspec on linux..."
```
The previous example generates the following jobs:
```plaintext
linux:build: [aws, monitoring]
linux:build: [aws, app1]
linux:build: [aws, app2]
linux:rspec
```
The `linux:rspec` job runs as soon as the `linux:build: [aws, app1]` job finishes.
**Related topics**:
- [Specify a parallelized job using needs with multiple parallelized jobs](../jobs/job_control.md#specify-a-parallelized-job-using-needs-with-multiple-parallelized-jobs).
**Additional details**:
- The order of the matrix variables in `needs:parallel:matrix` must match the order
of the matrix variables in the needed job. For example, reversing the order of
the variables in the `linux:rspec` job in the previous example would be invalid:
```yaml
linux:rspec:
stage: test
needs:
- job: linux:build
parallel:
matrix:
- STACK: app1 # The variable order does not match `linux:build` and is invalid.
PROVIDER: aws
script: echo "Running rspec on linux..."
```
---
### `pages`
Use `pages` to define a [GitLab Pages](../../user/project/pages/_index.md) job that
uploads static content to GitLab. The content is then published as a website.
You must:
- Define `pages: true` to publish a directory named `public`
- Alternatively, define [`pages.publish`](#pagespublish) if want to use a different content directory.
- Have a non-empty `index.html` file in the root of the content directory.
**Keyword type**: Job keyword or Job name (deprecated). You can use it only as part of a job.
**Supported Values**:
- A boolean. Uses the default configuration when set to `true`
- A hash of configuration options, see the following sections for details.
**Example of `pages`**:
```yaml
create-pages:
stage: deploy
script:
- mv my-html-content public
pages: true # specifies that this is a Pages job and publishes the default public directory
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
environment: production
```
This example renames the `my-html-content/` directory to `public/`.
This directory is exported as an artifact and published with GitLab Pages.
**Example using a configuration hash**:
```yaml
create-pages:
stage: deploy
script:
- echo "nothing to do here"
pages: # specifies that this is a Pages job and publishes the default public directory
publish: my-html-content
expire_in: "1 week"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
environment: production
```
This example does not move the directory, but uses the `publish` property directly.
It also configures the pages deployment to be unpublished after a week.
**Additional details**:
- Using `pages` as a job name [is deprecated](deprecated_keywords.md#publish-keyword-and-pages-job-name-for-gitlab-pages).
- To use `pages` as a job name without triggering a Pages deployment, set the `pages` property to false
---
#### `pages.publish`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/415821) in GitLab 16.1.
- [Changed](https://gitlab.com/gitlab-org/gitlab/-/issues/500000) to allow variables when passed to `publish` property in GitLab 17.9.
- [Moved](https://gitlab.com/gitlab-org/gitlab/-/issues/428018) the `publish` property under the `pages` keyword in GitLab 17.9.
- [Appended](https://gitlab.com/gitlab-org/gitlab/-/issues/428018) the `pages.publish` path automatically to `artifacts:paths` in GitLab 17.10.
{{< /history >}}
Use `pages.publish` to configure the content directory of a [`pages` job](#pages).
**Keyword type**: Job keyword. You can use it only as part of a `pages` job.
**Supported values**: A path to a directory containing the Pages content.
In [GitLab 17.10 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/428018),
if not specified, the default `public` directory is used and if specified,
this path is automatically appended to [`artifacts:paths`](#artifactspaths).
**Example of `pages.publish`**:
```yaml
create-pages:
stage: deploy
script:
- npx @11ty/eleventy --input=path/to/eleventy/root --output=dist
pages:
publish: dist # this path is automatically appended to artifacts:paths
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
environment: production
```
This example uses [Eleventy](https://www.11ty.dev) to generate a static website and
output the generated HTML files into a the `dist/` directory. This directory is exported
as an artifact and published with GitLab Pages.
It is also possible to use variables in the `pages.publish` field. For example:
```yaml
create-pages:
stage: deploy
script:
- mkdir -p $CUSTOM_FOLDER/$CUSTOM_PATH
- cp -r public $CUSTOM_FOLDER/$CUSTOM_SUBFOLDER
pages:
publish: $CUSTOM_FOLDER/$CUSTOM_SUBFOLDER # this path is automatically appended to artifacts:paths
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
variables:
CUSTOM_FOLDER: "custom_folder"
CUSTOM_SUBFOLDER: "custom_subfolder"
```
The publish path specified must be relative to the build root.
**Additional details**:
- The top-level `publish` keyword [is deprecated](deprecated_keywords.md#publish-keyword-and-pages-job-name-for-gitlab-pages) and must now be nested under the `pages` keyword
---
#### `pages.path_prefix`
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
- Status: Beta
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/129534) in GitLab 16.7 as an [experiment](../../policy/development_stages_support.md) [with a flag](../../administration/feature_flags/_index.md) named `pages_multiple_versions_setting`, disabled by default.
- [Enabled on GitLab.com, GitLab Self-Managed, and GitLab Dedicated](https://gitlab.com/gitlab-org/gitlab/-/issues/422145) in GitLab 17.4.
- [Changed](https://gitlab.com/gitlab-org/gitlab/-/issues/507423) to allow periods in GitLab 17.8.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/487161) in GitLab 17.9. Feature flag `pages_multiple_versions_setting` removed.
{{< /history >}}
Use `pages.path_prefix` to configure a path prefix for [parallel deployments](../../user/project/pages/_index.md#parallel-deployments) of GitLab Pages.
**Keyword type**: Job keyword. You can use it only as part of a `pages` job.
**Supported values**:
- A string
- [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file)
- A combination of both
The given value is converted to lowercase and shortened to 63 bytes.
Everything except alphanumeric characters or periods is replaced with a hyphen.
Leading and trailing hyphens or periods are not permitted.
**Example of `pages.path_prefix`**:
```yaml
create-pages:
stage: deploy
script:
- echo "Pages accessible through ${CI_PAGES_URL}/${CI_COMMIT_BRANCH}"
pages: # specifies that this is a Pages job and publishes the default public directory
path_prefix: "$CI_COMMIT_BRANCH"
```
In this example, a different pages deployment is created for each branch.
---
#### `pages.expire_in`
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/456478) in GitLab 17.4.
- Support for variables [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/492289) in GitLab 17.11.
{{< /history >}}
Use `expire_in` to specify how long a deployment should be available before
it expires. After the deployment is expired, it's deactivated by a cron
job running every 10 minutes.
By default, [parallel deployments](../../user/project/pages/_index.md#parallel-deployments) expire
automatically after 24 hours.
To disable this behavior, set the value to `never`.
**Keyword type**: Job keyword. You can use it only as part of a `pages` job.
**Supported values**: The expiry time. If no unit is provided, the time is in seconds.
Variables are also supported. Valid values include:
- `'42'`
- `42 seconds`
- `3 mins 4 sec`
- `2 hrs 20 min`
- `2h20min`
- `6 mos 1 day`
- `47 yrs 6 mos and 4d`
- `3 weeks and 2 days`
- `never`
- `$DURATION`
**Example of `pages.expire_in`**:
```yaml
create-pages:
stage: deploy
script:
- echo "Pages accessible through ${CI_PAGES_URL}"
pages: # specifies that this is a Pages job and publishes the default public directory
expire_in: 1 week
```
---
### `parallel`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/336576) in GitLab 15.9, the maximum value for `parallel` is increased from 50 to 200.
{{< /history >}}
Use `parallel` to run a job multiple times in parallel in a single pipeline.
Multiple runners must exist, or a single runner must be configured to run multiple jobs concurrently.
Parallel jobs are named sequentially from `job_name 1/N` to `job_name N/N`.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A numeric value from `1` to `200`.
**Example of `parallel`**:
```yaml
test:
script: rspec
parallel: 5
```
This example creates 5 jobs that run in parallel, named `test 1/5` to `test 5/5`.
**Additional details**:
- Every parallel job has a `CI_NODE_INDEX` and `CI_NODE_TOTAL`
[predefined CI/CD variable](../variables/_index.md#predefined-cicd-variables) set.
- A pipeline with jobs that use `parallel` might:
- Create more jobs running in parallel than available runners. Excess jobs are queued
and marked `pending` while waiting for an available runner.
- Create too many jobs, and the pipeline fails with a `job_activity_limit_exceeded` error.
The maximum number of jobs that can exist in active pipelines is [limited at the instance-level](../../administration/instance_limits.md#number-of-jobs-in-active-pipelines).
**Related topics**:
- [Parallelize large jobs](../jobs/job_control.md#parallelize-large-jobs).
---
#### `parallel:matrix`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/336576) in GitLab 15.9, the maximum number of permutations is increased from 50 to 200.
{{< /history >}}
Use `parallel:matrix` to run a job multiple times in parallel in a single pipeline,
but with different variable values for each instance of the job.
Multiple runners must exist, or a single runner must be configured to run multiple jobs concurrently.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: An array of hashes of variables:
- The variable names can use only numbers, letters, and underscores (`_`).
- The values must be either a string, or an array of strings.
- The number of permutations cannot exceed 200.
**Example of `parallel:matrix`**:
```yaml
deploystacks:
stage: deploy
script:
- bin/deploy
parallel:
matrix:
- PROVIDER: aws
STACK:
- monitoring
- app1
- app2
- PROVIDER: ovh
STACK: [monitoring, backup, app]
- PROVIDER: [gcp, vultr]
STACK: [data, processing]
environment: $PROVIDER/$STACK
```
The example generates 10 parallel `deploystacks` jobs, each with different values
for `PROVIDER` and `STACK`:
```plaintext
deploystacks: [aws, monitoring]
deploystacks: [aws, app1]
deploystacks: [aws, app2]
deploystacks: [ovh, monitoring]
deploystacks: [ovh, backup]
deploystacks: [ovh, app]
deploystacks: [gcp, data]
deploystacks: [gcp, processing]
deploystacks: [vultr, data]
deploystacks: [vultr, processing]
```
**Additional details**:
- `parallel:matrix` jobs add the variable values to the job names to differentiate
the jobs from each other, but [large values can cause names to exceed limits](https://gitlab.com/gitlab-org/gitlab/-/issues/362262):
- [Job names](../jobs/_index.md#job-names) must be 255 characters or fewer.
- When using [`needs`](#needs), job names must be 128 characters or fewer.
- You cannot create multiple matrix configurations with the same variable values but different variable names.
Job names are generated from the variable values, not the variable names, so matrix entries
with identical values generate identical job names that overwrite each other.
For example, this `test` configuration would try to create two series of identical jobs,
but the `OS2` versions overwrite the `OS` versions:
```yaml
test:
parallel:
matrix:
- OS: [ubuntu]
PROVIDER: [aws, gcp]
- OS2: [ubuntu]
PROVIDER: [aws, gcp]
```
- There's a [known issue](../debugging.md#config-should-be-an-array-of-hashes-error-message) when using [`!reference` tags](yaml_optimization.md#reference-tags) with `parallel:matrix`.
**Related topics**:
- [Run a one-dimensional matrix of parallel jobs](../jobs/job_control.md#run-a-one-dimensional-matrix-of-parallel-jobs).
- [Run a matrix of triggered parallel jobs](../jobs/job_control.md#run-a-matrix-of-parallel-trigger-jobs).
- [Select different runner tags for each parallel matrix job](../jobs/job_control.md#select-different-runner-tags-for-each-parallel-matrix-job).
---
### `release`
Use `release` to create a [release](../../user/project/releases/_index.md).
The release job must have access to the [`release-cli`](https://gitlab.com/gitlab-org/release-cli/-/tree/master/docs),
which must be in the `$PATH`.
If you use the [Docker executor](https://docs.gitlab.com/runner/executors/docker.html),
you can use this image from the GitLab container registry: `registry.gitlab.com/gitlab-org/release-cli:latest`
If you use the [Shell executor](https://docs.gitlab.com/runner/executors/shell.html) or similar,
[install `release-cli`](../../user/project/releases/release_cli.md) on the server where the runner is registered.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: The `release` subkeys:
- [`tag_name`](#releasetag_name)
- [`tag_message`](#releasetag_message) (optional)
- [`name`](#releasename) (optional)
- [`description`](#releasedescription)
- [`ref`](#releaseref) (optional)
- [`milestones`](#releasemilestones) (optional)
- [`released_at`](#releasereleased_at) (optional)
- [`assets:links`](#releaseassetslinks) (optional)
**Example of `release` keyword**:
```yaml
release_job:
stage: release
image: registry.gitlab.com/gitlab-org/release-cli:latest
rules:
- if: $CI_COMMIT_TAG # Run this job when a tag is created manually
script:
- echo "Running the release job."
release:
tag_name: $CI_COMMIT_TAG
name: 'Release $CI_COMMIT_TAG'
description: 'Release created using the release-cli.'
```
This example creates a release:
- When you push a Git tag.
- When you add a Git tag in the UI at **Code > Tags**.
**Additional details**:
- All release jobs, except [trigger](#trigger) jobs, must include the `script` keyword. A release
job can use the output from script commands. If you don't need the script, you can use a placeholder:
```yaml
script:
- echo "release job"
```
An [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/223856) exists to remove this requirement.
- The `release` section executes after the `script` keyword and before the `after_script`.
- A release is created only if the job's main script succeeds.
- If the release already exists, it is not updated and the job with the `release` keyword fails.
**Related topics**:
- [CI/CD example of the `release` keyword](../../user/project/releases/_index.md#creating-a-release-by-using-a-cicd-job).
- [Create multiple releases in a single pipeline](../../user/project/releases/_index.md#create-multiple-releases-in-a-single-pipeline).
- [Use a custom SSL CA certificate authority](../../user/project/releases/_index.md#use-a-custom-ssl-ca-certificate-authority).
---
#### `release:tag_name`
Required. The Git tag for the release.
If the tag does not exist in the project yet, it is created at the same time as the release.
New tags use the SHA associated with the pipeline.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A tag name.
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `release:tag_name`**:
To create a release when a new tag is added to the project:
- Use the `$CI_COMMIT_TAG` CI/CD variable as the `tag_name`.
- Use [`rules:if`](#rulesif) to configure the job to run only for new tags.
```yaml
job:
script: echo "Running the release job for the new tag."
release:
tag_name: $CI_COMMIT_TAG
description: 'Release description'
rules:
- if: $CI_COMMIT_TAG
```
To create a release and a new tag at the same time, your [`rules`](#rules)
should **not** configure the job to run only for new tags. A semantic versioning example:
```yaml
job:
script: echo "Running the release job and creating a new tag."
release:
tag_name: ${MAJOR}_${MINOR}_${REVISION}
description: 'Release description'
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
```
---
#### `release:tag_message`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/363024) in GitLab 15.3. Supported by `release-cli` v0.12.0 or later.
{{< /history >}}
If the tag does not exist, the newly created tag is annotated with the message specified by `tag_message`.
If omitted, a lightweight tag is created.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A text string.
**Example of `release:tag_message`**:
```yaml
release_job:
stage: release
release:
tag_name: $CI_COMMIT_TAG
description: 'Release description'
tag_message: 'Annotated tag message'
```
---
#### `release:name`
The release name. If omitted, it is populated with the value of `release: tag_name`.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A text string.
**Example of `release:name`**:
```yaml
release_job:
stage: release
release:
name: 'Release $CI_COMMIT_TAG'
```
---
#### `release:description`
The long description of the release.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A string with the long description.
- The path to a file that contains the description.
- The file location must be relative to the project directory (`$CI_PROJECT_DIR`).
- If the file is a symbolic link, it must be in the `$CI_PROJECT_DIR`.
- The `./path/to/file` and filename can't contain spaces.
**Example of `release:description`**:
```yaml
job:
release:
tag_name: ${MAJOR}_${MINOR}_${REVISION}
description: './path/to/CHANGELOG.md'
```
**Additional details**:
- The `description` is evaluated by the shell that runs `release-cli`.
You can use CI/CD variables to define the description, but some shells
[use different syntax](../variables/job_scripts.md)
to reference variables. Similarly, some shells might require special characters
to be escaped. For example, backticks (`` ` ``) might need to be escaped with a backslash (` \ `).
---
#### `release:ref`
The `ref` for the release, if the `release: tag_name` doesn't exist yet.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A commit SHA, another tag name, or a branch name.
---
#### `release:milestones`
The title of each milestone the release is associated with.
---
#### `release:released_at`
The date and time when the release is ready.
**Supported values**:
- A date enclosed in quotes and expressed in ISO 8601 format.
**Example of `release:released_at`**:
```yaml
released_at: '2021-03-15T08:00:00Z'
```
**Additional details**:
- If it is not defined, the current date and time is used.
---
#### `release:assets:links`
Use `release:assets:links` to include [asset links](../../user/project/releases/release_fields.md#release-assets) in the release.
Requires `release-cli` version v0.4.0 or later.
**Example of `release:assets:links`**:
```yaml
assets:
links:
- name: 'asset1'
url: 'https://example.com/assets/1'
- name: 'asset2'
url: 'https://example.com/assets/2'
filepath: '/pretty/url/1' # optional
link_type: 'other' # optional
```
---
### `resource_group`
Use `resource_group` to create a [resource group](../resource_groups/_index.md) that
ensures a job is mutually exclusive across different pipelines for the same project.
For example, if multiple jobs that belong to the same resource group are queued simultaneously,
only one of the jobs starts. The other jobs wait until the `resource_group` is free.
Resource groups behave similar to semaphores in other programming languages.
You can choose a [process mode](../resource_groups/_index.md#process-modes) to strategically control the job concurrency for your deployment preferences. The default process mode is `unordered`. To change the process mode of a resource group, use the [API](../../api/resource_groups.md#edit-an-existing-resource-group) to send a request to edit an existing resource group.
You can define multiple resource groups per environment. For example,
when deploying to physical devices, you might have multiple physical devices. Each device
can be deployed to, but only one deployment can occur per device at any given time.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- Only letters, digits, `-`, `_`, `/`, `$`, `{`, `}`, `.`, and spaces.
It can't start or end with `/`. CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `resource_group`**:
```yaml
deploy-to-production:
script: deploy
resource_group: production
```
In this example, two `deploy-to-production` jobs in two separate pipelines can never run at the same time. As a result,
you can ensure that concurrent deployments never happen to the production environment.
**Related topics**:
- [Pipeline-level concurrency control with cross-project/parent-child pipelines](../resource_groups/_index.md#pipeline-level-concurrency-control-with-cross-projectparent-child-pipelines).
---
### `retry`
Use `retry` to configure how many times a job is retried if it fails.
If not defined, defaults to `0` and jobs do not retry.
When a job fails, the job is processed up to two more times, until it succeeds or
reaches the maximum number of retries.
By default, all failure types cause the job to be retried. Use [`retry:when`](#retrywhen) or [`retry:exit_codes`](#retryexit_codes)
to select which failures to retry on.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- `0` (default), `1`, or `2`.
**Example of `retry`**:
```yaml
test:
script: rspec
retry: 2
test_advanced:
script:
- echo "Run a script that results in exit code 137."
- exit 137
retry:
max: 2
when: runner_system_failure
exit_codes: 137
```
`test_advanced` will be retried up to 2 times if the exit code is `137` or if it had
a runner system failure.
---
#### `retry:when`
Use `retry:when` with `retry:max` to retry jobs for only specific failure cases.
`retry:max` is the maximum number of retries, like [`retry`](#retry), and can be
`0`, `1`, or `2`.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- A single failure type, or an array of one or more failure types:
<!--
If you change any of the following values, make sure to update the `RETRY_WHEN_IN_DOCUMENTATION`
array in `spec/lib/gitlab/ci/config/entry/retry_spec.rb`.
The test there makes sure that all documented
values are valid as a configuration option and therefore should always
stay in sync with this documentation.
-->
- `always`: Retry on any failure (default).
- `unknown_failure`: Retry when the failure reason is unknown.
- `script_failure`: Retry when:
- The script failed.
- The runner failed to pull the Docker image. For `docker`, `docker+machine`, `kubernetes` [executors](https://docs.gitlab.com/runner/executors/).
- `api_failure`: Retry on API failure.
- `stuck_or_timeout_failure`: Retry when the job got stuck or timed out.
- `runner_system_failure`: Retry if there is a runner system failure (for example, job setup failed).
- `runner_unsupported`: Retry if the runner is unsupported.
- `stale_schedule`: Retry if a delayed job could not be executed.
- `job_execution_timeout`: Retry if the script exceeded the maximum execution time set for the job.
- `archived_failure`: Retry if the job is archived and can't be run.
- `unmet_prerequisites`: Retry if the job failed to complete prerequisite tasks.
- `scheduler_failure`: Retry if the scheduler failed to assign the job to a runner.
- `data_integrity_failure`: Retry if there is an unknown job problem.
**Example of `retry:when`** (single failure type):
```yaml
test:
script: rspec
retry:
max: 2
when: runner_system_failure
```
If there is a failure other than a runner system failure, the job is not retried.
**Example of `retry:when`** (array of failure types):
```yaml
test:
script: rspec
retry:
max: 2
when:
- runner_system_failure
- stuck_or_timeout_failure
```
---
#### `retry:exit_codes`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/430037) in GitLab 16.10 [with a flag](../../administration/feature_flags/_index.md) named `ci_retry_on_exit_codes`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/430037) in GitLab 16.11.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/452412) in GitLab 17.5. Feature flag `ci_retry_on_exit_codes` removed.
{{< /history >}}
Use `retry:exit_codes` with `retry:max` to retry jobs for only specific failure cases.
`retry:max` is the maximum number of retries, like [`retry`](#retry), and can be
`0`, `1`, or `2`.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- A single exit code.
- An array of exit codes.
**Example of `retry:exit_codes`**:
```yaml
test_job_1:
script:
- echo "Run a script that results in exit code 1. This job isn't retried."
- exit 1
retry:
max: 2
exit_codes: 137
test_job_2:
script:
- echo "Run a script that results in exit code 137. This job will be retried."
- exit 137
retry:
max: 1
exit_codes:
- 255
- 137
```
**Related topics**:
You can specify the number of [retry attempts for certain stages of job execution](../runners/configure_runners.md#job-stages-attempts)
using variables.
---
### `rules`
Use `rules` to include or exclude jobs in pipelines.
Rules are evaluated when the pipeline is created, and evaluated in order. When a match is found,
no more rules are checked and the job is either included or excluded from the pipeline
depending on the configuration. If no rules match, the job is not added to the pipeline.
`rules` accepts an array of rules. Each rules must have at least one of:
- `if`
- `changes`
- `exists`
- `when`
Rules can also optionally be combined with:
- `allow_failure`
- `needs`
- `variables`
- `interruptible`
You can combine multiple keywords together for [complex rules](../jobs/job_rules.md#complex-rules).
The job is added to the pipeline:
- If an `if`, `changes`, or `exists` rule matches, and is configured with `when: on_success` (default if not defined),
`when: delayed`, or `when: always`.
- If a rule is reached that is only `when: on_success`, `when: delayed`, or `when: always`.
The job is not added to the pipeline:
- If no rules match.
- If a rule matches and has `when: never`.
For additional examples, see [Specify when jobs run with `rules`](../jobs/job_rules.md).
---
#### `rules:if`
Use `rules:if` clauses to specify when to add a job to a pipeline:
- If an `if` statement is true, add the job to the pipeline.
- If an `if` statement is true, but it's combined with `when: never`, do not add the job to the pipeline.
- If an `if` statement is false, check the next `rules` item (if any more exist).
`if` clauses are evaluated:
- Based on the values of [CI/CD variables](../variables/_index.md) or [predefined CI/CD variables](../variables/predefined_variables.md),
with [some exceptions](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
- In order, following [`rules` execution flow](#rules).
**Keyword type**: Job-specific and pipeline-specific. You can use it as part of a job
to configure the job behavior, or with [`workflow`](#workflow) to configure the pipeline behavior.
**Supported values**:
- A [CI/CD variable expression](../jobs/job_rules.md#cicd-variable-expressions).
**Example of `rules:if`**:
```yaml
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/ && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME != $CI_DEFAULT_BRANCH
when: never
- if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/
when: manual
allow_failure: true
- if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME
```
**Additional details**:
- You cannot use [nested variables](../variables/where_variables_can_be_used.md#nested-variable-expansion)
with `if`. See [issue 327780](https://gitlab.com/gitlab-org/gitlab/-/issues/327780) for more details.
- If a rule matches and has no `when` defined, the rule uses the `when`
defined for the job, which defaults to `on_success` if not defined.
- You can [mix `when` at the job-level with `when` in rules](https://gitlab.com/gitlab-org/gitlab/-/issues/219437).
`when` configuration in `rules` takes precedence over `when` at the job-level.
- Unlike variables in [`script`](../variables/job_scripts.md)
sections, variables in rules expressions are always formatted as `$VARIABLE`.
- You can use `rules:if` with `include` to [conditionally include other configuration files](includes.md#use-rules-with-include).
- CI/CD variables on the right side of `=~` and `!~` expressions are [evaluated as regular expressions](../jobs/job_rules.md#store-a-regular-expression-in-a-variable).
**Related topics**:
- [Common `if` expressions for `rules`](../jobs/job_rules.md#common-if-clauses-with-predefined-variables).
- [Avoid duplicate pipelines](../jobs/job_rules.md#avoid-duplicate-pipelines).
- [Use `rules` to run merge request pipelines](../pipelines/merge_request_pipelines.md#add-jobs-to-merge-request-pipelines).
---
#### `rules:changes`
Use `rules:changes` to specify when to add a job to a pipeline by checking for changes
to specific files.
For new branch pipelines or when there is no Git `push` event, `rules: changes` always evaluates to true
and the job always runs. Pipelines like tag pipelines, scheduled pipelines,
and manual pipelines, all do **not** have a Git `push` event associated with them.
To cover these cases, use [`rules: changes: compare_to`](#ruleschangescompare_to) to specify
the branch to compare against the pipeline ref.
If you do not use `compare_to`, you should use `rules: changes` only with [branch pipelines](../pipelines/pipeline_types.md#branch-pipeline)
or [merge request pipelines](../pipelines/merge_request_pipelines.md), though
`rules: changes` still evaluates to true when creating a new branch. With:
- Merge request pipelines, `rules:changes` compares the changes with the target MR branch.
- Branch pipelines, `rules:changes` compares the changes with the previous commit on the branch.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
An array including any number of:
- Paths to files. The file paths can include [CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
- Wildcard paths for:
- Single directories, for example `path/to/directory/*`.
- A directory and all its subdirectories, for example `path/to/directory/**/*`.
- Wildcard [glob](https://en.wikipedia.org/wiki/Glob_(programming)) paths for all files
with the same extension or multiple extensions, for example `*.md` or `path/to/directory/*.{rb,py,sh}`.
- Wildcard paths to files in the root directory, or all directories, wrapped in double quotes.
For example `"*.json"` or `"**/*.json"`.
**Example of `rules:changes`**:
```yaml
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
- Dockerfile
when: manual
allow_failure: true
docker build alternative:
variables:
DOCKERFILES_DIR: 'path/to/dockerfiles'
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
- $DOCKERFILES_DIR/**/*
```
In this example:
- If the pipeline is a merge request pipeline, check `Dockerfile` and the files in
`$DOCKERFILES_DIR/**/*` for changes.
- If `Dockerfile` has changed, add the job to the pipeline as a manual job, and the pipeline
continues running even if the job is not triggered (`allow_failure: true`).
- If a file in `$DOCKERFILES_DIR/**/*` has changed, add the job to the pipeline.
- If no listed files have changed, do not add either job to any pipeline (same as `when: never`).
**Additional details**:
- Glob patterns are interpreted with Ruby's [`File.fnmatch`](https://docs.ruby-lang.org/en/master/File.html#method-c-fnmatch)
with the [flags](https://docs.ruby-lang.org/en/master/File/Constants.html#module-File::Constants-label-Filename+Globbing+Constants+-28File-3A-3AFNM_-2A-29)
`File::FNM_PATHNAME | File::FNM_DOTMATCH | File::FNM_EXTGLOB`.
- A maximum of 50 patterns or file paths can be defined per `rules:changes` section.
- `changes` resolves to `true` if any of the matching files are changed (an `OR` operation).
- For additional examples, see [Specify when jobs run with `rules`](../jobs/job_rules.md).
- You can use the `$` character for both variables and paths. For example, if the
`$VAR` variable exists, its value is used. If it does not exist, the `$` is interpreted
as being part of a path.
**Related topics**:
- [Jobs or pipelines can run unexpectedly when using `rules: changes`](../jobs/job_troubleshooting.md#jobs-or-pipelines-run-unexpectedly-when-using-changes).
---
##### `rules:changes:paths`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/90171) in GitLab 15.2.
{{< /history >}}
Use `rules:changes` to specify that a job only be added to a pipeline when specific
files are changed, and use `rules:changes:paths` to specify the files.
`rules:changes:paths` is the same as using [`rules:changes`](#ruleschanges) without
any subkeys. All additional details and related topics are the same.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- Same as `rules:changes`.
**Example of `rules:changes:paths`**:
```yaml
docker-build-1:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
- Dockerfile
docker-build-2:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
paths:
- Dockerfile
```
In this example, both jobs have the same behavior.
---
##### `rules:changes:compare_to`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/293645) in GitLab 15.3 [with a flag](../../administration/feature_flags/_index.md) named `ci_rules_changes_compare`. Enabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/366412) in GitLab 15.5. Feature flag `ci_rules_changes_compare` removed.
- Support for CI/CD variables [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/369916) in GitLab 17.2.
{{< /history >}}
Use `rules:changes:compare_to` to specify which ref to compare against for changes to the files
listed under [`rules:changes:paths`](#ruleschangespaths).
**Keyword type**: Job keyword. You can use it only as part of a job, and it must be combined with `rules:changes:paths`.
**Supported values**:
- A branch name, like `main`, `branch1`, or `refs/heads/branch1`.
- A tag name, like `tag1` or `refs/tags/tag1`.
- A commit SHA, like `2fg31ga14b`.
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `rules:changes:compare_to`**:
```yaml
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
paths:
- Dockerfile
compare_to: 'refs/heads/branch1'
```
In this example, the `docker build` job is only included when the `Dockerfile` has changed
relative to `refs/heads/branch1` and the pipeline source is a merge request event.
**Additional details**:
- Using `compare_to` with [merged results pipelines](../pipelines/merged_results_pipelines.md#troubleshooting) can cause unexpected results, because the comparison base is an internal commit that GitLab creates.
**Related topics**:
- You can use `rules:changes:compare_to` to [skip a job if the branch is empty](../jobs/job_rules.md#skip-jobs-if-the-branch-is-empty).
---
#### `rules:exists`
{{< history >}}
- CI/CD variable support [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/283881) in GitLab 15.6.
- Maximum number of checks against `exists` patterns or file paths [increased](https://gitlab.com/gitlab-org/gitlab/-/issues/227632) from 10,000 to 50,000 in GitLab 17.7.
- Support for directory paths [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/327485) in GitLab 18.2.
{{< /history >}}
Use `exists` to run a job when certain files or directories exist in the repository.
**Keyword type**: Job keyword. You can use it as part of a job or an [`include`](#include).
**Supported values**:
- An array of file or directory paths. Paths are relative to the project directory (`$CI_PROJECT_DIR`)
and can't directly link outside it. File paths can use glob patterns and
[CI/CD variables](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `rules:exists`**:
```yaml
job:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- exists:
- Dockerfile
job2:
variables:
DOCKERPATH: "**/Dockerfile"
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- exists:
- $DOCKERPATH
```
In this example:
- `job1` runs if a `Dockerfile` exists in the root directory of the repository.
- `job2` runs if a `Dockerfile` exists anywhere in the repository.
**Additional details**:
- Glob patterns are interpreted with Ruby's [`File.fnmatch`](https://docs.ruby-lang.org/en/master/File.html#method-c-fnmatch)
with the [flags](https://docs.ruby-lang.org/en/master/File/Constants.html#module-File::Constants-label-Filename+Globbing+Constants+-28File-3A-3AFNM_-2A-29)
`File::FNM_PATHNAME | File::FNM_DOTMATCH | File::FNM_EXTGLOB`.
- For performance reasons, GitLab performs a maximum of 50,000 checks against
`exists` patterns or file paths. After the 50,000th check, rules with patterned
globs always match. In other words, the `exists` rule always assumes a match in
projects with more than 50,000 files, or if there are fewer than 50,000 files but
the `exists` rules are checked more than 50,000 times.
- If there are multiple patterned globs, the limit is 50,000 divided by the number
of globs. For example, a rule with 5 patterned globs has file limit of 10,000.
- A maximum of 50 patterns or file paths can be defined per `rules:exists` section.
- `exists` resolves to `true` if any of the listed files are found (an `OR` operation).
- With job-level `rules:exists`, GitLab searches for the files in the project and
ref that runs the pipeline. When using [`include` with `rules:exists`](includes.md#include-with-rulesexists),
GitLab searches for the files or directories in the project and ref of the file that contains the `include`
section. The project containing the `include` section can be different than the project
running the pipeline when using:
- [Nested includes](includes.md#use-nested-includes).
- [Compliance pipelines](../../user/compliance/compliance_pipelines.md).
- `rules:exists` cannot search for the presence of [artifacts](../jobs/job_artifacts.md),
because `rules` evaluation happens before jobs run and artifacts are fetched.
- To test the existence of a directory, the path must end with a forward slash (/)
---
##### `rules:exists:paths`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/386040) in GitLab 16.11 [with a flag](../../administration/feature_flags/_index.md) named `ci_support_rules_exists_paths_and_project`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/386040) in GitLab 17.0. Feature flag `ci_support_rules_exists_paths_and_project` removed.
{{< /history >}}
`rules:exists:paths` is the same as using [`rules:exists`](#rulesexists) without
any subkeys. All additional details are the same.
**Keyword type**: Job keyword. You can use it as part of a job or an [`include`](#include).
**Supported values**:
- An array of file paths.
**Example of `rules:exists:paths`**:
```yaml
docker-build-1:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
exists:
- Dockerfile
docker-build-2:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
exists:
paths:
- Dockerfile
```
In this example, both jobs have the same behavior.
**Additional details**:
- In some cases you cannot use `/` or `./` in a CI/CD variable with `exists`.
See [issue 386595](https://gitlab.com/gitlab-org/gitlab/-/issues/386595) for more details.
---
##### `rules:exists:project`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/386040) in GitLab 16.11 [with a flag](../../administration/feature_flags/_index.md) named `ci_support_rules_exists_paths_and_project`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/386040) in GitLab 17.0. Feature flag `ci_support_rules_exists_paths_and_project` removed.
{{< /history >}}
Use `rules:exists:project` to specify the location in which to search for the files
listed under [`rules:exists:paths`](#rulesexistspaths). Must be used with `rules:exists:paths`.
**Keyword type**: Job keyword. You can use it as part of a job or an [`include`](#include), and it must be combined with `rules:exists:paths`.
**Supported values**:
- `exists:project`: A full project path, including namespace and group.
- `exists:ref`: Optional. The commit ref to use to search for the file. The ref can be a tag, branch name, or SHA. Defaults to the `HEAD` of the project when not specified.
**Example of `rules:exists:project`**:
```yaml
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- exists:
paths:
- Dockerfile
project: my-group/my-project
ref: v1.0.0
```
In this example, the `docker build` job is only included when the `Dockerfile` exists in
the project `my-group/my-project` on the commit tagged with `v1.0.0`.
---
#### `rules:when`
Use `rules:when` alone or as part of another rule to control conditions for adding
a job to a pipeline. `rules:when` is similar to [`when`](#when), but with slightly
different input options.
If a `rules:when` rule is not combined with `if`, `changes`, or `exists`, it always matches
if reached when evaluating a job's rules.
**Keyword type**: Job-specific. You can use it only as part of a job.
**Supported values**:
- `on_success` (default): Run the job only when no jobs in earlier stages fail.
- `on_failure`: Run the job only when at least one job in an earlier stage fails.
- `never`: Don't run the job regardless of the status of jobs in earlier stages.
- `always`: Run the job regardless of the status of jobs in earlier stages.
- `manual`: Add the job to the pipeline as a [manual job](../jobs/job_control.md#create-a-job-that-must-be-run-manually).
The default value for [`allow_failure`](#allow_failure) changes to `false`.
- `delayed`: Add the job to the pipeline as a [delayed job](../jobs/job_control.md#run-a-job-after-a-delay).
**Example of `rules:when`**:
```yaml
job1:
rules:
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
- if: $CI_COMMIT_REF_NAME =~ /feature/
when: delayed
- when: manual
script:
- echo
```
In this example, `job1` is added to pipelines:
- For the default branch, with `when: on_success` which is the default behavior
when `when` is not defined.
- For feature branches as a delayed job.
- In all other cases as a manual job.
**Additional details**:
- When evaluating the status of jobs for `on_success` and `on_failure`:
- Jobs with [`allow_failure: true`](#allow_failure) in earlier stages are considered successful, even if they failed.
- Skipped jobs in earlier stages, for example [manual jobs that have not been started](../jobs/job_control.md#create-a-job-that-must-be-run-manually),
are considered successful.
- When using `rules:when: manual` to [add a manual job](../jobs/job_control.md#create-a-job-that-must-be-run-manually):
- [`allow_failure`](#allow_failure) becomes `false` by default. This default is the opposite of
using [`when: manual`](#when) to add a manual job.
- To achieve the same behavior as `when: manual` defined outside of `rules`, set [`rules: allow_failure`](#rulesallow_failure) to `true`.
---
#### `rules:allow_failure`
Use [`allow_failure: true`](#allow_failure) in `rules` to allow a job to fail
without stopping the pipeline.
You can also use `allow_failure: true` with a manual job. The pipeline continues
running without waiting for the result of the manual job. `allow_failure: false`
combined with `when: manual` in rules causes the pipeline to wait for the manual
job to run before continuing.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `true` or `false`. Defaults to `false` if not defined.
**Example of `rules:allow_failure`**:
```yaml
job:
script: echo "Hello, Rules!"
rules:
- if: $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH
when: manual
allow_failure: true
```
If the rule matches, then the job is a manual job with `allow_failure: true`.
**Additional details**:
- The rule-level `rules:allow_failure` overrides the job-level [`allow_failure`](#allow_failure),
and only applies when the specific rule triggers the job.
---
#### `rules:needs`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/31581) in GitLab 16.0 [with a flag](../../administration/feature_flags/_index.md) named `introduce_rules_with_needs`. Disabled by default.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/408871) in GitLab 16.2. Feature flag `introduce_rules_with_needs` removed.
{{< /history >}}
Use `needs` in rules to update a job's [`needs`](#needs) for specific conditions. When a condition matches a rule, the job's `needs` configuration is completely replaced with the `needs` in the rule.
**Keyword type**: Job-specific. You can use it only as part of a job.
**Supported values**:
- An array of job names as strings.
- A hash with a job name, optionally with additional attributes.
- An empty array (`[]`), to set the job needs to none when the specific condition is met.
**Example of `rules:needs`**:
```yaml
build-dev:
stage: build
rules:
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
script: echo "Feature branch, so building dev version..."
build-prod:
stage: build
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
script: echo "Default branch, so building prod version..."
tests:
stage: test
rules:
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
needs: ['build-dev']
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
needs: ['build-prod']
script: echo "Running dev specs by default, or prod specs when default branch..."
```
In this example:
- If the pipeline runs on a branch that is not the default branch, and therefore the rule matches the first condition, the `specs` job needs the `build-dev` job.
- If the pipeline runs on the default branch, and therefore the rule matches the second condition, the `specs` job needs the `build-prod` job.
**Additional details**:
- `needs` in rules override any `needs` defined at the job-level. When overridden, the behavior is same as [job-level `needs`](#needs).
- `needs` in rules can accept [`artifacts`](#needsartifacts) and [`optional`](#needsoptional).
---
#### `rules:variables`
Use [`variables`](#variables) in `rules` to define variables for specific conditions.
**Keyword type**: Job-specific. You can use it only as part of a job.
**Supported values**:
- A hash of variables in the format `VARIABLE-NAME: value`.
**Example of `rules:variables`**:
```yaml
job:
variables:
DEPLOY_VARIABLE: "default-deploy"
rules:
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
variables: # Override DEPLOY_VARIABLE defined
DEPLOY_VARIABLE: "deploy-production" # at the job level.
- if: $CI_COMMIT_REF_NAME =~ /feature/
variables:
IS_A_FEATURE: "true" # Define a new variable.
script:
- echo "Run script with $DEPLOY_VARIABLE as an argument"
- echo "Run another script if $IS_A_FEATURE exists"
```
---
#### `rules:interruptible`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/194023) in GitLab 16.10.
{{< /history >}}
Use `interruptible` in rules to update a job's [`interruptible`](#interruptible) value for specific conditions.
**Keyword type**: Job-specific. You can use it only as part of a job.
**Supported values**:
- `true` or `false`.
**Example of `rules:interruptible`**:
```yaml
job:
script: echo "Hello, Rules!"
interruptible: true
rules:
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
interruptible: false # Override interruptible defined at the job level.
- when: on_success
```
**Additional details**:
- The rule-level `rules:interruptible` overrides the job-level [`interruptible`](#interruptible),
and only applies when the specific rule triggers the job.
---
### `run`
{{< details >}}
- Status: Experiment
{{< /details >}}
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/440487) in GitLab 17.3 [with a flag](../../administration/feature_flags/_index.md) named `pipeline_run_keyword`. Disabled by default. Requires GitLab Runner 17.1.
- Feature flag `pipeline_run_keyword` [removed](https://gitlab.com/gitlab-org/gitlab/-/issues/471925) in GitLab 17.5.
{{< /history >}}
{{< alert type="note" >}}
This feature is available for testing, but not ready for production use.
{{< /alert >}}
Use `run` to define a series of [steps](../steps/_index.md) to be executed in a job. Each step can be either a script or a predefined step.
You can also provide optional environment variables and inputs.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- An array of hashes, where each hash represents a step with the following possible keys:
- `name`: A string representing the name of the step.
- `script`: A string or array of strings containing shell commands to execute.
- `step`: A string identifying a predefined step to run.
- `env`: Optional. A hash of environment variables specific to this step.
- `inputs`: Optional. A hash of input parameters for predefined steps.
Each array entry must have a `name`, and one `script` or `step` (but not both).
**Example of `run`**:
``` yaml
job:
run:
- name: 'hello_steps'
script: 'echo "hello from step1"'
- name: 'bye_steps'
step: gitlab.com/gitlab-org/ci-cd/runner-tools/echo-step@main
inputs:
echo: 'bye steps!'
env:
var1: 'value 1'
```
In this example, the job has two steps:
- `hello_steps` runs the `echo` shell command.
- `bye_steps` uses a predefined step with an environment variable and an input parameter.
**Additional details**:
- A step can have either a `script` or a `step` key, but not both.
- A `run` configuration cannot be used together with existing [`script`](#script), [`after_script`](#after_script) or [`before_script`](#before_script) keywords.
- Multi-line scripts can be defined using [YAML block scalar syntax](script.md#split-long-commands).
---
### `script`
Use `script` to specify commands for the runner to execute.
All jobs except [trigger jobs](#trigger) require a `script` keyword.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: An array including:
- Single line commands.
- Long commands [split over multiple lines](script.md#split-long-commands).
- [YAML anchors](yaml_optimization.md#yaml-anchors-for-scripts).
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `script`**:
```yaml
job1:
script: "bundle exec rspec"
job2:
script:
- uname -a
- bundle exec rspec
```
**Additional details**:
- When you use [these special characters in `script`](script.md#use-special-characters-with-script), you must use single quotes (`'`) or double quotes (`"`).
**Related topics**:
- You can [ignore non-zero exit codes](script.md#ignore-non-zero-exit-codes).
- [Use color codes with `script`](script.md#add-color-codes-to-script-output)
to make job logs easier to review.
- [Create custom collapsible sections](../jobs/job_logs.md#custom-collapsible-sections)
to simplify job log output.
---
### `secrets`
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Use `secrets` to specify [CI/CD secrets](../secrets/_index.md) to:
- Retrieve from an external secrets provider.
- Make available in the job as [CI/CD variables](../variables/_index.md)
([`file` type](../variables/_index.md#use-file-type-cicd-variables) by default).
---
#### `secrets:vault`
{{< history >}}
- `generic` engine option [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/366492) in GitLab Runner 16.11.
{{< /history >}}
Use `secrets:vault` to specify secrets provided by a [HashiCorp Vault](https://www.vaultproject.io/).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `engine:name`: Name of the secrets engine. Can be one of `kv-v2` (default), `kv-v1`, or `generic`.
- `engine:path`: Path to the secrets engine.
- `path`: Path to the secret.
- `field`: Name of the field where the password is stored.
**Example of `secrets:vault`**:
To specify all details explicitly and use the [KV-V2](https://developer.hashicorp.com/vault/docs/secrets/kv/kv-v2) secrets engine:
```yaml
job:
secrets:
DATABASE_PASSWORD: # Store the path to the secret in this CI/CD variable
vault: # Translates to secret: `ops/data/production/db`, field: `password`
engine:
name: kv-v2
path: ops
path: production/db
field: password
```
You can shorten this syntax. With the short syntax, `engine:name` and `engine:path`
both default to `kv-v2`:
```yaml
job:
secrets:
DATABASE_PASSWORD: # Store the path to the secret in this CI/CD variable
vault: production/db/password # Translates to secret: `kv-v2/data/production/db`, field: `password`
```
To specify a custom secrets engine path in the short syntax, add a suffix that starts with `@`:
```yaml
job:
secrets:
DATABASE_PASSWORD: # Store the path to the secret in this CI/CD variable
vault: production/db/password@ops # Translates to secret: `ops/data/production/db`, field: `password`
```
---
#### `secrets:gcp_secret_manager`
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/11739) in GitLab 16.8 and GitLab Runner 16.8.
{{< /history >}}
Use `secrets:gcp_secret_manager` to specify secrets provided by [GCP Secret Manager](https://cloud.google.com/security/products/secret-manager).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `name`: Name of the secret.
- `version`: Version of the secret.
**Example of `secrets:gcp_secret_manager`**:
```yaml
job:
secrets:
DATABASE_PASSWORD:
gcp_secret_manager:
name: 'test'
version: 2
```
**Related topics**:
- [Use GCP Secret Manager secrets in GitLab CI/CD](../secrets/gcp_secret_manager.md).
---
#### `secrets:azure_key_vault`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/271271) in GitLab 16.3 and GitLab Runner 16.3.
{{< /history >}}
Use `secrets:azure_key_vault` to specify secrets provided by a [Azure Key Vault](https://azure.microsoft.com/en-us/products/key-vault/).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `name`: Name of the secret.
- `version`: Version of the secret.
**Example of `secrets:azure_key_vault`**:
```yaml
job:
secrets:
DATABASE_PASSWORD:
azure_key_vault:
name: 'test'
version: 'test'
```
**Related topics**:
- [Use Azure Key Vault secrets in GitLab CI/CD](../secrets/azure_key_vault.md).
---
#### `secrets:file`
Use `secrets:file` to configure the secret to be stored as either a
[`file` or `variable` type CI/CD variable](../variables/_index.md#use-file-type-cicd-variables)
By default, the secret is passed to the job as a `file` type CI/CD variable. The value
of the secret is stored in the file and the variable contains the path to the file.
If your software can't use `file` type CI/CD variables, set `file: false` to store
the secret value directly in the variable.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- `true` (default) or `false`.
**Example of `secrets:file`**:
```yaml
job:
secrets:
DATABASE_PASSWORD:
vault: production/db/password@ops
file: false
```
**Additional details**:
- The `file` keyword is a setting for the CI/CD variable and must be nested under
the CI/CD variable name, not in the `vault` section.
---
#### `secrets:token`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/356986) in GitLab 15.8, controlled by the **Limit JSON Web Token (JWT) access** setting.
- [Made always available and **Limit JSON Web Token (JWT) access** setting removed](https://gitlab.com/gitlab-org/gitlab/-/issues/366798) in GitLab 16.0.
{{< /history >}}
Use `secrets:token` to explicitly select a token to use when authenticating with the external secrets provider by referencing the token's CI/CD variable.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- The name of an ID token
**Example of `secrets:token`**:
```yaml
job:
id_tokens:
AWS_TOKEN:
aud: https://aws.example.com
VAULT_TOKEN:
aud: https://vault.example.com
secrets:
DB_PASSWORD:
vault: gitlab/production/db
token: $VAULT_TOKEN
```
**Additional details**:
- When the `token` keyword is not set and there is only one token defined, the defined token will automatically be used.
- If there is more than one token defined, you should specify which token to use by setting the `token` keyword.
If you do not specify which token to use, it is not possible to predict which token is used each time the job runs.
---
### `services`
Use `services` to specify any additional Docker images that your scripts require to run successfully. The [`services` image](../services/_index.md) is linked
to the image specified in the [`image`](#image) keyword.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: The name of the services image, including the registry path if needed, in one of these formats:
- `<image-name>` (Same as using `<image-name>` with the `latest` tag)
- `<image-name>:<tag>`
- `<image-name>@<digest>`
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file), but [not for `alias`](https://gitlab.com/gitlab-org/gitlab/-/issues/19561).
**Example of `services`**:
```yaml
default:
image:
name: ruby:2.6
entrypoint: ["/bin/bash"]
services:
- name: my-postgres:11.7
alias: db-postgres
entrypoint: ["/usr/local/bin/db-postgres"]
command: ["start"]
before_script:
- bundle install
test:
script:
- bundle exec rake spec
```
In this example, GitLab launches two containers for the job:
- A Ruby container that runs the `script` commands.
- A PostgreSQL container. The `script` commands in the Ruby container can connect to
the PostgreSQL database at the `db-postgres` hostname.
**Related topics**:
- [Available settings for `services`](../services/_index.md#available-settings-for-services).
- [Define `services` in the `.gitlab-ci.yml` file](../services/_index.md#define-services-in-the-gitlab-ciyml-file).
- [Run your CI/CD jobs in Docker containers](../docker/using_docker_images.md).
- [Use Docker to build Docker images](../docker/using_docker_build.md).
---
#### `services:docker`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/27919) in GitLab 16.7. Requires GitLab Runner 16.7 or later.
- `user` input option [introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/137907) in GitLab 16.8.
{{< /history >}}
Use `services:docker` to pass options to the Docker executor of a GitLab Runner.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
A hash of options for the Docker executor, which can include:
- `platform`: Selects the architecture of the image to pull. When not specified,
the default is the same platform as the host runner.
- `user`: Specify the username or UID to use when running the container.
**Example of `services:docker`**:
```yaml
arm-sql-job:
script: echo "Run sql tests in service container"
image: ruby:2.6
services:
- name: super/sql:experimental
docker:
platform: arm64/v8
user: dave
```
**Additional details**:
- `services:docker:platform` maps to the [`docker pull --platform` option](https://docs.docker.com/reference/cli/docker/image/pull/#options).
- `services:docker:user` maps to the [`docker run --user` option](https://docs.docker.com/reference/cli/docker/container/run/#options).
---
#### `services:kubernetes`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/38451) in GitLab 18.0. Requires GitLab Runner 17.11 or later.
- `user` input option [introduced](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/5469) in GitLab Runner 17.11.
- `user` input option [extended to support `uid:gid` format](https://gitlab.com/gitlab-org/gitlab-runner/-/merge_requests/5540) in GitLab 18.0.
{{< /history >}}
Use `services:kubernetes` to pass options to the GitLab Runner [Kubernetes executor](https://docs.gitlab.com/runner/executors/kubernetes/).
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
A hash of options for the Kubernetes executor, which can include:
- `user`: Specify the username or UID to use when the container runs. You can also use it to set GID by using the `UID:GID` format.
**Example of `services:kubernetes` with only UID**:
```yaml
arm-sql-job:
script: echo "Run sql tests"
image: ruby:2.6
services:
- name: super/sql:experimental
kubernetes:
user: "1001"
```
**Example of `services:kubernetes` with both UID and GID**:
```yaml
arm-sql-job:
script: echo "Run sql tests"
image: ruby:2.6
services:
- name: super/sql:experimental
kubernetes:
user: "1001:1001"
```
---
#### `services:pull_policy`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/21619) in GitLab 15.1 [with a flag](../../administration/feature_flags/_index.md) named `ci_docker_image_pull_policy`. Disabled by default.
- [Enabled on GitLab.com and GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/363186) in GitLab 15.2.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/363186) in GitLab 15.4. [Feature flag `ci_docker_image_pull_policy`](https://gitlab.com/gitlab-org/gitlab/-/issues/363186) removed.
{{< /history >}}
The pull policy that the runner uses to fetch the Docker image. Requires GitLab Runner 15.1 or later.
**Keyword type**: Job keyword. You can use it only as part of a job or in the [`default` section](#default).
**Supported values**:
- A single pull policy, or multiple pull policies in an array.
Can be `always`, `if-not-present`, or `never`.
**Examples of `services:pull_policy`**:
```yaml
job1:
script: echo "A single pull policy."
services:
- name: postgres:11.6
pull_policy: if-not-present
job2:
script: echo "Multiple pull policies."
services:
- name: postgres:11.6
pull_policy: [always, if-not-present]
```
**Additional details**:
- If the runner does not support the defined pull policy, the job fails with an error similar to:
`ERROR: Job failed (system failure): the configured PullPolicies ([always]) are not allowed by AllowedPullPolicies ([never])`.
**Related topics**:
- [Run your CI/CD jobs in Docker containers](../docker/using_docker_images.md).
- [Configure how runners pull images](https://docs.gitlab.com/runner/executors/docker.html#configure-how-runners-pull-images).
- [Set multiple pull policies](https://docs.gitlab.com/runner/executors/docker.html#set-multiple-pull-policies).
---
### `stage`
Use `stage` to define which [stage](#stages) a job runs in. Jobs in the same
`stage` can execute in parallel (see **Additional details**).
If `stage` is not defined, the job uses the `test` stage by default.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**: A string, which can be a:
- [Default stage](#stages).
- User-defined stages.
**Example of `stage`**:
```yaml
stages:
- build
- test
- deploy
job1:
stage: build
script:
- echo "This job compiles code."
job2:
stage: test
script:
- echo "This job tests the compiled code. It runs when the build stage completes."
job3:
script:
- echo "This job also runs in the test stage."
job4:
stage: deploy
script:
- echo "This job deploys the code. It runs when the test stage completes."
environment: production
```
**Additional details**:
- The stage name must be 255 characters or fewer.
- Jobs can run in parallel if they run on different runners.
- If you have only one runner, jobs can run in parallel if the runner's
[`concurrent` setting](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-global-section)
is greater than `1`.
---
#### `stage: .pre`
Use the `.pre` stage to make a job run at the start of a pipeline. By default, `.pre` is
the first stage in a pipeline. User-defined stages execute after `.pre`.
You do not have to define `.pre` in [`stages`](#stages).
If a pipeline contains only jobs in the `.pre` or `.post` stages, it does not run.
There must be at least one other job in a different stage.
**Keyword type**: You can only use it with a job's `stage` keyword.
**Example of `stage: .pre`**:
```yaml
stages:
- build
- test
job1:
stage: build
script:
- echo "This job runs in the build stage."
first-job:
stage: .pre
script:
- echo "This job runs in the .pre stage, before all other stages."
job2:
stage: test
script:
- echo "This job runs in the test stage."
```
**Additional details**:
- If a pipeline has jobs with [`needs: []`](#needs) and jobs in the `.pre` stage, they will
all start as soon as the pipeline is created. Jobs with `needs: []` start immediately,
ignoring any stage configuration.
- A [pipeline execution policy](../../user/application_security/policies/pipeline_execution_policies.md) can define a `.pipeline-policy-pre` stage which runs before `.pre`.
---
#### `stage: .post`
Use the `.post` stage to make a job run at the end of a pipeline. By default, `.post`
is the last stage in a pipeline. User-defined stages execute before `.post`.
You do not have to define `.post` in [`stages`](#stages).
If a pipeline contains only jobs in the `.pre` or `.post` stages, it does not run.
There must be at least one other job in a different stage.
**Keyword type**: You can only use it with a job's `stage` keyword.
**Example of `stage: .post`**:
```yaml
stages:
- build
- test
job1:
stage: build
script:
- echo "This job runs in the build stage."
last-job:
stage: .post
script:
- echo "This job runs in the .post stage, after all other stages."
job2:
stage: test
script:
- echo "This job runs in the test stage."
```
**Additional details**:
- A [pipeline execution policy](../../user/application_security/policies/pipeline_execution_policies.md) can define a `.pipeline-policy-post` stage which runs after `.post`.
---
### `tags`
Use `tags` to select a specific runner from the list of all runners that are
available for the project.
When you register a runner, you can specify the runner's tags, for
example `ruby`, `postgres`, or `development`. To pick up and run a job, a runner must
be assigned every tag listed in the job.
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**:
- An array of tag names, which are case-sensitive.
- CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of `tags`**:
```yaml
job:
tags:
- ruby
- postgres
```
In this example, only runners with both the `ruby` and `postgres` tags can run the job.
**Additional details**:
- The number of tags must be less than `50`.
**Related topics**:
- [Use tags to control which jobs a runner can run](../runners/configure_runners.md#control-jobs-that-a-runner-can-run)
- [Select different runner tags for each parallel matrix job](../jobs/job_control.md#select-different-runner-tags-for-each-parallel-matrix-job)
- Runner tags for hosted runners:
- [Hosted runners on Linux](../runners/hosted_runners/linux.md)
- [GPU-enabled hosted runners](../runners/hosted_runners/gpu_enabled.md)
- [Hosted runners on macOS](../runners/hosted_runners/macos.md)
- [Hosted runners on Windows](../runners/hosted_runners/windows.md)
---
### `timeout`
Use `timeout` to configure a timeout for a specific job. If the job runs for longer
than the timeout, the job fails.
The job-level timeout can be longer than the [project-level timeout](../pipelines/settings.md#set-a-limit-for-how-long-jobs-can-run),
but can't be longer than the [runner's timeout](../runners/configure_runners.md#set-the-maximum-job-timeout).
**Keyword type**: Job keyword. You can use it only as part of a job or in the
[`default` section](#default).
**Supported values**: A period of time written in natural language. For example, these are all equivalent:
- `3600 seconds`
- `60 minutes`
- `one hour`
**Example of `timeout`**:
```yaml
build:
script: build.sh
timeout: 3 hours 30 minutes
test:
script: rspec
timeout: 3h 30m
```
---
### `trigger`
{{< history >}}
- Support for `environment` [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/369061) in GitLab 16.4.
{{< /history >}}
Use `trigger` to declare that a job is a "trigger job" which starts a
[downstream pipeline](../pipelines/downstream_pipelines.md) that is either:
- [A multi-project pipeline](../pipelines/downstream_pipelines.md#multi-project-pipelines).
- [A child pipeline](../pipelines/downstream_pipelines.md#parent-child-pipelines).
Trigger jobs can use only a limited set of GitLab CI/CD configuration keywords.
The keywords available for use in trigger jobs are:
- [`allow_failure`](#allow_failure).
- [`extends`](#extends).
- [`needs`](#needs), but not [`needs:project`](#needsproject).
- [`only` and `except`](deprecated_keywords.md#only--except).
- [`parallel`](#parallel).
- [`rules`](#rules).
- [`stage`](#stage).
- [`trigger`](#trigger).
- [`variables`](#variables).
- [`when`](#when) (only with a value of `on_success`, `on_failure`, or `always`).
- [`resource_group`](#resource_group).
- [`environment`](#environment).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- For multi-project pipelines, the path to the downstream project. CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file)
in GitLab 15.3 and later, but not [job-only variables](../variables/predefined_variables.md#variable-availability).
Alternatively, use [`trigger:project`](#triggerproject).
- For child pipelines, use [`trigger:include`](#triggerinclude).
**Example of `trigger`**:
```yaml
trigger-multi-project-pipeline:
trigger: my-group/my-project
```
**Additional details**:
- You can use [`when:manual`](#when) in the same job as `trigger`, but you cannot
use the API to start `when:manual` trigger jobs. See [issue 284086](https://gitlab.com/gitlab-org/gitlab/-/issues/284086)
for more details.
- You cannot [manually specify CI/CD variables](../jobs/job_control.md#specify-variables-when-running-manual-jobs)
before running a manual trigger job.
- [CI/CD variables](#variables) defined in a top-level `variables` section (globally) or in the trigger job are forwarded
to the downstream pipeline as [trigger variables](../pipelines/downstream_pipelines.md#pass-cicd-variables-to-a-downstream-pipeline).
- [Pipeline variables](../variables/_index.md#cicd-variable-precedence) are not passed
to downstream pipelines by default. Use [trigger:forward](#triggerforward) to forward
these variables to downstream pipelines.
- [Job-only variables](../variables/predefined_variables.md#variable-availability)
are not available in trigger jobs.
- Environment variables [defined in the runner's `config.toml`](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runners-section) are not available to trigger jobs and are not passed to downstream pipelines.
- You cannot use [`needs:pipeline:job`](#needspipelinejob) in a trigger job.
**Related topics**:
- [Multi-project pipeline configuration examples](../pipelines/downstream_pipelines.md#trigger-a-downstream-pipeline-from-a-job-in-the-gitlab-ciyml-file).
- To run a pipeline for a specific branch, tag, or commit, you can use a [trigger token](../triggers/_index.md)
to authenticate with the [pipeline triggers API](../../api/pipeline_triggers.md).
The trigger token is different than the `trigger` keyword.
---
#### `trigger:inputs`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/519963) in GitLab 17.11.
{{</history >}}
Use `trigger:inputs` to set the [inputs](../inputs/_index.md) for a multi-project pipeline
when the downstream pipeline configuration uses [`spec:inputs`](#specinputs).
**Example of `trigger:inputs`**:
```yaml
trigger:
- project: 'my-group/my-project'
inputs:
website: "My website"
```
---
#### `trigger:include`
Use `trigger:include` to declare that a job is a "trigger job" which starts a
[child pipeline](../pipelines/downstream_pipelines.md#parent-child-pipelines).
Additionally, use:
- `trigger:include:artifact` to trigger a [dynamic child pipeline](../pipelines/downstream_pipelines.md#dynamic-child-pipelines).
- `trigger:include:inputs` to set the [inputs](../inputs/_index.md) when the downstream pipeline configuration
uses [`spec:inputs`](#specinputs).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- The path to the child pipeline's configuration file.
**Example of `trigger:include`**:
```yaml
trigger-child-pipeline:
trigger:
include: path/to/child-pipeline.gitlab-ci.yml
```
**Related topics**:
- [Child pipeline configuration examples](../pipelines/downstream_pipelines.md#trigger-a-downstream-pipeline-from-a-job-in-the-gitlab-ciyml-file).
---
#### `trigger:include:inputs`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/519963) in GitLab 17.11.
{{</history >}}
Use `trigger:include:inputs` to set the [inputs](../inputs/_index.md) for a child pipeline
when the downstream pipeline configuration uses [`spec:inputs`](#specinputs).
**Example of `trigger:inputs`**:
```yaml
trigger-job:
trigger:
include:
- local: path/to/child-pipeline.yml
inputs:
website: "My website"
```
---
#### `trigger:project`
Use `trigger:project` to declare that a job is a "trigger job" which starts a
[multi-project pipeline](../pipelines/downstream_pipelines.md#multi-project-pipelines).
By default, the multi-project pipeline triggers for the default branch. Use `trigger:branch`
to specify a different branch.
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- The path to the downstream project. CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file)
in GitLab 15.3 and later, but not [job-only variables](../variables/predefined_variables.md#variable-availability).
**Example of `trigger:project`**:
```yaml
trigger-multi-project-pipeline:
trigger:
project: my-group/my-project
```
**Example of `trigger:project` for a different branch**:
```yaml
trigger-multi-project-pipeline:
trigger:
project: my-group/my-project
branch: development
```
**Related topics**:
- [Multi-project pipeline configuration examples](../pipelines/downstream_pipelines.md#trigger-a-downstream-pipeline-from-a-job-in-the-gitlab-ciyml-file).
- To run a pipeline for a specific branch, tag, or commit, you can also use a [trigger token](../triggers/_index.md)
to authenticate with the [pipeline triggers API](../../api/pipeline_triggers.md).
The trigger token is different than the `trigger` keyword.
---
#### `trigger:strategy`
{{< history >}}
- `strategy:mirror` option [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/431882) in GitLab 18.2.
{{< /history >}}
Use `trigger:strategy` to force the `trigger` job to wait for the downstream pipeline to complete
before it is marked as **success**.
This behavior is different than the default, which is for the `trigger` job to be marked as
**success** as soon as the downstream pipeline is created.
This setting makes your pipeline execution linear rather than parallel.
**Supported values**:
- `mirror`: Mirrors the status of the downstream pipeline exactly.
- `depend`: The trigger job status shows **failed**, **success** or **running**,
depending on the downstream pipeline status. See additional details.
**Example of `trigger:strategy`**:
```yaml
trigger_job:
trigger:
include: path/to/child-pipeline.yml
strategy: mirror
```
In this example, jobs from subsequent stages wait for the triggered pipeline to
successfully complete before starting.
**Additional details**:
- [Optional manual jobs](../jobs/job_control.md#types-of-manual-jobs) in the downstream pipeline
do not affect the status of the downstream pipeline or the upstream trigger job.
The downstream pipeline can complete successfully without running any optional manual jobs.
- By default, jobs in later stages do not start until the trigger job completes.
- [Blocking manual jobs](../jobs/job_control.md#types-of-manual-jobs) in the downstream pipeline
must run before the trigger job is marked as successful or failed.
- When using `stratgy:depend`:
- The trigger job shows **running** ({{< icon name="status_running" >}}) if the downstream pipeline status is
**waiting for manual action** ({{< icon name="status_manual" >}}) due to manual jobs.
- If the downstream pipeline has a failed job, but the job uses [`allow_failure: true`](#allow_failure),
the downstream pipeline is considered successful and the trigger job shows **success**.
---
#### `trigger:forward`
{{< history >}}
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/355572) in GitLab 15.1. [Feature flag `ci_trigger_forward_variables`](https://gitlab.com/gitlab-org/gitlab/-/issues/355572) removed.
{{< /history >}}
Use `trigger:forward` to specify what to forward to the downstream pipeline. You can control
what is forwarded to both [parent-child pipelines](../pipelines/downstream_pipelines.md#parent-child-pipelines)
and [multi-project pipelines](../pipelines/downstream_pipelines.md#multi-project-pipelines).
Forwarded variables do not get forwarded again in nested downstream pipelines by default,
unless the nested downstream trigger job also uses `trigger:forward`.
**Supported values**:
- `yaml_variables`: `true` (default), or `false`. When `true`, variables defined
in the trigger job are passed to downstream pipelines.
- `pipeline_variables`: `true` or `false` (default). When `true`, [pipeline variables](../variables/_index.md#cicd-variable-precedence)
are passed to the downstream pipeline.
**Example of `trigger:forward`**:
[Run this pipeline manually](../pipelines/_index.md#run-a-pipeline-manually), with
the CI/CD variable `MYVAR = my value`:
```yaml
variables: # default variables for each job
VAR: value
---
# Default behavior:
---
# - VAR is passed to the child
---
# - MYVAR is not passed to the child
child1:
trigger:
include: .child-pipeline.yml
---
# Forward pipeline variables:
---
# - VAR is passed to the child
---
# - MYVAR is passed to the child
child2:
trigger:
include: .child-pipeline.yml
forward:
pipeline_variables: true
---
# Do not forward YAML variables:
---
# - VAR is not passed to the child
---
# - MYVAR is not passed to the child
child3:
trigger:
include: .child-pipeline.yml
forward:
yaml_variables: false
```
**Additional details**:
- CI/CD variables forwarded to downstream pipelines with `trigger:forward` are [pipeline variables](../variables/_index.md#cicd-variable-precedence),
which have high precedence. If a variable with the same name is defined in the downstream pipeline,
that variable is usually overwritten by the forwarded variable.
---
### `when`
Use `when` to configure the conditions for when jobs run. If not defined in a job,
the default value is `when: on_success`.
**Keyword type**: Job keyword. You can use it as part of a job. `when: always` and `when: never` can also be used in [`workflow:rules`](#workflow).
**Supported values**:
- `on_success` (default): Run the job only when no jobs in earlier stages fail.
- `on_failure`: Run the job only when at least one job in an earlier stage fails.
- `never`: Don't run the job regardless of the status of jobs in earlier stages.
Can only be used in a [`rules`](#ruleswhen) section or [`workflow: rules`](#workflowrules).
- `always`: Run the job regardless of the status of jobs in earlier stages.
- `manual`: Add the job to the pipeline as a [manual job](../jobs/job_control.md#create-a-job-that-must-be-run-manually).
- `delayed`: Add the job to the pipeline as a [delayed job](../jobs/job_control.md#run-a-job-after-a-delay).
**Example of `when`**:
```yaml
stages:
- build
- cleanup_build
- test
- deploy
- cleanup
build_job:
stage: build
script:
- make build
cleanup_build_job:
stage: cleanup_build
script:
- cleanup build when failed
when: on_failure
test_job:
stage: test
script:
- make test
deploy_job:
stage: deploy
script:
- make deploy
when: manual
environment: production
cleanup_job:
stage: cleanup
script:
- cleanup after jobs
when: always
```
In this example, the script:
1. Executes `cleanup_build_job` only when `build_job` fails.
1. Always executes `cleanup_job` as the last step in pipeline regardless of
success or failure.
1. Executes `deploy_job` when you run it manually in the GitLab UI.
**Additional details**:
- When evaluating the status of jobs for `on_success` and `on_failure`:
- Jobs with [`allow_failure: true`](#allow_failure) in earlier stages are considered successful, even if they failed.
- Skipped jobs in earlier stages, for example [manual jobs that have not been started](../jobs/job_control.md#create-a-job-that-must-be-run-manually),
are considered successful.
- The default value for [`allow_failure`](#allow_failure) is `true` with `when: manual`. The default value
changes to `false` with [`rules:when: manual`](#ruleswhen).
**Related topics**:
- `when` can be used with [`rules`](#rules) for more dynamic job control.
- `when` can be used with [`workflow`](#workflow) to control when a pipeline can start.
---
#### `manual_confirmation`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/18906) in GitLab 17.1.
{{< /history >}}
Use `manual_confirmation` with [`when: manual`](#when) to define a custom confirmation message for manual jobs.
If no manual job is defined with `when: manual`, this keyword has no effect.
Manual confirmation works with all manual jobs, including environment stop jobs that use
[`environment:action: stop`](#environmentaction).
**Keyword type**: Job keyword. You can use it only as part of a job.
**Supported values**:
- A string with the confirmation message.
**Example of `manual_confirmation`**:
```yaml
delete_job:
stage: post-deployment
script:
- make delete
when: manual
manual_confirmation: 'Are you sure you want to delete this environment?'
stop_production:
stage: cleanup
script:
- echo "Stopping production environment"
environment:
name: production
action: stop
when: manual
manual_confirmation: "Are you sure you want to stop the production environment?"
```
---
## `variables`
Use `variables` to define [CI/CD variables](../variables/_index.md#define-a-cicd-variable-in-the-gitlab-ciyml-file).
Variables can be [defined in a CI/CD job](#job-variables), or as a top-level (global) keyword to define
[default CI/CD variables](#default-variables) for all jobs.
**Additional details**:
- All YAML-defined variables are also set to any linked [Docker service containers](../services/_index.md).
- YAML-defined variables are meant for non-sensitive project configuration. Store sensitive information
in [protected variables](../variables/_index.md#protect-a-cicd-variable) or [CI/CD secrets](../secrets/_index.md).
- [Manual pipeline variables](../variables/_index.md#use-pipeline-variables)
and [scheduled pipeline variables](../pipelines/schedules.md#add-a-pipeline-schedule)
are not passed to downstream pipelines by default. Use [trigger:forward](#triggerforward)
to forward these variables to downstream pipelines.
**Related topics**:
- [Predefined variables](../variables/predefined_variables.md) are variables the runner
automatically creates and makes available in the job.
- You can [configure runner behavior with variables](../runners/configure_runners.md#configure-runner-behavior-with-variables).
---
### Job `variables`
You can use job variables in commands in the job's `script`, `before_script`, or `after_script` sections,
and also with some [job keywords](#job-keywords). Check the **Supported values** section of each job keyword
to see if it supports variables.
You cannot use job variables as values for [global keywords](#global-keywords) like
[`include`](includes.md#use-variables-with-include).
**Supported values**: Variable name and value pairs:
- The name can use only numbers, letters, and underscores (`_`). In some shells,
the first character must be a letter.
- The value must be a string.
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Example of job `variables`**:
```yaml
review_job:
variables:
DEPLOY_SITE: "https://dev.example.com/"
REVIEW_PATH: "/review"
script:
- deploy-review-script --url $DEPLOY_SITE --path $REVIEW_PATH
```
In this example:
- `review_job` has `DEPLOY_SITE` and `REVIEW_PATH` job variables defined.
Both job variables can be used in the `script` section.
---
### Default `variables`
Variables defined in a top-level `variables` section act as default variables
for all jobs.
Each default variable is made available to every job in the pipeline, except when
the job already has a variable defined with the same name. The variable defined in the job
[takes precedence](../variables/_index.md#cicd-variable-precedence), so the value of
the default variable with the same name cannot be used in the job.
Like job variables, you cannot use default variables as values for other global keywords,
like [`include`](includes.md#use-variables-with-include).
**Supported values**: Variable name and value pairs:
- The name can use only numbers, letters, and underscores (`_`). In some shells,
the first character must be a letter.
- The value must be a string.
CI/CD variables [are supported](../variables/where_variables_can_be_used.md#gitlab-ciyml-file).
**Examples of `variables`**:
```yaml
variables:
DEPLOY_SITE: "https://example.com/"
deploy_job:
stage: deploy
script:
- deploy-script --url $DEPLOY_SITE --path "/"
environment: production
deploy_review_job:
stage: deploy
variables:
DEPLOY_SITE: "https://dev.example.com/"
REVIEW_PATH: "/review"
script:
- deploy-review-script --url $DEPLOY_SITE --path $REVIEW_PATH
environment: production
```
In this example:
- `deploy_job` has no variables defined. The default `DEPLOY_SITE` variable is copied to the job
and can be used in the `script` section.
- `deploy_review_job` already has a `DEPLOY_SITE` variable defined, so the default `DEPLOY_SITE`
is not copied to the job. The job also has a `REVIEW_PATH` job variable defined.
Both job variables can be used in the `script` section.
---
#### `variables:description`
Use the `description` keyword to define a description for a default variable.
The description displays with [the prefilled variable name when running a pipeline manually](../pipelines/_index.md#prefill-variables-in-manual-pipelines).
**Keyword type**: You can only use this keyword with default `variables`, not job `variables`.
**Supported values**:
- A string. You can use Markdown.
**Example of `variables:description`**:
```yaml
variables:
DEPLOY_NOTE:
description: "The deployment note. Explain the reason for this deployment."
```
**Additional details**:
- When used without `value`, the variable exists in pipelines that were not triggered manually,
and the default value is an empty string (`''`).
---
#### `variables:value`
Use the `value` keyword to define a pipeline-level (default) variable's value. When used with
[`variables: description`](#variablesdescription), the variable value is [prefilled when running a pipeline manually](../pipelines/_index.md#prefill-variables-in-manual-pipelines).
**Keyword type**: You can only use this keyword with default `variables`, not job `variables`.
**Supported values**:
- A string.
**Example of `variables:value`**:
```yaml
variables:
DEPLOY_ENVIRONMENT:
value: "staging"
description: "The deployment target. Change this variable to 'canary' or 'production' if needed."
```
**Additional details**:
- If used without [`variables: description`](#variablesdescription), the behavior is
the same as [`variables`](#variables).
---
#### `variables:options`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/105502) in GitLab 15.7.
{{< /history >}}
Use `variables:options` to define an array of values that are [selectable in the UI when running a pipeline manually](../pipelines/_index.md#configure-a-list-of-selectable-prefilled-variable-values).
Must be used with `variables: value`, and the string defined for `value`:
- Must also be one of the strings in the `options` array.
- Is the default selection.
If there is no [`description`](#variablesdescription),
this keyword has no effect.
**Keyword type**: You can only use this keyword with default `variables`, not job `variables`.
**Supported values**:
- An array of strings.
**Example of `variables:options`**:
```yaml
variables:
DEPLOY_ENVIRONMENT:
value: "staging"
options:
- "production"
- "staging"
- "canary"
description: "The deployment target. Set to 'staging' by default."
```
---
### `variables:expand`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/353991) in GitLab 15.6 [with a flag](../../administration/feature_flags/_index.md) named `ci_raw_variables_in_yaml_config`. Disabled by default.
- [Enabled on GitLab.com](https://gitlab.com/gitlab-org/gitlab/-/issues/375034) in GitLab 15.6.
- [Enabled on GitLab Self-Managed](https://gitlab.com/gitlab-org/gitlab/-/issues/375034) in GitLab 15.7.
- [Generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/375034) in GitLab 15.8. Feature flag `ci_raw_variables_in_yaml_config` removed.
{{< /history >}}
Use the `expand` keyword to configure a variable to be expandable or not.
**Keyword type**: You can use this keyword with both default and job `variables`.
**Supported values**:
- `true` (default): The variable is expandable.
- `false`: The variable is not expandable.
**Example of `variables:expand`**:
```yaml
variables:
VAR1: value1
VAR2: value2 $VAR1
VAR3:
value: value3 $VAR1
expand: false
```
- The result of `VAR2` is `value2 value1`.
- The result of `VAR3` is `value3 $VAR1`.
**Additional details**:
- The `expand` keyword can only be used with default and job `variables` keywords.
You can't use it with [`rules:variables`](#rulesvariables) or [`workflow:rules:variables`](#workflowrulesvariables).
|
https://docs.gitlab.com/ci/includes
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/includes.md
|
2025-08-13
|
doc/ci/yaml
|
[
"doc",
"ci",
"yaml"
] |
includes.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Use CI/CD configuration from other files
|
Use the `include` keyword to extend your CI/CD configuration with content from other YAML files.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can use [`include`](_index.md#include) to include external YAML files in your CI/CD jobs.
## Include a single configuration file
To include a single configuration file, use `include` by itself with a single file
with either of these syntax options:
- On the same line:
```yaml
include: 'my-config.yml'
```
- As a single item in an array:
```yaml
include:
- 'my-config.yml'
```
If the file is a local file, the behavior is the same as [`include:local`](_index.md#includelocal).
If the file is a remote file, it is the same as [`include:remote`](_index.md#includeremote).
## Include an array of configuration files
You can include an array of configuration files:
- If you do not specify an `include` type, each array item defaults to [`include:local`](_index.md#includelocal)
or [`include:remote`](_index.md#includeremote), as needed:
```yaml
include:
- 'https://gitlab.com/awesome-project/raw/main/.before-script-template.yml'
- 'templates/.after-script-template.yml'
```
- You can define a single item array:
```yaml
include:
- remote: 'https://gitlab.com/awesome-project/raw/main/.before-script-template.yml'
```
- You can define an array and explicitly specify multiple `include` types:
```yaml
include:
- remote: 'https://gitlab.com/awesome-project/raw/main/.before-script-template.yml'
- local: 'templates/.after-script-template.yml'
- template: Auto-DevOps.gitlab-ci.yml
```
- You can define an array that combines both default and specific `include` types:
```yaml
include:
- 'https://gitlab.com/awesome-project/raw/main/.before-script-template.yml'
- 'templates/.after-script-template.yml'
- template: Auto-DevOps.gitlab-ci.yml
- project: 'my-group/my-project'
ref: main
file: 'templates/.gitlab-ci-template.yml'
```
## Use `default` configuration from an included configuration file
You can define a [`default`](_index.md#default) section in a
configuration file. When you use a `default` section with the `include` keyword, the defaults apply to
all jobs in the pipeline.
For example, you can use a `default` section with [`before_script`](_index.md#before_script).
Content of a custom configuration file named `/templates/.before-script-template.yml`:
```yaml
default:
before_script:
- apt-get update -qq && apt-get install -y -qq sqlite3 libsqlite3-dev nodejs
- gem install bundler --no-document
- bundle install --jobs $(nproc) "${FLAGS[@]}"
```
Content of `.gitlab-ci.yml`:
```yaml
include: 'templates/.before-script-template.yml'
rspec1:
script:
- bundle exec rspec
rspec2:
script:
- bundle exec rspec
```
The default `before_script` commands execute in both `rspec` jobs, before the `script` commands.
## Override included configuration values
When you use the `include` keyword, you can override the included configuration values to adapt them
to your pipeline requirements.
The following example shows an `include` file that is customized in the
`.gitlab-ci.yml` file. Specific YAML-defined variables and details of the
`production` job are overridden.
Content of a custom configuration file named `autodevops-template.yml`:
```yaml
variables:
POSTGRES_USER: user
POSTGRES_PASSWORD: testing_password
POSTGRES_DB: $CI_ENVIRONMENT_SLUG
production:
stage: production
script:
- install_dependencies
- deploy
environment:
name: production
url: https://$CI_PROJECT_PATH_SLUG.$KUBE_INGRESS_BASE_DOMAIN
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
Content of `.gitlab-ci.yml`:
```yaml
include: 'https://company.com/autodevops-template.yml'
default:
image: alpine:latest
variables:
POSTGRES_USER: root
POSTGRES_PASSWORD: secure_password
stages:
- build
- test
- production
production:
environment:
url: https://domain.com
```
The `POSTGRES_USER` and `POSTGRES_PASSWORD` variables
and the `environment:url` of the `production` job defined in the `.gitlab-ci.yml` file
override the values defined in the `autodevops-template.yml` file. The other keywords
do not change. This method is called *merging*.
### Merge method for `include`
The `include` configuration merges with the main configuration file with this process:
- Included files are read in the order defined in the configuration file, and
the included configuration is merged together in the same order.
- If an included file also uses `include`, that nested `include` configuration is merged first (recursively).
- If parameters overlap, the last included file takes precedence when merging the configuration
from the included files.
- After all configuration added with `include` is merged together, the main configuration
is merged with the included configuration.
This merge method is a _deep merge_, where hash maps are merged at any depth in the
configuration. To merge hash map "A" (that contains the configuration merged so far) and "B" (the next piece
of configuration), the keys and values are processed as follows:
- When the key only exists in A, use the key and value from A.
- When the key exists in both A and B, and their values are both hash maps, merge those hash maps.
- When the key exists in both A and B, and one of the values is not a hash map, use the value from B.
- Otherwise, use the key and value from B.
For example, with a configuration that consists of two files:
- The `.gitlab-ci.yml` file:
```yaml
include: 'common.yml'
variables:
POSTGRES_USER: username
test:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
artifacts:
reports:
junit: rspec.xml
```
- The `common.yml` file:
```yaml
variables:
POSTGRES_USER: common_username
POSTGRES_PASSWORD: testing_password
test:
rules:
- when: never
script:
- echo LOGIN=${POSTGRES_USER} > deploy.env
- rake spec
artifacts:
reports:
dotenv: deploy.env
```
The merged result is:
```yaml
variables:
POSTGRES_USER: username
POSTGRES_PASSWORD: testing_password
test:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
script:
- echo LOGIN=${POSTGRES_USER} > deploy.env
- rake spec
artifacts:
reports:
junit: rspec.xml
dotenv: deploy.env
```
In this example:
- Variables are only evaluated after all the files are merged together. A job in an included file
might end up using a variable value defined in a different file.
- `rules` is an array so it cannot be merged. The top-level file takes precedence.
- `artifacts` is a hash map so it can be deep merged.
## Override included configuration arrays
You can use merging to extend and override configuration in an included template, but
you cannot add or modify individual items in an array. For example, to add
an additional `notify_owner` command to the extended `production` job's `script` array:
Content of `autodevops-template.yml`:
```yaml
production:
stage: production
script:
- install_dependencies
- deploy
```
Content of `.gitlab-ci.yml`:
```yaml
include: 'autodevops-template.yml'
stages:
- production
production:
script:
- install_dependencies
- deploy
- notify_owner
```
If `install_dependencies` and `deploy` are not repeated in
the `.gitlab-ci.yml` file, the `production` job would have only `notify_owner` in the script.
## Use nested includes
You can nest `include` sections in configuration files that are then included
in another configuration. For example, for `include` keywords nested three deep:
Content of `.gitlab-ci.yml`:
```yaml
include:
- local: /.gitlab-ci/another-config.yml
```
Content of `/.gitlab-ci/another-config.yml`:
```yaml
include:
- local: /.gitlab-ci/config-defaults.yml
```
Content of `/.gitlab-ci/config-defaults.yml`:
```yaml
default:
after_script:
- echo "Job complete."
```
### Use nested includes with duplicate `include` entries
You can include the same configuration file multiple times in the main configuration file and
in nested includes.
If any file changes the included configuration using [overrides](#override-included-configuration-values),
then the order of the `include` entries might affect the final configuration. The last time
the configuration is included overrides any previous times the file was included.
For example:
- Contents of a `defaults.gitlab-ci.yml` file:
```yaml
default:
before_script: echo "Default before script"
```
- Contents of a `unit-tests.gitlab-ci.yml` file:
```yaml
include:
- template: defaults.gitlab-ci.yml
default: # Override the included default
before_script: echo "Unit test default override"
unit-test-job:
script: unit-test.sh
```
- Contents of a `smoke-tests.gitlab-ci.yml` file:
```yaml
include:
- template: defaults.gitlab-ci.yml
default: # Override the included default
before_script: echo "Smoke test default override"
smoke-test-job:
script: smoke-test.sh
```
With these three files, the order they are included changes the final configuration.
With:
- `unit-tests` included first, the contents of the `.gitlab-ci.yml` file is:
```yaml
include:
- local: unit-tests.gitlab-ci.yml
- local: smoke-tests.gitlab-ci.yml
```
The final configuration would be:
```yaml
unit-test-job:
before_script: echo "Smoke test default override"
script: unit-test.sh
smoke-test-job:
before_script: echo "Smoke test default override"
script: smoke-test.sh
```
- `unit-tests` included last, the contents of the `.gitlab-ci.yml` file is:
```yaml
include:
- local: smoke-tests.gitlab-ci.yml
- local: unit-tests.gitlab-ci.yml
```
- The final configuration would be:
```yaml
unit-test-job:
before_script: echo "Unit test default override"
script: unit-test.sh
smoke-test-job:
before_script: echo "Unit test default override"
script: smoke-test.sh
```
If no file overrides the included configuration, the order of the `include` entries
does not affect the final configuration
## Use variables with `include`
In `include` sections in your `.gitlab-ci.yml` file, you can use:
- [Project variables](../variables/_index.md#for-a-project).
- [Group variables](../variables/_index.md#for-a-group).
- [Instance variables](../variables/_index.md#for-an-instance).
- Project [predefined variables](../variables/predefined_variables.md) (`CI_PROJECT_*`).
- [Trigger variables](../triggers/_index.md#pass-cicd-variables-in-the-api-call).
- [Scheduled pipeline variables](../pipelines/schedules.md#add-a-pipeline-schedule).
- [Manual pipeline run variables](../pipelines/_index.md#run-a-pipeline-manually).
- The `CI_PIPELINE_SOURCE` and `CI_PIPELINE_TRIGGERED` [predefined variables](../variables/predefined_variables.md).
- The `$CI_COMMIT_REF_NAME` [predefined variable](../variables/predefined_variables.md).
For example:
```yaml
include:
project: '$CI_PROJECT_PATH'
file: '.compliance-gitlab-ci.yml'
```
You cannot use variables defined in jobs, or in a global [`variables`](_index.md#variables)
section which defines the default variables for all jobs. Includes are evaluated before jobs,
so these variables cannot be used with `include`.
For an example of how you can include predefined variables, and the variables' impact on CI/CD jobs,
see this [CI/CD variable demo](https://youtu.be/4XR8gw3Pkos).
You cannot use CI/CD variables in an `include` section in a dynamic child pipeline's configuration.
[Issue 378717](https://gitlab.com/gitlab-org/gitlab/-/issues/378717) proposes fixing
this issue.
## Use `rules` with `include`
{{< history >}}
- Support for `needs` job dependency [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/345377) in GitLab 15.11.
{{< /history >}}
You can use [`rules`](_index.md#rules) with `include` to conditionally include other configuration files.
You can only use `rules` with [certain variables](#use-variables-with-include), and
these keywords:
- [`rules:if`](_index.md#rulesif).
- [`rules:exists`](_index.md#rulesexists).
- [`rules:changes`](_index.md#ruleschanges).
### `include` with `rules:if`
{{< history >}}
- Support for `when: never` and `when:always` [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/348146) in GitLab 16.1 [with a flag](../../administration/feature_flags/_index.md) named `ci_support_include_rules_when_never`. Disabled by default.
- Support for `when: never` and `when:always` [generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/414517) in GitLab 16.2. Feature flag `ci_support_include_rules_when_never` removed.
{{< /history >}}
Use [`rules:if`](_index.md#rulesif) to conditionally include other configuration files
based on the status of CI/CD variables. For example:
```yaml
include:
- local: builds.yml
rules:
- if: $DONT_INCLUDE_BUILDS == "true"
when: never
- local: builds.yml
rules:
- if: $ALWAYS_INCLUDE_BUILDS == "true"
when: always
- local: builds.yml
rules:
- if: $INCLUDE_BUILDS == "true"
- local: deploys.yml
rules:
- if: $CI_COMMIT_BRANCH == "main"
test:
stage: test
script: exit 0
```
### `include` with `rules:exists`
{{< history >}}
- Support for `when: never` and `when:always` [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/348146) in GitLab 16.1 [with a flag](../../administration/feature_flags/_index.md) named `ci_support_include_rules_when_never`. Disabled by default.
- Support for `when: never` and `when:always` [generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/414517) in GitLab 16.2. Feature flag `ci_support_include_rules_when_never` removed.
{{< /history >}}
Use [`rules:exists`](_index.md#rulesexists) to conditionally include other configuration files
based on the existence of files. For example:
```yaml
include:
- local: builds.yml
rules:
- exists:
- exception-file.md
when: never
- local: builds.yml
rules:
- exists:
- important-file.md
when: always
- local: builds.yml
rules:
- exists:
- file.md
test:
stage: test
script: exit 0
```
In this example, GitLab checks for the existence of `file.md` in the current project.
Review your configuration carefully if you use `include` with `rules:exists` in an include file
from a different project. GitLab checks for the existence of the file in the other project.
For example:
```yaml
# Pipeline configuration in my-group/my-project
include:
- project: my-group/other-project
ref: other_branch
file: other-file.yml
test:
script: exit 0
# other-file.yml in my-group/other-project on ref other_branch
include:
- project: my-group/my-project
ref: main
file: my-file.yml
rules:
- exists:
- file.md
```
In this example, GitLab searches for the existence of `file.md` in `my-group/other-project`
on commit ref `other_branch`, not the project/ref in which the pipeline runs.
To change the search context you can use [`rules:exists:paths`](_index.md#rulesexistspaths)
with [`rules:exists:project`](_index.md#rulesexistsproject).
For example:
```yaml
include:
- project: my-group/my-project
ref: main
file: my-file.yml
rules:
- exists:
paths:
- file.md
project: my-group/my-project
ref: main
```
### `include` with `rules:changes`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/342209) in GitLab 16.4.
{{< /history >}}
Use [`rules:changes`](_index.md#ruleschanges) to conditionally include other configuration files
based on changed files. For example:
```yaml
include:
- local: builds1.yml
rules:
- changes:
- Dockerfile
- local: builds2.yml
rules:
- changes:
paths:
- Dockerfile
compare_to: 'refs/heads/branch1'
when: always
- local: builds3.yml
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
paths:
- Dockerfile
test:
stage: test
script: exit 0
```
In this example:
- `builds1.yml` is included when `Dockerfile` has changed.
- `builds2.yml` is included when `Dockerfile` has changed relative to `refs/heads/branch1`.
- `builds3.yml` is included when `Dockerfile` has changed and the pipeline source is a merge request event. The jobs in `builds3.yml` must also be configured to run for [merge request pipelines](../pipelines/merge_request_pipelines.md#add-jobs-to-merge-request-pipelines).
## Use `include:local` with wildcard file paths
You can use wildcard paths (`*` and `**`) with `include:local`.
Example:
```yaml
include: 'configs/*.yml'
```
When the pipeline runs, GitLab:
- Adds all `.yml` files in the `configs` directory into the pipeline configuration.
- Does not add `.yml` files in subfolders of the `configs` directory. To allow this,
add the following configuration:
```yaml
# This matches all `.yml` files in `configs` and any subfolder in it.
include: 'configs/**.yml'
# This matches all `.yml` files only in subfolders of `configs`.
include: 'configs/**/*.yml'
```
## Troubleshooting
### `Maximum of 150 nested includes are allowed!` error
The maximum number of [nested included files](#use-nested-includes) for a pipeline is 150.
If you receive the `Maximum 150 includes are allowed` error message in your pipeline,
it's likely that either:
- Some of the nested configuration includes an overly large number of additional nested `include` configuration.
- There is an accidental loop in the nested includes. For example, `include1.yml` includes
`include2.yml` which includes `include1.yml`, creating a recursive loop.
To help reduce the risk of this happening, edit the pipeline configuration file
with the [pipeline editor](../pipeline_editor/_index.md), which validates if the
limit is reached. You can remove one included file at a time to try to narrow down
which configuration file is the source of the loop or excessive included files.
In [GitLab 16.0 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/207270) users on GitLab Self-Managed can
change the [maximum includes](../../administration/settings/continuous_integration.md#set-maximum-includes) value.
### `SSL_connect SYSCALL returned=5 errno=0 state=SSLv3/TLS write client hello` and other network failures
When using [`include:remote`](_index.md#includeremote), GitLab tries to fetch the remote file
through HTTP(S). This process can fail because of a variety of connectivity issues.
The `SSL_connect SYSCALL returned=5 errno=0 state=SSLv3/TLS write client hello` error
happens when GitLab can't establish an HTTPS connection to the remote host. This issue
can be caused if the remote host has rate limits to prevent overloading the server
with requests.
For example, the [GitLab Pages](../../user/project/pages/_index.md) server for GitLab.com
is rate limited. Repeated attempts to fetch CI/CD configuration files hosted on GitLab Pages
can cause the rate limit to be reached and cause the error. You should avoid hosting
CI/CD configuration files on a GitLab Pages site.
When possible, use [`include:project`](_index.md#includeproject) to fetch configuration
files from other projects within the GitLab instance without making external HTTP(S) requests.
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Use CI/CD configuration from other files
description: Use the `include` keyword to extend your CI/CD configuration with content
from other YAML files.
breadcrumbs:
- doc
- ci
- yaml
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
You can use [`include`](_index.md#include) to include external YAML files in your CI/CD jobs.
## Include a single configuration file
To include a single configuration file, use `include` by itself with a single file
with either of these syntax options:
- On the same line:
```yaml
include: 'my-config.yml'
```
- As a single item in an array:
```yaml
include:
- 'my-config.yml'
```
If the file is a local file, the behavior is the same as [`include:local`](_index.md#includelocal).
If the file is a remote file, it is the same as [`include:remote`](_index.md#includeremote).
## Include an array of configuration files
You can include an array of configuration files:
- If you do not specify an `include` type, each array item defaults to [`include:local`](_index.md#includelocal)
or [`include:remote`](_index.md#includeremote), as needed:
```yaml
include:
- 'https://gitlab.com/awesome-project/raw/main/.before-script-template.yml'
- 'templates/.after-script-template.yml'
```
- You can define a single item array:
```yaml
include:
- remote: 'https://gitlab.com/awesome-project/raw/main/.before-script-template.yml'
```
- You can define an array and explicitly specify multiple `include` types:
```yaml
include:
- remote: 'https://gitlab.com/awesome-project/raw/main/.before-script-template.yml'
- local: 'templates/.after-script-template.yml'
- template: Auto-DevOps.gitlab-ci.yml
```
- You can define an array that combines both default and specific `include` types:
```yaml
include:
- 'https://gitlab.com/awesome-project/raw/main/.before-script-template.yml'
- 'templates/.after-script-template.yml'
- template: Auto-DevOps.gitlab-ci.yml
- project: 'my-group/my-project'
ref: main
file: 'templates/.gitlab-ci-template.yml'
```
## Use `default` configuration from an included configuration file
You can define a [`default`](_index.md#default) section in a
configuration file. When you use a `default` section with the `include` keyword, the defaults apply to
all jobs in the pipeline.
For example, you can use a `default` section with [`before_script`](_index.md#before_script).
Content of a custom configuration file named `/templates/.before-script-template.yml`:
```yaml
default:
before_script:
- apt-get update -qq && apt-get install -y -qq sqlite3 libsqlite3-dev nodejs
- gem install bundler --no-document
- bundle install --jobs $(nproc) "${FLAGS[@]}"
```
Content of `.gitlab-ci.yml`:
```yaml
include: 'templates/.before-script-template.yml'
rspec1:
script:
- bundle exec rspec
rspec2:
script:
- bundle exec rspec
```
The default `before_script` commands execute in both `rspec` jobs, before the `script` commands.
## Override included configuration values
When you use the `include` keyword, you can override the included configuration values to adapt them
to your pipeline requirements.
The following example shows an `include` file that is customized in the
`.gitlab-ci.yml` file. Specific YAML-defined variables and details of the
`production` job are overridden.
Content of a custom configuration file named `autodevops-template.yml`:
```yaml
variables:
POSTGRES_USER: user
POSTGRES_PASSWORD: testing_password
POSTGRES_DB: $CI_ENVIRONMENT_SLUG
production:
stage: production
script:
- install_dependencies
- deploy
environment:
name: production
url: https://$CI_PROJECT_PATH_SLUG.$KUBE_INGRESS_BASE_DOMAIN
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```
Content of `.gitlab-ci.yml`:
```yaml
include: 'https://company.com/autodevops-template.yml'
default:
image: alpine:latest
variables:
POSTGRES_USER: root
POSTGRES_PASSWORD: secure_password
stages:
- build
- test
- production
production:
environment:
url: https://domain.com
```
The `POSTGRES_USER` and `POSTGRES_PASSWORD` variables
and the `environment:url` of the `production` job defined in the `.gitlab-ci.yml` file
override the values defined in the `autodevops-template.yml` file. The other keywords
do not change. This method is called *merging*.
### Merge method for `include`
The `include` configuration merges with the main configuration file with this process:
- Included files are read in the order defined in the configuration file, and
the included configuration is merged together in the same order.
- If an included file also uses `include`, that nested `include` configuration is merged first (recursively).
- If parameters overlap, the last included file takes precedence when merging the configuration
from the included files.
- After all configuration added with `include` is merged together, the main configuration
is merged with the included configuration.
This merge method is a _deep merge_, where hash maps are merged at any depth in the
configuration. To merge hash map "A" (that contains the configuration merged so far) and "B" (the next piece
of configuration), the keys and values are processed as follows:
- When the key only exists in A, use the key and value from A.
- When the key exists in both A and B, and their values are both hash maps, merge those hash maps.
- When the key exists in both A and B, and one of the values is not a hash map, use the value from B.
- Otherwise, use the key and value from B.
For example, with a configuration that consists of two files:
- The `.gitlab-ci.yml` file:
```yaml
include: 'common.yml'
variables:
POSTGRES_USER: username
test:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
artifacts:
reports:
junit: rspec.xml
```
- The `common.yml` file:
```yaml
variables:
POSTGRES_USER: common_username
POSTGRES_PASSWORD: testing_password
test:
rules:
- when: never
script:
- echo LOGIN=${POSTGRES_USER} > deploy.env
- rake spec
artifacts:
reports:
dotenv: deploy.env
```
The merged result is:
```yaml
variables:
POSTGRES_USER: username
POSTGRES_PASSWORD: testing_password
test:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
script:
- echo LOGIN=${POSTGRES_USER} > deploy.env
- rake spec
artifacts:
reports:
junit: rspec.xml
dotenv: deploy.env
```
In this example:
- Variables are only evaluated after all the files are merged together. A job in an included file
might end up using a variable value defined in a different file.
- `rules` is an array so it cannot be merged. The top-level file takes precedence.
- `artifacts` is a hash map so it can be deep merged.
## Override included configuration arrays
You can use merging to extend and override configuration in an included template, but
you cannot add or modify individual items in an array. For example, to add
an additional `notify_owner` command to the extended `production` job's `script` array:
Content of `autodevops-template.yml`:
```yaml
production:
stage: production
script:
- install_dependencies
- deploy
```
Content of `.gitlab-ci.yml`:
```yaml
include: 'autodevops-template.yml'
stages:
- production
production:
script:
- install_dependencies
- deploy
- notify_owner
```
If `install_dependencies` and `deploy` are not repeated in
the `.gitlab-ci.yml` file, the `production` job would have only `notify_owner` in the script.
## Use nested includes
You can nest `include` sections in configuration files that are then included
in another configuration. For example, for `include` keywords nested three deep:
Content of `.gitlab-ci.yml`:
```yaml
include:
- local: /.gitlab-ci/another-config.yml
```
Content of `/.gitlab-ci/another-config.yml`:
```yaml
include:
- local: /.gitlab-ci/config-defaults.yml
```
Content of `/.gitlab-ci/config-defaults.yml`:
```yaml
default:
after_script:
- echo "Job complete."
```
### Use nested includes with duplicate `include` entries
You can include the same configuration file multiple times in the main configuration file and
in nested includes.
If any file changes the included configuration using [overrides](#override-included-configuration-values),
then the order of the `include` entries might affect the final configuration. The last time
the configuration is included overrides any previous times the file was included.
For example:
- Contents of a `defaults.gitlab-ci.yml` file:
```yaml
default:
before_script: echo "Default before script"
```
- Contents of a `unit-tests.gitlab-ci.yml` file:
```yaml
include:
- template: defaults.gitlab-ci.yml
default: # Override the included default
before_script: echo "Unit test default override"
unit-test-job:
script: unit-test.sh
```
- Contents of a `smoke-tests.gitlab-ci.yml` file:
```yaml
include:
- template: defaults.gitlab-ci.yml
default: # Override the included default
before_script: echo "Smoke test default override"
smoke-test-job:
script: smoke-test.sh
```
With these three files, the order they are included changes the final configuration.
With:
- `unit-tests` included first, the contents of the `.gitlab-ci.yml` file is:
```yaml
include:
- local: unit-tests.gitlab-ci.yml
- local: smoke-tests.gitlab-ci.yml
```
The final configuration would be:
```yaml
unit-test-job:
before_script: echo "Smoke test default override"
script: unit-test.sh
smoke-test-job:
before_script: echo "Smoke test default override"
script: smoke-test.sh
```
- `unit-tests` included last, the contents of the `.gitlab-ci.yml` file is:
```yaml
include:
- local: smoke-tests.gitlab-ci.yml
- local: unit-tests.gitlab-ci.yml
```
- The final configuration would be:
```yaml
unit-test-job:
before_script: echo "Unit test default override"
script: unit-test.sh
smoke-test-job:
before_script: echo "Unit test default override"
script: smoke-test.sh
```
If no file overrides the included configuration, the order of the `include` entries
does not affect the final configuration
## Use variables with `include`
In `include` sections in your `.gitlab-ci.yml` file, you can use:
- [Project variables](../variables/_index.md#for-a-project).
- [Group variables](../variables/_index.md#for-a-group).
- [Instance variables](../variables/_index.md#for-an-instance).
- Project [predefined variables](../variables/predefined_variables.md) (`CI_PROJECT_*`).
- [Trigger variables](../triggers/_index.md#pass-cicd-variables-in-the-api-call).
- [Scheduled pipeline variables](../pipelines/schedules.md#add-a-pipeline-schedule).
- [Manual pipeline run variables](../pipelines/_index.md#run-a-pipeline-manually).
- The `CI_PIPELINE_SOURCE` and `CI_PIPELINE_TRIGGERED` [predefined variables](../variables/predefined_variables.md).
- The `$CI_COMMIT_REF_NAME` [predefined variable](../variables/predefined_variables.md).
For example:
```yaml
include:
project: '$CI_PROJECT_PATH'
file: '.compliance-gitlab-ci.yml'
```
You cannot use variables defined in jobs, or in a global [`variables`](_index.md#variables)
section which defines the default variables for all jobs. Includes are evaluated before jobs,
so these variables cannot be used with `include`.
For an example of how you can include predefined variables, and the variables' impact on CI/CD jobs,
see this [CI/CD variable demo](https://youtu.be/4XR8gw3Pkos).
You cannot use CI/CD variables in an `include` section in a dynamic child pipeline's configuration.
[Issue 378717](https://gitlab.com/gitlab-org/gitlab/-/issues/378717) proposes fixing
this issue.
## Use `rules` with `include`
{{< history >}}
- Support for `needs` job dependency [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/345377) in GitLab 15.11.
{{< /history >}}
You can use [`rules`](_index.md#rules) with `include` to conditionally include other configuration files.
You can only use `rules` with [certain variables](#use-variables-with-include), and
these keywords:
- [`rules:if`](_index.md#rulesif).
- [`rules:exists`](_index.md#rulesexists).
- [`rules:changes`](_index.md#ruleschanges).
### `include` with `rules:if`
{{< history >}}
- Support for `when: never` and `when:always` [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/348146) in GitLab 16.1 [with a flag](../../administration/feature_flags/_index.md) named `ci_support_include_rules_when_never`. Disabled by default.
- Support for `when: never` and `when:always` [generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/414517) in GitLab 16.2. Feature flag `ci_support_include_rules_when_never` removed.
{{< /history >}}
Use [`rules:if`](_index.md#rulesif) to conditionally include other configuration files
based on the status of CI/CD variables. For example:
```yaml
include:
- local: builds.yml
rules:
- if: $DONT_INCLUDE_BUILDS == "true"
when: never
- local: builds.yml
rules:
- if: $ALWAYS_INCLUDE_BUILDS == "true"
when: always
- local: builds.yml
rules:
- if: $INCLUDE_BUILDS == "true"
- local: deploys.yml
rules:
- if: $CI_COMMIT_BRANCH == "main"
test:
stage: test
script: exit 0
```
### `include` with `rules:exists`
{{< history >}}
- Support for `when: never` and `when:always` [introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/348146) in GitLab 16.1 [with a flag](../../administration/feature_flags/_index.md) named `ci_support_include_rules_when_never`. Disabled by default.
- Support for `when: never` and `when:always` [generally available](https://gitlab.com/gitlab-org/gitlab/-/issues/414517) in GitLab 16.2. Feature flag `ci_support_include_rules_when_never` removed.
{{< /history >}}
Use [`rules:exists`](_index.md#rulesexists) to conditionally include other configuration files
based on the existence of files. For example:
```yaml
include:
- local: builds.yml
rules:
- exists:
- exception-file.md
when: never
- local: builds.yml
rules:
- exists:
- important-file.md
when: always
- local: builds.yml
rules:
- exists:
- file.md
test:
stage: test
script: exit 0
```
In this example, GitLab checks for the existence of `file.md` in the current project.
Review your configuration carefully if you use `include` with `rules:exists` in an include file
from a different project. GitLab checks for the existence of the file in the other project.
For example:
```yaml
# Pipeline configuration in my-group/my-project
include:
- project: my-group/other-project
ref: other_branch
file: other-file.yml
test:
script: exit 0
# other-file.yml in my-group/other-project on ref other_branch
include:
- project: my-group/my-project
ref: main
file: my-file.yml
rules:
- exists:
- file.md
```
In this example, GitLab searches for the existence of `file.md` in `my-group/other-project`
on commit ref `other_branch`, not the project/ref in which the pipeline runs.
To change the search context you can use [`rules:exists:paths`](_index.md#rulesexistspaths)
with [`rules:exists:project`](_index.md#rulesexistsproject).
For example:
```yaml
include:
- project: my-group/my-project
ref: main
file: my-file.yml
rules:
- exists:
paths:
- file.md
project: my-group/my-project
ref: main
```
### `include` with `rules:changes`
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/342209) in GitLab 16.4.
{{< /history >}}
Use [`rules:changes`](_index.md#ruleschanges) to conditionally include other configuration files
based on changed files. For example:
```yaml
include:
- local: builds1.yml
rules:
- changes:
- Dockerfile
- local: builds2.yml
rules:
- changes:
paths:
- Dockerfile
compare_to: 'refs/heads/branch1'
when: always
- local: builds3.yml
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
paths:
- Dockerfile
test:
stage: test
script: exit 0
```
In this example:
- `builds1.yml` is included when `Dockerfile` has changed.
- `builds2.yml` is included when `Dockerfile` has changed relative to `refs/heads/branch1`.
- `builds3.yml` is included when `Dockerfile` has changed and the pipeline source is a merge request event. The jobs in `builds3.yml` must also be configured to run for [merge request pipelines](../pipelines/merge_request_pipelines.md#add-jobs-to-merge-request-pipelines).
## Use `include:local` with wildcard file paths
You can use wildcard paths (`*` and `**`) with `include:local`.
Example:
```yaml
include: 'configs/*.yml'
```
When the pipeline runs, GitLab:
- Adds all `.yml` files in the `configs` directory into the pipeline configuration.
- Does not add `.yml` files in subfolders of the `configs` directory. To allow this,
add the following configuration:
```yaml
# This matches all `.yml` files in `configs` and any subfolder in it.
include: 'configs/**.yml'
# This matches all `.yml` files only in subfolders of `configs`.
include: 'configs/**/*.yml'
```
## Troubleshooting
### `Maximum of 150 nested includes are allowed!` error
The maximum number of [nested included files](#use-nested-includes) for a pipeline is 150.
If you receive the `Maximum 150 includes are allowed` error message in your pipeline,
it's likely that either:
- Some of the nested configuration includes an overly large number of additional nested `include` configuration.
- There is an accidental loop in the nested includes. For example, `include1.yml` includes
`include2.yml` which includes `include1.yml`, creating a recursive loop.
To help reduce the risk of this happening, edit the pipeline configuration file
with the [pipeline editor](../pipeline_editor/_index.md), which validates if the
limit is reached. You can remove one included file at a time to try to narrow down
which configuration file is the source of the loop or excessive included files.
In [GitLab 16.0 and later](https://gitlab.com/gitlab-org/gitlab/-/issues/207270) users on GitLab Self-Managed can
change the [maximum includes](../../administration/settings/continuous_integration.md#set-maximum-includes) value.
### `SSL_connect SYSCALL returned=5 errno=0 state=SSLv3/TLS write client hello` and other network failures
When using [`include:remote`](_index.md#includeremote), GitLab tries to fetch the remote file
through HTTP(S). This process can fail because of a variety of connectivity issues.
The `SSL_connect SYSCALL returned=5 errno=0 state=SSLv3/TLS write client hello` error
happens when GitLab can't establish an HTTPS connection to the remote host. This issue
can be caused if the remote host has rate limits to prevent overloading the server
with requests.
For example, the [GitLab Pages](../../user/project/pages/_index.md) server for GitLab.com
is rate limited. Repeated attempts to fetch CI/CD configuration files hosted on GitLab Pages
can cause the rate limit to be reached and cause the error. You should avoid hosting
CI/CD configuration files on a GitLab Pages site.
When possible, use [`include:project`](_index.md#includeproject) to fetch configuration
files from other projects within the GitLab instance without making external HTTP(S) requests.
|
https://docs.gitlab.com/ci/interactive_web_terminal
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/_index.md
|
2025-08-13
|
doc/ci/interactive_web_terminal
|
[
"doc",
"ci",
"interactive_web_terminal"
] |
_index.md
|
Verify
|
Runner
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Interactive web terminals
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Interactive web terminals give the user access to a terminal in GitLab for
running one-off commands for their CI pipeline. You can think of it like a method for
debugging with SSH, but done directly from the job page. Because this is giving the user
shell access to the environment where [GitLab Runner](https://docs.gitlab.com/runner/)
is deployed, some [security precautions](../../administration/integration/terminal.md#security) were
taken to protect the users.
{{< alert type="note" >}}
[Instance runners on GitLab.com](../runners/_index.md) do not
provide an interactive web terminal. Follow
[this issue](https://gitlab.com/gitlab-org/gitlab/-/issues/24674) for progress on
adding support. For groups and projects hosted on GitLab.com, interactive web
terminals are available when using your own group or project runner.
{{< /alert >}}
## Configuration
Two things need to be configured for the interactive web terminal to work:
- The runner needs to have
[`[session_server]` configured properly](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-session_server-section)
- If you are using a reverse proxy with your GitLab instance, web terminals need to be
[enabled](../../administration/integration/terminal.md#enabling-and-disabling-terminal-support)
### Partial support for Helm chart
Interactive web terminals are partially supported in `gitlab-runner` Helm chart.
They are enabled when:
- The number of replica is one
- You use the `loadBalancer` service
Support for fixing these limitations is tracked in the following issues:
- [Support of more than one replica](https://gitlab.com/gitlab-org/charts/gitlab-runner/-/issues/323)
- [Support of more service types](https://gitlab.com/gitlab-org/charts/gitlab-runner/-/issues/324)
## Debugging a running job
{{< alert type="note" >}}
Not all executors are
[supported](https://docs.gitlab.com/runner/executors/#compatibility-chart).
{{< /alert >}}
{{< alert type="note" >}}
The `docker` executor does not keep running
after the build script is finished. At that point, the terminal automatically
disconnects and does not wait for the user to finish. Follow
[this issue](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/3605) for updates on
improving this behavior.
{{< /alert >}}
Sometimes, when a job is running, things don't go as you expect. It
would be helpful if one can have a shell to aid debugging. When a job runs,
the right panel displays a `debug` button ({{< icon name="external-link" >}}) that opens the terminal
for the current job. Only the person who started a job can debug it.

When selected, a new tab opens to the terminal page where you can access
the terminal and type commands like in a standard shell.

If your terminal is open after the job completes,
the job doesn't finish until after the configured
[`[session_server].session_timeout`](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-session_server-section)
duration. To avoid this, you can close the terminal after the job finishes.

|
---
stage: Verify
group: Runner
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Interactive web terminals
breadcrumbs:
- doc
- ci
- interactive_web_terminal
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
Interactive web terminals give the user access to a terminal in GitLab for
running one-off commands for their CI pipeline. You can think of it like a method for
debugging with SSH, but done directly from the job page. Because this is giving the user
shell access to the environment where [GitLab Runner](https://docs.gitlab.com/runner/)
is deployed, some [security precautions](../../administration/integration/terminal.md#security) were
taken to protect the users.
{{< alert type="note" >}}
[Instance runners on GitLab.com](../runners/_index.md) do not
provide an interactive web terminal. Follow
[this issue](https://gitlab.com/gitlab-org/gitlab/-/issues/24674) for progress on
adding support. For groups and projects hosted on GitLab.com, interactive web
terminals are available when using your own group or project runner.
{{< /alert >}}
## Configuration
Two things need to be configured for the interactive web terminal to work:
- The runner needs to have
[`[session_server]` configured properly](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-session_server-section)
- If you are using a reverse proxy with your GitLab instance, web terminals need to be
[enabled](../../administration/integration/terminal.md#enabling-and-disabling-terminal-support)
### Partial support for Helm chart
Interactive web terminals are partially supported in `gitlab-runner` Helm chart.
They are enabled when:
- The number of replica is one
- You use the `loadBalancer` service
Support for fixing these limitations is tracked in the following issues:
- [Support of more than one replica](https://gitlab.com/gitlab-org/charts/gitlab-runner/-/issues/323)
- [Support of more service types](https://gitlab.com/gitlab-org/charts/gitlab-runner/-/issues/324)
## Debugging a running job
{{< alert type="note" >}}
Not all executors are
[supported](https://docs.gitlab.com/runner/executors/#compatibility-chart).
{{< /alert >}}
{{< alert type="note" >}}
The `docker` executor does not keep running
after the build script is finished. At that point, the terminal automatically
disconnects and does not wait for the user to finish. Follow
[this issue](https://gitlab.com/gitlab-org/gitlab-runner/-/issues/3605) for updates on
improving this behavior.
{{< /alert >}}
Sometimes, when a job is running, things don't go as you expect. It
would be helpful if one can have a shell to aid debugging. When a job runs,
the right panel displays a `debug` button ({{< icon name="external-link" >}}) that opens the terminal
for the current job. Only the person who started a job can debug it.

When selected, a new tab opens to the terminal page where you can access
the terminal and type commands like in a standard shell.

If your terminal is open after the job completes,
the job doesn't finish until after the configured
[`[session_server].session_timeout`](https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-session_server-section)
duration. To avoid this, you can close the terminal after the job finishes.

|
https://docs.gitlab.com/ci/gitlab_google_cloud_integration
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/_index.md
|
2025-08-13
|
doc/ci/gitlab_google_cloud_integration
|
[
"doc",
"ci",
"gitlab_google_cloud_integration"
] |
_index.md
|
Package
|
Container Registry
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab and Google Cloud integration
|
Cloud services and Kubernetes deployments.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
Use the Google Cloud integration to use Google Cloud resources in GitLab projects.
To get started, see [Set up the Google Cloud integration](../../tutorials/set_up_gitlab_google_integration/_index.md).
- [Google Cloud workload identity federation and IAM](../../integration/google_cloud_iam.md)
- [Google Artifact Management integration](../../user/project/integrations/google_artifact_management.md)
- [Provisioning runners in Google Cloud](../runners/provision_runners_google_cloud.md)
|
---
stage: Package
group: Container Registry
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: GitLab and Google Cloud integration
description: Cloud services and Kubernetes deployments.
breadcrumbs:
- doc
- ci
- gitlab_google_cloud_integration
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com
{{< /details >}}
Use the Google Cloud integration to use Google Cloud resources in GitLab projects.
To get started, see [Set up the Google Cloud integration](../../tutorials/set_up_gitlab_google_integration/_index.md).
- [Google Cloud workload identity federation and IAM](../../integration/google_cloud_iam.md)
- [Google Artifact Management integration](../../user/project/integrations/google_artifact_management.md)
- [Provisioning runners in Google Cloud](../runners/provision_runners_google_cloud.md)
|
https://docs.gitlab.com/ci/pipeline_editor
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/ci/_index.md
|
2025-08-13
|
doc/ci/pipeline_editor
|
[
"doc",
"ci",
"pipeline_editor"
] |
_index.md
|
Verify
|
Pipeline Authoring
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Pipeline editor
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
The pipeline editor is the primary place to edit the GitLab CI/CD configuration in
the `.gitlab-ci.yml` file in the root of your repository. To access the editor, go to **Build > Pipeline editor**.
From the pipeline editor page you can:
- Select the branch to work from.
- [Validate](#validate-ci-configuration) your configuration syntax while editing the file.
- Do a deeper [lint](#lint-ci-configuration) of your configuration, that verifies it with any configuration
added with the [`include`](../yaml/_index.md#include) keyword.
- View a [list of the CI/CD configuration added with the `include` keyword](#view-included-cicd-configuration).
- See a [visualization](#visualize-ci-configuration) of the current configuration.
- View the [full configuration](#view-full-configuration), which displays the configuration with any configuration from `include` added.
- [Commit](#commit-changes-to-ci-configuration) the changes to a specific branch.
## Validate CI configuration
As you edit your pipeline configuration, it is continually validated against the GitLab CI/CD
pipeline schema. It checks the syntax of your CI YAML configuration, and also runs
some basic logical validations.
The result of this validation is shown at the top of the editor page. If the validation fails,
this section displays a tip to help you fix the problem:
## Lint CI configuration
{{< alert type="note" >}}
The **Lint** tab is replaced with the **Validate** tab in GitLab 15.3. The lint results are included
in a successful [pipeline simulation](#simulate-a-cicd-pipeline).
{{< /alert >}}
To test the validity of your GitLab CI/CD configuration before committing the changes,
you can use the CI lint tool:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline editor**.
1. Select the **Validate** tab.
This tool checks for syntax and logical errors but goes into more detail than the
automatic [validation](#validate-ci-configuration) in the editor.
The results are updated in real-time. Any changes you make to the configuration are
reflected in the CI lint. It displays the same results as the existing [CI Lint tool](../yaml/lint.md).
## Simulate a CI/CD pipeline
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/337282) in GitLab 15.3.
{{< /history >}}
To look for pipeline syntax and logic issues, you can simulate the creation of a
GitLab CI/CD pipeline in the **Validate** tab. A pipeline simulation can help find
problems such as incorrect `rules` and `needs` job dependencies, and is similar to
simulations in the [CI Lint tool](../yaml/lint.md#simulate-a-pipeline).
## View included CI/CD configuration
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/7064) in GitLab 15.0 [with a flag](../../administration/feature_flags/_index.md) named `pipeline_editor_file_tree`. Disabled by default.
- [Feature flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/357219) in GitLab 15.1.
{{< /history >}}
You can review configuration added with the [`include`](../yaml/_index.md#include)
keyword in the pipeline editor. In the upper-right corner, select the file tree ({{< icon name="file-tree" >}})
to see a list of all included configuration files. Selected files open in a new tab
for review.
## Visualize CI configuration
To view a visualization of your `.gitlab-ci.yml` configuration, in your project,
go to **Build > Pipeline editor**, and then select the **Visualize** tab. The
visualization shows all stages and jobs. Any [`needs`](../yaml/_index.md#needs)
relationships are displayed as lines connecting jobs together, showing the
hierarchy of execution.
Hover over a job to highlight its `needs` relationships:

If the configuration does not have any `needs` relationships, then no lines are drawn because
each job depends only on the previous stage being completed successfully.
## View full configuration
{{< history >}}
- **View merged YAML** tab [renamed to **Full configuration**](https://gitlab.com/gitlab-org/gitlab/-/issues/377404) in GitLab 16.0.
{{< /history >}}
To view the fully expanded CI/CD configuration as one combined file, go to the
pipeline editor's **Full configuration** tab. This tab displays an expanded configuration
where:
- Configuration imported with [`include`](../yaml/_index.md#include) is copied into the view.
- Jobs that use [`extends`](../yaml/_index.md#extends) display with the
[extended configuration merged into the job](../yaml/yaml_optimization.md#merge-details).
- [YAML anchors](../yaml/yaml_optimization.md#anchors) are replaced with the linked configuration.
- [YAML `!reference` tags](../yaml/yaml_optimization.md#reference-tags) are also replaced
with the linked configuration.
- Conditional rules are evaluated assuming a default branch push event.
Using `!reference` tags can cause nested configuration that display with
multiple hyphens (`-`) at the start of the line in the expanded view. This behavior is expected, and the extra
hyphens do not affect the job's execution. For example, this configuration and
fully expanded version are both valid:
- `.gitlab-ci.yml` file:
```yaml
.python-req:
script:
- pip install pyflakes
.rule-01:
rules:
- if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/
when: manual
allow_failure: true
- if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME
.rule-02:
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: manual
allow_failure: true
lint-python:
image: python:latest
script:
- !reference [.python-req, script]
- pyflakes python/
rules:
- !reference [.rule-01, rules]
- !reference [.rule-02, rules]
```
- Expanded configuration in **Full configuration** tab:
```yaml
".python-req":
script:
- pip install pyflakes
".rule-01":
rules:
- if: "$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/"
when: manual
allow_failure: true
- if: "$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME"
".rule-02":
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: manual
allow_failure: true
lint-python:
image: python:latest
script:
- - pip install pyflakes # <- The extra hyphens do not affect the job's execution.
- pyflakes python/
rules:
- - if: "$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/" # <- The extra hyphens do not affect the job's execution.
when: manual
allow_failure: true
- if: "$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME" # <- No extra hyphen but aligned with previous rule
- - if: $CI_COMMIT_BRANCH == "main" # <- The extra hyphens do not affect the job's execution.
when: manual
allow_failure: true
```
## Commit changes to CI configuration
The commit form appears at the bottom of each tab in the editor so you can commit
your changes at any time.
When you are satisfied with your changes, add a descriptive commit message and enter
a branch. The branch field defaults to your project's default branch.
If you enter a new branch name, the **Start a new merge request with these changes**
checkbox appears. Select it to start a new merge request after you commit the changes.

## Editor accessibility options
The pipeline editor is based on the [Monaco Editor](https://github.com/microsoft/monaco-editor)
which has several [accessibility features](https://github.com/microsoft/monaco-editor/wiki/Monaco-Editor-Accessibility-Guide),
including:
| Feature | Shortcut on Windows or Linux | Shortcut on macOS | Details |
|----------------------------------|-----------------------------------|------------------------------------------------------|---------|
| Keyboard navigation command list | <kbd>F1</kbd> | <kbd>F1</kbd> | A [list of commands](https://github.com/microsoft/monaco-editor/wiki/Monaco-Editor-Accessibility-Guide#keyboard-navigation) that make the editor easier to use without a mouse. |
| Tab trapping | <kbd>Control</kbd> + <kbd>m</kbd> | <kbd>Control</kbd> + <kbd>Shift</kbd> + <kbd>m</kbd> | Enable [tab trapping](https://github.com/microsoft/monaco-editor/wiki/Monaco-Editor-Accessibility-Guide#tab-trapping) to go to the next focusable element on the page instead of inserting a tab character. |
## Troubleshooting
### `Unable to validate CI/CD configuration.` message
This message is caused by a problem validating the syntax in the pipeline editor.
It can happen when GitLab is unable to communicate with the service that validates the syntax.
The information in these sections may not display properly:
- The syntax status on the **Edit** tab (valid or invalid).
- The **Visualize** tab.
- The **Lint** tab.
- The **Full configuration** tab.
You can still work on your CI/CD configuration and commit the changes you made without
any issues. As soon as the service becomes available again, the syntax validation
should display immediately.
|
---
stage: Verify
group: Pipeline Authoring
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Pipeline editor
breadcrumbs:
- doc
- ci
- pipeline_editor
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab.com, GitLab Self-Managed, GitLab Dedicated
{{< /details >}}
The pipeline editor is the primary place to edit the GitLab CI/CD configuration in
the `.gitlab-ci.yml` file in the root of your repository. To access the editor, go to **Build > Pipeline editor**.
From the pipeline editor page you can:
- Select the branch to work from.
- [Validate](#validate-ci-configuration) your configuration syntax while editing the file.
- Do a deeper [lint](#lint-ci-configuration) of your configuration, that verifies it with any configuration
added with the [`include`](../yaml/_index.md#include) keyword.
- View a [list of the CI/CD configuration added with the `include` keyword](#view-included-cicd-configuration).
- See a [visualization](#visualize-ci-configuration) of the current configuration.
- View the [full configuration](#view-full-configuration), which displays the configuration with any configuration from `include` added.
- [Commit](#commit-changes-to-ci-configuration) the changes to a specific branch.
## Validate CI configuration
As you edit your pipeline configuration, it is continually validated against the GitLab CI/CD
pipeline schema. It checks the syntax of your CI YAML configuration, and also runs
some basic logical validations.
The result of this validation is shown at the top of the editor page. If the validation fails,
this section displays a tip to help you fix the problem:
## Lint CI configuration
{{< alert type="note" >}}
The **Lint** tab is replaced with the **Validate** tab in GitLab 15.3. The lint results are included
in a successful [pipeline simulation](#simulate-a-cicd-pipeline).
{{< /alert >}}
To test the validity of your GitLab CI/CD configuration before committing the changes,
you can use the CI lint tool:
1. On the left sidebar, select **Search or go to** and find your project.
1. Select **Build > Pipeline editor**.
1. Select the **Validate** tab.
This tool checks for syntax and logical errors but goes into more detail than the
automatic [validation](#validate-ci-configuration) in the editor.
The results are updated in real-time. Any changes you make to the configuration are
reflected in the CI lint. It displays the same results as the existing [CI Lint tool](../yaml/lint.md).
## Simulate a CI/CD pipeline
{{< history >}}
- [Introduced](https://gitlab.com/gitlab-org/gitlab/-/issues/337282) in GitLab 15.3.
{{< /history >}}
To look for pipeline syntax and logic issues, you can simulate the creation of a
GitLab CI/CD pipeline in the **Validate** tab. A pipeline simulation can help find
problems such as incorrect `rules` and `needs` job dependencies, and is similar to
simulations in the [CI Lint tool](../yaml/lint.md#simulate-a-pipeline).
## View included CI/CD configuration
{{< history >}}
- [Introduced](https://gitlab.com/groups/gitlab-org/-/epics/7064) in GitLab 15.0 [with a flag](../../administration/feature_flags/_index.md) named `pipeline_editor_file_tree`. Disabled by default.
- [Feature flag removed](https://gitlab.com/gitlab-org/gitlab/-/issues/357219) in GitLab 15.1.
{{< /history >}}
You can review configuration added with the [`include`](../yaml/_index.md#include)
keyword in the pipeline editor. In the upper-right corner, select the file tree ({{< icon name="file-tree" >}})
to see a list of all included configuration files. Selected files open in a new tab
for review.
## Visualize CI configuration
To view a visualization of your `.gitlab-ci.yml` configuration, in your project,
go to **Build > Pipeline editor**, and then select the **Visualize** tab. The
visualization shows all stages and jobs. Any [`needs`](../yaml/_index.md#needs)
relationships are displayed as lines connecting jobs together, showing the
hierarchy of execution.
Hover over a job to highlight its `needs` relationships:

If the configuration does not have any `needs` relationships, then no lines are drawn because
each job depends only on the previous stage being completed successfully.
## View full configuration
{{< history >}}
- **View merged YAML** tab [renamed to **Full configuration**](https://gitlab.com/gitlab-org/gitlab/-/issues/377404) in GitLab 16.0.
{{< /history >}}
To view the fully expanded CI/CD configuration as one combined file, go to the
pipeline editor's **Full configuration** tab. This tab displays an expanded configuration
where:
- Configuration imported with [`include`](../yaml/_index.md#include) is copied into the view.
- Jobs that use [`extends`](../yaml/_index.md#extends) display with the
[extended configuration merged into the job](../yaml/yaml_optimization.md#merge-details).
- [YAML anchors](../yaml/yaml_optimization.md#anchors) are replaced with the linked configuration.
- [YAML `!reference` tags](../yaml/yaml_optimization.md#reference-tags) are also replaced
with the linked configuration.
- Conditional rules are evaluated assuming a default branch push event.
Using `!reference` tags can cause nested configuration that display with
multiple hyphens (`-`) at the start of the line in the expanded view. This behavior is expected, and the extra
hyphens do not affect the job's execution. For example, this configuration and
fully expanded version are both valid:
- `.gitlab-ci.yml` file:
```yaml
.python-req:
script:
- pip install pyflakes
.rule-01:
rules:
- if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/
when: manual
allow_failure: true
- if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME
.rule-02:
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: manual
allow_failure: true
lint-python:
image: python:latest
script:
- !reference [.python-req, script]
- pyflakes python/
rules:
- !reference [.rule-01, rules]
- !reference [.rule-02, rules]
```
- Expanded configuration in **Full configuration** tab:
```yaml
".python-req":
script:
- pip install pyflakes
".rule-01":
rules:
- if: "$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/"
when: manual
allow_failure: true
- if: "$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME"
".rule-02":
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: manual
allow_failure: true
lint-python:
image: python:latest
script:
- - pip install pyflakes # <- The extra hyphens do not affect the job's execution.
- pyflakes python/
rules:
- - if: "$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/" # <- The extra hyphens do not affect the job's execution.
when: manual
allow_failure: true
- if: "$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME" # <- No extra hyphen but aligned with previous rule
- - if: $CI_COMMIT_BRANCH == "main" # <- The extra hyphens do not affect the job's execution.
when: manual
allow_failure: true
```
## Commit changes to CI configuration
The commit form appears at the bottom of each tab in the editor so you can commit
your changes at any time.
When you are satisfied with your changes, add a descriptive commit message and enter
a branch. The branch field defaults to your project's default branch.
If you enter a new branch name, the **Start a new merge request with these changes**
checkbox appears. Select it to start a new merge request after you commit the changes.

## Editor accessibility options
The pipeline editor is based on the [Monaco Editor](https://github.com/microsoft/monaco-editor)
which has several [accessibility features](https://github.com/microsoft/monaco-editor/wiki/Monaco-Editor-Accessibility-Guide),
including:
| Feature | Shortcut on Windows or Linux | Shortcut on macOS | Details |
|----------------------------------|-----------------------------------|------------------------------------------------------|---------|
| Keyboard navigation command list | <kbd>F1</kbd> | <kbd>F1</kbd> | A [list of commands](https://github.com/microsoft/monaco-editor/wiki/Monaco-Editor-Accessibility-Guide#keyboard-navigation) that make the editor easier to use without a mouse. |
| Tab trapping | <kbd>Control</kbd> + <kbd>m</kbd> | <kbd>Control</kbd> + <kbd>Shift</kbd> + <kbd>m</kbd> | Enable [tab trapping](https://github.com/microsoft/monaco-editor/wiki/Monaco-Editor-Accessibility-Guide#tab-trapping) to go to the next focusable element on the page instead of inserting a tab character. |
## Troubleshooting
### `Unable to validate CI/CD configuration.` message
This message is caused by a problem validating the syntax in the pipeline editor.
It can happen when GitLab is unable to communicate with the service that validates the syntax.
The information in these sections may not display properly:
- The syntax status on the **Edit** tab (valid or invalid).
- The **Visualize** tab.
- The **Lint** tab.
- The **Full configuration** tab.
You can still work on your CI/CD configuration and commit the changes you made without
any issues. As soon as the service becomes available again, the syntax validation
should display immediately.
|
https://docs.gitlab.com/next_steps
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/next_steps.md
|
2025-08-13
|
doc/install
|
[
"doc",
"install"
] |
next_steps.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Steps after installing GitLab
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Here are a few resources you might want to check out after completing the
installation.
## Email and notifications
- [SMTP](https://docs.gitlab.com/omnibus/settings/smtp.html): Configure SMTP
for proper email notifications support.
- [Incoming email](../administration/incoming_email.md): Configure incoming email
so that users can use email to reply to comments, create new issues and merge requests, etc.
## GitLab Duo
- [GitLab Duo](../user/gitlab_duo/_index.md): Learn about the AI-native features that GitLab offers and how to enable them.
- [GitLab Duo Self-Hosted](../administration/gitlab_duo_self_hosted/_index.md): Deploy GitLab Duo Self-Hosted to use your preferred GitLab-supported LLM.
- [GitLab Duo data usage](../user/gitlab_duo/data_usage.md): Learn how GitLab handles AI data privacy.
## CI/CD (Runner)
- [Set up runners](https://docs.gitlab.com/runner/): Set up one or more
runners, the agents that are responsible for running CI/CD jobs.
## Container Registry
- [Container Registry](../administration/packages/container_registry.md): Integrated container registry to store container images for each GitLab project.
- [GitLab Dependency Proxy](../administration/packages/dependency_proxy.md): Set up the dependency
proxy so you can cache container images from Docker Hub for faster, more reliable builds.
## Pages
- [GitLab Pages](../user/project/pages/_index.md): Publish static websites directly from a repository in GitLab
## Security
- [Secure GitLab](../security/_index.md):
Recommended practices to secure your GitLab instance.
- Sign up for the GitLab [Security Newsletter](https://about.gitlab.com/company/preference-center/) to get notified for security updates upon release.
## Authentication
- [LDAP](../administration/auth/ldap/_index.md): Configure LDAP to be used as
an authentication mechanism for GitLab.
- [SAML and OAuth](../integration/omniauth.md): Authenticate via online services like Okta, Google, Azure AD, and more.
## Backup and upgrade
- [Back up and restore GitLab](../administration/backup_restore/_index.md): Learn the different
ways you can back up or restore GitLab.
- [Upgrade GitLab](../update/_index.md): Every month, a new feature-rich GitLab version
is released. Learn how to upgrade to it, or to an interim release that contains a security fix.
- [Release and maintenance policy](../policy/maintenance.md): Learn about GitLab
policies governing version naming, as well as release pace for major, minor and patch releases.
## License
- [Add a license](../administration/license.md) or [start a free trial](https://about.gitlab.com/free-trial/):
Activate all GitLab Enterprise Edition functionality with a license.
- [Pricing](https://about.gitlab.com/pricing/): Pricing for the different tiers.
## Cross-repository Code Search
- [Advanced search](../integration/advanced_search/elasticsearch.md): Leverage [Elasticsearch](https://www.elastic.co/) or [OpenSearch](https://opensearch.org/) for
faster, more advanced code search across your entire GitLab instance.
## Scaling and replication
- [Scaling GitLab](../administration/reference_architectures/_index.md):
GitLab supports several different types of clustering.
- [Geo replication](../administration/geo/_index.md):
Geo is the solution for widely distributed development teams.
## Install the product documentation
Optional. If you want to host the documentation on your own
server, see how to [self-host the product documentation](../administration/docs_self_host.md).
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Steps after installing GitLab
breadcrumbs:
- doc
- install
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
Here are a few resources you might want to check out after completing the
installation.
## Email and notifications
- [SMTP](https://docs.gitlab.com/omnibus/settings/smtp.html): Configure SMTP
for proper email notifications support.
- [Incoming email](../administration/incoming_email.md): Configure incoming email
so that users can use email to reply to comments, create new issues and merge requests, etc.
## GitLab Duo
- [GitLab Duo](../user/gitlab_duo/_index.md): Learn about the AI-native features that GitLab offers and how to enable them.
- [GitLab Duo Self-Hosted](../administration/gitlab_duo_self_hosted/_index.md): Deploy GitLab Duo Self-Hosted to use your preferred GitLab-supported LLM.
- [GitLab Duo data usage](../user/gitlab_duo/data_usage.md): Learn how GitLab handles AI data privacy.
## CI/CD (Runner)
- [Set up runners](https://docs.gitlab.com/runner/): Set up one or more
runners, the agents that are responsible for running CI/CD jobs.
## Container Registry
- [Container Registry](../administration/packages/container_registry.md): Integrated container registry to store container images for each GitLab project.
- [GitLab Dependency Proxy](../administration/packages/dependency_proxy.md): Set up the dependency
proxy so you can cache container images from Docker Hub for faster, more reliable builds.
## Pages
- [GitLab Pages](../user/project/pages/_index.md): Publish static websites directly from a repository in GitLab
## Security
- [Secure GitLab](../security/_index.md):
Recommended practices to secure your GitLab instance.
- Sign up for the GitLab [Security Newsletter](https://about.gitlab.com/company/preference-center/) to get notified for security updates upon release.
## Authentication
- [LDAP](../administration/auth/ldap/_index.md): Configure LDAP to be used as
an authentication mechanism for GitLab.
- [SAML and OAuth](../integration/omniauth.md): Authenticate via online services like Okta, Google, Azure AD, and more.
## Backup and upgrade
- [Back up and restore GitLab](../administration/backup_restore/_index.md): Learn the different
ways you can back up or restore GitLab.
- [Upgrade GitLab](../update/_index.md): Every month, a new feature-rich GitLab version
is released. Learn how to upgrade to it, or to an interim release that contains a security fix.
- [Release and maintenance policy](../policy/maintenance.md): Learn about GitLab
policies governing version naming, as well as release pace for major, minor and patch releases.
## License
- [Add a license](../administration/license.md) or [start a free trial](https://about.gitlab.com/free-trial/):
Activate all GitLab Enterprise Edition functionality with a license.
- [Pricing](https://about.gitlab.com/pricing/): Pricing for the different tiers.
## Cross-repository Code Search
- [Advanced search](../integration/advanced_search/elasticsearch.md): Leverage [Elasticsearch](https://www.elastic.co/) or [OpenSearch](https://opensearch.org/) for
faster, more advanced code search across your entire GitLab instance.
## Scaling and replication
- [Scaling GitLab](../administration/reference_architectures/_index.md):
GitLab supports several different types of clustering.
- [Geo replication](../administration/geo/_index.md):
Geo is the solution for widely distributed development teams.
## Install the product documentation
Optional. If you want to host the documentation on your own
server, see how to [self-host the product documentation](../administration/docs_self_host.md).
|
https://docs.gitlab.com/requirements
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/requirements.md
|
2025-08-13
|
doc/install
|
[
"doc",
"install"
] |
requirements.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
GitLab installation requirements
|
Prerequisites for installation.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
GitLab has specific installation requirements.
## Storage
The necessary storage space largely depends on the size of the repositories you want to have in GitLab.
As a guideline, you should have at least as much free space as all your repositories combined.
The Linux package requires about 2.5 GB of storage space for installation.
For storage flexibility, consider mounting your hard drive through logical volume management.
You should have a hard drive with at least 7,200 RPM or a solid-state drive to reduce response times.
Because file system performance might affect the overall performance of GitLab, you should
[avoid using cloud-based file systems for storage](../administration/nfs.md#avoid-using-cloud-based-file-systems).
## CPU
CPU requirements depend on the number of users and expected workload.
The workload includes your users' activity, use of automation and mirroring, and repository size.
For a maximum of 20 requests per second or 1,000 users, you should have 8 vCPU.
For more users or higher workload,
see [reference architectures](../administration/reference_architectures/_index.md).
## Memory
Memory requirements depend on the number of users and expected workload.
The workload includes your users' activity, use of automation and mirroring, and repository size.
For a maximum of 20 requests per second or 1,000 users, you should have 16 GB of memory.
For more users or higher workload,
see [reference architectures](../administration/reference_architectures/_index.md).
In some cases, GitLab can run with at least 8 GB of memory.
For more information, see
[running GitLab in a memory-constrained environment](https://docs.gitlab.com/omnibus/settings/memory_constrained_envs.html).
## PostgreSQL
[PostgreSQL](https://www.postgresql.org/) is the only supported database and is bundled with the Linux package.
You can also use an [external PostgreSQL database](https://docs.gitlab.com/omnibus/settings/database.html#using-a-non-packaged-postgresql-database-management-server)
[which must be tuned correctly](#postgresql-tuning).
Depending on the [number of users](../administration/reference_architectures/_index.md),
the PostgreSQL server should have:
- For most GitLab instances, at least 5 to 10 GB of storage
- For GitLab Ultimate, at least 12 GB of storage
(1 GB of vulnerability data must be imported)
For the following versions of GitLab, use these PostgreSQL versions:
| GitLab version | Helm chart version | Minimum PostgreSQL version | Maximum PostgreSQL version |
| -------------- | ------------------ | -------------------------- | -------------------------- |
| 18.x | 9.x | 16.x | To be determined |
| 17.x | 8.x | 14.x | 16.x ([tested against GitLab 16.10 and later](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/145298)) |
| 16.x | 7.x | 13.6 | 15.x ([tested against GitLab 16.1 and later](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/119344)) |
| 15.x | 6.x | 12.10 | 14.x ([tested against GitLab 15.11 only](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/114624)), 13.x |
Minor PostgreSQL releases [include only bug and security fixes](https://www.postgresql.org/support/versioning/).
Always use the latest minor version to avoid known issues in PostgreSQL.
For more information, see [issue 364763](https://gitlab.com/gitlab-org/gitlab/-/issues/364763).
To use a later major version of PostgreSQL than specified, check if a
[later version is bundled with the Linux package](http://gitlab-org.gitlab.io/omnibus-gitlab/licenses.html).
You must also ensure some extensions are loaded into every GitLab database.
For more information, see [managing PostgreSQL extensions](postgresql_extensions.md).
### GitLab Geo
For [GitLab Geo](../administration/geo/_index.md), you should use the Linux package or
[validated cloud providers](../administration/reference_architectures/_index.md#recommended-cloud-providers-and-services)
to install GitLab.
Compatibility with other external databases is not guaranteed.
For more information, see [requirements for running Geo](../administration/geo/_index.md#requirements-for-running-geo).
### Locale compatibility
When you change locale data in `glibc`, PostgreSQL database files are
no longer fully compatible between different operating systems.
To avoid index corruption,
[check for locale compatibility](../administration/geo/replication/troubleshooting/common.md#check-os-locale-data-compatibility)
when you:
- Move binary PostgreSQL data between servers.
- Upgrade your Linux distribution.
- Update or change third-party container images.
For more information, see [upgrading operating systems for PostgreSQL](../administration/postgresql/upgrading_os.md).
### GitLab schemas
You should create or use databases exclusively for GitLab, [Geo](../administration/geo/_index.md),
[Gitaly Cluster (Praefect)](../administration/gitaly/praefect/_index.md), or other components.
Do not create or modify databases, schemas, users, or other properties except when you follow:
- Procedures in the GitLab documentation
- The directions of GitLab Support or engineers
The main GitLab application uses three schemas:
- The default `public` schema
- `gitlab_partitions_static` (created automatically)
- `gitlab_partitions_dynamic` (created automatically)
During Rails database migrations, GitLab might create or modify schemas or tables.
Database migrations are tested against the schema definition in the GitLab codebase.
If you modify any schema, [GitLab upgrades](../update/_index.md) might fail.
### PostgreSQL tuning
Here are some required settings for externally managed PostgreSQL instances.
| Tunable setting | Required value | More information |
|:-----------------------|:---------------|:-----------------|
| `work_mem` | minimum `8 MB` | This value is the Linux package default. In large deployments, if queries create temporary files, you should increase this setting. |
| `maintenance_work_mem` | minimum `64 MB` | You require [more for larger database servers](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/8377#note_1728173087). |
| `shared_buffers` | minimum `2 GB` | You require more for larger database servers. The Linux package default is set to 25% of server RAM. |
| `statement_timeout` | maximum 1 min | A statement timeout prevents runaway issues with locks and the database rejecting new clients. One minute matches the Puma rack timeout setting. |
You can configure some PostgreSQL settings for the specific database, rather than for all databases on the server. You might limit configuration to specific databases when hosting
multiple databases on the same server. For guidance on where to apply configuration, consult your database administrator.
## Puma
The recommended [Puma](https://puma.io/) settings depend on your [installation](install_methods.md).
By default, the Linux package uses the recommended settings.
To adjust Puma settings:
- For the Linux package, see [Puma settings](../administration/operations/puma.md).
- For the GitLab Helm chart, see the
[`webservice` chart](https://docs.gitlab.com/charts/charts/gitlab/webservice/).
### Workers
The recommended number of Puma workers largely depends on CPU and memory capacity.
By default, the Linux package uses the recommended number of workers.
For more information about how this number is calculated,
see [`puma.rb`](https://gitlab.com/gitlab-org/omnibus-gitlab/-/blob/master/files/gitlab-cookbooks/gitlab/libraries/puma.rb?ref_type=heads#L46-69).
A node must never have fewer than two Puma workers.
For example, a node should have:
- Two workers for 2 CPU cores and 8 GB of memory
- Two workers for 4 CPU cores and 4 GB of memory
- Four workers for 4 CPU cores and 8 GB of memory
- Six workers for 8 CPU cores and 8 GB of memory
- Eight workers for 8 CPU cores and 16 GB of memory
By default, each Puma worker is limited to 1.2 GB of memory.
You can [adjust this setting](../administration/operations/puma.md#reducing-memory-use) in `/etc/gitlab/gitlab.rb`.
You can also increase the number of Puma workers, provided enough CPU and memory capacity is available.
More workers would reduce response times and improve the ability to handle parallel requests.
Run tests to verify the optimal number of workers for your [installation](install_methods.md).
### Threads
The recommended number of Puma threads depends on total system memory.
A node should use:
- One thread for an operating system with a maximum of 2 GB of memory
- Four threads for an operating system with more than 2 GB of memory
More threads would lead to excessive swapping and lower performance.
## Redis
[Redis](https://redis.io/) stores all user sessions and background tasks
and requires about 25 kB per user on average.
In GitLab 16.0 and later, Redis 6.x or 7.x is required.
For more information about end-of-life dates, see the
[Redis documentation](https://redis.io/docs/latest/operate/rs/installing-upgrading/product-lifecycle/).
For Redis:
- Use a standalone instance (with or without high availability).
Redis Cluster is not supported.
- Set the [eviction policy](../administration/redis/replication_and_failover_external.md#setting-the-eviction-policy) as appropriate.
## Sidekiq
[Sidekiq](https://sidekiq.org/) uses a multi-threaded process for background jobs.
This process initially consumes more than 200 MB of memory
and might grow over time due to memory leaks.
On a very active server with more than 10,000 billable users,
the Sidekiq process might consume more than 1 GB of memory.
## Prometheus
By default, [Prometheus](https://prometheus.io) and its related exporters are enabled to monitor GitLab.
These processes consume approximately 200 MB of memory.
For more information, see
[monitoring GitLab with Prometheus](../administration/monitoring/prometheus/_index.md).
## Supported web browsers
GitLab supports the following web browsers:
- [Mozilla Firefox](https://www.mozilla.org/en-US/firefox/new/)
- [Google Chrome](https://www.google.com/chrome/)
- [Chromium](https://www.chromium.org/getting-involved/dev-channel/)
- [Apple Safari](https://www.apple.com/safari/)
- [Microsoft Edge](https://www.microsoft.com/en-us/edge?form=MA13QK)
GitLab supports:
- The two most recent major versions of these browsers
- The current minor version of a supported major version
Running GitLab with JavaScript disabled in these browsers is not supported.
## Related topics
- [Install GitLab Runner](https://docs.gitlab.com/runner/install/)
- [Secure your installation](../security/_index.md)
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Prerequisites for installation.
title: GitLab installation requirements
breadcrumbs:
- doc
- install
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
GitLab has specific installation requirements.
## Storage
The necessary storage space largely depends on the size of the repositories you want to have in GitLab.
As a guideline, you should have at least as much free space as all your repositories combined.
The Linux package requires about 2.5 GB of storage space for installation.
For storage flexibility, consider mounting your hard drive through logical volume management.
You should have a hard drive with at least 7,200 RPM or a solid-state drive to reduce response times.
Because file system performance might affect the overall performance of GitLab, you should
[avoid using cloud-based file systems for storage](../administration/nfs.md#avoid-using-cloud-based-file-systems).
## CPU
CPU requirements depend on the number of users and expected workload.
The workload includes your users' activity, use of automation and mirroring, and repository size.
For a maximum of 20 requests per second or 1,000 users, you should have 8 vCPU.
For more users or higher workload,
see [reference architectures](../administration/reference_architectures/_index.md).
## Memory
Memory requirements depend on the number of users and expected workload.
The workload includes your users' activity, use of automation and mirroring, and repository size.
For a maximum of 20 requests per second or 1,000 users, you should have 16 GB of memory.
For more users or higher workload,
see [reference architectures](../administration/reference_architectures/_index.md).
In some cases, GitLab can run with at least 8 GB of memory.
For more information, see
[running GitLab in a memory-constrained environment](https://docs.gitlab.com/omnibus/settings/memory_constrained_envs.html).
## PostgreSQL
[PostgreSQL](https://www.postgresql.org/) is the only supported database and is bundled with the Linux package.
You can also use an [external PostgreSQL database](https://docs.gitlab.com/omnibus/settings/database.html#using-a-non-packaged-postgresql-database-management-server)
[which must be tuned correctly](#postgresql-tuning).
Depending on the [number of users](../administration/reference_architectures/_index.md),
the PostgreSQL server should have:
- For most GitLab instances, at least 5 to 10 GB of storage
- For GitLab Ultimate, at least 12 GB of storage
(1 GB of vulnerability data must be imported)
For the following versions of GitLab, use these PostgreSQL versions:
| GitLab version | Helm chart version | Minimum PostgreSQL version | Maximum PostgreSQL version |
| -------------- | ------------------ | -------------------------- | -------------------------- |
| 18.x | 9.x | 16.x | To be determined |
| 17.x | 8.x | 14.x | 16.x ([tested against GitLab 16.10 and later](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/145298)) |
| 16.x | 7.x | 13.6 | 15.x ([tested against GitLab 16.1 and later](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/119344)) |
| 15.x | 6.x | 12.10 | 14.x ([tested against GitLab 15.11 only](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/114624)), 13.x |
Minor PostgreSQL releases [include only bug and security fixes](https://www.postgresql.org/support/versioning/).
Always use the latest minor version to avoid known issues in PostgreSQL.
For more information, see [issue 364763](https://gitlab.com/gitlab-org/gitlab/-/issues/364763).
To use a later major version of PostgreSQL than specified, check if a
[later version is bundled with the Linux package](http://gitlab-org.gitlab.io/omnibus-gitlab/licenses.html).
You must also ensure some extensions are loaded into every GitLab database.
For more information, see [managing PostgreSQL extensions](postgresql_extensions.md).
### GitLab Geo
For [GitLab Geo](../administration/geo/_index.md), you should use the Linux package or
[validated cloud providers](../administration/reference_architectures/_index.md#recommended-cloud-providers-and-services)
to install GitLab.
Compatibility with other external databases is not guaranteed.
For more information, see [requirements for running Geo](../administration/geo/_index.md#requirements-for-running-geo).
### Locale compatibility
When you change locale data in `glibc`, PostgreSQL database files are
no longer fully compatible between different operating systems.
To avoid index corruption,
[check for locale compatibility](../administration/geo/replication/troubleshooting/common.md#check-os-locale-data-compatibility)
when you:
- Move binary PostgreSQL data between servers.
- Upgrade your Linux distribution.
- Update or change third-party container images.
For more information, see [upgrading operating systems for PostgreSQL](../administration/postgresql/upgrading_os.md).
### GitLab schemas
You should create or use databases exclusively for GitLab, [Geo](../administration/geo/_index.md),
[Gitaly Cluster (Praefect)](../administration/gitaly/praefect/_index.md), or other components.
Do not create or modify databases, schemas, users, or other properties except when you follow:
- Procedures in the GitLab documentation
- The directions of GitLab Support or engineers
The main GitLab application uses three schemas:
- The default `public` schema
- `gitlab_partitions_static` (created automatically)
- `gitlab_partitions_dynamic` (created automatically)
During Rails database migrations, GitLab might create or modify schemas or tables.
Database migrations are tested against the schema definition in the GitLab codebase.
If you modify any schema, [GitLab upgrades](../update/_index.md) might fail.
### PostgreSQL tuning
Here are some required settings for externally managed PostgreSQL instances.
| Tunable setting | Required value | More information |
|:-----------------------|:---------------|:-----------------|
| `work_mem` | minimum `8 MB` | This value is the Linux package default. In large deployments, if queries create temporary files, you should increase this setting. |
| `maintenance_work_mem` | minimum `64 MB` | You require [more for larger database servers](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/8377#note_1728173087). |
| `shared_buffers` | minimum `2 GB` | You require more for larger database servers. The Linux package default is set to 25% of server RAM. |
| `statement_timeout` | maximum 1 min | A statement timeout prevents runaway issues with locks and the database rejecting new clients. One minute matches the Puma rack timeout setting. |
You can configure some PostgreSQL settings for the specific database, rather than for all databases on the server. You might limit configuration to specific databases when hosting
multiple databases on the same server. For guidance on where to apply configuration, consult your database administrator.
## Puma
The recommended [Puma](https://puma.io/) settings depend on your [installation](install_methods.md).
By default, the Linux package uses the recommended settings.
To adjust Puma settings:
- For the Linux package, see [Puma settings](../administration/operations/puma.md).
- For the GitLab Helm chart, see the
[`webservice` chart](https://docs.gitlab.com/charts/charts/gitlab/webservice/).
### Workers
The recommended number of Puma workers largely depends on CPU and memory capacity.
By default, the Linux package uses the recommended number of workers.
For more information about how this number is calculated,
see [`puma.rb`](https://gitlab.com/gitlab-org/omnibus-gitlab/-/blob/master/files/gitlab-cookbooks/gitlab/libraries/puma.rb?ref_type=heads#L46-69).
A node must never have fewer than two Puma workers.
For example, a node should have:
- Two workers for 2 CPU cores and 8 GB of memory
- Two workers for 4 CPU cores and 4 GB of memory
- Four workers for 4 CPU cores and 8 GB of memory
- Six workers for 8 CPU cores and 8 GB of memory
- Eight workers for 8 CPU cores and 16 GB of memory
By default, each Puma worker is limited to 1.2 GB of memory.
You can [adjust this setting](../administration/operations/puma.md#reducing-memory-use) in `/etc/gitlab/gitlab.rb`.
You can also increase the number of Puma workers, provided enough CPU and memory capacity is available.
More workers would reduce response times and improve the ability to handle parallel requests.
Run tests to verify the optimal number of workers for your [installation](install_methods.md).
### Threads
The recommended number of Puma threads depends on total system memory.
A node should use:
- One thread for an operating system with a maximum of 2 GB of memory
- Four threads for an operating system with more than 2 GB of memory
More threads would lead to excessive swapping and lower performance.
## Redis
[Redis](https://redis.io/) stores all user sessions and background tasks
and requires about 25 kB per user on average.
In GitLab 16.0 and later, Redis 6.x or 7.x is required.
For more information about end-of-life dates, see the
[Redis documentation](https://redis.io/docs/latest/operate/rs/installing-upgrading/product-lifecycle/).
For Redis:
- Use a standalone instance (with or without high availability).
Redis Cluster is not supported.
- Set the [eviction policy](../administration/redis/replication_and_failover_external.md#setting-the-eviction-policy) as appropriate.
## Sidekiq
[Sidekiq](https://sidekiq.org/) uses a multi-threaded process for background jobs.
This process initially consumes more than 200 MB of memory
and might grow over time due to memory leaks.
On a very active server with more than 10,000 billable users,
the Sidekiq process might consume more than 1 GB of memory.
## Prometheus
By default, [Prometheus](https://prometheus.io) and its related exporters are enabled to monitor GitLab.
These processes consume approximately 200 MB of memory.
For more information, see
[monitoring GitLab with Prometheus](../administration/monitoring/prometheus/_index.md).
## Supported web browsers
GitLab supports the following web browsers:
- [Mozilla Firefox](https://www.mozilla.org/en-US/firefox/new/)
- [Google Chrome](https://www.google.com/chrome/)
- [Chromium](https://www.chromium.org/getting-involved/dev-channel/)
- [Apple Safari](https://www.apple.com/safari/)
- [Microsoft Edge](https://www.microsoft.com/en-us/edge?form=MA13QK)
GitLab supports:
- The two most recent major versions of these browsers
- The current minor version of a supported major version
Running GitLab with JavaScript disabled in these browsers is not supported.
## Related topics
- [Install GitLab Runner](https://docs.gitlab.com/runner/install/)
- [Secure your installation](../security/_index.md)
|
https://docs.gitlab.com/install_methods
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install_methods.md
|
2025-08-13
|
doc/install
|
[
"doc",
"install"
] |
install_methods.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Installation methods
|
Linux, Helm, Docker, Operator, source, or scripts.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can install GitLab on several [cloud providers](cloud_providers.md),
or use one of the following methods.
## Linux package
The Linux package includes the official `deb` and `rpm` packages. The package has GitLab and dependent components, including PostgreSQL, Redis, and Sidekiq.
Use if you want the most mature, scalable method. This version is also used on GitLab.com.
For more information, see:
- [Linux package](package/_index.md)
- [Reference architectures](../administration/reference_architectures/_index.md)
- [System requirements](requirements.md)
- [Supported Linux operating systems](package/_index.md#supported-platforms)
## Helm chart
Use a chart to install a cloud-native version of GitLab and its components on Kubernetes.
Use if your infrastructure is on Kubernetes and you're familiar with how it works.
Before you use this installation method, consider that:
- Management, observability, and some other concepts are different than traditional deployments.
- Administration and troubleshooting requires Kubernetes knowledge.
- It can be more expensive for smaller installations.
- The default installation requires more resources than a single node Linux package deployment, because most services are deployed in a redundant fashion.
For more information, see [Helm charts](https://docs.gitlab.com/charts/).
## GitLab Operator
To install a cloud-native version of GitLab and its components in Kubernetes, use GitLab Operator.
This installation and management method follows the [Kubernetes Operator pattern](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/).
Use if your infrastructure is on Kubernetes or [OpenShift](openshift_and_gitlab/_index.md), and you're familiar with how Operators work.
This installation method provides additional functionality beyond the Helm chart installation method, including automation of the [GitLab upgrade steps](https://docs.gitlab.com/operator/gitlab_upgrades.html). The considerations for the Helm chart also apply here.
Consider the Helm chart installation method if you are limited by [GitLab Operator known issues](https://docs.gitlab.com/operator/#known-issues).
For more information, see [GitLab Operator](https://docs.gitlab.com/operator/).
## Docker
Installs the GitLab packages in a Docker container.
Use if you're familiar with Docker.
For more information, see [Docker](docker/_index.md).
## Self-compiled
Installs GitLab and its components from scratch.
Use if none of the previous methods are available for your platform. Can use for unsupported systems like \*BSD.
For more information, see [self-compiled installation](installation.md).
## GitLab Environment Toolkit (GET)
[GitLab Environment Toolkit (GET)](https://gitlab.com/gitlab-org/gitlab-environment-toolkit#documentation) is a set of opinionated Terraform and Ansible scripts.
Use to deploy a [reference architecture](../administration/reference_architectures/_index.md) on selected major cloud providers.
This installation methods has some [limitations](https://gitlab.com/gitlab-org/gitlab-environment-toolkit#missing-features-to-be-aware-of), and requires manual setup for production environments.
## Unsupported Linux distributions and Unix-like operating systems
[Self-compiled installation](installation.md) of GitLab on the following operating systems is possible, but not supported:
- Arch Linux
- FreeBSD
- Gentoo
- macOS
## Microsoft Windows
GitLab is developed for Linux-based operating systems.
It does **not** run on Microsoft Windows, and we have no plans to support it in the near future. For the latest development status, view this [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/22337).
Consider using a virtual machine to run GitLab.
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Linux, Helm, Docker, Operator, source, or scripts.
title: Installation methods
breadcrumbs:
- doc
- install
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can install GitLab on several [cloud providers](cloud_providers.md),
or use one of the following methods.
## Linux package
The Linux package includes the official `deb` and `rpm` packages. The package has GitLab and dependent components, including PostgreSQL, Redis, and Sidekiq.
Use if you want the most mature, scalable method. This version is also used on GitLab.com.
For more information, see:
- [Linux package](package/_index.md)
- [Reference architectures](../administration/reference_architectures/_index.md)
- [System requirements](requirements.md)
- [Supported Linux operating systems](package/_index.md#supported-platforms)
## Helm chart
Use a chart to install a cloud-native version of GitLab and its components on Kubernetes.
Use if your infrastructure is on Kubernetes and you're familiar with how it works.
Before you use this installation method, consider that:
- Management, observability, and some other concepts are different than traditional deployments.
- Administration and troubleshooting requires Kubernetes knowledge.
- It can be more expensive for smaller installations.
- The default installation requires more resources than a single node Linux package deployment, because most services are deployed in a redundant fashion.
For more information, see [Helm charts](https://docs.gitlab.com/charts/).
## GitLab Operator
To install a cloud-native version of GitLab and its components in Kubernetes, use GitLab Operator.
This installation and management method follows the [Kubernetes Operator pattern](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/).
Use if your infrastructure is on Kubernetes or [OpenShift](openshift_and_gitlab/_index.md), and you're familiar with how Operators work.
This installation method provides additional functionality beyond the Helm chart installation method, including automation of the [GitLab upgrade steps](https://docs.gitlab.com/operator/gitlab_upgrades.html). The considerations for the Helm chart also apply here.
Consider the Helm chart installation method if you are limited by [GitLab Operator known issues](https://docs.gitlab.com/operator/#known-issues).
For more information, see [GitLab Operator](https://docs.gitlab.com/operator/).
## Docker
Installs the GitLab packages in a Docker container.
Use if you're familiar with Docker.
For more information, see [Docker](docker/_index.md).
## Self-compiled
Installs GitLab and its components from scratch.
Use if none of the previous methods are available for your platform. Can use for unsupported systems like \*BSD.
For more information, see [self-compiled installation](installation.md).
## GitLab Environment Toolkit (GET)
[GitLab Environment Toolkit (GET)](https://gitlab.com/gitlab-org/gitlab-environment-toolkit#documentation) is a set of opinionated Terraform and Ansible scripts.
Use to deploy a [reference architecture](../administration/reference_architectures/_index.md) on selected major cloud providers.
This installation methods has some [limitations](https://gitlab.com/gitlab-org/gitlab-environment-toolkit#missing-features-to-be-aware-of), and requires manual setup for production environments.
## Unsupported Linux distributions and Unix-like operating systems
[Self-compiled installation](installation.md) of GitLab on the following operating systems is possible, but not supported:
- Arch Linux
- FreeBSD
- Gentoo
- macOS
## Microsoft Windows
GitLab is developed for Linux-based operating systems.
It does **not** run on Microsoft Windows, and we have no plans to support it in the near future. For the latest development status, view this [issue](https://gitlab.com/gitlab-org/gitlab/-/issues/22337).
Consider using a virtual machine to run GitLab.
|
https://docs.gitlab.com/relative_url
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/relative_url.md
|
2025-08-13
|
doc/install
|
[
"doc",
"install"
] |
relative_url.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install GitLab under a relative URL
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
While you should install GitLab on its own (sub)domain, sometimes
this is not possible due to a variety of reasons. In that case, GitLab can also
be installed under a relative URL, for example `https://example.com/gitlab`.
This document describes how to run GitLab under a relative URL for installations
from source. If you are using an official Linux package,
[the steps are different](https://docs.gitlab.com/omnibus/settings/configuration.html#configuring-a-relative-url-for-gitlab). Use this guide along with the
[installation guide](self_compiled/_index.md) if you are installing GitLab for the
first time.
There is no limit to how deeply nested the relative URL can be. For example you
could serve GitLab under `/foo/bar/gitlab/git` without any issues.
Changing the URL on an existing GitLab installation, changes all remote
URLs, so you have to manually edit them in any local repository
that points to your GitLab instance.
The list of configuration files you must change to serve GitLab from a
relative URL is:
- `/home/git/gitlab/config/initializers/relative_url.rb`
- `/home/git/gitlab/config/gitlab.yml`
- `/home/git/gitlab/config/puma.rb`
- `/home/git/gitlab-shell/config.yml`
- `/etc/default/gitlab`
After all the changes, you must recompile the assets and [restart GitLab](../administration/restart_gitlab.md#self-compiled-installations).
## Relative URL requirements
If you configure GitLab with a relative URL, the assets (including JavaScript,
CSS, fonts, and images) must be recompiled, which can consume a lot of CPU and
memory resources. To avoid out-of-memory errors, you should have at least 2 GB
of RAM available on your computer, and we recommend 4 GB RAM, and four or eight
CPU cores.
See the [requirements](requirements.md) document for more information.
## Enable relative URL in GitLab
{{< alert type="note" >}}
Do not make any changes to your web server configuration file regarding
relative URL. The relative URL support is implemented by GitLab Workhorse.
{{< /alert >}}
---
This process assumes:
- GitLab is served under `/gitlab`
- The directory under which GitLab is installed is `/home/git/`
To enable relative URLs in GitLab:
1. Optional. If you run short on resources, you can temporarily free up some
memory by shutting down the GitLab service with the following command:
```shell
sudo service gitlab stop
```
1. Create `/home/git/gitlab/config/initializers/relative_url.rb`
```shell
cp /home/git/gitlab/config/initializers/relative_url.rb.sample \
/home/git/gitlab/config/initializers/relative_url.rb
```
and change the following line:
```ruby
config.relative_url_root = "/gitlab"
```
1. Edit `/home/git/gitlab/config/gitlab.yml` and uncomment/change the
following line:
```yaml
relative_url_root: /gitlab
```
1. Edit `/home/git/gitlab/config/puma.rb` and uncomment/change the
following line:
```ruby
ENV['RAILS_RELATIVE_URL_ROOT'] = "/gitlab"
```
1. Edit `/home/git/gitlab-shell/config.yml` and append the relative path to
the following line:
```yaml
gitlab_url: http://127.0.0.1/gitlab
```
1. Make sure you have copied either the supplied systemd services, or the init
script and the defaults file, as stated in the
[installation guide](self_compiled/_index.md#install-the-service).
Then, edit `/etc/default/gitlab` and set in `gitlab_workhorse_options` the
`-authBackend` setting to read like:
```shell
-authBackend http://127.0.0.1:8080/gitlab
```
{{< alert type="note" >}}
If you are using a custom init script, make sure to edit the previous
GitLab Workhorse setting as needed.
{{< /alert >}}
1. [Restart GitLab](../administration/restart_gitlab.md#self-compiled-installations) for the changes to take effect.
## Disable relative URL in GitLab
To disable the relative URL:
1. Remove `/home/git/gitlab/config/initializers/relative_url.rb`
1. Follow the previous steps starting from 2. and set up the
GitLab URL to one that doesn't contain a relative path.
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Install GitLab under a relative URL
breadcrumbs:
- doc
- install
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
While you should install GitLab on its own (sub)domain, sometimes
this is not possible due to a variety of reasons. In that case, GitLab can also
be installed under a relative URL, for example `https://example.com/gitlab`.
This document describes how to run GitLab under a relative URL for installations
from source. If you are using an official Linux package,
[the steps are different](https://docs.gitlab.com/omnibus/settings/configuration.html#configuring-a-relative-url-for-gitlab). Use this guide along with the
[installation guide](self_compiled/_index.md) if you are installing GitLab for the
first time.
There is no limit to how deeply nested the relative URL can be. For example you
could serve GitLab under `/foo/bar/gitlab/git` without any issues.
Changing the URL on an existing GitLab installation, changes all remote
URLs, so you have to manually edit them in any local repository
that points to your GitLab instance.
The list of configuration files you must change to serve GitLab from a
relative URL is:
- `/home/git/gitlab/config/initializers/relative_url.rb`
- `/home/git/gitlab/config/gitlab.yml`
- `/home/git/gitlab/config/puma.rb`
- `/home/git/gitlab-shell/config.yml`
- `/etc/default/gitlab`
After all the changes, you must recompile the assets and [restart GitLab](../administration/restart_gitlab.md#self-compiled-installations).
## Relative URL requirements
If you configure GitLab with a relative URL, the assets (including JavaScript,
CSS, fonts, and images) must be recompiled, which can consume a lot of CPU and
memory resources. To avoid out-of-memory errors, you should have at least 2 GB
of RAM available on your computer, and we recommend 4 GB RAM, and four or eight
CPU cores.
See the [requirements](requirements.md) document for more information.
## Enable relative URL in GitLab
{{< alert type="note" >}}
Do not make any changes to your web server configuration file regarding
relative URL. The relative URL support is implemented by GitLab Workhorse.
{{< /alert >}}
---
This process assumes:
- GitLab is served under `/gitlab`
- The directory under which GitLab is installed is `/home/git/`
To enable relative URLs in GitLab:
1. Optional. If you run short on resources, you can temporarily free up some
memory by shutting down the GitLab service with the following command:
```shell
sudo service gitlab stop
```
1. Create `/home/git/gitlab/config/initializers/relative_url.rb`
```shell
cp /home/git/gitlab/config/initializers/relative_url.rb.sample \
/home/git/gitlab/config/initializers/relative_url.rb
```
and change the following line:
```ruby
config.relative_url_root = "/gitlab"
```
1. Edit `/home/git/gitlab/config/gitlab.yml` and uncomment/change the
following line:
```yaml
relative_url_root: /gitlab
```
1. Edit `/home/git/gitlab/config/puma.rb` and uncomment/change the
following line:
```ruby
ENV['RAILS_RELATIVE_URL_ROOT'] = "/gitlab"
```
1. Edit `/home/git/gitlab-shell/config.yml` and append the relative path to
the following line:
```yaml
gitlab_url: http://127.0.0.1/gitlab
```
1. Make sure you have copied either the supplied systemd services, or the init
script and the defaults file, as stated in the
[installation guide](self_compiled/_index.md#install-the-service).
Then, edit `/etc/default/gitlab` and set in `gitlab_workhorse_options` the
`-authBackend` setting to read like:
```shell
-authBackend http://127.0.0.1:8080/gitlab
```
{{< alert type="note" >}}
If you are using a custom init script, make sure to edit the previous
GitLab Workhorse setting as needed.
{{< /alert >}}
1. [Restart GitLab](../administration/restart_gitlab.md#self-compiled-installations) for the changes to take effect.
## Disable relative URL in GitLab
To disable the relative URL:
1. Remove `/home/git/gitlab/config/initializers/relative_url.rb`
1. Follow the previous steps starting from 2. and set up the
GitLab URL to one that doesn't contain a relative path.
|
https://docs.gitlab.com/install
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/_index.md
|
2025-08-13
|
doc/install
|
[
"doc",
"install"
] |
_index.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install GitLab
|
Read through the GitLab installation methods.
|
You can install GitLab on most GNU/Linux distributions, on several
cloud providers, and in Kubernetes clusters.
To get the best experience, you should balance performance, reliability,
ease of administration (backups, upgrades, and troubleshooting) with the cost of hosting.
{{< cards >}}
- [Installation requirements](requirements.md)
- [Installation methods](install_methods.md)
- [Install GitLab on a cloud provider](cloud_providers.md)
- [Offline GitLab](../topics/offline/_index.md)
- [Reference architectures](../administration/reference_architectures/_index.md)
- [Upgrade GitLab](../update/_index.md)
- [Install GitLab Runner](https://docs.gitlab.com/runner/install/)
- [Configure GitLab Runner](https://docs.gitlab.com/runner/configuration/)
- [Install GitLab AI gateway](install_ai_gateway.md)
{{< /cards >}}
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Read through the GitLab installation methods.
title: Install GitLab
breadcrumbs:
- doc
- install
---
You can install GitLab on most GNU/Linux distributions, on several
cloud providers, and in Kubernetes clusters.
To get the best experience, you should balance performance, reliability,
ease of administration (backups, upgrades, and troubleshooting) with the cost of hosting.
{{< cards >}}
- [Installation requirements](requirements.md)
- [Installation methods](install_methods.md)
- [Install GitLab on a cloud provider](cloud_providers.md)
- [Offline GitLab](../topics/offline/_index.md)
- [Reference architectures](../administration/reference_architectures/_index.md)
- [Upgrade GitLab](../update/_index.md)
- [Install GitLab Runner](https://docs.gitlab.com/runner/install/)
- [Configure GitLab Runner](https://docs.gitlab.com/runner/configuration/)
- [Install GitLab AI gateway](install_ai_gateway.md)
{{< /cards >}}
|
https://docs.gitlab.com/cloud_providers
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/cloud_providers.md
|
2025-08-13
|
doc/install
|
[
"doc",
"install"
] |
cloud_providers.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install GitLab on a cloud provider
|
AWS, Google Cloud Platform, Azure.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can install GitLab on several cloud providers.
| Cloud provider | Description |
|----------------------------------------------------------------|-------------|
| [AWS](aws/_index.md) | Install GitLab on AWS using the community AMIs provided by GitLab. |
| [Google Cloud Platform (GCP)](google_cloud_platform/_index.md) | Install GitLab on a VM in GCP. |
| [Azure](azure/_index.md) | Install GitLab from Azure Marketplace. |
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: AWS, Google Cloud Platform, Azure.
title: Install GitLab on a cloud provider
breadcrumbs:
- doc
- install
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can install GitLab on several cloud providers.
| Cloud provider | Description |
|----------------------------------------------------------------|-------------|
| [AWS](aws/_index.md) | Install GitLab on AWS using the community AMIs provided by GitLab. |
| [Google Cloud Platform (GCP)](google_cloud_platform/_index.md) | Install GitLab on a VM in GCP. |
| [Azure](azure/_index.md) | Install GitLab from Azure Marketplace. |
|
https://docs.gitlab.com/installation
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/installation.md
|
2025-08-13
|
doc/install
|
[
"doc",
"install"
] |
installation.md
| null | null | null | null | null |
<!-- markdownlint-disable -->
This document was moved to [another location](self_compiled/_index.md).
<!-- This redirect file can be deleted after <2025-10-30>. -->
<!-- Redirects that point to other docs in the same project expire in three months. -->
<!-- Redirects that point to docs in a different project or site (link is not relative and starts with `https:`) expire in one year. -->
<!-- Before deletion, see: https://docs.gitlab.com/ee/development/documentation/redirects.html -->
|
---
redirect_to: self_compiled/_index.md
remove_date: '2025-10-30'
breadcrumbs:
- doc
- install
---
<!-- markdownlint-disable -->
This document was moved to [another location](self_compiled/_index.md).
<!-- This redirect file can be deleted after <2025-10-30>. -->
<!-- Redirects that point to other docs in the same project expire in three months. -->
<!-- Redirects that point to docs in a different project or site (link is not relative and starts with `https:`) expire in one year. -->
<!-- Before deletion, see: https://docs.gitlab.com/ee/development/documentation/redirects.html -->
|
https://docs.gitlab.com/install_ai_gateway
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install_ai_gateway.md
|
2025-08-13
|
doc/install
|
[
"doc",
"install"
] |
install_ai_gateway.md
|
AI-powered
|
AI Framework
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install the GitLab AI gateway
|
Gateway between GitLab and large language models.
|
The [AI gateway](../user/gitlab_duo/gateway.md)
is a standalone service that gives access to AI-native GitLab Duo features.
## Install by using Docker
The GitLab AI gateway Docker image contains all necessary code and dependencies
in a single container.
Prerequisites:
- Install a Docker container engine, like [Docker](https://docs.docker.com/engine/install/#server).
- Use a valid hostname that is accessible in your network. Do not use `localhost`.
- Ensure you have approximately 340 MB (compressed) for the `linux/amd64` architecture and
a minimum of 512 MB of RAM.
To ensure better performance, especially under heavy usage, consider allocating
more disk space, memory, and resources than the minimum requirements.
Higher RAM and disk capacity can enhance the AI gateway's efficiency during peak loads.
A GPU is not needed for the GitLab AI gateway.
### Find the AI gateway image
The GitLab official Docker image is available:
- In the container registry:
- [Stable](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/container_registry/3809284?orderBy=PUBLISHED_AT&search%5B%5D=self-hosted)
- [Nightly](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/container_registry/8086262)
- On DockerHub:
- [Stable](https://hub.docker.com/r/gitlab/model-gateway/tags)
- [Nightly](https://hub.docker.com/r/gitlab/model-gateway-self-hosted/tags)
[View the release process for the self-hosted AI gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/-/blob/main/docs/release.md).
If your GitLab version is `vX.Y.*-ee`, use the AI gateway Docker image with the latest `self-hosted-vX.Y.*-ee` tag. For example, if GitLab is on version `v18.2.1-ee`, and the AI gateway Docker image has:
- Versions `self-hosted-v18.2.0-ee`, `self-hosted-v18.2.1-ee`, and `self-hosted-v18.2.2-ee`, use `self-hosted-v18.2.2-ee`.
- Versions `self-hosted-v18.2.0-ee` and `self-hosted-v18.2.1-ee`, use `self-hosted-v18.2.1-ee`.
- Only one version, `self-hosted-v18.2.0-ee`, use `self-hosted-v18.2.0-ee`.
Newer features are available from nightly builds, but backwards compatibility is not guaranteed.
{{< alert type="note" >}}
Using the nightly version is **not recommended** because it can cause incompatibility if your GitLab version is behind or ahead of the AI gateway release. Always use an explicit version tag.
{{< /alert >}}
### Start a container from the image
1. Run the following command, replacing `<your_gitlab_instance>` and `<your_gitlab_domain>` with your GitLab instance's URL and domain:
```shell
docker run -d -p 5052:5052 \
-e AIGW_GITLAB_URL=<your_gitlab_instance> \
-e AIGW_GITLAB_API_URL=https://<your_gitlab_domain>/api/v4/ \
registry.gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/model-gateway:<ai-gateway-tag> \
```
Replace `<ai-gateway-tag>` with the version that matches your GitLab instance. For example, if your GitLab version is `vX.Y.0`, use `self-hosted-vX.Y.0-ee`.
From the container host, accessing `http://localhost:5052` should return `{"error":"No authorization header presented"}`.
1. Ensure that port `5052` is forwarded to the container from the host and configure the AI gateway URL through the [Rails console](../administration/operations/rails_console.md):
```ruby
Ai::Setting.instance.update!(ai_gateway_url: 'http://ai-gateway-host.example.com:5052')
```
You should configure the URL this way because the URL is stored in the database, and you can then manage it through the Admin area. Although the `AI_GATEWAY_URL` environment variable is still supported for legacy reasons, using the database setting is preferred for better configuration management.
If you encounter issues loading the PEM file, resulting in errors like `JWKError`, you may need to resolve an SSL certificate error.
To fix this issue, set the appropriate certificate bundle path in the Docker container by using the following environment variables:
- `SSL_CERT_FILE=/path/to/ca-bundle.pem`
- `REQUESTS_CA_BUNDLE=/path/to/ca-bundle.pem`
Replace `/path/to/ca-bundle.pem` with the actual path to your certificate bundle.
## Set up Docker with NGINX and SSL
{{< alert type="note" >}}
This method of deploying NGINX or Caddy as a reverse proxy is a temporary workaround to support SSL
until [issue 455854](https://gitlab.com/gitlab-org/gitlab/-/issues/455854)
is implemented.
{{< /alert >}}
You can set up SSL for an AI gateway instance by using Docker,
NGINX as a reverse proxy, and Let's Encrypt for SSL certificates.
NGINX manages the secure connection with external clients, decrypting incoming HTTPS requests before
passing them to the AI gateway.
Prerequisites:
- Docker and Docker Compose installed
- Registered and configured domain name
### Create configuration files
Start by creating the following files in your working directory.
1. `nginx.conf`:
```nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
```
1. `default.conf`:
```nginx
# nginx/conf.d/default.conf
server {
listen 80;
server_name _;
# Forward all requests to the AI gateway
location / {
proxy_pass http://gitlab-ai-gateway:5052;
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
proxy_buffering off;
}
}
server {
listen 443 ssl;
server_name _;
# SSL configuration
ssl_certificate /etc/nginx/ssl/server.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
# Configuration for self-signed certificates
ssl_verify_client off;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# Proxy headers
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket support (if needed)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# Forward all requests to the AI gateway
location / {
proxy_pass http://gitlab-ai-gateway:5052;
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
proxy_buffering off;
}
}
```
### Set up SSL certificate by using Let's Encrypt
Now set up an SSL certificate:
- For Docker-based NGINX servers, Certbot
[provides an automated way to implement Let's Encrypt certificates](https://phoenixnap.com/kb/letsencrypt-docker).
- Alternatively, you can use the [Certbot manual installation](https://eff-certbot.readthedocs.io/en/stable/using.html#manual).
### Create Docker-compose file
Now create a `docker-compose.yaml` file.
```yaml
version: '3.8'
services:
nginx-proxy:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- /path/to/nginx.conf:/etc/nginx/nginx.conf:ro
- /path/to/default.conf:/etc/nginx/conf.d/default.conf:ro
- /path/to/fullchain.pem:/etc/nginx/ssl/server.crt:ro
- /path/to/privkey.pem:/etc/nginx/ssl/server.key:ro
networks:
- proxy-network
depends_on:
- gitlab-ai-gateway
gitlab-ai-gateway:
image: registry.gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/model-gateway:<ai-gateway-tag>
expose:
- "5052"
environment:
- AIGW_GITLAB_URL=<your_gitlab_instance>
- AIGW_GITLAB_API_URL=https://<your_gitlab_domain>/api/v4/
networks:
- proxy-network
restart: always
networks:
proxy-network:
driver: bridge
```
### Deploy and validate
Noe deploy and validate the solution.
1. Start the `nginx` and `AIGW` containers and verify that they're running:
```shell
docker-compose up
docker ps
```
1. Configure your [GitLab instance to access the AI gateway](../administration/gitlab_duo_self_hosted/configure_duo_features.md#configure-your-gitlab-instance-to-access-the-ai-gateway).
1. Perform the health check and confirm that the AI gateway is accessible.
## Install by using Helm chart
Prerequisites:
- You must have a:
- Domain you own, to which you can add a DNS record.
- Kubernetes cluster.
- Working installation of `kubectl`.
- Working installation of Helm, version v3.11.0 or later.
For more information, see [Test the GitLab chart on GKE or EKS](https://docs.gitlab.com/charts/quickstart/).
### Add the AI gateway Helm repository
Add the AI gateway Helm repository to the Helm configuration:
```shell
helm repo add ai-gateway \
https://gitlab.com/api/v4/projects/gitlab-org%2fcharts%2fai-gateway-helm-chart/packages/helm/devel
```
### Install the AI gateway
1. Create the `ai-gateway` namespace:
```shell
kubectl create namespace ai-gateway
```
1. Generate the certificate for the domain where you plan to expose the AI gateway.
1. Create the TLS secret in the previously created namespace:
```shell
kubectl -n ai-gateway create secret tls ai-gateway-tls --cert="<path_to_cert>" --key="<path_to_cert_key>"
```
1. For the AI gateway to access the API, it must know where the GitLab instance
is located. To do this, set the `gitlab.url` and `gitlab.apiUrl` together with
the `ingress.hosts` and `ingress.tls` values as follows:
```shell
helm repo add ai-gateway \
https://gitlab.com/api/v4/projects/gitlab-org%2fcharts%2fai-gateway-helm-chart/packages/helm/devel
helm repo update
helm upgrade --install ai-gateway \
ai-gateway/ai-gateway \
--version 0.5.0 \
--namespace=ai-gateway \
--set="image.tag=<ai-gateway-image-version>" \
--set="gitlab.url=https://<your_gitlab_domain>" \
--set="gitlab.apiUrl=https://<your_gitlab_domain>/api/v4/" \
--set "ingress.enabled=true" \
--set "ingress.hosts[0].host=<your_gateway_domain>" \
--set "ingress.hosts[0].paths[0].path=/" \
--set "ingress.hosts[0].paths[0].pathType=ImplementationSpecific" \
--set "ingress.tls[0].secretName=ai-gateway-tls" \
--set "ingress.tls[0].hosts[0]=<your_gateway_domain>" \
--set="ingress.className=nginx" \
--timeout=300s --wait --wait-for-jobs
```
You can find the list of AI gateway versions that can be used as `image.tag` in the [container registry](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/container_registry/3809284?orderBy=PUBLISHED_AT&search%5B%5D=self-hosted).
This step can take will take a few seconds in order for all resources to be allocated
and the AI gateway to start.
You might need to set up your own **Ingress Controller** for the AI gateway if your existing `nginx` Ingress controller does not serve services in a different namespace. Make sure Ingress is set up correctly for multi-namespace deployments.
For versions of the `ai-gateway` Helm chart, use `helm search repo ai-gateway --versions` to find the appropriate chart version.
Wait for your pods to get up and running:
```shell
kubectl wait pod \
--all \
--for=condition=Ready \
--namespace=ai-gateway \
--timeout=300s
```
When your pods are up and running, you can set up your IP ingresses and DNS records.
## Upgrade the AI gateway Docker image
To upgrade the AI gateway, download the newest Docker image tag.
1. Stop the running container:
```shell
sudo docker stop gitlab-aigw
```
1. Remove the existing container:
```shell
sudo docker rm gitlab-aigw
```
1. Pull and [run the new image](#start-a-container-from-the-image).
1. Ensure that the environment variables are all set correctly.
## Alternative installation methods
For information on alternative ways to install the AI gateway, see
[issue 463773](https://gitlab.com/gitlab-org/gitlab/-/issues/463773).
## Health check and debugging
To debug issues with your self-hosted Duo installation, run the following command:
```shell
sudo gitlab-rake gitlab:duo:verify_self_hosted_setup
```
Ensure that:
- The AI gateway URL is correctly configured (through `Ai::Setting.instance.ai_gateway_url`).
- Duo access has been explicitly enabled for the root user through `/admin/code_suggestions`.
If access issues persist, check that authentication is correctly configured, and that the health check passes.
In case of persistent issues, the error message may suggest bypassing authentication with `AIGW_AUTH__BYPASS_EXTERNAL=true`, but only do this for troubleshooting.
You can also run a [health check](../administration/gitlab_duo/setup.md#run-a-health-check-for-gitlab-duo) by going to **Admin > GitLab Duo**.
These tests are performed for offline environments:
| Test | Description |
|-----------------|-------------|
| Network | Tests whether: <br>- The AI gateway URL has been properly configured in the database through the `ai_settings` table.<br> - Your instance can connect to the configured URL.<br><br>If your instance cannot connect to the URL, ensure that your firewall or proxy server settings [allow connection](../user/gitlab_duo/setup.md). Although the environment variable `AI_GATEWAY_URL` is still supported for legacy compatibility, configuring the URL through the database is recommended for better manageability. |
| License | Tests whether your license has the ability to access Code Suggestions feature. |
| System exchange | Tests whether Code Suggestions can be used in your instance. If the system exchange assessment fails, users might not be able to use GitLab Duo features. |
## Does the AI gateway need to autoscale?
Autoscaling is not mandatory but is recommended for environments with variable workloads, high concurrency requirements, or unpredictable usage patterns. In the GitLab production environment:
- Baseline setup: A single AI gateway instance with 2 CPU cores and 8 GB RAM can handle approximately 40 concurrent requests.
- Scaling guidelines: For larger setups, such as an AWS t3.2xlarge instance (8 vCPUs, 32 GB RAM), the gateway can handle up to 160 concurrent requests, equivalent to 4x the baseline setup.
- Request throughput: GitLab.com's observed usage suggests that 7 RPS (requests per second) per 1000 active users is a reasonable metric for planning.
- Autoscaling options: Use Kubernetes Horizontal Pod Autoscalers (HPA) or similar mechanisms to dynamically adjust the number of instances based on metrics like CPU, memory utilization, or request latency thresholds.
## Configuration examples by deployment size
- Small deployment:
- Single instance with 2 vCPUs and 8 GB RAM.
- Handles up to 40 concurrent requests.
- Teams or organizations with up to 50 users and predictable workloads.
- Fixed instances may suffice; autoscaling can be disabled for cost efficiency.
- Medium deployment:
- Single AWS t3.2xlarge instance with 8 vCPUs and 32 GB RAM.
- Handles up to 160 concurrent requests.
- Organizations with 50-200 users and moderate concurrency requirements.
- Implement Kubernetes HPA with thresholds for 50% CPU utilization or request latency above 500ms.
- Large deployment:
- Cluster of multiple AWS t3.2xlarge instances or equivalent.
- Each instance handles 160 concurrent requests, scaling to thousands of users with multiple instances.
- Enterprises with over 200 users and variable, high-concurrency workloads.
- Use HPA to scale pods based on real-time demand, combined with node autoscaling for cluster-wide resource adjustments.
## What specs does the AI gateway container have access to, and how does resource allocation affect performance?
The AI gateway operates effectively under the following resource allocations:
- 2 CPU cores and 8 GB of RAM per container.
- Containers typically utilize about 7.39% CPU and proportionate memory in the GitLab production environment, leaving room for growth or handling burst activity.
## Mitigation strategies for resource contention
- Use Kubernetes resource requests and limits to ensure AI gateway containers receive guaranteed CPU and memory allocations. For example:
```yaml
resources:
requests:
memory: "16Gi"
cpu: "4"
limits:
memory: "32Gi"
cpu: "8"
```
- Implement tools like Prometheus and Grafana to track resource utilization (CPU, memory, latency) and detect bottlenecks early.
- Dedicate nodes or instances exclusively to the AI gateway to prevent resource competition with other services.
## Scaling strategies
- Use Kubernetes HPA to scale pods based on real-time metrics like:
- Average CPU utilization exceeding 50%.
- Request latency consistently above 500ms.
- Enable node autoscaling to scale infrastructure resources dynamically as pods increase.
## Scaling recommendations
| Deployment size | Instance type | Resources | Capacity (concurrent requests) | Scaling recommendations |
|------------------|--------------------|------------------------|---------------------------------|---------------------------------------------|
| Small | 2 vCPUs, 8 GB RAM | Single instance | 40 | Fixed deployment; no autoscaling. |
| Medium | AWS t3.2xlarge | Single instance | 160 | HPA based on CPU or latency thresholds. |
| Large | Multiple t3.2xlarge | Clustered instances | 160 per instance | HPA + node autoscaling for high demand. |
## Support multiple GitLab instances
You can deploy a single AI gateway to support multiple GitLab instances, or deploy separate AI gateways per instance or geographic region. To help decide which is appropriate, consider:
- Expected traffic of approximately seven requests per second per 1,000 billable users.
- Resource requirements based on total concurrent requests across all instances.
- Best practice authentication configuration for each GitLab instance.
## Co-locate your AI gateway and instance
The AI gateway is available in multiple regions globally to ensure optimal performance for users regardless of location, through:
- Improved response times for Duo features.
- Reduced latency for geographically distributed users.
- Data sovereignty requirements compliance.
You should locate your AI gateway in the same geographic region as your GitLab instance to help provide a frictionless developer experience, particularly for latency-sensitive features like Code Suggestions.
## Troubleshooting
When working with the AI gateway, you might encounter the following issues.
### OpenShift permission issues
When deploying the AI gateway on OpenShift, you might encounter permission errors due to the OpenShift security model.
#### Read-only filesystem at `/tmp`
The AI gateway needs to write to `/tmp`. However, based on the OpenShift environment, which is security-restricted,
`/tmp` might be read-only.
To resolve this issue, create a new `EmptyDir` volume and mount it at `/tmp`.
You can do this in either of the following ways:
- From the command line:
```shell
oc set volume <object_type>/<name> --add --name=tmpVol --type=emptyDir --mountPoint=/tmp
```
- Added to your `values.yaml`:
```yaml
volumes:
- name: tmp-volume
emptyDir: {}
volumeMounts:
- name: tmp-volume
mountPath: "/tmp"
```
#### HuggingFace models
By default, the AI gateway uses `/home/aigateway/.hf` for caching HuggingFace models, which may not be writable in OpenShift's
security-restricted environment. This can result in permission errors like:
```shell
[Errno 13] Permission denied: '/home/aigateway/.hf/...'
```
To resolve this, set the `HF_HOME` environment variable to a writable location. You can use `/var/tmp/huggingface` or any other directory that is writable by the container.
You can configure this in either of the following ways:
- Add to your `values.yaml`:
```yaml
extraEnvironmentVariables:
- name: HF_HOME
value: /var/tmp/huggingface # Use any writable directory
```
- Or include in your Helm upgrade command:
```shell
--set "extraEnvironmentVariables[0].name=HF_HOME" \
--set "extraEnvironmentVariables[0].value=/var/tmp/huggingface" # Use any writable directory
```
This configuration ensures the AI gateway can properly cache HuggingFace models while respecting the OpenShift security constraints. The exact directory you choose may depend on your specific OpenShift configuration and security policies.
### Self-signed certificate error
A `[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate in certificate chain` error is logged by the AI gateway
when the gateway tries to connect to a GitLab instance using either a certificate signed by a custom certificate authority (CA), or a self-signed certificate:
- The use of custom CA certificates in the Helm chart configuration when deploying the AI gateway is not supported. For more information, see [issue 3](https://gitlab.com/gitlab-org/charts/ai-gateway-helm-chart/-/issues/3). Use the [workaround](https://gitlab.com/gitlab-org/charts/ai-gateway-helm-chart/-/issues/3#workaround) detailed in this issue.
- The use of a self-signed certificate by the GitLab instance is not supported. For more information, see [issue 799](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/-/issues/799).
|
---
stage: AI-powered
group: AI Framework
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Gateway between GitLab and large language models.
title: Install the GitLab AI gateway
breadcrumbs:
- doc
- install
---
The [AI gateway](../user/gitlab_duo/gateway.md)
is a standalone service that gives access to AI-native GitLab Duo features.
## Install by using Docker
The GitLab AI gateway Docker image contains all necessary code and dependencies
in a single container.
Prerequisites:
- Install a Docker container engine, like [Docker](https://docs.docker.com/engine/install/#server).
- Use a valid hostname that is accessible in your network. Do not use `localhost`.
- Ensure you have approximately 340 MB (compressed) for the `linux/amd64` architecture and
a minimum of 512 MB of RAM.
To ensure better performance, especially under heavy usage, consider allocating
more disk space, memory, and resources than the minimum requirements.
Higher RAM and disk capacity can enhance the AI gateway's efficiency during peak loads.
A GPU is not needed for the GitLab AI gateway.
### Find the AI gateway image
The GitLab official Docker image is available:
- In the container registry:
- [Stable](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/container_registry/3809284?orderBy=PUBLISHED_AT&search%5B%5D=self-hosted)
- [Nightly](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/container_registry/8086262)
- On DockerHub:
- [Stable](https://hub.docker.com/r/gitlab/model-gateway/tags)
- [Nightly](https://hub.docker.com/r/gitlab/model-gateway-self-hosted/tags)
[View the release process for the self-hosted AI gateway](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/-/blob/main/docs/release.md).
If your GitLab version is `vX.Y.*-ee`, use the AI gateway Docker image with the latest `self-hosted-vX.Y.*-ee` tag. For example, if GitLab is on version `v18.2.1-ee`, and the AI gateway Docker image has:
- Versions `self-hosted-v18.2.0-ee`, `self-hosted-v18.2.1-ee`, and `self-hosted-v18.2.2-ee`, use `self-hosted-v18.2.2-ee`.
- Versions `self-hosted-v18.2.0-ee` and `self-hosted-v18.2.1-ee`, use `self-hosted-v18.2.1-ee`.
- Only one version, `self-hosted-v18.2.0-ee`, use `self-hosted-v18.2.0-ee`.
Newer features are available from nightly builds, but backwards compatibility is not guaranteed.
{{< alert type="note" >}}
Using the nightly version is **not recommended** because it can cause incompatibility if your GitLab version is behind or ahead of the AI gateway release. Always use an explicit version tag.
{{< /alert >}}
### Start a container from the image
1. Run the following command, replacing `<your_gitlab_instance>` and `<your_gitlab_domain>` with your GitLab instance's URL and domain:
```shell
docker run -d -p 5052:5052 \
-e AIGW_GITLAB_URL=<your_gitlab_instance> \
-e AIGW_GITLAB_API_URL=https://<your_gitlab_domain>/api/v4/ \
registry.gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/model-gateway:<ai-gateway-tag> \
```
Replace `<ai-gateway-tag>` with the version that matches your GitLab instance. For example, if your GitLab version is `vX.Y.0`, use `self-hosted-vX.Y.0-ee`.
From the container host, accessing `http://localhost:5052` should return `{"error":"No authorization header presented"}`.
1. Ensure that port `5052` is forwarded to the container from the host and configure the AI gateway URL through the [Rails console](../administration/operations/rails_console.md):
```ruby
Ai::Setting.instance.update!(ai_gateway_url: 'http://ai-gateway-host.example.com:5052')
```
You should configure the URL this way because the URL is stored in the database, and you can then manage it through the Admin area. Although the `AI_GATEWAY_URL` environment variable is still supported for legacy reasons, using the database setting is preferred for better configuration management.
If you encounter issues loading the PEM file, resulting in errors like `JWKError`, you may need to resolve an SSL certificate error.
To fix this issue, set the appropriate certificate bundle path in the Docker container by using the following environment variables:
- `SSL_CERT_FILE=/path/to/ca-bundle.pem`
- `REQUESTS_CA_BUNDLE=/path/to/ca-bundle.pem`
Replace `/path/to/ca-bundle.pem` with the actual path to your certificate bundle.
## Set up Docker with NGINX and SSL
{{< alert type="note" >}}
This method of deploying NGINX or Caddy as a reverse proxy is a temporary workaround to support SSL
until [issue 455854](https://gitlab.com/gitlab-org/gitlab/-/issues/455854)
is implemented.
{{< /alert >}}
You can set up SSL for an AI gateway instance by using Docker,
NGINX as a reverse proxy, and Let's Encrypt for SSL certificates.
NGINX manages the secure connection with external clients, decrypting incoming HTTPS requests before
passing them to the AI gateway.
Prerequisites:
- Docker and Docker Compose installed
- Registered and configured domain name
### Create configuration files
Start by creating the following files in your working directory.
1. `nginx.conf`:
```nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
```
1. `default.conf`:
```nginx
# nginx/conf.d/default.conf
server {
listen 80;
server_name _;
# Forward all requests to the AI gateway
location / {
proxy_pass http://gitlab-ai-gateway:5052;
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
proxy_buffering off;
}
}
server {
listen 443 ssl;
server_name _;
# SSL configuration
ssl_certificate /etc/nginx/ssl/server.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
# Configuration for self-signed certificates
ssl_verify_client off;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# Proxy headers
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# WebSocket support (if needed)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# Forward all requests to the AI gateway
location / {
proxy_pass http://gitlab-ai-gateway:5052;
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
proxy_buffering off;
}
}
```
### Set up SSL certificate by using Let's Encrypt
Now set up an SSL certificate:
- For Docker-based NGINX servers, Certbot
[provides an automated way to implement Let's Encrypt certificates](https://phoenixnap.com/kb/letsencrypt-docker).
- Alternatively, you can use the [Certbot manual installation](https://eff-certbot.readthedocs.io/en/stable/using.html#manual).
### Create Docker-compose file
Now create a `docker-compose.yaml` file.
```yaml
version: '3.8'
services:
nginx-proxy:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- /path/to/nginx.conf:/etc/nginx/nginx.conf:ro
- /path/to/default.conf:/etc/nginx/conf.d/default.conf:ro
- /path/to/fullchain.pem:/etc/nginx/ssl/server.crt:ro
- /path/to/privkey.pem:/etc/nginx/ssl/server.key:ro
networks:
- proxy-network
depends_on:
- gitlab-ai-gateway
gitlab-ai-gateway:
image: registry.gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/model-gateway:<ai-gateway-tag>
expose:
- "5052"
environment:
- AIGW_GITLAB_URL=<your_gitlab_instance>
- AIGW_GITLAB_API_URL=https://<your_gitlab_domain>/api/v4/
networks:
- proxy-network
restart: always
networks:
proxy-network:
driver: bridge
```
### Deploy and validate
Noe deploy and validate the solution.
1. Start the `nginx` and `AIGW` containers and verify that they're running:
```shell
docker-compose up
docker ps
```
1. Configure your [GitLab instance to access the AI gateway](../administration/gitlab_duo_self_hosted/configure_duo_features.md#configure-your-gitlab-instance-to-access-the-ai-gateway).
1. Perform the health check and confirm that the AI gateway is accessible.
## Install by using Helm chart
Prerequisites:
- You must have a:
- Domain you own, to which you can add a DNS record.
- Kubernetes cluster.
- Working installation of `kubectl`.
- Working installation of Helm, version v3.11.0 or later.
For more information, see [Test the GitLab chart on GKE or EKS](https://docs.gitlab.com/charts/quickstart/).
### Add the AI gateway Helm repository
Add the AI gateway Helm repository to the Helm configuration:
```shell
helm repo add ai-gateway \
https://gitlab.com/api/v4/projects/gitlab-org%2fcharts%2fai-gateway-helm-chart/packages/helm/devel
```
### Install the AI gateway
1. Create the `ai-gateway` namespace:
```shell
kubectl create namespace ai-gateway
```
1. Generate the certificate for the domain where you plan to expose the AI gateway.
1. Create the TLS secret in the previously created namespace:
```shell
kubectl -n ai-gateway create secret tls ai-gateway-tls --cert="<path_to_cert>" --key="<path_to_cert_key>"
```
1. For the AI gateway to access the API, it must know where the GitLab instance
is located. To do this, set the `gitlab.url` and `gitlab.apiUrl` together with
the `ingress.hosts` and `ingress.tls` values as follows:
```shell
helm repo add ai-gateway \
https://gitlab.com/api/v4/projects/gitlab-org%2fcharts%2fai-gateway-helm-chart/packages/helm/devel
helm repo update
helm upgrade --install ai-gateway \
ai-gateway/ai-gateway \
--version 0.5.0 \
--namespace=ai-gateway \
--set="image.tag=<ai-gateway-image-version>" \
--set="gitlab.url=https://<your_gitlab_domain>" \
--set="gitlab.apiUrl=https://<your_gitlab_domain>/api/v4/" \
--set "ingress.enabled=true" \
--set "ingress.hosts[0].host=<your_gateway_domain>" \
--set "ingress.hosts[0].paths[0].path=/" \
--set "ingress.hosts[0].paths[0].pathType=ImplementationSpecific" \
--set "ingress.tls[0].secretName=ai-gateway-tls" \
--set "ingress.tls[0].hosts[0]=<your_gateway_domain>" \
--set="ingress.className=nginx" \
--timeout=300s --wait --wait-for-jobs
```
You can find the list of AI gateway versions that can be used as `image.tag` in the [container registry](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/container_registry/3809284?orderBy=PUBLISHED_AT&search%5B%5D=self-hosted).
This step can take will take a few seconds in order for all resources to be allocated
and the AI gateway to start.
You might need to set up your own **Ingress Controller** for the AI gateway if your existing `nginx` Ingress controller does not serve services in a different namespace. Make sure Ingress is set up correctly for multi-namespace deployments.
For versions of the `ai-gateway` Helm chart, use `helm search repo ai-gateway --versions` to find the appropriate chart version.
Wait for your pods to get up and running:
```shell
kubectl wait pod \
--all \
--for=condition=Ready \
--namespace=ai-gateway \
--timeout=300s
```
When your pods are up and running, you can set up your IP ingresses and DNS records.
## Upgrade the AI gateway Docker image
To upgrade the AI gateway, download the newest Docker image tag.
1. Stop the running container:
```shell
sudo docker stop gitlab-aigw
```
1. Remove the existing container:
```shell
sudo docker rm gitlab-aigw
```
1. Pull and [run the new image](#start-a-container-from-the-image).
1. Ensure that the environment variables are all set correctly.
## Alternative installation methods
For information on alternative ways to install the AI gateway, see
[issue 463773](https://gitlab.com/gitlab-org/gitlab/-/issues/463773).
## Health check and debugging
To debug issues with your self-hosted Duo installation, run the following command:
```shell
sudo gitlab-rake gitlab:duo:verify_self_hosted_setup
```
Ensure that:
- The AI gateway URL is correctly configured (through `Ai::Setting.instance.ai_gateway_url`).
- Duo access has been explicitly enabled for the root user through `/admin/code_suggestions`.
If access issues persist, check that authentication is correctly configured, and that the health check passes.
In case of persistent issues, the error message may suggest bypassing authentication with `AIGW_AUTH__BYPASS_EXTERNAL=true`, but only do this for troubleshooting.
You can also run a [health check](../administration/gitlab_duo/setup.md#run-a-health-check-for-gitlab-duo) by going to **Admin > GitLab Duo**.
These tests are performed for offline environments:
| Test | Description |
|-----------------|-------------|
| Network | Tests whether: <br>- The AI gateway URL has been properly configured in the database through the `ai_settings` table.<br> - Your instance can connect to the configured URL.<br><br>If your instance cannot connect to the URL, ensure that your firewall or proxy server settings [allow connection](../user/gitlab_duo/setup.md). Although the environment variable `AI_GATEWAY_URL` is still supported for legacy compatibility, configuring the URL through the database is recommended for better manageability. |
| License | Tests whether your license has the ability to access Code Suggestions feature. |
| System exchange | Tests whether Code Suggestions can be used in your instance. If the system exchange assessment fails, users might not be able to use GitLab Duo features. |
## Does the AI gateway need to autoscale?
Autoscaling is not mandatory but is recommended for environments with variable workloads, high concurrency requirements, or unpredictable usage patterns. In the GitLab production environment:
- Baseline setup: A single AI gateway instance with 2 CPU cores and 8 GB RAM can handle approximately 40 concurrent requests.
- Scaling guidelines: For larger setups, such as an AWS t3.2xlarge instance (8 vCPUs, 32 GB RAM), the gateway can handle up to 160 concurrent requests, equivalent to 4x the baseline setup.
- Request throughput: GitLab.com's observed usage suggests that 7 RPS (requests per second) per 1000 active users is a reasonable metric for planning.
- Autoscaling options: Use Kubernetes Horizontal Pod Autoscalers (HPA) or similar mechanisms to dynamically adjust the number of instances based on metrics like CPU, memory utilization, or request latency thresholds.
## Configuration examples by deployment size
- Small deployment:
- Single instance with 2 vCPUs and 8 GB RAM.
- Handles up to 40 concurrent requests.
- Teams or organizations with up to 50 users and predictable workloads.
- Fixed instances may suffice; autoscaling can be disabled for cost efficiency.
- Medium deployment:
- Single AWS t3.2xlarge instance with 8 vCPUs and 32 GB RAM.
- Handles up to 160 concurrent requests.
- Organizations with 50-200 users and moderate concurrency requirements.
- Implement Kubernetes HPA with thresholds for 50% CPU utilization or request latency above 500ms.
- Large deployment:
- Cluster of multiple AWS t3.2xlarge instances or equivalent.
- Each instance handles 160 concurrent requests, scaling to thousands of users with multiple instances.
- Enterprises with over 200 users and variable, high-concurrency workloads.
- Use HPA to scale pods based on real-time demand, combined with node autoscaling for cluster-wide resource adjustments.
## What specs does the AI gateway container have access to, and how does resource allocation affect performance?
The AI gateway operates effectively under the following resource allocations:
- 2 CPU cores and 8 GB of RAM per container.
- Containers typically utilize about 7.39% CPU and proportionate memory in the GitLab production environment, leaving room for growth or handling burst activity.
## Mitigation strategies for resource contention
- Use Kubernetes resource requests and limits to ensure AI gateway containers receive guaranteed CPU and memory allocations. For example:
```yaml
resources:
requests:
memory: "16Gi"
cpu: "4"
limits:
memory: "32Gi"
cpu: "8"
```
- Implement tools like Prometheus and Grafana to track resource utilization (CPU, memory, latency) and detect bottlenecks early.
- Dedicate nodes or instances exclusively to the AI gateway to prevent resource competition with other services.
## Scaling strategies
- Use Kubernetes HPA to scale pods based on real-time metrics like:
- Average CPU utilization exceeding 50%.
- Request latency consistently above 500ms.
- Enable node autoscaling to scale infrastructure resources dynamically as pods increase.
## Scaling recommendations
| Deployment size | Instance type | Resources | Capacity (concurrent requests) | Scaling recommendations |
|------------------|--------------------|------------------------|---------------------------------|---------------------------------------------|
| Small | 2 vCPUs, 8 GB RAM | Single instance | 40 | Fixed deployment; no autoscaling. |
| Medium | AWS t3.2xlarge | Single instance | 160 | HPA based on CPU or latency thresholds. |
| Large | Multiple t3.2xlarge | Clustered instances | 160 per instance | HPA + node autoscaling for high demand. |
## Support multiple GitLab instances
You can deploy a single AI gateway to support multiple GitLab instances, or deploy separate AI gateways per instance or geographic region. To help decide which is appropriate, consider:
- Expected traffic of approximately seven requests per second per 1,000 billable users.
- Resource requirements based on total concurrent requests across all instances.
- Best practice authentication configuration for each GitLab instance.
## Co-locate your AI gateway and instance
The AI gateway is available in multiple regions globally to ensure optimal performance for users regardless of location, through:
- Improved response times for Duo features.
- Reduced latency for geographically distributed users.
- Data sovereignty requirements compliance.
You should locate your AI gateway in the same geographic region as your GitLab instance to help provide a frictionless developer experience, particularly for latency-sensitive features like Code Suggestions.
## Troubleshooting
When working with the AI gateway, you might encounter the following issues.
### OpenShift permission issues
When deploying the AI gateway on OpenShift, you might encounter permission errors due to the OpenShift security model.
#### Read-only filesystem at `/tmp`
The AI gateway needs to write to `/tmp`. However, based on the OpenShift environment, which is security-restricted,
`/tmp` might be read-only.
To resolve this issue, create a new `EmptyDir` volume and mount it at `/tmp`.
You can do this in either of the following ways:
- From the command line:
```shell
oc set volume <object_type>/<name> --add --name=tmpVol --type=emptyDir --mountPoint=/tmp
```
- Added to your `values.yaml`:
```yaml
volumes:
- name: tmp-volume
emptyDir: {}
volumeMounts:
- name: tmp-volume
mountPath: "/tmp"
```
#### HuggingFace models
By default, the AI gateway uses `/home/aigateway/.hf` for caching HuggingFace models, which may not be writable in OpenShift's
security-restricted environment. This can result in permission errors like:
```shell
[Errno 13] Permission denied: '/home/aigateway/.hf/...'
```
To resolve this, set the `HF_HOME` environment variable to a writable location. You can use `/var/tmp/huggingface` or any other directory that is writable by the container.
You can configure this in either of the following ways:
- Add to your `values.yaml`:
```yaml
extraEnvironmentVariables:
- name: HF_HOME
value: /var/tmp/huggingface # Use any writable directory
```
- Or include in your Helm upgrade command:
```shell
--set "extraEnvironmentVariables[0].name=HF_HOME" \
--set "extraEnvironmentVariables[0].value=/var/tmp/huggingface" # Use any writable directory
```
This configuration ensures the AI gateway can properly cache HuggingFace models while respecting the OpenShift security constraints. The exact directory you choose may depend on your specific OpenShift configuration and security policies.
### Self-signed certificate error
A `[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate in certificate chain` error is logged by the AI gateway
when the gateway tries to connect to a GitLab instance using either a certificate signed by a custom certificate authority (CA), or a self-signed certificate:
- The use of custom CA certificates in the Helm chart configuration when deploying the AI gateway is not supported. For more information, see [issue 3](https://gitlab.com/gitlab-org/charts/ai-gateway-helm-chart/-/issues/3). Use the [workaround](https://gitlab.com/gitlab-org/charts/ai-gateway-helm-chart/-/issues/3#workaround) detailed in this issue.
- The use of a self-signed certificate by the GitLab instance is not supported. For more information, see [issue 799](https://gitlab.com/gitlab-org/modelops/applied-ml/code-suggestions/ai-assist/-/issues/799).
|
https://docs.gitlab.com/postgresql_extensions
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/postgresql_extensions.md
|
2025-08-13
|
doc/install
|
[
"doc",
"install"
] |
postgresql_extensions.md
|
Tenant Scale
|
Database
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Managing PostgreSQL extensions
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This guide documents how to manage PostgreSQL extensions for installations with an external
PostgreSQL database.
You must load the following extensions into the main GitLab database (defaults to `gitlabhq_production`):
| Extension | Minimum GitLab version |
|--------------|------------------------|
| `pg_trgm` | 8.6 |
| `btree_gist` | 13.1 |
| `plpgsql` | 11.7 |
If you are using [GitLab Geo](../administration/geo/_index.md), you must load the following
extensions into all secondary tracking databases (defaults to `gitlabhq_geo_production`):
| Extension | Minimum GitLab version |
|--------------|------------------------|
| `plpgsql` | 9.0 |
To install extensions, PostgreSQL requires the user to have superuser privileges.
Typically, the GitLab database user is not a superuser. Therefore, regular database migrations
cannot be used in installing extensions and instead, extensions have to be installed manually
prior to upgrading GitLab to a newer version.
## Installing PostgreSQL extensions manually
To install a PostgreSQL extension, this procedure should be followed:
1. Connect to the GitLab PostgreSQL database using a superuser, for example:
```shell
sudo gitlab-psql -d gitlabhq_production
```
1. Install the extension (`btree_gist` in this example) using [`CREATE EXTENSION`](https://www.postgresql.org/docs/16/sql-createextension.html):
```sql
CREATE EXTENSION IF NOT EXISTS btree_gist
```
1. Verify installed extensions:
```shell
gitlabhq_production=# \dx
List of installed extensions
Name | Version | Schema | Description
------------+---------+------------+-------------------------------------------------------------------
btree_gist | 1.5 | public | support for indexing common datatypes in GiST
pg_trgm | 1.4 | public | text similarity measurement and index searching based on trigrams
plpgsql | 1.0 | pg_catalog | PL/pgSQL procedural language
(3 rows)
```
On some systems you may need to install an additional package (for example,
`postgresql-contrib`) for certain extensions to become available.
## Typical failure scenarios
The following is an example of a new GitLab installation failing because the extension hasn't been
installed first.
```shell
---- Begin output of "bash" "/tmp/chef-script20210513-52940-d9b1gs" ----
STDOUT: psql:/opt/gitlab/embedded/service/gitlab-rails/db/structure.sql:9: ERROR: permission denied to create extension "btree_gist"
HINT: Must be superuser to create this extension.
rake aborted!
failed to execute:
psql -v ON_ERROR_STOP=1 -q -X -f /opt/gitlab/embedded/service/gitlab-rails/db/structure.sql --single-transaction gitlabhq_production
```
The following is an example of a situation when the extension hasn't been installed before running migrations.
In this scenario, the database migration fails to create the extension `btree_gist` because of insufficient
privileges.
```shell
== 20200515152649 EnableBtreeGistExtension: migrating =========================
-- execute("CREATE EXTENSION IF NOT EXISTS btree_gist")
GitLab requires the PostgreSQL extension 'btree_gist' installed in database 'gitlabhq_production', but
the database user is not allowed to install the extension.
You can either install the extension manually using a database superuser:
CREATE EXTENSION IF NOT EXISTS btree_gist
Or, you can solve this by logging in to the GitLab database (gitlabhq_production) using a superuser and running:
ALTER regular WITH SUPERUSER
This query will grant the user superuser permissions, ensuring any database extensions
can be installed through migrations.
```
To recover from failed migrations, the extension must be installed manually by a superuser, and the
GitLab upgrade completed by [re-running the database migrations](../administration/raketasks/maintenance.md#run-incomplete-database-migrations):
```shell
sudo gitlab-rake db:migrate
```
|
---
stage: Tenant Scale
group: Database
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Managing PostgreSQL extensions
breadcrumbs:
- doc
- install
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This guide documents how to manage PostgreSQL extensions for installations with an external
PostgreSQL database.
You must load the following extensions into the main GitLab database (defaults to `gitlabhq_production`):
| Extension | Minimum GitLab version |
|--------------|------------------------|
| `pg_trgm` | 8.6 |
| `btree_gist` | 13.1 |
| `plpgsql` | 11.7 |
If you are using [GitLab Geo](../administration/geo/_index.md), you must load the following
extensions into all secondary tracking databases (defaults to `gitlabhq_geo_production`):
| Extension | Minimum GitLab version |
|--------------|------------------------|
| `plpgsql` | 9.0 |
To install extensions, PostgreSQL requires the user to have superuser privileges.
Typically, the GitLab database user is not a superuser. Therefore, regular database migrations
cannot be used in installing extensions and instead, extensions have to be installed manually
prior to upgrading GitLab to a newer version.
## Installing PostgreSQL extensions manually
To install a PostgreSQL extension, this procedure should be followed:
1. Connect to the GitLab PostgreSQL database using a superuser, for example:
```shell
sudo gitlab-psql -d gitlabhq_production
```
1. Install the extension (`btree_gist` in this example) using [`CREATE EXTENSION`](https://www.postgresql.org/docs/16/sql-createextension.html):
```sql
CREATE EXTENSION IF NOT EXISTS btree_gist
```
1. Verify installed extensions:
```shell
gitlabhq_production=# \dx
List of installed extensions
Name | Version | Schema | Description
------------+---------+------------+-------------------------------------------------------------------
btree_gist | 1.5 | public | support for indexing common datatypes in GiST
pg_trgm | 1.4 | public | text similarity measurement and index searching based on trigrams
plpgsql | 1.0 | pg_catalog | PL/pgSQL procedural language
(3 rows)
```
On some systems you may need to install an additional package (for example,
`postgresql-contrib`) for certain extensions to become available.
## Typical failure scenarios
The following is an example of a new GitLab installation failing because the extension hasn't been
installed first.
```shell
---- Begin output of "bash" "/tmp/chef-script20210513-52940-d9b1gs" ----
STDOUT: psql:/opt/gitlab/embedded/service/gitlab-rails/db/structure.sql:9: ERROR: permission denied to create extension "btree_gist"
HINT: Must be superuser to create this extension.
rake aborted!
failed to execute:
psql -v ON_ERROR_STOP=1 -q -X -f /opt/gitlab/embedded/service/gitlab-rails/db/structure.sql --single-transaction gitlabhq_production
```
The following is an example of a situation when the extension hasn't been installed before running migrations.
In this scenario, the database migration fails to create the extension `btree_gist` because of insufficient
privileges.
```shell
== 20200515152649 EnableBtreeGistExtension: migrating =========================
-- execute("CREATE EXTENSION IF NOT EXISTS btree_gist")
GitLab requires the PostgreSQL extension 'btree_gist' installed in database 'gitlabhq_production', but
the database user is not allowed to install the extension.
You can either install the extension manually using a database superuser:
CREATE EXTENSION IF NOT EXISTS btree_gist
Or, you can solve this by logging in to the GitLab database (gitlabhq_production) using a superuser and running:
ALTER regular WITH SUPERUSER
This query will grant the user superuser permissions, ensuring any database extensions
can be installed through migrations.
```
To recover from failed migrations, the extension must be installed manually by a superuser, and the
GitLab upgrade completed by [re-running the database migrations](../administration/raketasks/maintenance.md#run-incomplete-database-migrations):
```shell
sudo gitlab-rake db:migrate
```
|
https://docs.gitlab.com/install/openshift_and_gitlab
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/_index.md
|
2025-08-13
|
doc/install/openshift_and_gitlab
|
[
"doc",
"install",
"openshift_and_gitlab"
] |
_index.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
OpenShift support
| null |
OpenShift - GitLab compatibility can be addressed in three different aspects. This page helps navigating between these aspects and provides introductory information for getting started with OpenShift and GitLab.
## What is OpenShift
OpenShift helps you to develop, deploy, and manage container-based applications. It provides you with a self-service platform to create, modify, and deploy applications on demand, thus enabling faster development and release lifecycles.
## Use OpenShift to run GitLab Self-Managed
You can run GitLab in an OpenShift cluster with the GitLab Operator. For more information about
setting up GitLab on OpenShift, see [GitLab Operator](https://docs.gitlab.com/operator/).
## Use OpenShift to run a GitLab Runner Fleet
The GitLab Operator does not include the GitLab Runner. To install and manage a GitLab Runner fleet in an OpenShift cluster, use the
[GitLab Runner Operator](https://gitlab.com/gitlab-org/gl-openshift/gitlab-runner-operator).
### Deploy to and integrate with OpenShift from GitLab
Deploying custom or COTS applications on top of OpenShift from GitLab is supported using the
[GitLab agent for Kubernetes](../../user/clusters/agent/_index.md).
### Unsupported GitLab features
#### Docker-in-Docker
When using OpenShift to run a GitLab Runner Fleet, we do not support some GitLab features given OpenShift's security model.
Features requiring Docker-in-Docker might not work.
For Auto DevOps, the following features are not supported yet:
- [Auto Code Quality](../../ci/testing/code_quality.md)
- [License approval policies](../../user/compliance/license_approval_policies.md)
- Auto Browser Performance Testing
- Auto Build
- [Operational Container Scanning](../../user/clusters/agent/vulnerabilities.md) (Note: Pipeline [Container Scanning](../../user/application_security/container_scanning/_index.md) is supported)
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: OpenShift support
breadcrumbs:
- doc
- install
- openshift_and_gitlab
---
OpenShift - GitLab compatibility can be addressed in three different aspects. This page helps navigating between these aspects and provides introductory information for getting started with OpenShift and GitLab.
## What is OpenShift
OpenShift helps you to develop, deploy, and manage container-based applications. It provides you with a self-service platform to create, modify, and deploy applications on demand, thus enabling faster development and release lifecycles.
## Use OpenShift to run GitLab Self-Managed
You can run GitLab in an OpenShift cluster with the GitLab Operator. For more information about
setting up GitLab on OpenShift, see [GitLab Operator](https://docs.gitlab.com/operator/).
## Use OpenShift to run a GitLab Runner Fleet
The GitLab Operator does not include the GitLab Runner. To install and manage a GitLab Runner fleet in an OpenShift cluster, use the
[GitLab Runner Operator](https://gitlab.com/gitlab-org/gl-openshift/gitlab-runner-operator).
### Deploy to and integrate with OpenShift from GitLab
Deploying custom or COTS applications on top of OpenShift from GitLab is supported using the
[GitLab agent for Kubernetes](../../user/clusters/agent/_index.md).
### Unsupported GitLab features
#### Docker-in-Docker
When using OpenShift to run a GitLab Runner Fleet, we do not support some GitLab features given OpenShift's security model.
Features requiring Docker-in-Docker might not work.
For Auto DevOps, the following features are not supported yet:
- [Auto Code Quality](../../ci/testing/code_quality.md)
- [License approval policies](../../user/compliance/license_approval_policies.md)
- Auto Browser Performance Testing
- Auto Build
- [Operational Container Scanning](../../user/clusters/agent/vulnerabilities.md) (Note: Pipeline [Container Scanning](../../user/application_security/container_scanning/_index.md) is supported)
|
https://docs.gitlab.com/install/almalinux
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/almalinux.md
|
2025-08-13
|
doc/install/package
|
[
"doc",
"install",
"package"
] |
almalinux.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install the Linux package on AlmaLinux and RHEL-compatible distributions
|
Install the Linux package on AlmaLinux and RHEL-compatible distributions
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
See [supported platforms](_index.md#supported-platforms) for the full list of
supported distributions and architectures.
{{< /alert >}}
## Prerequisites
- OS requirements:
- AlmaLinux 8
- AlmaLinux 9
- Red Hat Enterprise Linux 8
- Red Hat Enterprise Linux 9
- Oracle Linux 8
- Oracle Linux 9
- Any distribution compatible with a supported Red Hat Enterprise Linux version
- See the [installation requirements](../requirements.md) to learn about the
minimum hardware requirements.
- Before you begin, make sure you have correctly
[set up your DNS](https://docs.gitlab.com/omnibus/settings/dns),
and change `https://gitlab.example.com` to the URL at which you want to access
your GitLab instance. The installation automatically configures and starts
GitLab at that URL.
- For `https://` URLs, GitLab automatically
[requests a certificate with Let's Encrypt](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
which requires inbound HTTP access and a valid hostname. You can also use
[your own certificate](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
or just use `http://` (without the `s`) for an unencrypted URL.
## Enable SSH and open firewall ports
To open the needed firewall ports (80, 443, 22) and be able to access GitLab:
1. Enable and start the OpenSSH server daemon:
```shell
sudo systemctl enable --now sshd
```
1. With `firewalld` installed, open the firewall ports:
```shell
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-service=ssh
sudo systemctl reload firewalld
```
## Add the GitLab package repository
To install GitLab, first add the GitLab package repository.
1. Install the needed packages:
```shell
sudo dnf install -y curl
```
1. Use the following script to add the GitLab repository (you can paste the
script's URL to your browser to see what it does before piping it to
`bash`):
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< /tabs >}}
## Install the package
Install GitLab using your system's package manager. You can customize the
initial setup by configuring environment variables before installation.
If you don't customize the root credentials during installation:
- GitLab generates a random password and email address for the root
administrator account.
- The password is stored in `/etc/gitlab/initial_root_password` for 24 hours.
- After 24 hours, this file is automatically removed for security reasons.
{{< alert type="note" >}}
While you can also set the initial password in `/etc/gitlab/gitlab.rb` by setting
`gitlab_rails['initial_root_password'] = "password"`, it is not recommended. If
you do set the password with this method, be sure to remove the password from
`/etc/gitlab/gitlab.rb` as it only gets read with the first reconfigure after
the package is installed.
{{< /alert >}}
### Available environment variables
You can customize your GitLab installation by setting the following optional
environment variables. **These variables only work during the first
installation** and have no effect on subsequent reconfigure runs. For existing
installations, use the password from `/etc/gitlab/initial_root_password` or
[reset the root password](../../security/reset_user_password.md).
| Variable | Purpose | Required | Example |
|----------|---------|----------|---------|
| `EXTERNAL_URL` | Sets the external URL for your GitLab instance | Recommended | `EXTERNAL_URL="https://gitlab.example.com"` |
| `GITLAB_ROOT_EMAIL` | Custom email for the root administrator account | Optional | `GITLAB_ROOT_EMAIL="admin@example.com"` |
| `GITLAB_ROOT_PASSWORD` | Custom password (8 characters minimum) for the root administrator account | Optional | `GITLAB_ROOT_PASSWORD="strongpassword"` |
{{< alert type="note" >}}
If GitLab can't detect a valid hostname during installation, reconfigure won't run automatically. In this case, pass any needed environment variables to your first `gitlab-ctl reconfigure` command.
{{< /alert >}}
### Installation commands
Choose your GitLab edition and customize with the environment variables above:
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ee
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ee
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ce
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ce
```
{{< /tab >}}
{{< /tabs >}}
## Set up your communication preferences
Visit our [email subscription preference center](https://about.gitlab.com/company/preference-center/)
to let us know when to communicate with you. We have an explicit email opt-in
policy so you have complete control over what and how often we send you emails.
Twice a month, we send out the GitLab news you need to know, including new
features, integrations, documentation, and behind the scenes stories from our development teams.
For critical security updates related to bugs and system performance, sign up
for our dedicated security newsletter.
{{< alert type="note" >}}
If you do not opt-in to the security newsletter, you will not receive security alerts.
{{< /alert >}}
## Recommended next steps
After completing your installation, consider the
[recommended next steps, including authentication options and sign-up restrictions](../next_steps.md).
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Install the Linux package on AlmaLinux and RHEL-compatible distributions
title: Install the Linux package on AlmaLinux and RHEL-compatible distributions
breadcrumbs:
- doc
- install
- package
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
See [supported platforms](_index.md#supported-platforms) for the full list of
supported distributions and architectures.
{{< /alert >}}
## Prerequisites
- OS requirements:
- AlmaLinux 8
- AlmaLinux 9
- Red Hat Enterprise Linux 8
- Red Hat Enterprise Linux 9
- Oracle Linux 8
- Oracle Linux 9
- Any distribution compatible with a supported Red Hat Enterprise Linux version
- See the [installation requirements](../requirements.md) to learn about the
minimum hardware requirements.
- Before you begin, make sure you have correctly
[set up your DNS](https://docs.gitlab.com/omnibus/settings/dns),
and change `https://gitlab.example.com` to the URL at which you want to access
your GitLab instance. The installation automatically configures and starts
GitLab at that URL.
- For `https://` URLs, GitLab automatically
[requests a certificate with Let's Encrypt](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
which requires inbound HTTP access and a valid hostname. You can also use
[your own certificate](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
or just use `http://` (without the `s`) for an unencrypted URL.
## Enable SSH and open firewall ports
To open the needed firewall ports (80, 443, 22) and be able to access GitLab:
1. Enable and start the OpenSSH server daemon:
```shell
sudo systemctl enable --now sshd
```
1. With `firewalld` installed, open the firewall ports:
```shell
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-service=ssh
sudo systemctl reload firewalld
```
## Add the GitLab package repository
To install GitLab, first add the GitLab package repository.
1. Install the needed packages:
```shell
sudo dnf install -y curl
```
1. Use the following script to add the GitLab repository (you can paste the
script's URL to your browser to see what it does before piping it to
`bash`):
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< /tabs >}}
## Install the package
Install GitLab using your system's package manager. You can customize the
initial setup by configuring environment variables before installation.
If you don't customize the root credentials during installation:
- GitLab generates a random password and email address for the root
administrator account.
- The password is stored in `/etc/gitlab/initial_root_password` for 24 hours.
- After 24 hours, this file is automatically removed for security reasons.
{{< alert type="note" >}}
While you can also set the initial password in `/etc/gitlab/gitlab.rb` by setting
`gitlab_rails['initial_root_password'] = "password"`, it is not recommended. If
you do set the password with this method, be sure to remove the password from
`/etc/gitlab/gitlab.rb` as it only gets read with the first reconfigure after
the package is installed.
{{< /alert >}}
### Available environment variables
You can customize your GitLab installation by setting the following optional
environment variables. **These variables only work during the first
installation** and have no effect on subsequent reconfigure runs. For existing
installations, use the password from `/etc/gitlab/initial_root_password` or
[reset the root password](../../security/reset_user_password.md).
| Variable | Purpose | Required | Example |
|----------|---------|----------|---------|
| `EXTERNAL_URL` | Sets the external URL for your GitLab instance | Recommended | `EXTERNAL_URL="https://gitlab.example.com"` |
| `GITLAB_ROOT_EMAIL` | Custom email for the root administrator account | Optional | `GITLAB_ROOT_EMAIL="admin@example.com"` |
| `GITLAB_ROOT_PASSWORD` | Custom password (8 characters minimum) for the root administrator account | Optional | `GITLAB_ROOT_PASSWORD="strongpassword"` |
{{< alert type="note" >}}
If GitLab can't detect a valid hostname during installation, reconfigure won't run automatically. In this case, pass any needed environment variables to your first `gitlab-ctl reconfigure` command.
{{< /alert >}}
### Installation commands
Choose your GitLab edition and customize with the environment variables above:
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ee
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ee
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ce
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ce
```
{{< /tab >}}
{{< /tabs >}}
## Set up your communication preferences
Visit our [email subscription preference center](https://about.gitlab.com/company/preference-center/)
to let us know when to communicate with you. We have an explicit email opt-in
policy so you have complete control over what and how often we send you emails.
Twice a month, we send out the GitLab news you need to know, including new
features, integrations, documentation, and behind the scenes stories from our development teams.
For critical security updates related to bugs and system performance, sign up
for our dedicated security newsletter.
{{< alert type="note" >}}
If you do not opt-in to the security newsletter, you will not receive security alerts.
{{< /alert >}}
## Recommended next steps
After completing your installation, consider the
[recommended next steps, including authentication options and sign-up restrictions](../next_steps.md).
|
https://docs.gitlab.com/install/debian
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/debian.md
|
2025-08-13
|
doc/install/package
|
[
"doc",
"install",
"package"
] |
debian.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install the Linux package on Debian
|
Install the Linux package on Debian
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
See [supported platforms](_index.md#supported-platforms) for the full list of
supported distributions and architectures.
{{< /alert >}}
## Prerequisites
- OS requirements:
- Debian 11
- Debian 12
- See the [installation requirements](../requirements.md) to learn about the
minimum hardware requirements.
- Before you begin, make sure you have correctly
[set up your DNS](https://docs.gitlab.com/omnibus/settings/dns),
and change `https://gitlab.example.com` to the URL at which you want to access
your GitLab instance. The installation automatically configures and starts
GitLab at that URL.
- For `https://` URLs, GitLab automatically
[requests a certificate with Let's Encrypt](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
which requires inbound HTTP access and a valid hostname. You can also use
[your own certificate](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
or just use `http://` (without the `s`) for an unencrypted URL.
## Enable SSH and open firewall ports
To open the needed firewall ports (80, 443, 22) and be able to access GitLab:
1. Enable and start the OpenSSH server daemon:
```shell
sudo systemctl enable --now ssh
```
1. With `ufw` installed, open the firewall ports:
```shell
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
```
## Add the GitLab package repository
To install GitLab, first add the GitLab package repository.
1. Install the needed packages:
```shell
sudo apt install -y curl
```
1. Use the following script to add the GitLab repository (you can paste the
script's URL to your browser to see what it does before piping it to
`bash`):
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.deb.sh" | sudo bash
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh" | sudo bash
```
{{< /tab >}}
{{< /tabs >}}
## Install the package
Install GitLab using your system's package manager. You can customize the
initial setup by configuring environment variables before installation.
If you don't customize the root credentials during installation:
- GitLab generates a random password and email address for the root
administrator account.
- The password is stored in `/etc/gitlab/initial_root_password` for 24 hours.
- After 24 hours, this file is automatically removed for security reasons.
{{< alert type="note" >}}
While you can also set the initial password in `/etc/gitlab/gitlab.rb` by setting
`gitlab_rails['initial_root_password'] = "password"`, it is not recommended. If
you do set the password with this method, be sure to remove the password from
`/etc/gitlab/gitlab.rb` as it only gets read with the first reconfigure after
the package is installed.
{{< /alert >}}
### Available environment variables
You can customize your GitLab installation by setting the following optional
environment variables. **These variables only work during the first
installation** and have no effect on subsequent reconfigure runs. For existing
installations, use the password from `/etc/gitlab/initial_root_password` or
[reset the root password](../../security/reset_user_password.md).
| Variable | Purpose | Required | Example |
|----------|---------|----------|---------|
| `EXTERNAL_URL` | Sets the external URL for your GitLab instance | Recommended | `EXTERNAL_URL="https://gitlab.example.com"` |
| `GITLAB_ROOT_EMAIL` | Custom email for the root administrator account | Optional | `GITLAB_ROOT_EMAIL="admin@example.com"` |
| `GITLAB_ROOT_PASSWORD` | Custom password (8 characters minimum) for the root administrator account | Optional | `GITLAB_ROOT_PASSWORD="strongpassword"` |
{{< alert type="note" >}}
If GitLab can't detect a valid hostname during installation, reconfigure won't run automatically. In this case, pass any needed environment variables to your first `gitlab-ctl reconfigure` command.
{{< /alert >}}
### Installation commands
Choose your GitLab edition and customize with the environment variables above:
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ee
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ee
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ce
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ce
```
{{< /tab >}}
{{< /tabs >}}
## Set up your communication preferences
Visit our [email subscription preference center](https://about.gitlab.com/company/preference-center/)
to let us know when to communicate with you. We have an explicit email opt-in
policy so you have complete control over what and how often we send you emails.
Twice a month, we send out the GitLab news you need to know, including new
features, integrations, documentation, and behind the scenes stories from our development teams.
For critical security updates related to bugs and system performance, sign up
for our dedicated security newsletter.
{{< alert type="note" >}}
If you do not opt-in to the security newsletter, you will not receive security alerts.
{{< /alert >}}
## Recommended next steps
After completing your installation, consider the
[recommended next steps, including authentication options and sign-up restrictions](../next_steps.md).
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Install the Linux package on Debian
title: Install the Linux package on Debian
breadcrumbs:
- doc
- install
- package
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
See [supported platforms](_index.md#supported-platforms) for the full list of
supported distributions and architectures.
{{< /alert >}}
## Prerequisites
- OS requirements:
- Debian 11
- Debian 12
- See the [installation requirements](../requirements.md) to learn about the
minimum hardware requirements.
- Before you begin, make sure you have correctly
[set up your DNS](https://docs.gitlab.com/omnibus/settings/dns),
and change `https://gitlab.example.com` to the URL at which you want to access
your GitLab instance. The installation automatically configures and starts
GitLab at that URL.
- For `https://` URLs, GitLab automatically
[requests a certificate with Let's Encrypt](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
which requires inbound HTTP access and a valid hostname. You can also use
[your own certificate](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
or just use `http://` (without the `s`) for an unencrypted URL.
## Enable SSH and open firewall ports
To open the needed firewall ports (80, 443, 22) and be able to access GitLab:
1. Enable and start the OpenSSH server daemon:
```shell
sudo systemctl enable --now ssh
```
1. With `ufw` installed, open the firewall ports:
```shell
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
```
## Add the GitLab package repository
To install GitLab, first add the GitLab package repository.
1. Install the needed packages:
```shell
sudo apt install -y curl
```
1. Use the following script to add the GitLab repository (you can paste the
script's URL to your browser to see what it does before piping it to
`bash`):
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.deb.sh" | sudo bash
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh" | sudo bash
```
{{< /tab >}}
{{< /tabs >}}
## Install the package
Install GitLab using your system's package manager. You can customize the
initial setup by configuring environment variables before installation.
If you don't customize the root credentials during installation:
- GitLab generates a random password and email address for the root
administrator account.
- The password is stored in `/etc/gitlab/initial_root_password` for 24 hours.
- After 24 hours, this file is automatically removed for security reasons.
{{< alert type="note" >}}
While you can also set the initial password in `/etc/gitlab/gitlab.rb` by setting
`gitlab_rails['initial_root_password'] = "password"`, it is not recommended. If
you do set the password with this method, be sure to remove the password from
`/etc/gitlab/gitlab.rb` as it only gets read with the first reconfigure after
the package is installed.
{{< /alert >}}
### Available environment variables
You can customize your GitLab installation by setting the following optional
environment variables. **These variables only work during the first
installation** and have no effect on subsequent reconfigure runs. For existing
installations, use the password from `/etc/gitlab/initial_root_password` or
[reset the root password](../../security/reset_user_password.md).
| Variable | Purpose | Required | Example |
|----------|---------|----------|---------|
| `EXTERNAL_URL` | Sets the external URL for your GitLab instance | Recommended | `EXTERNAL_URL="https://gitlab.example.com"` |
| `GITLAB_ROOT_EMAIL` | Custom email for the root administrator account | Optional | `GITLAB_ROOT_EMAIL="admin@example.com"` |
| `GITLAB_ROOT_PASSWORD` | Custom password (8 characters minimum) for the root administrator account | Optional | `GITLAB_ROOT_PASSWORD="strongpassword"` |
{{< alert type="note" >}}
If GitLab can't detect a valid hostname during installation, reconfigure won't run automatically. In this case, pass any needed environment variables to your first `gitlab-ctl reconfigure` command.
{{< /alert >}}
### Installation commands
Choose your GitLab edition and customize with the environment variables above:
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ee
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ee
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ce
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ce
```
{{< /tab >}}
{{< /tabs >}}
## Set up your communication preferences
Visit our [email subscription preference center](https://about.gitlab.com/company/preference-center/)
to let us know when to communicate with you. We have an explicit email opt-in
policy so you have complete control over what and how often we send you emails.
Twice a month, we send out the GitLab news you need to know, including new
features, integrations, documentation, and behind the scenes stories from our development teams.
For critical security updates related to bugs and system performance, sign up
for our dedicated security newsletter.
{{< alert type="note" >}}
If you do not opt-in to the security newsletter, you will not receive security alerts.
{{< /alert >}}
## Recommended next steps
After completing your installation, consider the
[recommended next steps, including authentication options and sign-up restrictions](../next_steps.md).
|
https://docs.gitlab.com/install/package
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/_index.md
|
2025-08-13
|
doc/install/package
|
[
"doc",
"install",
"package"
] |
_index.md
|
GitLab Delivery
|
Build
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install GitLab using the Linux package
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The Linux packages are mature, scalable, and are used on GitLab.com. If you need additional
flexibility and resilience, we recommend deploying GitLab as described in the
[reference architecture documentation](../../administration/reference_architectures/_index.md).
The Linux package is quicker to install, easier to upgrade, and contains
features to enhance reliability not found in other installation methods. Install through a
single package (also known as Omnibus GitLab) that bundles all the different services
and tools required to run GitLab. See the [installation requirements](../requirements.md)
to learn about the minimum hardware requirements.
Linux packages are available in our packages repository for:
- [GitLab Enterprise Edition](https://packages.gitlab.com/gitlab/gitlab-ee).
- [GitLab Community Edition](https://packages.gitlab.com/gitlab/gitlab-ce).
Check that the required GitLab version is available for your host operating system.
## Supported platforms
GitLab officially supports long term support (LTS) versions of operating
systems. Some operating systems, such as Ubuntu, have a clear distinction
between LTS and non-LTS versions. However, there are other operating systems,
openSUSE for example, that don't follow the LTS concept.
We will usually provide support for a version of an operating system until it
is no longer supported by its vendor, where support is defined as standard or
maintenance support and not as expanded, extended, or premium support. However,
we might end support earlier than the operating system's vendor in these
circumstances:
- Business considerations: Including but not limited to low customer adoption,
disproportionate maintenance costs, or strategic product direction changes.
- Technical constraints: When third-party dependencies, security requirements,
or underlying technology changes make continued support impractical or
impossible.
- Vendor actions: When operating system vendors make changes that fundamentally
impact our software's functionality or when required components become
unavailable.
We will usually issue a deprecation notice at least 6 months before support for
any operating system version is discontinued, on a best-effort basis. In cases
where technical constraints, vendor actions, or other external factors require
that we provide shorter notice periods, we will communicate any support changes
as soon as reasonably possible.
{{< alert type="note" >}}
`amd64` and `x86_64` refer to the same 64-bit architecture. The names `arm64` and `aarch64` are also interchangeable
and refer to the same architecture.
{{< /alert >}}
| Operating system | First supported GitLab version | Architecture | Operating system EOL | Proposed last supported GitLab version | Upstream release notes |
|------------------------------------------------------------------------------------|--------------------------------|-----------------------|----------------------|-------------------------------|---------------------------------------------------------------------------------------------------------------|
| [AlmaLinux 8](almalinux.md) | GitLab CE / GitLab EE 14.5.0 | `x86_64`, `aarch64` <sup>1</sup> | Mar 2029 | GitLab CE / GitLab EE 21.10.0 | [AlmaLinux details](https://almalinux.org/) |
| [AlmaLinux 9](almalinux.md) | GitLab CE / GitLab EE 16.0.0 | `x86_64`, `aarch64` <sup>1</sup> | May 2032 | GitLab CE / GitLab EE 25.0.0 | [AlmaLinux details](https://almalinux.org/) |
| [Amazon Linux 2](amazonlinux_2.md) | GitLab CE / GitLab EE 14.9.0 | `amd64`, `arm64` <sup>1</sup> | June 2026 | GitLab CE / GitLab EE 19.1.0 | [Amazon Linux details](https://aws.amazon.com/amazon-linux-2/faqs/) |
| [Amazon Linux 2023](amazonlinux_2023.md) | GitLab CE / GitLab EE 16.3.0 | `amd64`, `arm64` <sup>1</sup> | June 2029 | GitLab CE / GitLab EE 22.1.0 | [Amazon Linux details](https://docs.aws.amazon.com/linux/al2023/ug/release-cadence.html) |
| [Debian 11](debian.md) | GitLab CE / GitLab EE 14.6.0 | `amd64`, `arm64` <sup>1</sup> | Aug 2026 | GitLab CE / GitLab EE 19.3.0 | [Debian Linux details](https://wiki.debian.org/LTS) |
| [Debian 12](debian.md) | GitLab CE / GitLab EE 16.1.0 | `amd64`, `arm64` <sup>1</sup> | June 2028 | GitLab CE / GitLab EE 19.3.0 | [Debian Linux details](https://wiki.debian.org/LTS) |
| [openSUSE Leap 15.6](suse.md) | GitLab CE / GitLab EE 17.6.0 | `x86_64`, `aarch64` <sup>1</sup> | Dec 2025 | TBD | [openSUSE details](https://en.opensuse.org/Lifetime) |
| [SUSE Linux Enterprise Server 12](suse.md) | GitLab EE 9.0.0 | `x86_64` | Oct 2027 | TBD | [SUSE Linux Enterprise Server details](https://www.suse.com/lifecycle/) |
| [SUSE Linux Enterprise Server 15](suse.md) | GitLab EE 14.8.0 | `x86_64` | Dec 2024 | TBD | [SUSE Linux Enterprise Server details](https://www.suse.com/lifecycle/) |
| [Oracle Linux 8](almalinux.md) | GitLab CE / GitLab EE 12.8.1 | `x86_64` | July 2029 | GitLab CE / GitLab EE 22.2.0 | [Oracle Linux details](https://www.oracle.com/a/ocom/docs/elsp-lifetime-069338.pdf) |
| [Oracle Linux 9](almalinux.md) | GitLab CE / GitLab EE 16.2.0 | `x86_64` | June 2032 | GitLab CE / GitLab EE 25.1.0 | [Oracle Linux details](https://www.oracle.com/a/ocom/docs/elsp-lifetime-069338.pdf) |
| [Red Hat Enterprise Linux 8](almalinux.md) | GitLab CE / GitLab EE 12.8.1 | `x86_64`, `arm64` <sup>1</sup> | May 2029 | GitLab CE / GitLab EE 22.0.0 | [Red Hat Enterprise Linux details](https://access.redhat.com/support/policy/updates/errata/#Life_Cycle_Dates) |
| [Red Hat Enterprise Linux 9](almalinux.md) | GitLab CE / GitLab EE 16.0.0 | `x86_64`, `arm64` <sup>1</sup> | May 2032 | GitLab CE / GitLab EE 25.0.0 | [Red Hat Enterprise Linux details](https://access.redhat.com/support/policy/updates/errata/#Life_Cycle_Dates) |
| [Ubuntu 20.04](ubuntu.md) | GitLab CE / GitLab EE 13.2.0 | `amd64`, `arm64` <sup>1</sup> | April 2025 | GitLab CE / GitLab EE 18.8.0 | [Ubuntu details](https://wiki.ubuntu.com/Releases) |
| [Ubuntu 22.04](ubuntu.md) | GitLab CE / GitLab EE 15.5.0 | `amd64`, `arm64` <sup>1</sup> | April 2027 | GitLab CE / GitLab EE 19.11.0 | [Ubuntu details](https://wiki.ubuntu.com/Releases) |
| [Ubuntu 24.04](ubuntu.md) | GitLab CE / GitLab EE 17.1.0 | `amd64`, `arm64` <sup>1</sup> | April 2029 | GitLab CE / GitLab EE 21.11.0 | [Ubuntu details](https://wiki.ubuntu.com/Releases) |
**Footnotes**:
1. [Known issues](https://gitlab.com/groups/gitlab-org/-/epics/4397) exist for running GitLab on ARM.
### Unofficial, unsupported installation methods
The following installation methods are provided as-is by the wider GitLab
community and are not supported by GitLab:
- [Debian native package](https://wiki.debian.org/gitlab/) (by Pirate Praveen)
- [FreeBSD package](http://www.freshports.org/www/gitlab-ce) (by Torsten Zühlsdorff)
- [Arch Linux package](https://archlinux.org/packages/extra/x86_64/gitlab/) (by the Arch Linux community)
- [Puppet module](https://forge.puppet.com/puppet/gitlab) (by Vox Pupuli)
- [Ansible playbook](https://github.com/geerlingguy/ansible-role-gitlab) (by Jeff Geerling)
- [GitLab virtual appliance (KVM)](https://marketplace.opennebula.io/appliance/6b54a412-03a5-11e9-8652-f0def1753696) (by OpenNebula)
- [GitLab on Cloudron](https://cloudron.io/store/com.gitlab.cloudronapp.html) (via Cloudron App Library)
## End-of-life versions
GitLab provides Linux packages for operating systems only until their
end-of-life (EOL) date. After the EOL date, GitLab stops releasing
official packages.
However, sometimes we don't deprecate an operating system even after it's EOL
because we can't provide packages for a newer version.
The most common reason for this is PackageCloud, our package repository provider,
not supporting newer versions and so we can't upload packages to it.
The list of deprecated operating systems and the final GitLab
release for them can be found below:
| OS version | End of life | Last supported GitLab version |
|:-----------------|:------------------------------------------------------------------------------------|:------------------------------|
| CentOS 6 and RHEL 6 | [November 2020](https://www.centos.org/about/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=13.6&filter=all&filter=all&dist=el%2F6) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=13.6&filter=all&filter=all&dist=el%2F6) 13.6 |
| CentOS 7 and RHEL 7 | [June 2024](https://www.centos.org/about/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=17.7&filter=all&filter=all&dist=el%2F7) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=17.7&filter=all&filter=all&dist=el%2F7) 17.7 |
| CentOS 8 | [December 2021](https://www.centos.org/about/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=14.6&filter=all&filter=all&dist=el%2F8) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=14.6&filter=all&filter=all&dist=el%2F8) 14.6 |
| Oracle Linux 7 | [December 2024](https://endoflife.date/oracle-linux) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=17.7&filter=all&filter=all&dist=ol%2F7) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=17.7&filter=all&filter=all&dist=ol%2F7) 17.7 |
| Scientific Linux 7 | [June 2024](https://scientificlinux.org/downloads/sl-versions/sl7/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=17.7&filter=all&filter=all&dist=scientific%2F7) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=17.7&filter=all&filter=all&dist=scientific%2F7) 17.7 |
| Debian 7 Wheezy | [May 2018](https://www.debian.org/News/2018/20180601) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_11.6&dist=debian%2Fwheezy) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_11.6&dist=debian%2Fwheezy) 11.6 |
| Debian 8 Jessie | [June 2020](https://www.debian.org/News/2020/20200709) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_13.2&dist=debian%2Fjessie) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_13.2&dist=debian%2Fjessie) 13.3 |
| Debian 9 Stretch | [June 2022](https://lists.debian.org/debian-lts-announce/2022/07/msg00002.html) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_15.2&dist=debian%2Fstretch) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_15.2&dist=debian%2Fstretch) 15.2 |
| Debian 10 Buster | [June 2024](https://www.debian.org/News/2024/20240615) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_17.5&dist=debian%2Fbuster) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_17.5&dist=debian%2Fbuster) 17.5 |
| OpenSUSE 42.1 | [May 2017](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-9.3&dist=opensuse%2F42.1) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-9.3&dist=opensuse%2F42.1) 9.3 |
| OpenSUSE 42.2 | [January 2018](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-10.4&dist=opensuse%2F42.2) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-10.4&dist=opensuse%2F42.2) 10.4 |
| OpenSUSE 42.3 | [July 2019](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-12.1&dist=opensuse%2F42.3) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-12.1&dist=opensuse%2F42.3) 12.1 |
| OpenSUSE 13.2 | [January 2017](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-9.1&dist=opensuse%2F13.2) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-9.1&dist=opensuse%2F13.2) 9.1 |
| OpenSUSE 15.0 | [December 2019](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-12.5&dist=opensuse%2F15.0) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-12.5&dist=opensuse%2F15.0) 12.5 |
| OpenSUSE 15.1 | [November 2020](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-13.12&dist=opensuse%2F15.1) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-13.12&dist=opensuse%2F15.1) 13.12 |
| OpenSUSE 15.2 | [December 2021](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-14.7&dist=opensuse%2F15.2) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-14.7&dist=opensuse%2F15.2) 14.7 |
| OpenSUSE 15.3 | [December 2022](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-15.10&dist=opensuse%2F15.3) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-15.10&dist=opensuse%2F15.3) 15.10 |
| OpenSUSE 15.4 | [December 2023](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-16.7&dist=opensuse%2F15.4) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-16.7&dist=opensuse%2F15.4) 16.7 |
| OpenSUSE 15.5 | [December 2024](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-17.8&dist=opensuse%2F15.5) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-17.8&dist=opensuse%2F15.5) 17.8 |
| SLES 15 SP2 | [December 2024](https://www.suse.com/lifecycle/#suse-linux-enterprise-server-15) | [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-18.1&filter=all&filter=all&dist=sles%2F15.2) |
| Raspbian Wheezy | [May 2015](https://downloads.raspberrypi.org/raspbian/images/raspbian-2015-05-07/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/raspberry-pi2/search?q=gitlab-ce_8.17&dist=debian%2Fwheezy) 8.17 |
| Raspbian Jessie | [May 2017](https://downloads.raspberrypi.org/raspbian/images/raspbian-2017-07-05/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/raspberry-pi2/search?q=gitlab-ce_11.7&dist=debian%2Fjessie) 11.7 |
| Raspbian Stretch | [June 2020](https://downloads.raspberrypi.org/raspbian/images/raspbian-2019-04-09/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/raspberry-pi2/search?q=gitlab-ce_13.3&dist=raspbian%2Fstretch) 13.3 |
| Raspberry Pi OS Buster | [June 2024](https://www.debian.org/News/2024/20240615) | [GitLab CE](https://packages.gitlab.com/app/gitlab/raspberry-pi2/search?q=gitlab-ce_17.7&dist=raspbian%2Fbuster) 17.7 |
| Ubuntu 12.04 | [April 2017](https://ubuntu.com/info/release-end-of-life) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_9.1&dist=ubuntu%2Fprecise) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_9.1&dist=ubuntu%2Fprecise) 9.1 |
| Ubuntu 14.04 | [April 2019](https://ubuntu.com/info/release-end-of-life) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_11.10&dist=ubuntu%2Ftrusty) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_11.10&dist=ubuntu%2Ftrusty) 11.10 |
| Ubuntu 16.04 | [April 2021](https://ubuntu.com/info/release-end-of-life) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_13.12&dist=ubuntu%2Fxenial) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_13.12&dist=ubuntu%2Fxenial) 13.12 |
| Ubuntu 18.04 | [June 2023](https://ubuntu.com/info/release-end-of-life) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_16.11&dist=ubuntu%2Fbionic) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=ggitlab-ee_16.11&dist=ubuntu%2Fbionic) 16.11 |
### Raspberry Pi OS (32-bit - Raspbian)
GitLab dropped support for Raspberry Pi OS (32 bit - Raspbian) with GitLab
17.11 being the last version available for the 32-bit platform. Starting with
GitLab 18.0, you should move to Raspberry Pi OS (64 bit) and use the
[Debian arm64 package](debian.md).
For information on backing up data on a 32-bit OS and restoring it to a 64-bit
OS, see [Upgrading operating systems for PostgreSQL](../../administration/postgresql/upgrading_os.md).
## Uninstall the Linux package
To uninstall the Linux package, you can opt to either keep your data (repositories,
database, configuration) or remove all of them:
1. Optional. To remove
[all users and groups created by the Linux package](https://docs.gitlab.com/omnibus/settings/configuration/#disable-user-and-group-account-management)
before removing the package:
```shell
sudo gitlab-ctl stop && sudo gitlab-ctl remove-accounts
```
{{< alert type="note" >}}
If you have a problem removing accounts or groups, run `userdel` or `groupdel` manually
to delete them. You might also want to manually remove the leftover user home directories
from `/home/`.
{{< /alert >}}
1. Choose whether to keep your data or remove all of them:
- To preserve your data (repositories, database, configuration), stop GitLab and
remove its supervision process:
```shell
sudo systemctl stop gitlab-runsvdir
sudo systemctl disable gitlab-runsvdir
sudo rm /usr/lib/systemd/system/gitlab-runsvdir.service
sudo systemctl daemon-reload
sudo systemctl reset-failed
sudo gitlab-ctl uninstall
```
- To remove all data:
```shell
sudo gitlab-ctl cleanse && sudo rm -r /opt/gitlab
```
1. Uninstall the package (replace with `gitlab-ce` if you have GitLab FOSS installed):
{{< tabs >}}
{{< tab title="apt" >}}
```shell
# Debian/Ubuntu
sudo apt remove gitlab-ee
```
{{< /tab >}}
{{< tab title="dnf" >}}
```shell
# AlmaLinux/RHEL/Oracle Linux/Amazon Linux 2023
sudo dnf remove gitlab-ee
```
{{< /tab >}}
{{< tab title="zypper" >}}
```shell
# OpenSUSE Leap/SLES
sudo zypper remove gitlab-ee
```
{{< /tab >}}
{{< tab title="yum" >}}
```shell
# Amazon Linux 2
sudo yum remove gitlab-ee
```
{{< /tab >}}
{{< /tabs >}}
|
---
stage: GitLab Delivery
group: Build
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Install GitLab using the Linux package
breadcrumbs:
- doc
- install
- package
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
The Linux packages are mature, scalable, and are used on GitLab.com. If you need additional
flexibility and resilience, we recommend deploying GitLab as described in the
[reference architecture documentation](../../administration/reference_architectures/_index.md).
The Linux package is quicker to install, easier to upgrade, and contains
features to enhance reliability not found in other installation methods. Install through a
single package (also known as Omnibus GitLab) that bundles all the different services
and tools required to run GitLab. See the [installation requirements](../requirements.md)
to learn about the minimum hardware requirements.
Linux packages are available in our packages repository for:
- [GitLab Enterprise Edition](https://packages.gitlab.com/gitlab/gitlab-ee).
- [GitLab Community Edition](https://packages.gitlab.com/gitlab/gitlab-ce).
Check that the required GitLab version is available for your host operating system.
## Supported platforms
GitLab officially supports long term support (LTS) versions of operating
systems. Some operating systems, such as Ubuntu, have a clear distinction
between LTS and non-LTS versions. However, there are other operating systems,
openSUSE for example, that don't follow the LTS concept.
We will usually provide support for a version of an operating system until it
is no longer supported by its vendor, where support is defined as standard or
maintenance support and not as expanded, extended, or premium support. However,
we might end support earlier than the operating system's vendor in these
circumstances:
- Business considerations: Including but not limited to low customer adoption,
disproportionate maintenance costs, or strategic product direction changes.
- Technical constraints: When third-party dependencies, security requirements,
or underlying technology changes make continued support impractical or
impossible.
- Vendor actions: When operating system vendors make changes that fundamentally
impact our software's functionality or when required components become
unavailable.
We will usually issue a deprecation notice at least 6 months before support for
any operating system version is discontinued, on a best-effort basis. In cases
where technical constraints, vendor actions, or other external factors require
that we provide shorter notice periods, we will communicate any support changes
as soon as reasonably possible.
{{< alert type="note" >}}
`amd64` and `x86_64` refer to the same 64-bit architecture. The names `arm64` and `aarch64` are also interchangeable
and refer to the same architecture.
{{< /alert >}}
| Operating system | First supported GitLab version | Architecture | Operating system EOL | Proposed last supported GitLab version | Upstream release notes |
|------------------------------------------------------------------------------------|--------------------------------|-----------------------|----------------------|-------------------------------|---------------------------------------------------------------------------------------------------------------|
| [AlmaLinux 8](almalinux.md) | GitLab CE / GitLab EE 14.5.0 | `x86_64`, `aarch64` <sup>1</sup> | Mar 2029 | GitLab CE / GitLab EE 21.10.0 | [AlmaLinux details](https://almalinux.org/) |
| [AlmaLinux 9](almalinux.md) | GitLab CE / GitLab EE 16.0.0 | `x86_64`, `aarch64` <sup>1</sup> | May 2032 | GitLab CE / GitLab EE 25.0.0 | [AlmaLinux details](https://almalinux.org/) |
| [Amazon Linux 2](amazonlinux_2.md) | GitLab CE / GitLab EE 14.9.0 | `amd64`, `arm64` <sup>1</sup> | June 2026 | GitLab CE / GitLab EE 19.1.0 | [Amazon Linux details](https://aws.amazon.com/amazon-linux-2/faqs/) |
| [Amazon Linux 2023](amazonlinux_2023.md) | GitLab CE / GitLab EE 16.3.0 | `amd64`, `arm64` <sup>1</sup> | June 2029 | GitLab CE / GitLab EE 22.1.0 | [Amazon Linux details](https://docs.aws.amazon.com/linux/al2023/ug/release-cadence.html) |
| [Debian 11](debian.md) | GitLab CE / GitLab EE 14.6.0 | `amd64`, `arm64` <sup>1</sup> | Aug 2026 | GitLab CE / GitLab EE 19.3.0 | [Debian Linux details](https://wiki.debian.org/LTS) |
| [Debian 12](debian.md) | GitLab CE / GitLab EE 16.1.0 | `amd64`, `arm64` <sup>1</sup> | June 2028 | GitLab CE / GitLab EE 19.3.0 | [Debian Linux details](https://wiki.debian.org/LTS) |
| [openSUSE Leap 15.6](suse.md) | GitLab CE / GitLab EE 17.6.0 | `x86_64`, `aarch64` <sup>1</sup> | Dec 2025 | TBD | [openSUSE details](https://en.opensuse.org/Lifetime) |
| [SUSE Linux Enterprise Server 12](suse.md) | GitLab EE 9.0.0 | `x86_64` | Oct 2027 | TBD | [SUSE Linux Enterprise Server details](https://www.suse.com/lifecycle/) |
| [SUSE Linux Enterprise Server 15](suse.md) | GitLab EE 14.8.0 | `x86_64` | Dec 2024 | TBD | [SUSE Linux Enterprise Server details](https://www.suse.com/lifecycle/) |
| [Oracle Linux 8](almalinux.md) | GitLab CE / GitLab EE 12.8.1 | `x86_64` | July 2029 | GitLab CE / GitLab EE 22.2.0 | [Oracle Linux details](https://www.oracle.com/a/ocom/docs/elsp-lifetime-069338.pdf) |
| [Oracle Linux 9](almalinux.md) | GitLab CE / GitLab EE 16.2.0 | `x86_64` | June 2032 | GitLab CE / GitLab EE 25.1.0 | [Oracle Linux details](https://www.oracle.com/a/ocom/docs/elsp-lifetime-069338.pdf) |
| [Red Hat Enterprise Linux 8](almalinux.md) | GitLab CE / GitLab EE 12.8.1 | `x86_64`, `arm64` <sup>1</sup> | May 2029 | GitLab CE / GitLab EE 22.0.0 | [Red Hat Enterprise Linux details](https://access.redhat.com/support/policy/updates/errata/#Life_Cycle_Dates) |
| [Red Hat Enterprise Linux 9](almalinux.md) | GitLab CE / GitLab EE 16.0.0 | `x86_64`, `arm64` <sup>1</sup> | May 2032 | GitLab CE / GitLab EE 25.0.0 | [Red Hat Enterprise Linux details](https://access.redhat.com/support/policy/updates/errata/#Life_Cycle_Dates) |
| [Ubuntu 20.04](ubuntu.md) | GitLab CE / GitLab EE 13.2.0 | `amd64`, `arm64` <sup>1</sup> | April 2025 | GitLab CE / GitLab EE 18.8.0 | [Ubuntu details](https://wiki.ubuntu.com/Releases) |
| [Ubuntu 22.04](ubuntu.md) | GitLab CE / GitLab EE 15.5.0 | `amd64`, `arm64` <sup>1</sup> | April 2027 | GitLab CE / GitLab EE 19.11.0 | [Ubuntu details](https://wiki.ubuntu.com/Releases) |
| [Ubuntu 24.04](ubuntu.md) | GitLab CE / GitLab EE 17.1.0 | `amd64`, `arm64` <sup>1</sup> | April 2029 | GitLab CE / GitLab EE 21.11.0 | [Ubuntu details](https://wiki.ubuntu.com/Releases) |
**Footnotes**:
1. [Known issues](https://gitlab.com/groups/gitlab-org/-/epics/4397) exist for running GitLab on ARM.
### Unofficial, unsupported installation methods
The following installation methods are provided as-is by the wider GitLab
community and are not supported by GitLab:
- [Debian native package](https://wiki.debian.org/gitlab/) (by Pirate Praveen)
- [FreeBSD package](http://www.freshports.org/www/gitlab-ce) (by Torsten Zühlsdorff)
- [Arch Linux package](https://archlinux.org/packages/extra/x86_64/gitlab/) (by the Arch Linux community)
- [Puppet module](https://forge.puppet.com/puppet/gitlab) (by Vox Pupuli)
- [Ansible playbook](https://github.com/geerlingguy/ansible-role-gitlab) (by Jeff Geerling)
- [GitLab virtual appliance (KVM)](https://marketplace.opennebula.io/appliance/6b54a412-03a5-11e9-8652-f0def1753696) (by OpenNebula)
- [GitLab on Cloudron](https://cloudron.io/store/com.gitlab.cloudronapp.html) (via Cloudron App Library)
## End-of-life versions
GitLab provides Linux packages for operating systems only until their
end-of-life (EOL) date. After the EOL date, GitLab stops releasing
official packages.
However, sometimes we don't deprecate an operating system even after it's EOL
because we can't provide packages for a newer version.
The most common reason for this is PackageCloud, our package repository provider,
not supporting newer versions and so we can't upload packages to it.
The list of deprecated operating systems and the final GitLab
release for them can be found below:
| OS version | End of life | Last supported GitLab version |
|:-----------------|:------------------------------------------------------------------------------------|:------------------------------|
| CentOS 6 and RHEL 6 | [November 2020](https://www.centos.org/about/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=13.6&filter=all&filter=all&dist=el%2F6) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=13.6&filter=all&filter=all&dist=el%2F6) 13.6 |
| CentOS 7 and RHEL 7 | [June 2024](https://www.centos.org/about/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=17.7&filter=all&filter=all&dist=el%2F7) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=17.7&filter=all&filter=all&dist=el%2F7) 17.7 |
| CentOS 8 | [December 2021](https://www.centos.org/about/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=14.6&filter=all&filter=all&dist=el%2F8) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=14.6&filter=all&filter=all&dist=el%2F8) 14.6 |
| Oracle Linux 7 | [December 2024](https://endoflife.date/oracle-linux) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=17.7&filter=all&filter=all&dist=ol%2F7) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=17.7&filter=all&filter=all&dist=ol%2F7) 17.7 |
| Scientific Linux 7 | [June 2024](https://scientificlinux.org/downloads/sl-versions/sl7/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=17.7&filter=all&filter=all&dist=scientific%2F7) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=17.7&filter=all&filter=all&dist=scientific%2F7) 17.7 |
| Debian 7 Wheezy | [May 2018](https://www.debian.org/News/2018/20180601) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_11.6&dist=debian%2Fwheezy) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_11.6&dist=debian%2Fwheezy) 11.6 |
| Debian 8 Jessie | [June 2020](https://www.debian.org/News/2020/20200709) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_13.2&dist=debian%2Fjessie) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_13.2&dist=debian%2Fjessie) 13.3 |
| Debian 9 Stretch | [June 2022](https://lists.debian.org/debian-lts-announce/2022/07/msg00002.html) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_15.2&dist=debian%2Fstretch) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_15.2&dist=debian%2Fstretch) 15.2 |
| Debian 10 Buster | [June 2024](https://www.debian.org/News/2024/20240615) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_17.5&dist=debian%2Fbuster) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_17.5&dist=debian%2Fbuster) 17.5 |
| OpenSUSE 42.1 | [May 2017](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-9.3&dist=opensuse%2F42.1) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-9.3&dist=opensuse%2F42.1) 9.3 |
| OpenSUSE 42.2 | [January 2018](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-10.4&dist=opensuse%2F42.2) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-10.4&dist=opensuse%2F42.2) 10.4 |
| OpenSUSE 42.3 | [July 2019](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-12.1&dist=opensuse%2F42.3) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-12.1&dist=opensuse%2F42.3) 12.1 |
| OpenSUSE 13.2 | [January 2017](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-9.1&dist=opensuse%2F13.2) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-9.1&dist=opensuse%2F13.2) 9.1 |
| OpenSUSE 15.0 | [December 2019](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-12.5&dist=opensuse%2F15.0) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-12.5&dist=opensuse%2F15.0) 12.5 |
| OpenSUSE 15.1 | [November 2020](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-13.12&dist=opensuse%2F15.1) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-13.12&dist=opensuse%2F15.1) 13.12 |
| OpenSUSE 15.2 | [December 2021](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-14.7&dist=opensuse%2F15.2) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-14.7&dist=opensuse%2F15.2) 14.7 |
| OpenSUSE 15.3 | [December 2022](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-15.10&dist=opensuse%2F15.3) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-15.10&dist=opensuse%2F15.3) 15.10 |
| OpenSUSE 15.4 | [December 2023](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-16.7&dist=opensuse%2F15.4) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-16.7&dist=opensuse%2F15.4) 16.7 |
| OpenSUSE 15.5 | [December 2024](https://en.opensuse.org/Lifetime#Discontinued_distributions) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce-17.8&dist=opensuse%2F15.5) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-17.8&dist=opensuse%2F15.5) 17.8 |
| SLES 15 SP2 | [December 2024](https://www.suse.com/lifecycle/#suse-linux-enterprise-server-15) | [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee-18.1&filter=all&filter=all&dist=sles%2F15.2) |
| Raspbian Wheezy | [May 2015](https://downloads.raspberrypi.org/raspbian/images/raspbian-2015-05-07/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/raspberry-pi2/search?q=gitlab-ce_8.17&dist=debian%2Fwheezy) 8.17 |
| Raspbian Jessie | [May 2017](https://downloads.raspberrypi.org/raspbian/images/raspbian-2017-07-05/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/raspberry-pi2/search?q=gitlab-ce_11.7&dist=debian%2Fjessie) 11.7 |
| Raspbian Stretch | [June 2020](https://downloads.raspberrypi.org/raspbian/images/raspbian-2019-04-09/) | [GitLab CE](https://packages.gitlab.com/app/gitlab/raspberry-pi2/search?q=gitlab-ce_13.3&dist=raspbian%2Fstretch) 13.3 |
| Raspberry Pi OS Buster | [June 2024](https://www.debian.org/News/2024/20240615) | [GitLab CE](https://packages.gitlab.com/app/gitlab/raspberry-pi2/search?q=gitlab-ce_17.7&dist=raspbian%2Fbuster) 17.7 |
| Ubuntu 12.04 | [April 2017](https://ubuntu.com/info/release-end-of-life) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_9.1&dist=ubuntu%2Fprecise) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_9.1&dist=ubuntu%2Fprecise) 9.1 |
| Ubuntu 14.04 | [April 2019](https://ubuntu.com/info/release-end-of-life) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_11.10&dist=ubuntu%2Ftrusty) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_11.10&dist=ubuntu%2Ftrusty) 11.10 |
| Ubuntu 16.04 | [April 2021](https://ubuntu.com/info/release-end-of-life) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_13.12&dist=ubuntu%2Fxenial) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=gitlab-ee_13.12&dist=ubuntu%2Fxenial) 13.12 |
| Ubuntu 18.04 | [June 2023](https://ubuntu.com/info/release-end-of-life) | [GitLab CE](https://packages.gitlab.com/app/gitlab/gitlab-ce/search?q=gitlab-ce_16.11&dist=ubuntu%2Fbionic) / [GitLab EE](https://packages.gitlab.com/app/gitlab/gitlab-ee/search?q=ggitlab-ee_16.11&dist=ubuntu%2Fbionic) 16.11 |
### Raspberry Pi OS (32-bit - Raspbian)
GitLab dropped support for Raspberry Pi OS (32 bit - Raspbian) with GitLab
17.11 being the last version available for the 32-bit platform. Starting with
GitLab 18.0, you should move to Raspberry Pi OS (64 bit) and use the
[Debian arm64 package](debian.md).
For information on backing up data on a 32-bit OS and restoring it to a 64-bit
OS, see [Upgrading operating systems for PostgreSQL](../../administration/postgresql/upgrading_os.md).
## Uninstall the Linux package
To uninstall the Linux package, you can opt to either keep your data (repositories,
database, configuration) or remove all of them:
1. Optional. To remove
[all users and groups created by the Linux package](https://docs.gitlab.com/omnibus/settings/configuration/#disable-user-and-group-account-management)
before removing the package:
```shell
sudo gitlab-ctl stop && sudo gitlab-ctl remove-accounts
```
{{< alert type="note" >}}
If you have a problem removing accounts or groups, run `userdel` or `groupdel` manually
to delete them. You might also want to manually remove the leftover user home directories
from `/home/`.
{{< /alert >}}
1. Choose whether to keep your data or remove all of them:
- To preserve your data (repositories, database, configuration), stop GitLab and
remove its supervision process:
```shell
sudo systemctl stop gitlab-runsvdir
sudo systemctl disable gitlab-runsvdir
sudo rm /usr/lib/systemd/system/gitlab-runsvdir.service
sudo systemctl daemon-reload
sudo systemctl reset-failed
sudo gitlab-ctl uninstall
```
- To remove all data:
```shell
sudo gitlab-ctl cleanse && sudo rm -r /opt/gitlab
```
1. Uninstall the package (replace with `gitlab-ce` if you have GitLab FOSS installed):
{{< tabs >}}
{{< tab title="apt" >}}
```shell
# Debian/Ubuntu
sudo apt remove gitlab-ee
```
{{< /tab >}}
{{< tab title="dnf" >}}
```shell
# AlmaLinux/RHEL/Oracle Linux/Amazon Linux 2023
sudo dnf remove gitlab-ee
```
{{< /tab >}}
{{< tab title="zypper" >}}
```shell
# OpenSUSE Leap/SLES
sudo zypper remove gitlab-ee
```
{{< /tab >}}
{{< tab title="yum" >}}
```shell
# Amazon Linux 2
sudo yum remove gitlab-ee
```
{{< /tab >}}
{{< /tabs >}}
|
https://docs.gitlab.com/install/amazonlinux_2023
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/amazonlinux_2023.md
|
2025-08-13
|
doc/install/package
|
[
"doc",
"install",
"package"
] |
amazonlinux_2023.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install the Linux package on Amazon Linux 2023
|
Install the Linux package on Amazon Linux 2023
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
See [supported platforms](_index.md#supported-platforms) for the full list of
supported distributions and architectures.
{{< /alert >}}
## Prerequisites
- OS requirements:
- Amazon Linux 2023
- See the [installation requirements](../requirements.md) to learn about the
minimum hardware requirements.
- Before you begin, make sure you have correctly
[set up your DNS](https://docs.gitlab.com/omnibus/settings/dns),
and change `https://gitlab.example.com` to the URL at which you want to access
your GitLab instance. The installation automatically configures and starts
GitLab at that URL.
- For `https://` URLs, GitLab automatically
[requests a certificate with Let's Encrypt](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
which requires inbound HTTP access and a valid hostname. You can also use
[your own certificate](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
or just use `http://` (without the `s`) for an unencrypted URL.
## Enable SSH and open firewall ports
To open the needed firewall ports (80, 443, 22) and be able to access GitLab:
1. Enable and start the OpenSSH server daemon:
```shell
sudo systemctl enable --now sshd
```
1. With `firewalld` installed, open the firewall ports:
```shell
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-service=ssh
sudo systemctl reload firewalld
```
## Add the GitLab package repository
To install GitLab, first add the GitLab package repository.
1. Install the needed packages:
```shell
sudo dnf install -y curl
```
1. Use the following script to add the GitLab repository (you can paste the
script's URL to your browser to see what it does before piping it to
`bash`):
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< /tabs >}}
## Install the package
Install GitLab using your system's package manager. You can customize the
initial setup by configuring environment variables before installation.
If you don't customize the root credentials during installation:
- GitLab generates a random password and email address for the root
administrator account.
- The password is stored in `/etc/gitlab/initial_root_password` for 24 hours.
- After 24 hours, this file is automatically removed for security reasons.
{{< alert type="note" >}}
While you can also set the initial password in `/etc/gitlab/gitlab.rb` by setting
`gitlab_rails['initial_root_password'] = "password"`, it is not recommended. If
you do set the password with this method, be sure to remove the password from
`/etc/gitlab/gitlab.rb` as it only gets read with the first reconfigure after
the package is installed.
{{< /alert >}}
### Available environment variables
You can customize your GitLab installation by setting the following optional
environment variables. **These variables only work during the first
installation** and have no effect on subsequent reconfigure runs. For existing
installations, use the password from `/etc/gitlab/initial_root_password` or
[reset the root password](../../security/reset_user_password.md).
| Variable | Purpose | Required | Example |
|----------|---------|----------|---------|
| `EXTERNAL_URL` | Sets the external URL for your GitLab instance | Recommended | `EXTERNAL_URL="https://gitlab.example.com"` |
| `GITLAB_ROOT_EMAIL` | Custom email for the root administrator account | Optional | `GITLAB_ROOT_EMAIL="admin@example.com"` |
| `GITLAB_ROOT_PASSWORD` | Custom password (8 characters minimum) for the root administrator account | Optional | `GITLAB_ROOT_PASSWORD="strongpassword"` |
{{< alert type="note" >}}
If GitLab can't detect a valid hostname during installation, reconfigure won't run automatically. In this case, pass any needed environment variables to your first `gitlab-ctl reconfigure` command.
{{< /alert >}}
### Installation commands
Choose your GitLab edition and customize with the environment variables above:
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ee
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ee
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ce
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ce
```
{{< /tab >}}
{{< /tabs >}}
## Set up your communication preferences
Visit our [email subscription preference center](https://about.gitlab.com/company/preference-center/)
to let us know when to communicate with you. We have an explicit email opt-in
policy so you have complete control over what and how often we send you emails.
Twice a month, we send out the GitLab news you need to know, including new
features, integrations, documentation, and behind the scenes stories from our development teams.
For critical security updates related to bugs and system performance, sign up
for our dedicated security newsletter.
{{< alert type="note" >}}
If you do not opt-in to the security newsletter, you will not receive security alerts.
{{< /alert >}}
## Recommended next steps
After completing your installation, consider the
[recommended next steps, including authentication options and sign-up restrictions](../next_steps.md).
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Install the Linux package on Amazon Linux 2023
title: Install the Linux package on Amazon Linux 2023
breadcrumbs:
- doc
- install
- package
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
See [supported platforms](_index.md#supported-platforms) for the full list of
supported distributions and architectures.
{{< /alert >}}
## Prerequisites
- OS requirements:
- Amazon Linux 2023
- See the [installation requirements](../requirements.md) to learn about the
minimum hardware requirements.
- Before you begin, make sure you have correctly
[set up your DNS](https://docs.gitlab.com/omnibus/settings/dns),
and change `https://gitlab.example.com` to the URL at which you want to access
your GitLab instance. The installation automatically configures and starts
GitLab at that URL.
- For `https://` URLs, GitLab automatically
[requests a certificate with Let's Encrypt](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
which requires inbound HTTP access and a valid hostname. You can also use
[your own certificate](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
or just use `http://` (without the `s`) for an unencrypted URL.
## Enable SSH and open firewall ports
To open the needed firewall ports (80, 443, 22) and be able to access GitLab:
1. Enable and start the OpenSSH server daemon:
```shell
sudo systemctl enable --now sshd
```
1. With `firewalld` installed, open the firewall ports:
```shell
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-service=ssh
sudo systemctl reload firewalld
```
## Add the GitLab package repository
To install GitLab, first add the GitLab package repository.
1. Install the needed packages:
```shell
sudo dnf install -y curl
```
1. Use the following script to add the GitLab repository (you can paste the
script's URL to your browser to see what it does before piping it to
`bash`):
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< /tabs >}}
## Install the package
Install GitLab using your system's package manager. You can customize the
initial setup by configuring environment variables before installation.
If you don't customize the root credentials during installation:
- GitLab generates a random password and email address for the root
administrator account.
- The password is stored in `/etc/gitlab/initial_root_password` for 24 hours.
- After 24 hours, this file is automatically removed for security reasons.
{{< alert type="note" >}}
While you can also set the initial password in `/etc/gitlab/gitlab.rb` by setting
`gitlab_rails['initial_root_password'] = "password"`, it is not recommended. If
you do set the password with this method, be sure to remove the password from
`/etc/gitlab/gitlab.rb` as it only gets read with the first reconfigure after
the package is installed.
{{< /alert >}}
### Available environment variables
You can customize your GitLab installation by setting the following optional
environment variables. **These variables only work during the first
installation** and have no effect on subsequent reconfigure runs. For existing
installations, use the password from `/etc/gitlab/initial_root_password` or
[reset the root password](../../security/reset_user_password.md).
| Variable | Purpose | Required | Example |
|----------|---------|----------|---------|
| `EXTERNAL_URL` | Sets the external URL for your GitLab instance | Recommended | `EXTERNAL_URL="https://gitlab.example.com"` |
| `GITLAB_ROOT_EMAIL` | Custom email for the root administrator account | Optional | `GITLAB_ROOT_EMAIL="admin@example.com"` |
| `GITLAB_ROOT_PASSWORD` | Custom password (8 characters minimum) for the root administrator account | Optional | `GITLAB_ROOT_PASSWORD="strongpassword"` |
{{< alert type="note" >}}
If GitLab can't detect a valid hostname during installation, reconfigure won't run automatically. In this case, pass any needed environment variables to your first `gitlab-ctl reconfigure` command.
{{< /alert >}}
### Installation commands
Choose your GitLab edition and customize with the environment variables above:
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ee
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ee
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ce
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" dnf install gitlab-ce
```
{{< /tab >}}
{{< /tabs >}}
## Set up your communication preferences
Visit our [email subscription preference center](https://about.gitlab.com/company/preference-center/)
to let us know when to communicate with you. We have an explicit email opt-in
policy so you have complete control over what and how often we send you emails.
Twice a month, we send out the GitLab news you need to know, including new
features, integrations, documentation, and behind the scenes stories from our development teams.
For critical security updates related to bugs and system performance, sign up
for our dedicated security newsletter.
{{< alert type="note" >}}
If you do not opt-in to the security newsletter, you will not receive security alerts.
{{< /alert >}}
## Recommended next steps
After completing your installation, consider the
[recommended next steps, including authentication options and sign-up restrictions](../next_steps.md).
|
https://docs.gitlab.com/install/amazonlinux_2
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/amazonlinux_2.md
|
2025-08-13
|
doc/install/package
|
[
"doc",
"install",
"package"
] |
amazonlinux_2.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install the Linux package on Amazon Linux 2
|
Install the Linux package on Amazon Linux 2
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
See [supported platforms](_index.md#supported-platforms) for a full list of
supported distributions and architectures.
{{< /alert >}}
## Prerequisites
- OS requirements:
- Amazon Linux 2
- See the [installation requirements](../requirements.md) to learn about the
minimum hardware requirements.
- Before you begin, make sure you have correctly
[set up your DNS](https://docs.gitlab.com/omnibus/settings/dns),
and change `https://gitlab.example.com` to the URL at which you want to access
your GitLab instance. The installation automatically configures and starts
GitLab at that URL.
- For `https://` URLs, GitLab automatically
[requests a certificate with Let's Encrypt](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
which requires inbound HTTP access and a valid hostname. You can also use
[your own certificate](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
or just use `http://` (without the `s`) for an unencrypted URL.
## Enable SSH and open firewall ports
To open the needed firewall ports (80, 443, 22) and be able to access GitLab:
1. Enable and start the OpenSSH server daemon:
```shell
sudo systemctl enable --now sshd
```
1. With `firewalld` installed, open the firewall ports:
```shell
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-service=ssh
sudo systemctl reload firewalld
```
## Add the GitLab package repository
To install GitLab, first add the GitLab package repository.
1. Install the needed packages:
```shell
sudo yum install -y curl
```
1. Use the following script to add the GitLab repository (you can paste the
script's URL to your browser to see what it does before piping it to
`bash`):
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< /tabs >}}
## Install the package
Install GitLab using your system's package manager. You can customize the
initial setup by configuring environment variables before installation.
If you don't customize the root credentials during installation:
- GitLab generates a random password and email address for the root
administrator account.
- The password is stored in `/etc/gitlab/initial_root_password` for 24 hours.
- After 24 hours, this file is automatically removed for security reasons.
{{< alert type="note" >}}
While you can also set the initial password in `/etc/gitlab/gitlab.rb` by setting
`gitlab_rails['initial_root_password'] = "password"`, it is not recommended. If
you do set the password with this method, be sure to remove the password from
`/etc/gitlab/gitlab.rb` as it only gets read with the first reconfigure after
the package is installed.
{{< /alert >}}
### Available environment variables
You can customize your GitLab installation by setting the following optional
environment variables. **These variables only work during the first
installation** and have no effect on subsequent reconfigure runs. For existing
installations, use the password from `/etc/gitlab/initial_root_password` or
[reset the root password](../../security/reset_user_password.md).
| Variable | Purpose | Required | Example |
|----------|---------|----------|---------|
| `EXTERNAL_URL` | Sets the external URL for your GitLab instance | Recommended | `EXTERNAL_URL="https://gitlab.example.com"` |
| `GITLAB_ROOT_EMAIL` | Custom email for the root administrator account | Optional | `GITLAB_ROOT_EMAIL="admin@example.com"` |
| `GITLAB_ROOT_PASSWORD` | Custom password (8 characters minimum) for the root administrator account | Optional | `GITLAB_ROOT_PASSWORD="strongpassword"` |
{{< alert type="note" >}}
If GitLab can't detect a valid hostname during installation, reconfigure won't run automatically. In this case, pass any needed environment variables to your first `gitlab-ctl reconfigure` command.
{{< /alert >}}
### Installation commands
Choose your GitLab edition and customize with the environment variables above:
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" yum install gitlab-ee
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" yum install gitlab-ee
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" yum install gitlab-ce
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" yum install gitlab-ce
```
{{< /tab >}}
{{< /tabs >}}
## Set up your communication preferences
Visit our [email subscription preference center](https://about.gitlab.com/company/preference-center/)
to let us know when to communicate with you. We have an explicit email opt-in
policy so you have complete control over what and how often we send you emails.
Twice a month, we send out the GitLab news you need to know, including new
features, integrations, documentation, and behind the scenes stories from our development teams.
For critical security updates related to bugs and system performance, sign up
for our dedicated security newsletter.
{{< alert type="note" >}}
If you do not opt-in to the security newsletter, you will not receive security alerts.
{{< /alert >}}
## Recommended next steps
After completing your installation, consider the
[recommended next steps, including authentication options and sign-up restrictions](../next_steps.md).
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Install the Linux package on Amazon Linux 2
title: Install the Linux package on Amazon Linux 2
breadcrumbs:
- doc
- install
- package
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
See [supported platforms](_index.md#supported-platforms) for a full list of
supported distributions and architectures.
{{< /alert >}}
## Prerequisites
- OS requirements:
- Amazon Linux 2
- See the [installation requirements](../requirements.md) to learn about the
minimum hardware requirements.
- Before you begin, make sure you have correctly
[set up your DNS](https://docs.gitlab.com/omnibus/settings/dns),
and change `https://gitlab.example.com` to the URL at which you want to access
your GitLab instance. The installation automatically configures and starts
GitLab at that URL.
- For `https://` URLs, GitLab automatically
[requests a certificate with Let's Encrypt](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
which requires inbound HTTP access and a valid hostname. You can also use
[your own certificate](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
or just use `http://` (without the `s`) for an unencrypted URL.
## Enable SSH and open firewall ports
To open the needed firewall ports (80, 443, 22) and be able to access GitLab:
1. Enable and start the OpenSSH server daemon:
```shell
sudo systemctl enable --now sshd
```
1. With `firewalld` installed, open the firewall ports:
```shell
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-service=ssh
sudo systemctl reload firewalld
```
## Add the GitLab package repository
To install GitLab, first add the GitLab package repository.
1. Install the needed packages:
```shell
sudo yum install -y curl
```
1. Use the following script to add the GitLab repository (you can paste the
script's URL to your browser to see what it does before piping it to
`bash`):
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< /tabs >}}
## Install the package
Install GitLab using your system's package manager. You can customize the
initial setup by configuring environment variables before installation.
If you don't customize the root credentials during installation:
- GitLab generates a random password and email address for the root
administrator account.
- The password is stored in `/etc/gitlab/initial_root_password` for 24 hours.
- After 24 hours, this file is automatically removed for security reasons.
{{< alert type="note" >}}
While you can also set the initial password in `/etc/gitlab/gitlab.rb` by setting
`gitlab_rails['initial_root_password'] = "password"`, it is not recommended. If
you do set the password with this method, be sure to remove the password from
`/etc/gitlab/gitlab.rb` as it only gets read with the first reconfigure after
the package is installed.
{{< /alert >}}
### Available environment variables
You can customize your GitLab installation by setting the following optional
environment variables. **These variables only work during the first
installation** and have no effect on subsequent reconfigure runs. For existing
installations, use the password from `/etc/gitlab/initial_root_password` or
[reset the root password](../../security/reset_user_password.md).
| Variable | Purpose | Required | Example |
|----------|---------|----------|---------|
| `EXTERNAL_URL` | Sets the external URL for your GitLab instance | Recommended | `EXTERNAL_URL="https://gitlab.example.com"` |
| `GITLAB_ROOT_EMAIL` | Custom email for the root administrator account | Optional | `GITLAB_ROOT_EMAIL="admin@example.com"` |
| `GITLAB_ROOT_PASSWORD` | Custom password (8 characters minimum) for the root administrator account | Optional | `GITLAB_ROOT_PASSWORD="strongpassword"` |
{{< alert type="note" >}}
If GitLab can't detect a valid hostname during installation, reconfigure won't run automatically. In this case, pass any needed environment variables to your first `gitlab-ctl reconfigure` command.
{{< /alert >}}
### Installation commands
Choose your GitLab edition and customize with the environment variables above:
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" yum install gitlab-ee
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" yum install gitlab-ee
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" yum install gitlab-ce
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" yum install gitlab-ce
```
{{< /tab >}}
{{< /tabs >}}
## Set up your communication preferences
Visit our [email subscription preference center](https://about.gitlab.com/company/preference-center/)
to let us know when to communicate with you. We have an explicit email opt-in
policy so you have complete control over what and how often we send you emails.
Twice a month, we send out the GitLab news you need to know, including new
features, integrations, documentation, and behind the scenes stories from our development teams.
For critical security updates related to bugs and system performance, sign up
for our dedicated security newsletter.
{{< alert type="note" >}}
If you do not opt-in to the security newsletter, you will not receive security alerts.
{{< /alert >}}
## Recommended next steps
After completing your installation, consider the
[recommended next steps, including authentication options and sign-up restrictions](../next_steps.md).
|
https://docs.gitlab.com/install/ubuntu
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/ubuntu.md
|
2025-08-13
|
doc/install/package
|
[
"doc",
"install",
"package"
] |
ubuntu.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install the Linux package on Ubuntu
|
Install the Linux package on Ubuntu
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
See [supported platforms](_index.md#supported-platforms) for the full list of
supported distributions and architectures.
{{< /alert >}}
## Prerequisites
- OS requirements:
- Ubuntu 20.04
- Ubuntu 22.04
- Ubuntu 24.04
- See the [installation requirements](../requirements.md) to learn about the
minimum hardware requirements.
- Before you begin, make sure you have correctly
[set up your DNS](https://docs.gitlab.com/omnibus/settings/dns),
and change `https://gitlab.example.com` to the URL at which you want to access
your GitLab instance. The installation automatically configures and starts
GitLab at that URL.
- For `https://` URLs, GitLab automatically
[requests a certificate with Let's Encrypt](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
which requires inbound HTTP access and a valid hostname. You can also use
[your own certificate](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
or just use `http://` (without the `s`) for an unencrypted URL.
## Enable SSH and open firewall ports
To open the needed firewall ports (80, 443, 22) and be able to access GitLab:
1. Enable and start the OpenSSH server daemon:
```shell
sudo systemctl enable --now ssh
```
1. With `ufw` installed, open the firewall ports:
```shell
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
```
## Add the GitLab package repository
To install GitLab, first add the GitLab package repository.
1. Install the needed packages:
```shell
sudo apt install -y curl
```
1. Use the following script to add the GitLab repository (you can paste the
script's URL to your browser to see what it does before piping it to
`bash`):
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.deb.sh" | sudo bash
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh" | sudo bash
```
{{< /tab >}}
{{< /tabs >}}
## Install the package
Install GitLab using your system's package manager. You can customize the
initial setup by configuring environment variables before installation.
If you don't customize the root credentials during installation:
- GitLab generates a random password and email address for the root
administrator account.
- The password is stored in `/etc/gitlab/initial_root_password` for 24 hours.
- After 24 hours, this file is automatically removed for security reasons.
{{< alert type="note" >}}
While you can also set the initial password in `/etc/gitlab/gitlab.rb` by setting
`gitlab_rails['initial_root_password'] = "password"`, it is not recommended. If
you do set the password with this method, be sure to remove the password from
`/etc/gitlab/gitlab.rb` as it only gets read with the first reconfigure after
the package is installed.
{{< /alert >}}
### Available environment variables
You can customize your GitLab installation by setting the following optional
environment variables. **These variables only work during the first
installation** and have no effect on subsequent reconfigure runs. For existing
installations, use the password from `/etc/gitlab/initial_root_password` or
[reset the root password](../../security/reset_user_password.md).
| Variable | Purpose | Required | Example |
|----------|---------|----------|---------|
| `EXTERNAL_URL` | Sets the external URL for your GitLab instance | Recommended | `EXTERNAL_URL="https://gitlab.example.com"` |
| `GITLAB_ROOT_EMAIL` | Custom email for the root administrator account | Optional | `GITLAB_ROOT_EMAIL="admin@example.com"` |
| `GITLAB_ROOT_PASSWORD` | Custom password (8 characters minimum) for the root administrator account | Optional | `GITLAB_ROOT_PASSWORD="strongpassword"` |
{{< alert type="note" >}}
If GitLab can't detect a valid hostname during installation, reconfigure won't run automatically. In this case, pass any needed environment variables to your first `gitlab-ctl reconfigure` command.
{{< /alert >}}
### Installation commands
Choose your GitLab edition and customize with the environment variables above:
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ee
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ee
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ce
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ce
```
{{< /tab >}}
{{< /tabs >}}
## Set up your communication preferences
Visit our [email subscription preference center](https://about.gitlab.com/company/preference-center/)
to let us know when to communicate with you. We have an explicit email opt-in
policy so you have complete control over what and how often we send you emails.
Twice a month, we send out the GitLab news you need to know, including new
features, integrations, documentation, and behind the scenes stories from our development teams.
For critical security updates related to bugs and system performance, sign up
for our dedicated security newsletter.
{{< alert type="note" >}}
If you do not opt-in to the security newsletter, you will not receive security alerts.
{{< /alert >}}
## Recommended next steps
After completing your installation, consider the
[recommended next steps, including authentication options and sign-up restrictions](../next_steps.md).
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Install the Linux package on Ubuntu
title: Install the Linux package on Ubuntu
breadcrumbs:
- doc
- install
- package
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
See [supported platforms](_index.md#supported-platforms) for the full list of
supported distributions and architectures.
{{< /alert >}}
## Prerequisites
- OS requirements:
- Ubuntu 20.04
- Ubuntu 22.04
- Ubuntu 24.04
- See the [installation requirements](../requirements.md) to learn about the
minimum hardware requirements.
- Before you begin, make sure you have correctly
[set up your DNS](https://docs.gitlab.com/omnibus/settings/dns),
and change `https://gitlab.example.com` to the URL at which you want to access
your GitLab instance. The installation automatically configures and starts
GitLab at that URL.
- For `https://` URLs, GitLab automatically
[requests a certificate with Let's Encrypt](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
which requires inbound HTTP access and a valid hostname. You can also use
[your own certificate](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
or just use `http://` (without the `s`) for an unencrypted URL.
## Enable SSH and open firewall ports
To open the needed firewall ports (80, 443, 22) and be able to access GitLab:
1. Enable and start the OpenSSH server daemon:
```shell
sudo systemctl enable --now ssh
```
1. With `ufw` installed, open the firewall ports:
```shell
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
```
## Add the GitLab package repository
To install GitLab, first add the GitLab package repository.
1. Install the needed packages:
```shell
sudo apt install -y curl
```
1. Use the following script to add the GitLab repository (you can paste the
script's URL to your browser to see what it does before piping it to
`bash`):
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.deb.sh" | sudo bash
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh" | sudo bash
```
{{< /tab >}}
{{< /tabs >}}
## Install the package
Install GitLab using your system's package manager. You can customize the
initial setup by configuring environment variables before installation.
If you don't customize the root credentials during installation:
- GitLab generates a random password and email address for the root
administrator account.
- The password is stored in `/etc/gitlab/initial_root_password` for 24 hours.
- After 24 hours, this file is automatically removed for security reasons.
{{< alert type="note" >}}
While you can also set the initial password in `/etc/gitlab/gitlab.rb` by setting
`gitlab_rails['initial_root_password'] = "password"`, it is not recommended. If
you do set the password with this method, be sure to remove the password from
`/etc/gitlab/gitlab.rb` as it only gets read with the first reconfigure after
the package is installed.
{{< /alert >}}
### Available environment variables
You can customize your GitLab installation by setting the following optional
environment variables. **These variables only work during the first
installation** and have no effect on subsequent reconfigure runs. For existing
installations, use the password from `/etc/gitlab/initial_root_password` or
[reset the root password](../../security/reset_user_password.md).
| Variable | Purpose | Required | Example |
|----------|---------|----------|---------|
| `EXTERNAL_URL` | Sets the external URL for your GitLab instance | Recommended | `EXTERNAL_URL="https://gitlab.example.com"` |
| `GITLAB_ROOT_EMAIL` | Custom email for the root administrator account | Optional | `GITLAB_ROOT_EMAIL="admin@example.com"` |
| `GITLAB_ROOT_PASSWORD` | Custom password (8 characters minimum) for the root administrator account | Optional | `GITLAB_ROOT_PASSWORD="strongpassword"` |
{{< alert type="note" >}}
If GitLab can't detect a valid hostname during installation, reconfigure won't run automatically. In this case, pass any needed environment variables to your first `gitlab-ctl reconfigure` command.
{{< /alert >}}
### Installation commands
Choose your GitLab edition and customize with the environment variables above:
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ee
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ee
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ce
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" apt install gitlab-ce
```
{{< /tab >}}
{{< /tabs >}}
## Set up your communication preferences
Visit our [email subscription preference center](https://about.gitlab.com/company/preference-center/)
to let us know when to communicate with you. We have an explicit email opt-in
policy so you have complete control over what and how often we send you emails.
Twice a month, we send out the GitLab news you need to know, including new
features, integrations, documentation, and behind the scenes stories from our development teams.
For critical security updates related to bugs and system performance, sign up
for our dedicated security newsletter.
{{< alert type="note" >}}
If you do not opt-in to the security newsletter, you will not receive security alerts.
{{< /alert >}}
## Recommended next steps
After completing your installation, consider the
[recommended next steps, including authentication options and sign-up restrictions](../next_steps.md).
|
https://docs.gitlab.com/install/suse
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/suse.md
|
2025-08-13
|
doc/install/package
|
[
"doc",
"install",
"package"
] |
suse.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install the Linux package on OpenSUSE and SLES
|
Install the Linux package on OpenSUSE and SLES
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
See [supported platforms](_index.md#supported-platforms) for the full list of
supported distributions and architectures.
{{< /alert >}}
## Prerequisites
- OS requirements:
- OpenSUSE Leap 15.6
- SLES 12
- SLES 15 SP6
- See the [installation requirements](../requirements.md) to learn about the
minimum hardware requirements.
- Before you begin, make sure you have correctly
[set up your DNS](https://docs.gitlab.com/omnibus/settings/dns),
and change `https://gitlab.example.com` to the URL at which you want to access
your GitLab instance. The installation automatically configures and starts
GitLab at that URL.
- For `https://` URLs, GitLab automatically
[requests a certificate with Let's Encrypt](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
which requires inbound HTTP access and a valid hostname. You can also use
[your own certificate](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
or just use `http://` (without the `s`) for an unencrypted URL.
## Enable SSH and open firewall ports
To open the needed firewall ports (80, 443, 22) and be able to access GitLab:
1. Enable and start the OpenSSH server daemon:
```shell
sudo systemctl enable --now sshd
```
1. With `firewalld` installed, open the firewall ports:
```shell
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-service=ssh
sudo systemctl reload firewalld
```
## Add the GitLab package repository
To install GitLab, first add the GitLab package repository.
1. Install the needed packages:
```shell
sudo zypper install curl
```
1. Use the following script to add the GitLab repository (you can paste the
script's URL to your browser to see what it does before piping it to
`bash`):
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< /tabs >}}
## Install the package
Install GitLab using your system's package manager. You can customize the
initial setup by configuring environment variables before installation.
If you don't customize the root credentials during installation:
- GitLab generates a random password and email address for the root
administrator account.
- The password is stored in `/etc/gitlab/initial_root_password` for 24 hours.
- After 24 hours, this file is automatically removed for security reasons.
{{< alert type="note" >}}
While you can also set the initial password in `/etc/gitlab/gitlab.rb` by setting
`gitlab_rails['initial_root_password'] = "password"`, it is not recommended. If
you do set the password with this method, be sure to remove the password from
`/etc/gitlab/gitlab.rb` as it only gets read with the first reconfigure after
the package is installed.
{{< /alert >}}
### Available environment variables
You can customize your GitLab installation by setting the following optional
environment variables. **These variables only work during the first
installation** and have no effect on subsequent reconfigure runs. For existing
installations, use the password from `/etc/gitlab/initial_root_password` or
[reset the root password](../../security/reset_user_password.md).
| Variable | Purpose | Required | Example |
|----------|---------|----------|---------|
| `EXTERNAL_URL` | Sets the external URL for your GitLab instance | Recommended | `EXTERNAL_URL="https://gitlab.example.com"` |
| `GITLAB_ROOT_EMAIL` | Custom email for the root administrator account | Optional | `GITLAB_ROOT_EMAIL="admin@example.com"` |
| `GITLAB_ROOT_PASSWORD` | Custom password (8 characters minimum) for the root administrator account | Optional | `GITLAB_ROOT_PASSWORD="strongpassword"` |
{{< alert type="note" >}}
If GitLab can't detect a valid hostname during installation, reconfigure won't run automatically. In this case, pass any needed environment variables to your first `gitlab-ctl reconfigure` command.
{{< /alert >}}
### Installation commands
Choose your GitLab edition and customize with the environment variables above:
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" zypper install gitlab-ee
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" zypper install gitlab-ee
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" zypper install gitlab-ce
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" zypper install gitlab-ce
```
{{< /tab >}}
{{< /tabs >}}
## Set up your communication preferences
Visit our [email subscription preference center](https://about.gitlab.com/company/preference-center/)
to let us know when to communicate with you. We have an explicit email opt-in
policy so you have complete control over what and how often we send you emails.
Twice a month, we send out the GitLab news you need to know, including new
features, integrations, documentation, and behind the scenes stories from our development teams.
For critical security updates related to bugs and system performance, sign up
for our dedicated security newsletter.
{{< alert type="note" >}}
If you do not opt-in to the security newsletter, you will not receive security alerts.
{{< /alert >}}
## Recommended next steps
After completing your installation, consider the
[recommended next steps, including authentication options and sign-up restrictions](../next_steps.md).
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Install the Linux package on OpenSUSE and SLES
title: Install the Linux package on OpenSUSE and SLES
breadcrumbs:
- doc
- install
- package
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
{{< alert type="note" >}}
See [supported platforms](_index.md#supported-platforms) for the full list of
supported distributions and architectures.
{{< /alert >}}
## Prerequisites
- OS requirements:
- OpenSUSE Leap 15.6
- SLES 12
- SLES 15 SP6
- See the [installation requirements](../requirements.md) to learn about the
minimum hardware requirements.
- Before you begin, make sure you have correctly
[set up your DNS](https://docs.gitlab.com/omnibus/settings/dns),
and change `https://gitlab.example.com` to the URL at which you want to access
your GitLab instance. The installation automatically configures and starts
GitLab at that URL.
- For `https://` URLs, GitLab automatically
[requests a certificate with Let's Encrypt](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration),
which requires inbound HTTP access and a valid hostname. You can also use
[your own certificate](https://docs.gitlab.com/omnibus/settings/ssl/#configure-https-manually),
or just use `http://` (without the `s`) for an unencrypted URL.
## Enable SSH and open firewall ports
To open the needed firewall ports (80, 443, 22) and be able to access GitLab:
1. Enable and start the OpenSSH server daemon:
```shell
sudo systemctl enable --now sshd
```
1. With `firewalld` installed, open the firewall ports:
```shell
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-service=ssh
sudo systemctl reload firewalld
```
## Add the GitLab package repository
To install GitLab, first add the GitLab package repository.
1. Install the needed packages:
```shell
sudo zypper install curl
```
1. Use the following script to add the GitLab repository (you can paste the
script's URL to your browser to see what it does before piping it to
`bash`):
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
```shell
curl "https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh" | sudo bash
```
{{< /tab >}}
{{< /tabs >}}
## Install the package
Install GitLab using your system's package manager. You can customize the
initial setup by configuring environment variables before installation.
If you don't customize the root credentials during installation:
- GitLab generates a random password and email address for the root
administrator account.
- The password is stored in `/etc/gitlab/initial_root_password` for 24 hours.
- After 24 hours, this file is automatically removed for security reasons.
{{< alert type="note" >}}
While you can also set the initial password in `/etc/gitlab/gitlab.rb` by setting
`gitlab_rails['initial_root_password'] = "password"`, it is not recommended. If
you do set the password with this method, be sure to remove the password from
`/etc/gitlab/gitlab.rb` as it only gets read with the first reconfigure after
the package is installed.
{{< /alert >}}
### Available environment variables
You can customize your GitLab installation by setting the following optional
environment variables. **These variables only work during the first
installation** and have no effect on subsequent reconfigure runs. For existing
installations, use the password from `/etc/gitlab/initial_root_password` or
[reset the root password](../../security/reset_user_password.md).
| Variable | Purpose | Required | Example |
|----------|---------|----------|---------|
| `EXTERNAL_URL` | Sets the external URL for your GitLab instance | Recommended | `EXTERNAL_URL="https://gitlab.example.com"` |
| `GITLAB_ROOT_EMAIL` | Custom email for the root administrator account | Optional | `GITLAB_ROOT_EMAIL="admin@example.com"` |
| `GITLAB_ROOT_PASSWORD` | Custom password (8 characters minimum) for the root administrator account | Optional | `GITLAB_ROOT_PASSWORD="strongpassword"` |
{{< alert type="note" >}}
If GitLab can't detect a valid hostname during installation, reconfigure won't run automatically. In this case, pass any needed environment variables to your first `gitlab-ctl reconfigure` command.
{{< /alert >}}
### Installation commands
Choose your GitLab edition and customize with the environment variables above:
{{< tabs >}}
{{< tab title="Enterprise Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" zypper install gitlab-ee
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" zypper install gitlab-ee
```
{{< /tab >}}
{{< tab title="Community Edition" >}}
**Basic installation:**
```shell
sudo EXTERNAL_URL="https://gitlab.example.com" zypper install gitlab-ce
```
**With custom root credentials:**
```shell
sudo GITLAB_ROOT_EMAIL="admin@example.com" GITLAB_ROOT_PASSWORD="strongpassword" EXTERNAL_URL="https://gitlab.example.com" zypper install gitlab-ce
```
{{< /tab >}}
{{< /tabs >}}
## Set up your communication preferences
Visit our [email subscription preference center](https://about.gitlab.com/company/preference-center/)
to let us know when to communicate with you. We have an explicit email opt-in
policy so you have complete control over what and how often we send you emails.
Twice a month, we send out the GitLab news you need to know, including new
features, integrations, documentation, and behind the scenes stories from our development teams.
For critical security updates related to bugs and system performance, sign up
for our dedicated security newsletter.
{{< alert type="note" >}}
If you do not opt-in to the security newsletter, you will not receive security alerts.
{{< /alert >}}
## Recommended next steps
After completing your installation, consider the
[recommended next steps, including authentication options and sign-up restrictions](../next_steps.md).
|
https://docs.gitlab.com/install/aws
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/_index.md
|
2025-08-13
|
doc/install/aws
|
[
"doc",
"install",
"aws"
] |
_index.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Installing a GitLab POC on Amazon Web Services (AWS)
|
Read through the GitLab installation methods.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page offers a walkthrough of a common configuration for GitLab on AWS using the official Linux package. You should customize it to accommodate your needs.
{{< alert type="note" >}}
For organizations with 1,000 users or less, the recommended AWS installation method is to launch an EC2 single box [Linux package installation](https://about.gitlab.com/install/) and implement a snapshot strategy for backing up the data. See the [20 RPS or 1,000 user reference architecture](../../administration/reference_architectures/1k_users.md) for more information.
{{< /alert >}}
## Getting started for production-grade GitLab
{{< alert type="note" >}}
This document is an installation guide for a proof of concept instance. It is not a reference architecture, and it does not result in a highly available configuration.
It's highly recommended to use the [GitLab Environment Toolkit (GET)](https://gitlab.com/gitlab-org/gitlab-environment-toolkit) instead.
{{< /alert >}}
Following this guide exactly results in a proof of concept instance that roughly equates to a **scaled down** version of a **two availability zone implementation** of the **Non-HA** [40 RPS or 2,000 User Reference Architecture](../../administration/reference_architectures/2k_users.md). The 2K reference architecture is not HA because it is primarily intended to provide some scaling while keeping costs and complexity low. The [60 RPS or 3,000 User Reference Architecture](../../administration/reference_architectures/3k_users.md) is the smallest size that is GitLab HA. It has additional service roles to achieve HA, most notably it uses Gitaly Cluster (Praefect) to achieve HA for Git repository storage and specifies triple redundancy.
GitLab maintains and tests two main types of Reference Architectures. The **Linux package architectures** are implemented on instance compute while **Cloud Native Hybrid architectures** maximize the use of a Kubernetes cluster. Cloud Native Hybrid reference architecture specifications are addendum sections to the Reference Architecture size pages that start by describing the Linux package architecture. For example, the 60 RPS or 3,000 User Cloud Native Reference Architecture is in the subsection titled [Cloud Native Hybrid reference architecture with Helm Charts (alternative)](../../administration/reference_architectures/3k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) in the 60 RPS or 3,000 User Reference Architecture page.
### Getting started for production-grade Linux package installations
The Infrastructure as Code tooling [GitLab Environment Tool (GET)](https://gitlab.com/gitlab-org/gitlab-environment-toolkit/-/tree/main) is the best place to start for building using the Linux package on AWS and most especially if you are targeting an HA setup. While it does not automate everything, it does complete complex setups like Gitaly Cluster (Praefect) for you. GET is open source so anyone can build on top of it and contribute improvements to it.
### Getting started for production-grade Cloud Native Hybrid GitLab
The [GitLab Environment Toolkit (GET)](https://gitlab.com/gitlab-org/gitlab-environment-toolkit/-/blob/main/README.md) is a set of opinionated Terraform and Ansible scripts. These scripts help with the deployment of Linux package or Cloud Native Hybrid environments on selected cloud providers and are used by GitLab developers for [GitLab Dedicated](../../subscriptions/gitlab_dedicated/_index.md) (for example).
You can use the GitLab Environment Toolkit to deploy a Cloud Native Hybrid environment on AWS. However, it's not required and may not support every valid permutation. That said, the scripts are presented as-is and you can adapt them accordingly.
## Introduction
For the most part, we make use of the Linux package in our setup, but we also leverage native AWS services. Instead of using the Linux package-bundled PostgreSQL and Redis, we use Amazon RDS and ElastiCache.
In this guide, we go through a multi-node setup where we start by
configuring our Virtual Private Cloud and subnets to later integrate
services such as RDS for our database server and ElastiCache as a Redis
cluster to finally manage them in an auto scaling group with custom
scaling policies.
## Requirements
In addition to having a basic familiarity with [AWS](https://docs.aws.amazon.com/) and [Amazon EC2](https://docs.aws.amazon.com/ec2/), you need:
- [An AWS account](https://console.aws.amazon.com/console/home)
- [To create or upload an SSH key](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)
to connect to the instance via SSH
- A domain name for the GitLab instance
- An SSL/TLS certificate to secure your domain. If you do not already own one, you can provision a free public SSL/TLS certificate through [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/)(ACM) for use with the [Elastic Load Balancer](#load-balancer) we create.
{{< alert type="note" >}}
It can take a few hours to validate a certificate provisioned through ACM. To avoid delays later, request your certificate as soon as possible.
{{< /alert >}}
## Architecture
The following diagram outlines the recommended architecture.

## AWS costs
GitLab uses the following AWS services, with links to pricing information:
- **EC2**: GitLab is deployed on shared hardware, for which
[on-demand pricing](https://aws.amazon.com/ec2/pricing/on-demand/) applies.
If you want to run GitLab on a dedicated or reserved instance, see the
[EC2 pricing page](https://aws.amazon.com/ec2/pricing/) for information about
its cost.
- **S3**: GitLab uses S3 ([pricing page](https://aws.amazon.com/s3/pricing/)) to
store backups, artifacts, and LFS objects.
- **NLB**: A Network Load Balancer ([pricing page](https://aws.amazon.com/elasticloadbalancing/pricing/)),
used to route requests to the GitLab instances.
- **RDS**: An Amazon Relational Database Service using PostgreSQL
([pricing page](https://aws.amazon.com/rds/postgresql/pricing/)).
- **ElastiCache**: An in-memory cache environment ([pricing page](https://aws.amazon.com/elasticache/pricing/)),
used to provide a Redis configuration.
## Create an IAM EC2 instance role and profile
As we are using [Amazon S3 object storage](#amazon-s3-object-storage), our EC2 instances must have read, write, and list permissions for our S3 buckets. To avoid embedding AWS keys in our GitLab configuration, we make use of an [IAM Role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) to allow our GitLab instance with this access. We must create an IAM policy to attach to our IAM role:
### Create an IAM Policy
1. Go to the IAM dashboard and select **Policies** in the left menu.
1. Select **Create policy**, select the `JSON` tab, and add a policy. We want to [follow security best practices and grant _least privilege_](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege), giving our role only the permissions needed to perform the required actions.
1. Assuming you prefix the S3 bucket names with `gl-` as shown in the diagram, add the following policy:
```json
{ "Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject",
"s3:PutObjectAcl"
],
"Resource": "arn:aws:s3:::gl-*/*"
},
{
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:AbortMultipartUpload",
"s3:ListMultipartUploadParts",
"s3:ListBucketMultipartUploads"
],
"Resource": "arn:aws:s3:::gl-*"
}
]
}
```
1. Select **Next** to review the policy. Give your policy a name (we use `gl-s3-policy`), and select **Create policy**.
### Create an IAM Role
1. Still on the IAM dashboard, select **Roles** in the left menu, and
select **Create role**.
1. For the **Trusted entity type**, select `AWS service`. For the **Use case**, select `EC2` for both the dropdown list and radio buttons and select **Next**.
1. In the policy filter, search for the `gl-s3-policy` we previously created, select it, and select **Next**.
1. Give the role a name (we use `GitLabS3Access`). If required, add some tags. Select **Create role**.
We use this role when we [create a launch template](#create-a-launch-template) later on.
## Configuring the network
We start by creating a VPC for our GitLab cloud infrastructure, then
we can create subnets to have public and private instances in at least
two [Availability Zones (AZs)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html). Public subnets require a Route Table keep and an associated
Internet Gateway.
### Creating the Virtual Private Cloud (VPC)
We now create a VPC, a virtual networking environment that you control:
1. Sign in to [Amazon Web Services](https://console.aws.amazon.com/vpc/home).
1. Select **Your VPCs** from the left menu and then select **Create VPC**.
At the "Name tag" enter `gitlab-vpc` and at the "IPv4 CIDR block" enter
`10.0.0.0/16`. If you don't require dedicated hardware, you can leave
"Tenancy" as default. Select **Create VPC** when ready.

1. Select the VPC, select **Actions**, select **Edit VPC Settings** and check **Enable DNS resolution**. Select **Save** when done.
### Subnets
Now, let's create some subnets in different Availability Zones. Make sure
that each subnet is associated to the VPC we just created and
that CIDR blocks don't overlap. This also
allows us to enable multi AZ for redundancy.
We create private and public subnets to match load balancers and
RDS instances as well:
1. Select **Subnets** from the left menu.
1. Select **Create subnet**. Give it a descriptive name tag based on the IP,
for example `gitlab-public-10.0.0.0`, select the VPC we created previously, select an availability zone (we use `us-west-2a`),
and at the IPv4 CIDR block let's give it a 24 subnet `10.0.0.0/24`:

1. Follow the same steps to create all subnets:
| Name tag | Type | Availability Zone | CIDR block |
| ------------------------- | ------- | ----------------- | ------------- |
| `gitlab-public-10.0.0.0` | public | `us-west-2a` | `10.0.0.0/24` |
| `gitlab-private-10.0.1.0` | private | `us-west-2a` | `10.0.1.0/24` |
| `gitlab-public-10.0.2.0` | public | `us-west-2b` | `10.0.2.0/24` |
| `gitlab-private-10.0.3.0` | private | `us-west-2b` | `10.0.3.0/24` |
1. Once all the subnets are created, enable **Auto-assign IPv4** for the two public subnets:
1. Select each public subnet in turn, select **Actions**, and select **Edit subnet settings**. Check the **Enable auto-assign public IPv4 address** option and save.
### Internet Gateway
Now, still on the same dashboard, go to Internet Gateways and
create a new one:
1. Select **Internet Gateways** from the left menu.
1. Select **Create internet gateway**, give it the name `gitlab-gateway` and
select **Create**.
1. Select it from the table, and then under the **Actions** dropdown list choose
"Attach to VPC".

1. Choose `gitlab-vpc` from the list and hit **Attach**.
### Create NAT Gateways
Instances deployed in our private subnets must connect to the internet for updates, but should not be reachable from the public internet. To achieve this, we make use of [NAT Gateways](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) deployed in each of our public subnets:
1. Go to the VPC dashboard and select **NAT Gateways** in the left menu bar.
1. Select **Create NAT Gateway** and complete the following:
1. **Subnet**: Select `gitlab-public-10.0.0.0` from the dropdown list.
1. **Elastic IP Allocation ID**: Enter an existing Elastic IP or select **Allocate Elastic IP address** to allocate a new IP to your NAT gateway.
1. Add tags if needed.
1. Select **Create NAT Gateway**.
Create a second NAT gateway but this time place it in the second public subnet, `gitlab-public-10.0.2.0`.
### Route Tables
#### Public Route Table
We must create a route table for our public subnets to reach the internet via the internet gateway we created in the previous step.
On the VPC dashboard:
1. Select **Route Tables** from the left menu.
1. Select **Create Route Table**.
1. At the "Name tag" enter `gitlab-public` and choose `gitlab-vpc` under "VPC".
1. Select **Create**.
We now must add our internet gateway as a new target and have
it receive traffic from any destination.
1. Select **Route Tables** from the left menu and select the `gitlab-public`
route to show the options at the bottom.
1. Select the **Routes** tab, select **Edit routes > Add route** and set `0.0.0.0/0`
as the destination. In the target column, select the **Internet Gateway** and select the `gitlab-gateway` we created previously.
Select **Save changes** when done.
Next, we must associate the **public** subnets to the route table:
1. Select the **Subnet Associations** tab and select **Edit subnet associations**.
1. Check only the public subnets and select **Save associations**.
#### Private Route Tables
We also must create two private route tables so that instances in each private subnet can reach the internet via the NAT gateway in the corresponding public subnet in the same availability zone.
1. Follow the previous steps to create two private route tables. Name them `gitlab-private-a` and `gitlab-private-b`.
1. Next, add a new route to each of the private route tables where the destination is `0.0.0.0/0` and the target is one of the NAT gateways we created earlier.
1. Add the NAT gateway we created in `gitlab-public-10.0.0.0` as the target for the new route in the `gitlab-private-a` route table.
1. Similarly, add the NAT gateway in `gitlab-public-10.0.2.0` as the target for the new route in the `gitlab-private-b`.
1. Lastly, associate each private subnet with a private route table.
1. Associate `gitlab-private-10.0.1.0` with `gitlab-private-a`.
1. Associate `gitlab-private-10.0.3.0` with `gitlab-private-b`.
## Load Balancer
We create a load balancer to evenly distribute inbound traffic on ports `80` and `443` across our GitLab application servers. Based on the [scaling policies](#create-an-auto-scaling-group) we create later, instances are added to or removed from our load balancer as needed. Additionally, the load balancer performs health checks on our instances. While there are [different ways](../../administration/load_balancer.md#ssl) to handle SSL/TLS in our environment, for this POC we terminate SSL in the load balancer without backend SSL.
On the EC2 dashboard, look for **Load Balancers** in the left navigation bar:
1. Select **Create Load Balancer**.
1. Choose the **Network Load Balancer** and select **Create**.
1. Set the Load Balancer name to `gitlab-loadbalancer`. Set the following additional options:
- Scheme: Select **Internet-facing**
- IP address type: Select **IPv4**
- VPC: Select the `gitlab-vpc` from the dropdown list.
- Mapping: Select both public subnets from the list so that the load balancer can route traffic to both availability zones.
1. We add a security group for our load balancer to act as a firewall to control what traffic is allowed through. Under the Security Group section, select the **create a new security group**, give it a name
(we use `gitlab-loadbalancer-sec-group`) and description, and allow both HTTP and HTTPS traffic
from anywhere (`0.0.0.0/0, ::/0`). Also allow SSH traffic, select a custom source, and add a single trusted IP address, or an IP address range in CIDR notation. This allows users to perform Git actions over SSH.
1. In the **Listeners and routing** section, set up listeners for port `22`, `80`, and `443` with the following target groups in mind.
| Protocol | Port | Target group |
| ------ | ------ | ------ |
| TCP | 22 | `gitlab-loadbalancer-ssh-target` |
| TCP | 80 | `gitlab-loadbalancer-http-target` |
| TLS | 443 | `gitlab-loadbalancer-http-target` |
1. For the TLS listener on port `443`, under **Security Policy** settings:
1. **Policy name**: Pick a predefined security policy from the dropdown list. You can see a breakdown of [Predefined SSL Security Policies for Network Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/create-tls-listener.html#describe-ssl-policies) in the AWS documentation. Check the GitLab codebase for a list of [supported SSL ciphers and protocols](https://gitlab.com/gitlab-org/gitlab/-/blob/9ee7ad433269b37251e0dd5b5e00a0f00d8126b4/lib/support/nginx/gitlab-ssl#L97-99).
1. **Default SSL/TLS server certificate**: Select an SSL/TLS certificate from ACM or upload a certificate to IAM.
1. For each listener we created, we need to create a target group and assign them based on the table earlier. We haven't created any EC2 instances yet so you don't need to register targets. The EC2 instances are created and assigned as part of the [auto scaling group setup](#create-an-auto-scaling-group) later on.
1. Select `Create target group`.on. Select **Instances** as the target type.
1. Select an appropriate `Target group name` for each listener:
- `gitlab-loadbalancer-http-target` - TCP Protocol for port 80
- `gitlab-loadbalancer-ssh-target` - TCP Protocol for port 22
1. Select **IPv4** as the IP address type.
1. Select `gitlab-vpc` from the VPC dropdown list.
1. For `gitlab-loadbalancer-http-target` Health checks, you should [use the Readiness check endpoint](../../administration/load_balancer.md#readiness-check). You must add [the VPC IP Address Range (CIDR)](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-security-groups.html) to the [IP allowlist](../../administration/monitoring/ip_allowlist.md) for the [Health check endpoints](../../administration/monitoring/health_check.md)
1. For `gitlab-loadbalancer-ssh-target` Health checks, select **TCP**.
- Assign `gitlab-loadbalancer-http-target` to both port 80 and 443 listener.
- Assign `gitlab-loadbalancer-ssh-target` to port 22 listener.
1. Some attributes can only be configured after the target groups have already been created. Here are a couple of features you might configure based on your requirements.
- [Client IP preservation](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html#client-ip-preservation) is enabled for the target groups by default. This allows the IP of the client connected in the Load Balancer to be preserved in the GitLab application. You can make enable/disable this based on your requirements.
- [Proxy Protocol](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html#proxy-protocol) is disabled for the target groups by default. This allows the Load Balancer to send additional information in the proxy protocol headers. If you want to enable this, make sure that other environment components like internal load balancers, NGINX, etc. are configured as well. For this POC we only need to enable it in the [GitLab node later](#proxy-protocol).
1. Select **Create load balancer**.
After the Load Balancer is up and running, you can revisit your Security
Groups to refine the access only through the NLB and any other requirements
you might have.
### Configure DNS for Load Balancer
On the Route 53 dashboard, select **Hosted zones** in the left navigation bar:
1. Select an existing hosted zone or, if you do not already have one for your domain, select **Create Hosted Zone**, enter your domain name, and select **Create**.
1. Select **Create record** and provide the following values:
1. **Name**: Use the domain name (the default value) or enter a subdomain.
1. **Type**: Select **A - IPv4 address**.
1. **Alias**: Defaults to **disabled**. Enable this option.
1. **Route traffic to**: Select **Alias to Network Load Balancer**.
1. **Region**: Select the region where the Network Load Balancer resides.
1. **Choose network load balancer**: Select the Network Load Balancer we created earlier.
1. **Routing Policy**: We use **Simple** but you can choose a different policy based on your use case.
1. **Evaluate Target Health**: We set this to **No** but you can choose to have the load balancer route traffic based on target health.
1. Select **Create**.
1. If you registered your domain through Route 53, you're done. If you used a different domain registrar, you must update your DNS records with your domain registrar. You must:
1. Select **Hosted zones** and select the domain you added previously.
1. You see a list of `NS` records. From your domain registrar's administrator panel, add each of these as `NS` records to your domain's DNS records. These steps may vary between domain registrars. If you're stuck, Google **"name of your registrar" add DNS records** and you should find a help article specific to your domain registrar.
The steps for doing this vary depending on which registrar you use and is beyond the scope of this guide.
## PostgreSQL with RDS
For our database server we use Amazon RDS for PostgreSQL which offers Multi AZ
for redundancy ([Aurora is **not** supported](https://gitlab.com/gitlab-partners-public/aws/aws-known-issues/-/issues/10)). First we create a security group and subnet group, then we
create the actual RDS instance.
### RDS Security Group
We need a security group for our database that allows inbound traffic from the instances we deploy in our `gitlab-loadbalancer-sec-group` later on:
1. From the EC2 dashboard, select **Security Groups** from the left menu bar.
1. Select **Create security group**.
1. Give it a name (we use `gitlab-rds-sec-group`), a description, and select the `gitlab-vpc` from the **VPC** dropdown list.
1. In the **Inbound rules** section, select **Add rule** and set the following:
1. **Type**: search for and select the **PostgreSQL** rule.
1. **Source type**: set as "Custom".
1. **Source**: select the `gitlab-loadbalancer-sec-group` we created earlier.
1. When done, select **Create security group**.
### RDS Subnet Group
1. Go to the RDS dashboard and select **Subnet Groups** from the left menu.
1. Select **Create DB Subnet Group**.
1. Under **Subnet group details**, enter a name (we use `gitlab-rds-group`), a description, and choose the `gitlab-vpc` from the VPC dropdown list.
1. From the **Availability Zones** dropdown list, select the Availability Zones that include the subnets you've configured. In our case, we add `eu-west-2a` and `eu-west-2b`.
1. From the **Subnets** dropdown list, select the two private subnets (`10.0.1.0/24` and `10.0.3.0/24`) as we defined them in the [subnets section](#subnets).
1. Select **Create** when ready.
### Create the database
{{< alert type="warning" >}}
Avoid using burstable instances (t class instances) for the database as this could lead to performance issues due to CPU credits running out during sustained periods of high load.
{{< /alert >}}
Now, it's time to create the database:
1. Go to the RDS dashboard, select **Databases** from the left menu, and select **Create database**.
1. Select **Standard Create** for the database creation method.
1. Select **PostgreSQL** as the database engine and select the minimum PostgreSQL version as defined for your GitLab version in our [database requirements](../requirements.md#postgresql).
1. Because this is a production server, let's choose **Production** from the **Templates** section.
1. Under **Availability & durability**, select **Multi-AZ DB instance** to have a standby RDS instance provisioned in a different [Availability Zone](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZ.html).
1. Under **Settings**, use:
- `gitlab-db-ha` for the DB instance identifier.
- `gitlab` for a master username.
- A very secure password for the master password.
Make a note of these as we need them later.
1. For the DB instance size, select **Standard classes** and select an instance size that meets your requirements from the dropdown list. We use a `db.m5.large` instance.
1. Under **Storage**, configure the following:
1. Select **Provisioned IOPS (SSD)** from the storage type dropdown list. Provisioned IOPS (SSD) storage is best suited for this use (though you can choose General Purpose (SSD) to reduce the costs). Read more about it at [Storage for Amazon RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html).
1. Allocate storage and set provisioned IOPS. We use the minimum values, `100` and `1000`.
1. Enable storage autoscaling (optional) and set a maximum storage threshold.
1. Under **Connectivity**, configure the following:
1. Under the **Virtual Private Cloud (VPC)** dropdown list select the VPC we created earlier (`gitlab-vpc`).
1. Under the **DB subnet group** select the subnet group (`gitlab-rds-group`) we created earlier.
1. Set public access to **No**.
1. Under **VPC security group**, select **Choose existing** and select the `gitlab-rds-sec-group` we created previously from the dropdown list.
1. Under **Additional configuration** leave the database port as the default `5432`.
1. For **Database authentication**, select **Password authentication**.
1. Expand the **Additional configuration** section and complete the following:
1. The initial database name. We use `gitlabhq_production`.
1. Configure your preferred backup settings.
1. The only other change we make here is to disable auto minor version updates under **Maintenance**.
1. Leave all the other settings as is or tweak according to your needs.
1. If you're happy, select **Create database**.
Now that the database is created, let's move on to setting up Redis with ElastiCache.
## Redis with ElastiCache
ElastiCache is an in-memory hosted caching solution. Redis maintains its own
persistence and is used to store session data, temporary cache information, and background job queues for the GitLab application.
### Create a Redis Security Group
1. Go to the EC2 dashboard.
1. Select **Security Groups** from the left menu.
1. Select **Create security group** and fill in the details. Give it a name (we use `gitlab-redis-sec-group`),
add a description, and choose the VPC we created earlier (`gitlab-vpc`).
1. In the **Inbound rules** section, select **Add rule** and add a **Custom TCP** rule, set port `6379`, and set the "Custom" source as the `gitlab-loadbalancer-sec-group` we created earlier.
1. When done, select **Create security group**.
### Redis Subnet Group
1. Go to the ElastiCache dashboard from your AWS console.
1. Go to **Subnet Groups** in the left menu, and create a new subnet group (we name ours `gitlab-redis-group`).
Select the VPC we created earlier (`gitlab-vpc`) and ensure the selected subnets table only contains the [private subnets](#subnets).
1. Select **Create** when ready.

### Create the Redis Cluster
1. Go back to the ElastiCache dashboard.
1. Select **Redis caches** on the left menu and select **Create Redis cache** to create a new
Redis cluster.
1. Under **Deployment option** select **Design your own cache**.
1. Under **Creation method** select **Cluster cache**.
1. Under **Cluster mode** select **Disabled** as it is [not supported](../../administration/redis/replication_and_failover_external.md#requirements). Even without cluster mode on, you still get the
chance to deploy Redis in multiple availability zones.
1. Under **Cluster info** give the cluster a name (`gitlab-redis`) and a description.
1. Under **Location** select **AWS Cloud** and enable **Multi-AZ** option.
1. In the Cluster settings section:
1. For the Engine version, select the Redis version as defined for your GitLab version in our [Redis requirements](../requirements.md#redis).
1. Leave the port as `6379` because this is what we previously used in our Redis security group.
1. Select the node type (at least `cache.t3.medium`, but adjust to your needs) and the number of replicas.
1. In the Connectivity settings section:
1. **Network type**: IPv4
1. **Subnet groups**: Select **Choose existing subnet group** and choose the `gitlab-redis-group` we had previously created.
1. In the Availability Zone placements section:
1. Manually select the preferred availability zones, and under "Replica 2"
choose a different zone than the other two.

1. Select **Next**.
1. In the security settings, edit the security groups and choose the
`gitlab-redis-sec-group` we had previously created. Select **Next**.
1. Leave the rest of the settings to their default values or edit to your liking.
1. When done, select **Create**.
## Setting up Bastion Hosts
Because our GitLab instances are in private subnets, we need a way to connect
to these instances with SSH for actions that include making configuration changes
and performing upgrades. One way of doing this is by using a [bastion host](https://en.wikipedia.org/wiki/Bastion_host),
sometimes also referred to as a jump box.
{{< alert type="note" >}}
If you do not want to maintain bastion hosts, you can set up [AWS Systems Manager Session Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html) for access to instances. This is beyond the scope of this document.
{{< /alert >}}
### Create Bastion Host A
1. Go to the EC2 Dashboard and select **Launch instance**.
1. In the **Name and tags** section, set the **Name** to `Bastion Host A`.
1. Select the latest **Ubuntu Server LTS (HVM)** AMI. Check the GitLab documentation for the [latest supported OS version](../../administration/package_information/supported_os.md).
1. Choose an instance type. We use a `t2.micro` as we only use the bastion host to SSH into our other instances.
1. In the **Key pair** section, select **Create new key pair**.
1. Give the key pair a name (we use `bastion-host-a`) and save the `bastion-host-a.pem` file for later use.
1. Edit the Network settings section:
1. Under **VPC**, select the `gitlab-vpc` from the dropdown list.
1. Under **Subnet**, select the public subnet we created earlier (`gitlab-public-10.0.0.0`).
1. Check that under **Auto-assign Public IP** you have **Disabled** selected. An [Elastic IP address](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) is assigned later to the host in the [next section](#assign-elastic-ip-to-the-bastion-host-a).
1. Under **Firewall** select **Create security group**, enter a **Security group name** (we use `bastion-sec-group`), and add a description.
1. We enable SSH access from anywhere (`0.0.0.0/0`). If you want stricter security, specify a single IP address or an IP address range in CIDR notation.
1. For storage, we leave everything as default and only add an 8 GB root volume. We do not store anything on this instance.
1. Review all your settings and, if you're happy, select **Launch Instance**.
#### Assign Elastic IP to the Bastion Host A
1. Go to the EC2 Dashboard and select **Network & Security**.
1. Select **Elastic IPs** and set the `Network border group` to `us-west-2`.
1. Select **Allocate**.
1. Select the Elastic IP address that was created.
1. Select **Actions** and choose **Associate Elastic IP address**.
1. Under the **Resource Type** select **Instance** and choose the `Bastion Host A` host under the **Instance** dropdown list.
1. Select **Associate**.
#### Confirm that you can SSH into the instance
1. On the EC2 Dashboard, select **Instances** in the left menu.
1. Select **Bastion Host A** from your list of instances.
1. Select **Connect** and follow the connection instructions.
1. If you are able to connect successfully, let's move on to setting up our second bastion host for redundancy.
### Create Bastion Host B
1. Create an EC2 instance following the same steps used previously with the following changes:
1. For the **Subnet**, select the second public subnet we created earlier (`gitlab-public-10.0.2.0`).
1. Under the **Add Tags** section, we set `Key: Name` and `Value: Bastion Host B` so that we can easily identify our two instances.
1. For the security group, select the existing `bastion-sec-group` we previously created.
### Use SSH Agent Forwarding
EC2 instances running Linux use private key files for SSH authentication. You connect to your bastion host using an SSH client and the private key file stored on your client. Because the private key file is not present on the bastion host, you are not able to connect to your instances in private subnets.
Storing private key files on your bastion host is a bad idea. To get around this, use SSH agent forwarding on your client.
For example, the command-line `ssh` client uses agent forwarding with its `-A` switch, like this:
```shell
ssh -A user@<bastion-public-IP-address>
```
See [Securely Connect to Linux Instances Running in a Private Amazon VPC](https://aws.amazon.com/blogs/security/securely-connect-to-linux-instances-running-in-a-private-amazon-vpc/) for a step-by-step guide on how to use SSH agent forwarding for other clients.
## Install GitLab and create custom AMI
We need a preconfigured, custom GitLab AMI to use in our launch configuration later. As a starting point, we use the official GitLab AMI to create a GitLab instance. Then, we add our custom configuration for PostgreSQL, Redis, and Gitaly. If you prefer, instead of using the official GitLab AMI, you can also spin up an EC2 instance of your choosing and [manually install GitLab](https://about.gitlab.com/install/).
### Install GitLab
From the EC2 dashboard:
1. Use the following section titled "[Find official GitLab-created AMI IDs on AWS](#find-official-gitlab-created-ami-ids-on-aws)" to find the correct AMI and select **Launch**.
1. In the **Name and tags** section, set the **Name** to `GitLab`.
1. In the **Instance type** dropdown list, select an instance type based on your workload. Consult the [hardware requirements](../requirements.md) to choose one that fits your needs (at least `c5.2xlarge`, which is sufficient to accommodate 100 users).
1. In the **Key pair** section, select **Create new key pair**.
1. Give the key pair a name (we use `gitlab`) and save the `gitlab.pem` file for later use.
1. In the **Network settings** section:
1. **VPC**: Select `gitlab-vpc`, the VPC we created earlier.
1. **Subnet**: Select `gitlab-private-10.0.1.0` from the list of subnets we created earlier.
1. **Auto-assign Public IP**: Select `Disable`.
1. **Firewall**: Chose **Select existing security group** and select the `gitlab-loadbalancer-sec-group` we created earlier.
1. For storage, the root volume is 8 GiB by default and should be enough given that we do not store any data there.
1. Review all your settings and, if you're happy, select **Launch Instance**.
### Add custom configuration
Connect to your GitLab instance via **Bastion Host A** using [SSH Agent Forwarding](#use-ssh-agent-forwarding). Once connected, add the following custom configuration:
#### Disable Let's Encrypt
Because we're adding our SSL certificate at the load balancer, we do not need the GitLab built-in support for Let's Encrypt. Let's Encrypt [is enabled by default](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration) when using an `https` domain, so we must explicitly disable it:
1. Open `/etc/gitlab/gitlab.rb` and disable it:
```ruby
letsencrypt['enable'] = false
```
1. Save the file and reconfigure for the changes to take effect:
```shell
sudo gitlab-ctl reconfigure
```
#### Install the required extensions for PostgreSQL
From your GitLab instance, connect to the RDS instance to verify access and to install the required `pg_trgm` and `btree_gist` extensions.
To find the host or endpoint, go to **Amazon RDS > Databases** and select the database you created earlier. Look for the endpoint under the **Connectivity & security** tab.
Do not to include the colon and port number:
```shell
sudo /opt/gitlab/embedded/bin/psql -U gitlab -h <rds-endpoint> -d gitlabhq_production
```
At the `psql` prompt create the extension and then quit the session:
```shell
psql (10.9)
Type "help" for help.
gitlab=# CREATE EXTENSION pg_trgm;
gitlab=# CREATE EXTENSION btree_gist;
gitlab=# \q
```
#### Configure GitLab to connect to PostgreSQL and Redis
1. Edit `/etc/gitlab/gitlab.rb`, find the `external_url 'http://<domain>'` option
and change it to the `https` domain you are using.
1. Look for the GitLab database settings and uncomment as necessary. In
our current case we specify the database adapter, encoding, host, name,
username, and password:
```ruby
# Disable the built-in Postgres
postgresql['enable'] = false
# Fill in the connection details
gitlab_rails['db_adapter'] = "postgresql"
gitlab_rails['db_encoding'] = "unicode"
gitlab_rails['db_database'] = "gitlabhq_production"
gitlab_rails['db_username'] = "gitlab"
gitlab_rails['db_password'] = "mypassword"
gitlab_rails['db_host'] = "<rds-endpoint>"
```
1. Next, we must configure the Redis section by adding the host and
uncommenting the port:
```ruby
# Disable the built-in Redis
redis['enable'] = false
# Fill in the connection details
gitlab_rails['redis_host'] = "<redis-endpoint>"
gitlab_rails['redis_port'] = 6379
```
1. Finally, reconfigure GitLab for the changes to take effect:
```shell
sudo gitlab-ctl reconfigure
```
1. You can also run a check and a service status to make sure
everything has been setup correctly:
```shell
sudo gitlab-rake gitlab:check
sudo gitlab-ctl status
```
#### Set up Gitaly
{{< alert type="warning" >}}
In this architecture, having a single Gitaly server creates a single point of failure. Use
[Gitaly Cluster (Praefect)](../../administration/gitaly/praefect/_index.md) to remove this limitation.
{{< /alert >}}
Gitaly is a service that provides high-level RPC access to Git repositories.
It should be enabled and configured on a separate EC2 instance in one of the
[private subnets](#subnets) we configured previously.
Let's create an EC2 instance where we install Gitaly:
1. From the EC2 dashboard, select **Launch instance**.
1. In the **Name and tags** section, set the **Name** to `Gitaly`.
1. Choose an AMI. In this example, we select the latest **Ubuntu Server LTS (HVM), SSD Volume Type**. Check the GitLab documentation for the [latest supported OS version](../../administration/package_information/supported_os.md).
1. Choose an instance type. We pick a `m5.xlarge`.
1. In the **Key pair** section, select **Create new key pair**.
1. Give the key pair a name (we use `gitaly`) and save the `gitaly.pem` file for later use.
1. In the Network settings section:
1. Under **VPC**, select the `gitlab-vpc` from the dropdown list.
1. Under **Subnet**, select the private subnet we created earlier (`gitlab-private-10.0.1.0`).
1. Check that under **Auto-assign Public IP** you have **Disable** selected.
1. Under **Firewall** select **Create security group**, enter a **Security group name** (we use `gitlab-gitaly-sec-group`), and add a description.
1. Create a **Custom TCP** rule and add port `8075` to the **Port Range**. For the **Source**, select the `gitlab-loadbalancer-sec-group`.
1. Also add an inbound rule for SSH from the `bastion-sec-group` so that we can connect using [SSH Agent Forwarding](#use-ssh-agent-forwarding) from the Bastion hosts.
1. Increase the Root volume size to `20 GiB` and change the **Volume Type** to `Provisioned IOPS SSD (io1)`. (The volume size is an arbitrary value. Create a volume big enough for your repository storage requirements.)
1. For **IOPS** set `1000` (20 GiB x 50 IOPS). You can provision up to 50 IOPS per GiB. If you select a larger volume, increase the IOPS accordingly. Workloads where many small files are written in a serialized manner, like `git`, requires performant storage, hence the choice of `Provisioned IOPS SSD (io1)`.
1. Review all your settings and, if you're happy, select **Launch Instance**.
{{< alert type="note" >}}
Instead of storing configuration and repository data on the root volume, you can also choose to add an additional EBS volume for repository storage. Follow
the same guidance mentioned previously. See the [Amazon EBS pricing page](https://aws.amazon.com/ebs/pricing/).
{{< /alert >}}
Now that we have our EC2 instance ready, follow the [documentation to install GitLab and set up Gitaly on its own server](../../administration/gitaly/configure_gitaly.md#run-gitaly-on-its-own-server). Perform the client setup steps from that document on the [GitLab instance we created](#install-gitlab) previously.
##### Elastic File System (EFS)
{{< alert type="warning" >}}
We do not recommend using EFS because it can negatively impact the performance of GitLab. For more information, see the
[documentation about avoiding cloud-based file systems](../../administration/nfs.md#avoid-using-cloud-based-file-systems).
{{< /alert >}}
If you do decide to use EFS, ensure that the [PosixUser](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-posixuser)
attribute is either omitted or correctly specified with the UID and GID of the `git` user on the system that Gitaly is
installed. The UID and GID can be retrieved with the following commands:
```shell
# UID
$ id -u git
# GID
$ id -g git
```
Additionally, you should not configure multiple [access points](https://docs.aws.amazon.com/efs/latest/ug/efs-access-points.html),
especially if they specify different credentials. An application other than Gitaly can manipulate permissions on
the Gitaly storage directories in a way that prevents Gitaly from operating correctly. For an example of this problem, see
[`omnibus-gitlab` issue 8893](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/8893).
#### Add Support for Proxied SSL
As we are terminating SSL at our [load balancer](#load-balancer), follow the steps at [Supporting proxied SSL](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination) to configure this in `/etc/gitlab/gitlab.rb`.
Remember to run `sudo gitlab-ctl reconfigure` after saving the changes to the `gitlab.rb` file.
#### Fast lookup of authorized SSH keys
The public SSH keys for users allowed to access GitLab are stored in `/var/opt/gitlab/.ssh/authorized_keys`. Typically we'd use shared storage so that all the instances are able to access this file when a user performs a Git action over SSH. Because we do not have shared storage in our setup, we update our configuration to authorize SSH users via indexed lookup in the GitLab database.
Follow the instructions at [Set up fast SSH key lookup](../../administration/operations/fast_ssh_key_lookup.md#set-up-fast-lookup) to switch from using the `authorized_keys` file to the database.
If you do not configure fast lookup, Git actions over SSH results in the following error:
```shell
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
```
#### Configure host keys
Ordinarily we would manually copy the contents (primary and public keys) of `/etc/ssh/` on the primary application server to `/etc/ssh` on all secondary servers. This prevents false man-in-the-middle-attack alerts when accessing servers in your cluster behind a load balancer.
We automate this by creating static host keys as part of our custom AMI. As these host keys are also rotated every time an EC2 instance boots up, "hard coding" them into our custom AMI serves as a workaround.
On your GitLab instance run the following:
```shell
sudo mkdir /etc/ssh_static
sudo cp -R /etc/ssh/* /etc/ssh_static
```
In `/etc/ssh/sshd_config` update the following:
```shell
# HostKeys for protocol version 2
HostKey /etc/ssh_static/ssh_host_rsa_key
HostKey /etc/ssh_static/ssh_host_dsa_key
HostKey /etc/ssh_static/ssh_host_ecdsa_key
HostKey /etc/ssh_static/ssh_host_ed25519_key
```
#### Amazon S3 object storage
Because we're not using NFS for shared storage, we use [Amazon S3](https://aws.amazon.com/s3/) buckets to store backups, artifacts, LFS objects, uploads, merge request diffs, container registry images, and more. Our documentation includes [instructions on how to configure object storage](../../administration/object_storage.md) for each of these data types, and other information about using object storage with GitLab.
{{< alert type="note" >}}
Because we are using the [AWS IAM profile](#create-an-iam-role) we created earlier, be sure to omit the AWS access key and secret access key/value pairs when configuring object storage. Instead, use `'use_iam_profile' => true` in your configuration as shown in the object storage documentation linked previously.
{{< /alert >}}
Remember to run `sudo gitlab-ctl reconfigure` after saving the changes to the `gitlab.rb` file.
---
That concludes the configuration changes for our GitLab instance. Next, we create a custom AMI based on this instance to use for our launch configuration and auto scaling group.
### IP allowlist
We must add [the VPC IP Address Range (CIDR)](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-security-groups.html) of the `gitlab-vpc` we created earlier to the [IP allowlist](../../administration/monitoring/ip_allowlist.md) for the [Health check endpoints](../../administration/monitoring/health_check.md)
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['monitoring_whitelist'] = ['127.0.0.0/8', '10.0.0.0/16']
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
### Proxy Protocol
If Proxy protocol is enabled in the [load balancer](#load-balancer) we created earlier, we must also [enable](https://docs.gitlab.com/omnibus/settings/nginx.html#configuring-the-proxy-protocol) this on the `gitlab.rb` file.
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
nginx['proxy_protocol'] = true
nginx['real_ip_trusted_addresses'] = [ "127.0.0.0/8", "IP_OF_THE_PROXY/32"]
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
### Sign in for the first time
Using the domain name you used when setting up [DNS for the load balancer](#configure-dns-for-load-balancer), you should now be able to visit GitLab in your browser.
Depending on how you installed GitLab and if you did not change the password by any other means, the default password is either:
- Your instance ID if you used the official GitLab AMI.
- A randomly generated password stored for 24 hours in `/etc/gitlab/initial_root_password`.
To change the default password, sign in as the `root` user with the default password and [change it in the user profile](../../user/profile/user_passwords.md#change-your-password).
When our [auto scaling group](#create-an-auto-scaling-group) spins up new instances, we are able to sign in with username `root` and the newly created password.
### Create custom AMI
On the EC2 dashboard:
1. Select the `GitLab` instance we [created earlier](#install-gitlab).
1. Select **Actions**, scroll down to **Image and templates** and select **Create image**.
1. Give your image a name and description (we use `GitLab-Source` for both).
1. Leave everything else as default and select **Create Image**
Now we have a custom AMI that we use to create our launch configuration the next step.
## Deploy GitLab inside an auto scaling group
### Create a launch template
From the EC2 dashboard:
1. Select **Launch Templates** from the left menu and select **create launch template**.
1. Enter a name for your launch template (we use `gitlab-launch-template`).
1. Select **Launch template contents** and select **My AMIs** tab/
1. Select **Owned by me** and select the `GitLab-Source` custom AMI we created previously.
1. Select an instance type best suited for your needs (at least a `c5.2xlarge`).
1. In the **Key pair** section, select **Create new key pair**.
1. Give the key pair a name (we use `gitlab-launch-template`) and save the `gitlab-launch-template.pem` file for later use.
1. The root volume is 8 GiB by default and should be enough given that we do not store any data there. Select **Configure Security Group**.
1. Check **Select and existing security group** and select the `gitlab-loadbalancer-sec-group` we created earlier.
1. In the **Network settings** section:
1. **Firewall**: Choose **Select existing security group** and select the `gitlab-loadbalancer-sec-group` we created earlier.
1. In the **Advanced details** section:
1. **IAM instance profile**: Select the `GitLabS3Access` role we [created earlier](#create-an-iam-role).
1. Review all your settings and, if you're happy, select **Create launch template**.
### Create an auto scaling group
From the EC2 dashboard:
1. Select **Auto scaling groups** from the left menu and select **Create Auto Scaling group**.
1. Enter a **Group name** (we use `gitlab-auto-scaling-group`).
1. Under **Launch template**, select the launch template we created earlier. Select **Next**
1. In the Network settings section:
1. Under **VPC**, select the `gitlab-vpc` from the dropdown list.
1. Under **Availability Zones and subnets**, select the private [subnets we created earlier](#subnets) (`gitlab-private-10.0.1.0` and `gitlab-private-10.0.3.0`).
1. Select **Next**.
1. In the Load Balancing settings section:
1. Select **Attach to an existing load balancer**.
1. Select the target groups we created earlier in the **Existing load balancer target groups** dropdown list.
1. For **Health Check Type**, check the **Turn on Elastic Load Balancing health checks** option. We leave our **Health Check Grace Period** as the default `300` seconds.
1. Select **Next**.
1. For **Group size**, set **Desired capacity** to `2`.
1. In the Scaling settings section:
1. Select **No scaling policies**. The policies are configured later one.
1. **Min desired capacity**: Set to `2`.
1. **Max desired capacity**: Set to `4`.
1. Select **Next**.
1. Finally, configure notifications and tags as you see fit, review your changes, and create the
auto scaling group.
1. After the auto scaling group is created, we need to create a scale up and down policy in [Cloudwatch](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html) and assign them.
1. Create an alarm for the `CPUUtilization` for metrics from **EC2** instances **By Auto Scaling Group** we created earlier.
1. Create a [scale up policy](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html#step-scaling-create-scale-out-policy) using the following conditions:
1. **Add** `1` capacity unit when `CPUUtilization` is greater than or equal to 60%.
1. Set the **Scaling policy name** to `Scale Up Policy`.

1. Create a [scale down policy](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html#step-scaling-create-scale-in-policy) using the following conditions:
1. **Remove** `1` capacity unit when `CPUUtilization` is less than or equal to 45%.
1. Set the **Scaling policy name** to `Scale Down Policy`.

1. Assign the new dynamic scaling policy to the auto scaling group we created earlier.
As the auto scaling group is created, you see your new instances spinning up in your EC2 dashboard. You also see the new instances added to your load balancer. After the instances pass the heath check, they are ready to start receiving traffic from the load balancer.
Because our instances are created by the auto scaling group, go back to your instances and terminate the [instance we previously created manually](#install-gitlab). We only needed this instance to create our custom AMI.
## Health check and monitoring with Prometheus
Apart from Amazon CloudWatch, which you can enable on various services,
GitLab provides its own integrated monitoring solution based on Prometheus.
For more information about how to set it up, see
[GitLab Prometheus](../../administration/monitoring/prometheus/_index.md).
GitLab also has various [health check endpoints](../../administration/monitoring/health_check.md)
that you can ping and get reports.
## GitLab Runner
If you want to take advantage of [GitLab CI/CD](../../ci/_index.md), you have to
set up at least one [runner](https://docs.gitlab.com/runner/).
Read more on configuring an
[autoscaling GitLab Runner on AWS](https://docs.gitlab.com/runner/configuration/runner_autoscale_aws/).
## Backup and restore
GitLab provides [a tool to back up](../../administration/backup_restore/_index.md)
and restore its Git data, database, attachments, LFS objects, and so on.
Some important things to know:
- The backup/restore tool **does not** store some configuration files, like secrets; you
must [configure this yourself](../../administration/backup_restore/backup_gitlab.md#storing-configuration-files).
- By default, the backup files are stored locally, but you can
[backup GitLab using S3](../../administration/backup_restore/backup_gitlab.md#using-amazon-s3).
- You can [exclude specific directories form the backup](../../administration/backup_restore/backup_gitlab.md#excluding-specific-data-from-the-backup).
### Backing up GitLab
To back up GitLab:
1. SSH into your instance.
1. Take a backup:
```shell
sudo gitlab-backup create
```
### Restoring GitLab from a backup
To restore GitLab, first review the [restore documentation](../../administration/backup_restore/_index.md#restore-gitlab),
and primarily the restore prerequisites. Then, follow the steps under the
[Linux package installations section](../../administration/backup_restore/restore_gitlab.md#restore-for-linux-package-installations).
## Updating GitLab
GitLab releases a new version every month on the [release date](https://about.gitlab.com/releases/). Whenever a new version is
released, you can update your GitLab instance:
1. SSH into your instance
1. Take a backup:
```shell
sudo gitlab-backup create
```
1. Update the repositories and install GitLab:
```shell
sudo apt update
sudo apt install gitlab-ee
```
After a few minutes, the new version should be up and running.
## Find official GitLab-created AMI IDs on AWS
Read more on how to use [GitLab releases as AMIs](../../solutions/cloud/aws/gitlab_single_box_on_aws.md#official-gitlab-releases-as-amis).
## Conclusion
In this guide, we went mostly through scaling and some redundancy options,
your mileage may vary.
Keep in mind that all solutions come with a trade-off between
cost/complexity and uptime. The more uptime you want, the more complex the solution.
And the more complex the solution, the more work is involved in setting up and
maintaining it.
Have a read through these other resources and feel free to
[open an issue](https://gitlab.com/gitlab-org/gitlab/-/issues/new)
to request additional material:
- [Scaling GitLab](../../administration/reference_architectures/_index.md):
GitLab supports several different types of clustering.
- [Geo replication](../../administration/geo/_index.md):
Geo is the solution for widely distributed development teams.
- [Linux package](https://docs.gitlab.com/omnibus/) - Everything you must know
about administering your GitLab instance.
- [Add a license](../../administration/license.md):
Activate all GitLab Enterprise Edition functionality with a license.
- [Pricing](https://about.gitlab.com/pricing/): Pricing for the different tiers.
## Troubleshooting
### Instances are failing health checks
If your instances are failing the load balancer's health checks, verify that they are returning a status `200` from the health check endpoint we configured earlier. Any other status, including redirects like status `302`, causes the health check to fail.
You may have to set a password on the `root` user to prevent automatic redirects on the sign-in endpoint before health checks pass.
### "The change you requested was rejected (422)"
If you see this page when trying to set a password via the web interface, make sure `external_url` in `gitlab.rb` matches the domain you are making a request from, and run `sudo gitlab-ctl reconfigure` after making any changes to it.
### Some job logs are not uploaded to object storage
When the GitLab deployment is scaled up to more than one node, some job logs may not be uploaded to [object storage](../../administration/object_storage.md) properly. [Incremental logging is required](../../administration/object_storage.md#alternatives-to-file-system-storage) for CI to use object storage.
Enable [incremental logging](../../administration/cicd/job_logs.md#incremental-logging) if it has not already been enabled.
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Read through the GitLab installation methods.
title: Installing a GitLab POC on Amazon Web Services (AWS)
breadcrumbs:
- doc
- install
- aws
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This page offers a walkthrough of a common configuration for GitLab on AWS using the official Linux package. You should customize it to accommodate your needs.
{{< alert type="note" >}}
For organizations with 1,000 users or less, the recommended AWS installation method is to launch an EC2 single box [Linux package installation](https://about.gitlab.com/install/) and implement a snapshot strategy for backing up the data. See the [20 RPS or 1,000 user reference architecture](../../administration/reference_architectures/1k_users.md) for more information.
{{< /alert >}}
## Getting started for production-grade GitLab
{{< alert type="note" >}}
This document is an installation guide for a proof of concept instance. It is not a reference architecture, and it does not result in a highly available configuration.
It's highly recommended to use the [GitLab Environment Toolkit (GET)](https://gitlab.com/gitlab-org/gitlab-environment-toolkit) instead.
{{< /alert >}}
Following this guide exactly results in a proof of concept instance that roughly equates to a **scaled down** version of a **two availability zone implementation** of the **Non-HA** [40 RPS or 2,000 User Reference Architecture](../../administration/reference_architectures/2k_users.md). The 2K reference architecture is not HA because it is primarily intended to provide some scaling while keeping costs and complexity low. The [60 RPS or 3,000 User Reference Architecture](../../administration/reference_architectures/3k_users.md) is the smallest size that is GitLab HA. It has additional service roles to achieve HA, most notably it uses Gitaly Cluster (Praefect) to achieve HA for Git repository storage and specifies triple redundancy.
GitLab maintains and tests two main types of Reference Architectures. The **Linux package architectures** are implemented on instance compute while **Cloud Native Hybrid architectures** maximize the use of a Kubernetes cluster. Cloud Native Hybrid reference architecture specifications are addendum sections to the Reference Architecture size pages that start by describing the Linux package architecture. For example, the 60 RPS or 3,000 User Cloud Native Reference Architecture is in the subsection titled [Cloud Native Hybrid reference architecture with Helm Charts (alternative)](../../administration/reference_architectures/3k_users.md#cloud-native-hybrid-reference-architecture-with-helm-charts-alternative) in the 60 RPS or 3,000 User Reference Architecture page.
### Getting started for production-grade Linux package installations
The Infrastructure as Code tooling [GitLab Environment Tool (GET)](https://gitlab.com/gitlab-org/gitlab-environment-toolkit/-/tree/main) is the best place to start for building using the Linux package on AWS and most especially if you are targeting an HA setup. While it does not automate everything, it does complete complex setups like Gitaly Cluster (Praefect) for you. GET is open source so anyone can build on top of it and contribute improvements to it.
### Getting started for production-grade Cloud Native Hybrid GitLab
The [GitLab Environment Toolkit (GET)](https://gitlab.com/gitlab-org/gitlab-environment-toolkit/-/blob/main/README.md) is a set of opinionated Terraform and Ansible scripts. These scripts help with the deployment of Linux package or Cloud Native Hybrid environments on selected cloud providers and are used by GitLab developers for [GitLab Dedicated](../../subscriptions/gitlab_dedicated/_index.md) (for example).
You can use the GitLab Environment Toolkit to deploy a Cloud Native Hybrid environment on AWS. However, it's not required and may not support every valid permutation. That said, the scripts are presented as-is and you can adapt them accordingly.
## Introduction
For the most part, we make use of the Linux package in our setup, but we also leverage native AWS services. Instead of using the Linux package-bundled PostgreSQL and Redis, we use Amazon RDS and ElastiCache.
In this guide, we go through a multi-node setup where we start by
configuring our Virtual Private Cloud and subnets to later integrate
services such as RDS for our database server and ElastiCache as a Redis
cluster to finally manage them in an auto scaling group with custom
scaling policies.
## Requirements
In addition to having a basic familiarity with [AWS](https://docs.aws.amazon.com/) and [Amazon EC2](https://docs.aws.amazon.com/ec2/), you need:
- [An AWS account](https://console.aws.amazon.com/console/home)
- [To create or upload an SSH key](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)
to connect to the instance via SSH
- A domain name for the GitLab instance
- An SSL/TLS certificate to secure your domain. If you do not already own one, you can provision a free public SSL/TLS certificate through [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/)(ACM) for use with the [Elastic Load Balancer](#load-balancer) we create.
{{< alert type="note" >}}
It can take a few hours to validate a certificate provisioned through ACM. To avoid delays later, request your certificate as soon as possible.
{{< /alert >}}
## Architecture
The following diagram outlines the recommended architecture.

## AWS costs
GitLab uses the following AWS services, with links to pricing information:
- **EC2**: GitLab is deployed on shared hardware, for which
[on-demand pricing](https://aws.amazon.com/ec2/pricing/on-demand/) applies.
If you want to run GitLab on a dedicated or reserved instance, see the
[EC2 pricing page](https://aws.amazon.com/ec2/pricing/) for information about
its cost.
- **S3**: GitLab uses S3 ([pricing page](https://aws.amazon.com/s3/pricing/)) to
store backups, artifacts, and LFS objects.
- **NLB**: A Network Load Balancer ([pricing page](https://aws.amazon.com/elasticloadbalancing/pricing/)),
used to route requests to the GitLab instances.
- **RDS**: An Amazon Relational Database Service using PostgreSQL
([pricing page](https://aws.amazon.com/rds/postgresql/pricing/)).
- **ElastiCache**: An in-memory cache environment ([pricing page](https://aws.amazon.com/elasticache/pricing/)),
used to provide a Redis configuration.
## Create an IAM EC2 instance role and profile
As we are using [Amazon S3 object storage](#amazon-s3-object-storage), our EC2 instances must have read, write, and list permissions for our S3 buckets. To avoid embedding AWS keys in our GitLab configuration, we make use of an [IAM Role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) to allow our GitLab instance with this access. We must create an IAM policy to attach to our IAM role:
### Create an IAM Policy
1. Go to the IAM dashboard and select **Policies** in the left menu.
1. Select **Create policy**, select the `JSON` tab, and add a policy. We want to [follow security best practices and grant _least privilege_](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege), giving our role only the permissions needed to perform the required actions.
1. Assuming you prefix the S3 bucket names with `gl-` as shown in the diagram, add the following policy:
```json
{ "Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject",
"s3:PutObjectAcl"
],
"Resource": "arn:aws:s3:::gl-*/*"
},
{
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:AbortMultipartUpload",
"s3:ListMultipartUploadParts",
"s3:ListBucketMultipartUploads"
],
"Resource": "arn:aws:s3:::gl-*"
}
]
}
```
1. Select **Next** to review the policy. Give your policy a name (we use `gl-s3-policy`), and select **Create policy**.
### Create an IAM Role
1. Still on the IAM dashboard, select **Roles** in the left menu, and
select **Create role**.
1. For the **Trusted entity type**, select `AWS service`. For the **Use case**, select `EC2` for both the dropdown list and radio buttons and select **Next**.
1. In the policy filter, search for the `gl-s3-policy` we previously created, select it, and select **Next**.
1. Give the role a name (we use `GitLabS3Access`). If required, add some tags. Select **Create role**.
We use this role when we [create a launch template](#create-a-launch-template) later on.
## Configuring the network
We start by creating a VPC for our GitLab cloud infrastructure, then
we can create subnets to have public and private instances in at least
two [Availability Zones (AZs)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html). Public subnets require a Route Table keep and an associated
Internet Gateway.
### Creating the Virtual Private Cloud (VPC)
We now create a VPC, a virtual networking environment that you control:
1. Sign in to [Amazon Web Services](https://console.aws.amazon.com/vpc/home).
1. Select **Your VPCs** from the left menu and then select **Create VPC**.
At the "Name tag" enter `gitlab-vpc` and at the "IPv4 CIDR block" enter
`10.0.0.0/16`. If you don't require dedicated hardware, you can leave
"Tenancy" as default. Select **Create VPC** when ready.

1. Select the VPC, select **Actions**, select **Edit VPC Settings** and check **Enable DNS resolution**. Select **Save** when done.
### Subnets
Now, let's create some subnets in different Availability Zones. Make sure
that each subnet is associated to the VPC we just created and
that CIDR blocks don't overlap. This also
allows us to enable multi AZ for redundancy.
We create private and public subnets to match load balancers and
RDS instances as well:
1. Select **Subnets** from the left menu.
1. Select **Create subnet**. Give it a descriptive name tag based on the IP,
for example `gitlab-public-10.0.0.0`, select the VPC we created previously, select an availability zone (we use `us-west-2a`),
and at the IPv4 CIDR block let's give it a 24 subnet `10.0.0.0/24`:

1. Follow the same steps to create all subnets:
| Name tag | Type | Availability Zone | CIDR block |
| ------------------------- | ------- | ----------------- | ------------- |
| `gitlab-public-10.0.0.0` | public | `us-west-2a` | `10.0.0.0/24` |
| `gitlab-private-10.0.1.0` | private | `us-west-2a` | `10.0.1.0/24` |
| `gitlab-public-10.0.2.0` | public | `us-west-2b` | `10.0.2.0/24` |
| `gitlab-private-10.0.3.0` | private | `us-west-2b` | `10.0.3.0/24` |
1. Once all the subnets are created, enable **Auto-assign IPv4** for the two public subnets:
1. Select each public subnet in turn, select **Actions**, and select **Edit subnet settings**. Check the **Enable auto-assign public IPv4 address** option and save.
### Internet Gateway
Now, still on the same dashboard, go to Internet Gateways and
create a new one:
1. Select **Internet Gateways** from the left menu.
1. Select **Create internet gateway**, give it the name `gitlab-gateway` and
select **Create**.
1. Select it from the table, and then under the **Actions** dropdown list choose
"Attach to VPC".

1. Choose `gitlab-vpc` from the list and hit **Attach**.
### Create NAT Gateways
Instances deployed in our private subnets must connect to the internet for updates, but should not be reachable from the public internet. To achieve this, we make use of [NAT Gateways](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html) deployed in each of our public subnets:
1. Go to the VPC dashboard and select **NAT Gateways** in the left menu bar.
1. Select **Create NAT Gateway** and complete the following:
1. **Subnet**: Select `gitlab-public-10.0.0.0` from the dropdown list.
1. **Elastic IP Allocation ID**: Enter an existing Elastic IP or select **Allocate Elastic IP address** to allocate a new IP to your NAT gateway.
1. Add tags if needed.
1. Select **Create NAT Gateway**.
Create a second NAT gateway but this time place it in the second public subnet, `gitlab-public-10.0.2.0`.
### Route Tables
#### Public Route Table
We must create a route table for our public subnets to reach the internet via the internet gateway we created in the previous step.
On the VPC dashboard:
1. Select **Route Tables** from the left menu.
1. Select **Create Route Table**.
1. At the "Name tag" enter `gitlab-public` and choose `gitlab-vpc` under "VPC".
1. Select **Create**.
We now must add our internet gateway as a new target and have
it receive traffic from any destination.
1. Select **Route Tables** from the left menu and select the `gitlab-public`
route to show the options at the bottom.
1. Select the **Routes** tab, select **Edit routes > Add route** and set `0.0.0.0/0`
as the destination. In the target column, select the **Internet Gateway** and select the `gitlab-gateway` we created previously.
Select **Save changes** when done.
Next, we must associate the **public** subnets to the route table:
1. Select the **Subnet Associations** tab and select **Edit subnet associations**.
1. Check only the public subnets and select **Save associations**.
#### Private Route Tables
We also must create two private route tables so that instances in each private subnet can reach the internet via the NAT gateway in the corresponding public subnet in the same availability zone.
1. Follow the previous steps to create two private route tables. Name them `gitlab-private-a` and `gitlab-private-b`.
1. Next, add a new route to each of the private route tables where the destination is `0.0.0.0/0` and the target is one of the NAT gateways we created earlier.
1. Add the NAT gateway we created in `gitlab-public-10.0.0.0` as the target for the new route in the `gitlab-private-a` route table.
1. Similarly, add the NAT gateway in `gitlab-public-10.0.2.0` as the target for the new route in the `gitlab-private-b`.
1. Lastly, associate each private subnet with a private route table.
1. Associate `gitlab-private-10.0.1.0` with `gitlab-private-a`.
1. Associate `gitlab-private-10.0.3.0` with `gitlab-private-b`.
## Load Balancer
We create a load balancer to evenly distribute inbound traffic on ports `80` and `443` across our GitLab application servers. Based on the [scaling policies](#create-an-auto-scaling-group) we create later, instances are added to or removed from our load balancer as needed. Additionally, the load balancer performs health checks on our instances. While there are [different ways](../../administration/load_balancer.md#ssl) to handle SSL/TLS in our environment, for this POC we terminate SSL in the load balancer without backend SSL.
On the EC2 dashboard, look for **Load Balancers** in the left navigation bar:
1. Select **Create Load Balancer**.
1. Choose the **Network Load Balancer** and select **Create**.
1. Set the Load Balancer name to `gitlab-loadbalancer`. Set the following additional options:
- Scheme: Select **Internet-facing**
- IP address type: Select **IPv4**
- VPC: Select the `gitlab-vpc` from the dropdown list.
- Mapping: Select both public subnets from the list so that the load balancer can route traffic to both availability zones.
1. We add a security group for our load balancer to act as a firewall to control what traffic is allowed through. Under the Security Group section, select the **create a new security group**, give it a name
(we use `gitlab-loadbalancer-sec-group`) and description, and allow both HTTP and HTTPS traffic
from anywhere (`0.0.0.0/0, ::/0`). Also allow SSH traffic, select a custom source, and add a single trusted IP address, or an IP address range in CIDR notation. This allows users to perform Git actions over SSH.
1. In the **Listeners and routing** section, set up listeners for port `22`, `80`, and `443` with the following target groups in mind.
| Protocol | Port | Target group |
| ------ | ------ | ------ |
| TCP | 22 | `gitlab-loadbalancer-ssh-target` |
| TCP | 80 | `gitlab-loadbalancer-http-target` |
| TLS | 443 | `gitlab-loadbalancer-http-target` |
1. For the TLS listener on port `443`, under **Security Policy** settings:
1. **Policy name**: Pick a predefined security policy from the dropdown list. You can see a breakdown of [Predefined SSL Security Policies for Network Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/create-tls-listener.html#describe-ssl-policies) in the AWS documentation. Check the GitLab codebase for a list of [supported SSL ciphers and protocols](https://gitlab.com/gitlab-org/gitlab/-/blob/9ee7ad433269b37251e0dd5b5e00a0f00d8126b4/lib/support/nginx/gitlab-ssl#L97-99).
1. **Default SSL/TLS server certificate**: Select an SSL/TLS certificate from ACM or upload a certificate to IAM.
1. For each listener we created, we need to create a target group and assign them based on the table earlier. We haven't created any EC2 instances yet so you don't need to register targets. The EC2 instances are created and assigned as part of the [auto scaling group setup](#create-an-auto-scaling-group) later on.
1. Select `Create target group`.on. Select **Instances** as the target type.
1. Select an appropriate `Target group name` for each listener:
- `gitlab-loadbalancer-http-target` - TCP Protocol for port 80
- `gitlab-loadbalancer-ssh-target` - TCP Protocol for port 22
1. Select **IPv4** as the IP address type.
1. Select `gitlab-vpc` from the VPC dropdown list.
1. For `gitlab-loadbalancer-http-target` Health checks, you should [use the Readiness check endpoint](../../administration/load_balancer.md#readiness-check). You must add [the VPC IP Address Range (CIDR)](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-security-groups.html) to the [IP allowlist](../../administration/monitoring/ip_allowlist.md) for the [Health check endpoints](../../administration/monitoring/health_check.md)
1. For `gitlab-loadbalancer-ssh-target` Health checks, select **TCP**.
- Assign `gitlab-loadbalancer-http-target` to both port 80 and 443 listener.
- Assign `gitlab-loadbalancer-ssh-target` to port 22 listener.
1. Some attributes can only be configured after the target groups have already been created. Here are a couple of features you might configure based on your requirements.
- [Client IP preservation](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html#client-ip-preservation) is enabled for the target groups by default. This allows the IP of the client connected in the Load Balancer to be preserved in the GitLab application. You can make enable/disable this based on your requirements.
- [Proxy Protocol](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html#proxy-protocol) is disabled for the target groups by default. This allows the Load Balancer to send additional information in the proxy protocol headers. If you want to enable this, make sure that other environment components like internal load balancers, NGINX, etc. are configured as well. For this POC we only need to enable it in the [GitLab node later](#proxy-protocol).
1. Select **Create load balancer**.
After the Load Balancer is up and running, you can revisit your Security
Groups to refine the access only through the NLB and any other requirements
you might have.
### Configure DNS for Load Balancer
On the Route 53 dashboard, select **Hosted zones** in the left navigation bar:
1. Select an existing hosted zone or, if you do not already have one for your domain, select **Create Hosted Zone**, enter your domain name, and select **Create**.
1. Select **Create record** and provide the following values:
1. **Name**: Use the domain name (the default value) or enter a subdomain.
1. **Type**: Select **A - IPv4 address**.
1. **Alias**: Defaults to **disabled**. Enable this option.
1. **Route traffic to**: Select **Alias to Network Load Balancer**.
1. **Region**: Select the region where the Network Load Balancer resides.
1. **Choose network load balancer**: Select the Network Load Balancer we created earlier.
1. **Routing Policy**: We use **Simple** but you can choose a different policy based on your use case.
1. **Evaluate Target Health**: We set this to **No** but you can choose to have the load balancer route traffic based on target health.
1. Select **Create**.
1. If you registered your domain through Route 53, you're done. If you used a different domain registrar, you must update your DNS records with your domain registrar. You must:
1. Select **Hosted zones** and select the domain you added previously.
1. You see a list of `NS` records. From your domain registrar's administrator panel, add each of these as `NS` records to your domain's DNS records. These steps may vary between domain registrars. If you're stuck, Google **"name of your registrar" add DNS records** and you should find a help article specific to your domain registrar.
The steps for doing this vary depending on which registrar you use and is beyond the scope of this guide.
## PostgreSQL with RDS
For our database server we use Amazon RDS for PostgreSQL which offers Multi AZ
for redundancy ([Aurora is **not** supported](https://gitlab.com/gitlab-partners-public/aws/aws-known-issues/-/issues/10)). First we create a security group and subnet group, then we
create the actual RDS instance.
### RDS Security Group
We need a security group for our database that allows inbound traffic from the instances we deploy in our `gitlab-loadbalancer-sec-group` later on:
1. From the EC2 dashboard, select **Security Groups** from the left menu bar.
1. Select **Create security group**.
1. Give it a name (we use `gitlab-rds-sec-group`), a description, and select the `gitlab-vpc` from the **VPC** dropdown list.
1. In the **Inbound rules** section, select **Add rule** and set the following:
1. **Type**: search for and select the **PostgreSQL** rule.
1. **Source type**: set as "Custom".
1. **Source**: select the `gitlab-loadbalancer-sec-group` we created earlier.
1. When done, select **Create security group**.
### RDS Subnet Group
1. Go to the RDS dashboard and select **Subnet Groups** from the left menu.
1. Select **Create DB Subnet Group**.
1. Under **Subnet group details**, enter a name (we use `gitlab-rds-group`), a description, and choose the `gitlab-vpc` from the VPC dropdown list.
1. From the **Availability Zones** dropdown list, select the Availability Zones that include the subnets you've configured. In our case, we add `eu-west-2a` and `eu-west-2b`.
1. From the **Subnets** dropdown list, select the two private subnets (`10.0.1.0/24` and `10.0.3.0/24`) as we defined them in the [subnets section](#subnets).
1. Select **Create** when ready.
### Create the database
{{< alert type="warning" >}}
Avoid using burstable instances (t class instances) for the database as this could lead to performance issues due to CPU credits running out during sustained periods of high load.
{{< /alert >}}
Now, it's time to create the database:
1. Go to the RDS dashboard, select **Databases** from the left menu, and select **Create database**.
1. Select **Standard Create** for the database creation method.
1. Select **PostgreSQL** as the database engine and select the minimum PostgreSQL version as defined for your GitLab version in our [database requirements](../requirements.md#postgresql).
1. Because this is a production server, let's choose **Production** from the **Templates** section.
1. Under **Availability & durability**, select **Multi-AZ DB instance** to have a standby RDS instance provisioned in a different [Availability Zone](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZ.html).
1. Under **Settings**, use:
- `gitlab-db-ha` for the DB instance identifier.
- `gitlab` for a master username.
- A very secure password for the master password.
Make a note of these as we need them later.
1. For the DB instance size, select **Standard classes** and select an instance size that meets your requirements from the dropdown list. We use a `db.m5.large` instance.
1. Under **Storage**, configure the following:
1. Select **Provisioned IOPS (SSD)** from the storage type dropdown list. Provisioned IOPS (SSD) storage is best suited for this use (though you can choose General Purpose (SSD) to reduce the costs). Read more about it at [Storage for Amazon RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html).
1. Allocate storage and set provisioned IOPS. We use the minimum values, `100` and `1000`.
1. Enable storage autoscaling (optional) and set a maximum storage threshold.
1. Under **Connectivity**, configure the following:
1. Under the **Virtual Private Cloud (VPC)** dropdown list select the VPC we created earlier (`gitlab-vpc`).
1. Under the **DB subnet group** select the subnet group (`gitlab-rds-group`) we created earlier.
1. Set public access to **No**.
1. Under **VPC security group**, select **Choose existing** and select the `gitlab-rds-sec-group` we created previously from the dropdown list.
1. Under **Additional configuration** leave the database port as the default `5432`.
1. For **Database authentication**, select **Password authentication**.
1. Expand the **Additional configuration** section and complete the following:
1. The initial database name. We use `gitlabhq_production`.
1. Configure your preferred backup settings.
1. The only other change we make here is to disable auto minor version updates under **Maintenance**.
1. Leave all the other settings as is or tweak according to your needs.
1. If you're happy, select **Create database**.
Now that the database is created, let's move on to setting up Redis with ElastiCache.
## Redis with ElastiCache
ElastiCache is an in-memory hosted caching solution. Redis maintains its own
persistence and is used to store session data, temporary cache information, and background job queues for the GitLab application.
### Create a Redis Security Group
1. Go to the EC2 dashboard.
1. Select **Security Groups** from the left menu.
1. Select **Create security group** and fill in the details. Give it a name (we use `gitlab-redis-sec-group`),
add a description, and choose the VPC we created earlier (`gitlab-vpc`).
1. In the **Inbound rules** section, select **Add rule** and add a **Custom TCP** rule, set port `6379`, and set the "Custom" source as the `gitlab-loadbalancer-sec-group` we created earlier.
1. When done, select **Create security group**.
### Redis Subnet Group
1. Go to the ElastiCache dashboard from your AWS console.
1. Go to **Subnet Groups** in the left menu, and create a new subnet group (we name ours `gitlab-redis-group`).
Select the VPC we created earlier (`gitlab-vpc`) and ensure the selected subnets table only contains the [private subnets](#subnets).
1. Select **Create** when ready.

### Create the Redis Cluster
1. Go back to the ElastiCache dashboard.
1. Select **Redis caches** on the left menu and select **Create Redis cache** to create a new
Redis cluster.
1. Under **Deployment option** select **Design your own cache**.
1. Under **Creation method** select **Cluster cache**.
1. Under **Cluster mode** select **Disabled** as it is [not supported](../../administration/redis/replication_and_failover_external.md#requirements). Even without cluster mode on, you still get the
chance to deploy Redis in multiple availability zones.
1. Under **Cluster info** give the cluster a name (`gitlab-redis`) and a description.
1. Under **Location** select **AWS Cloud** and enable **Multi-AZ** option.
1. In the Cluster settings section:
1. For the Engine version, select the Redis version as defined for your GitLab version in our [Redis requirements](../requirements.md#redis).
1. Leave the port as `6379` because this is what we previously used in our Redis security group.
1. Select the node type (at least `cache.t3.medium`, but adjust to your needs) and the number of replicas.
1. In the Connectivity settings section:
1. **Network type**: IPv4
1. **Subnet groups**: Select **Choose existing subnet group** and choose the `gitlab-redis-group` we had previously created.
1. In the Availability Zone placements section:
1. Manually select the preferred availability zones, and under "Replica 2"
choose a different zone than the other two.

1. Select **Next**.
1. In the security settings, edit the security groups and choose the
`gitlab-redis-sec-group` we had previously created. Select **Next**.
1. Leave the rest of the settings to their default values or edit to your liking.
1. When done, select **Create**.
## Setting up Bastion Hosts
Because our GitLab instances are in private subnets, we need a way to connect
to these instances with SSH for actions that include making configuration changes
and performing upgrades. One way of doing this is by using a [bastion host](https://en.wikipedia.org/wiki/Bastion_host),
sometimes also referred to as a jump box.
{{< alert type="note" >}}
If you do not want to maintain bastion hosts, you can set up [AWS Systems Manager Session Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html) for access to instances. This is beyond the scope of this document.
{{< /alert >}}
### Create Bastion Host A
1. Go to the EC2 Dashboard and select **Launch instance**.
1. In the **Name and tags** section, set the **Name** to `Bastion Host A`.
1. Select the latest **Ubuntu Server LTS (HVM)** AMI. Check the GitLab documentation for the [latest supported OS version](../../administration/package_information/supported_os.md).
1. Choose an instance type. We use a `t2.micro` as we only use the bastion host to SSH into our other instances.
1. In the **Key pair** section, select **Create new key pair**.
1. Give the key pair a name (we use `bastion-host-a`) and save the `bastion-host-a.pem` file for later use.
1. Edit the Network settings section:
1. Under **VPC**, select the `gitlab-vpc` from the dropdown list.
1. Under **Subnet**, select the public subnet we created earlier (`gitlab-public-10.0.0.0`).
1. Check that under **Auto-assign Public IP** you have **Disabled** selected. An [Elastic IP address](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) is assigned later to the host in the [next section](#assign-elastic-ip-to-the-bastion-host-a).
1. Under **Firewall** select **Create security group**, enter a **Security group name** (we use `bastion-sec-group`), and add a description.
1. We enable SSH access from anywhere (`0.0.0.0/0`). If you want stricter security, specify a single IP address or an IP address range in CIDR notation.
1. For storage, we leave everything as default and only add an 8 GB root volume. We do not store anything on this instance.
1. Review all your settings and, if you're happy, select **Launch Instance**.
#### Assign Elastic IP to the Bastion Host A
1. Go to the EC2 Dashboard and select **Network & Security**.
1. Select **Elastic IPs** and set the `Network border group` to `us-west-2`.
1. Select **Allocate**.
1. Select the Elastic IP address that was created.
1. Select **Actions** and choose **Associate Elastic IP address**.
1. Under the **Resource Type** select **Instance** and choose the `Bastion Host A` host under the **Instance** dropdown list.
1. Select **Associate**.
#### Confirm that you can SSH into the instance
1. On the EC2 Dashboard, select **Instances** in the left menu.
1. Select **Bastion Host A** from your list of instances.
1. Select **Connect** and follow the connection instructions.
1. If you are able to connect successfully, let's move on to setting up our second bastion host for redundancy.
### Create Bastion Host B
1. Create an EC2 instance following the same steps used previously with the following changes:
1. For the **Subnet**, select the second public subnet we created earlier (`gitlab-public-10.0.2.0`).
1. Under the **Add Tags** section, we set `Key: Name` and `Value: Bastion Host B` so that we can easily identify our two instances.
1. For the security group, select the existing `bastion-sec-group` we previously created.
### Use SSH Agent Forwarding
EC2 instances running Linux use private key files for SSH authentication. You connect to your bastion host using an SSH client and the private key file stored on your client. Because the private key file is not present on the bastion host, you are not able to connect to your instances in private subnets.
Storing private key files on your bastion host is a bad idea. To get around this, use SSH agent forwarding on your client.
For example, the command-line `ssh` client uses agent forwarding with its `-A` switch, like this:
```shell
ssh -A user@<bastion-public-IP-address>
```
See [Securely Connect to Linux Instances Running in a Private Amazon VPC](https://aws.amazon.com/blogs/security/securely-connect-to-linux-instances-running-in-a-private-amazon-vpc/) for a step-by-step guide on how to use SSH agent forwarding for other clients.
## Install GitLab and create custom AMI
We need a preconfigured, custom GitLab AMI to use in our launch configuration later. As a starting point, we use the official GitLab AMI to create a GitLab instance. Then, we add our custom configuration for PostgreSQL, Redis, and Gitaly. If you prefer, instead of using the official GitLab AMI, you can also spin up an EC2 instance of your choosing and [manually install GitLab](https://about.gitlab.com/install/).
### Install GitLab
From the EC2 dashboard:
1. Use the following section titled "[Find official GitLab-created AMI IDs on AWS](#find-official-gitlab-created-ami-ids-on-aws)" to find the correct AMI and select **Launch**.
1. In the **Name and tags** section, set the **Name** to `GitLab`.
1. In the **Instance type** dropdown list, select an instance type based on your workload. Consult the [hardware requirements](../requirements.md) to choose one that fits your needs (at least `c5.2xlarge`, which is sufficient to accommodate 100 users).
1. In the **Key pair** section, select **Create new key pair**.
1. Give the key pair a name (we use `gitlab`) and save the `gitlab.pem` file for later use.
1. In the **Network settings** section:
1. **VPC**: Select `gitlab-vpc`, the VPC we created earlier.
1. **Subnet**: Select `gitlab-private-10.0.1.0` from the list of subnets we created earlier.
1. **Auto-assign Public IP**: Select `Disable`.
1. **Firewall**: Chose **Select existing security group** and select the `gitlab-loadbalancer-sec-group` we created earlier.
1. For storage, the root volume is 8 GiB by default and should be enough given that we do not store any data there.
1. Review all your settings and, if you're happy, select **Launch Instance**.
### Add custom configuration
Connect to your GitLab instance via **Bastion Host A** using [SSH Agent Forwarding](#use-ssh-agent-forwarding). Once connected, add the following custom configuration:
#### Disable Let's Encrypt
Because we're adding our SSL certificate at the load balancer, we do not need the GitLab built-in support for Let's Encrypt. Let's Encrypt [is enabled by default](https://docs.gitlab.com/omnibus/settings/ssl/#enable-the-lets-encrypt-integration) when using an `https` domain, so we must explicitly disable it:
1. Open `/etc/gitlab/gitlab.rb` and disable it:
```ruby
letsencrypt['enable'] = false
```
1. Save the file and reconfigure for the changes to take effect:
```shell
sudo gitlab-ctl reconfigure
```
#### Install the required extensions for PostgreSQL
From your GitLab instance, connect to the RDS instance to verify access and to install the required `pg_trgm` and `btree_gist` extensions.
To find the host or endpoint, go to **Amazon RDS > Databases** and select the database you created earlier. Look for the endpoint under the **Connectivity & security** tab.
Do not to include the colon and port number:
```shell
sudo /opt/gitlab/embedded/bin/psql -U gitlab -h <rds-endpoint> -d gitlabhq_production
```
At the `psql` prompt create the extension and then quit the session:
```shell
psql (10.9)
Type "help" for help.
gitlab=# CREATE EXTENSION pg_trgm;
gitlab=# CREATE EXTENSION btree_gist;
gitlab=# \q
```
#### Configure GitLab to connect to PostgreSQL and Redis
1. Edit `/etc/gitlab/gitlab.rb`, find the `external_url 'http://<domain>'` option
and change it to the `https` domain you are using.
1. Look for the GitLab database settings and uncomment as necessary. In
our current case we specify the database adapter, encoding, host, name,
username, and password:
```ruby
# Disable the built-in Postgres
postgresql['enable'] = false
# Fill in the connection details
gitlab_rails['db_adapter'] = "postgresql"
gitlab_rails['db_encoding'] = "unicode"
gitlab_rails['db_database'] = "gitlabhq_production"
gitlab_rails['db_username'] = "gitlab"
gitlab_rails['db_password'] = "mypassword"
gitlab_rails['db_host'] = "<rds-endpoint>"
```
1. Next, we must configure the Redis section by adding the host and
uncommenting the port:
```ruby
# Disable the built-in Redis
redis['enable'] = false
# Fill in the connection details
gitlab_rails['redis_host'] = "<redis-endpoint>"
gitlab_rails['redis_port'] = 6379
```
1. Finally, reconfigure GitLab for the changes to take effect:
```shell
sudo gitlab-ctl reconfigure
```
1. You can also run a check and a service status to make sure
everything has been setup correctly:
```shell
sudo gitlab-rake gitlab:check
sudo gitlab-ctl status
```
#### Set up Gitaly
{{< alert type="warning" >}}
In this architecture, having a single Gitaly server creates a single point of failure. Use
[Gitaly Cluster (Praefect)](../../administration/gitaly/praefect/_index.md) to remove this limitation.
{{< /alert >}}
Gitaly is a service that provides high-level RPC access to Git repositories.
It should be enabled and configured on a separate EC2 instance in one of the
[private subnets](#subnets) we configured previously.
Let's create an EC2 instance where we install Gitaly:
1. From the EC2 dashboard, select **Launch instance**.
1. In the **Name and tags** section, set the **Name** to `Gitaly`.
1. Choose an AMI. In this example, we select the latest **Ubuntu Server LTS (HVM), SSD Volume Type**. Check the GitLab documentation for the [latest supported OS version](../../administration/package_information/supported_os.md).
1. Choose an instance type. We pick a `m5.xlarge`.
1. In the **Key pair** section, select **Create new key pair**.
1. Give the key pair a name (we use `gitaly`) and save the `gitaly.pem` file for later use.
1. In the Network settings section:
1. Under **VPC**, select the `gitlab-vpc` from the dropdown list.
1. Under **Subnet**, select the private subnet we created earlier (`gitlab-private-10.0.1.0`).
1. Check that under **Auto-assign Public IP** you have **Disable** selected.
1. Under **Firewall** select **Create security group**, enter a **Security group name** (we use `gitlab-gitaly-sec-group`), and add a description.
1. Create a **Custom TCP** rule and add port `8075` to the **Port Range**. For the **Source**, select the `gitlab-loadbalancer-sec-group`.
1. Also add an inbound rule for SSH from the `bastion-sec-group` so that we can connect using [SSH Agent Forwarding](#use-ssh-agent-forwarding) from the Bastion hosts.
1. Increase the Root volume size to `20 GiB` and change the **Volume Type** to `Provisioned IOPS SSD (io1)`. (The volume size is an arbitrary value. Create a volume big enough for your repository storage requirements.)
1. For **IOPS** set `1000` (20 GiB x 50 IOPS). You can provision up to 50 IOPS per GiB. If you select a larger volume, increase the IOPS accordingly. Workloads where many small files are written in a serialized manner, like `git`, requires performant storage, hence the choice of `Provisioned IOPS SSD (io1)`.
1. Review all your settings and, if you're happy, select **Launch Instance**.
{{< alert type="note" >}}
Instead of storing configuration and repository data on the root volume, you can also choose to add an additional EBS volume for repository storage. Follow
the same guidance mentioned previously. See the [Amazon EBS pricing page](https://aws.amazon.com/ebs/pricing/).
{{< /alert >}}
Now that we have our EC2 instance ready, follow the [documentation to install GitLab and set up Gitaly on its own server](../../administration/gitaly/configure_gitaly.md#run-gitaly-on-its-own-server). Perform the client setup steps from that document on the [GitLab instance we created](#install-gitlab) previously.
##### Elastic File System (EFS)
{{< alert type="warning" >}}
We do not recommend using EFS because it can negatively impact the performance of GitLab. For more information, see the
[documentation about avoiding cloud-based file systems](../../administration/nfs.md#avoid-using-cloud-based-file-systems).
{{< /alert >}}
If you do decide to use EFS, ensure that the [PosixUser](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-posixuser)
attribute is either omitted or correctly specified with the UID and GID of the `git` user on the system that Gitaly is
installed. The UID and GID can be retrieved with the following commands:
```shell
# UID
$ id -u git
# GID
$ id -g git
```
Additionally, you should not configure multiple [access points](https://docs.aws.amazon.com/efs/latest/ug/efs-access-points.html),
especially if they specify different credentials. An application other than Gitaly can manipulate permissions on
the Gitaly storage directories in a way that prevents Gitaly from operating correctly. For an example of this problem, see
[`omnibus-gitlab` issue 8893](https://gitlab.com/gitlab-org/omnibus-gitlab/-/issues/8893).
#### Add Support for Proxied SSL
As we are terminating SSL at our [load balancer](#load-balancer), follow the steps at [Supporting proxied SSL](https://docs.gitlab.com/omnibus/settings/ssl/#configure-a-reverse-proxy-or-load-balancer-ssl-termination) to configure this in `/etc/gitlab/gitlab.rb`.
Remember to run `sudo gitlab-ctl reconfigure` after saving the changes to the `gitlab.rb` file.
#### Fast lookup of authorized SSH keys
The public SSH keys for users allowed to access GitLab are stored in `/var/opt/gitlab/.ssh/authorized_keys`. Typically we'd use shared storage so that all the instances are able to access this file when a user performs a Git action over SSH. Because we do not have shared storage in our setup, we update our configuration to authorize SSH users via indexed lookup in the GitLab database.
Follow the instructions at [Set up fast SSH key lookup](../../administration/operations/fast_ssh_key_lookup.md#set-up-fast-lookup) to switch from using the `authorized_keys` file to the database.
If you do not configure fast lookup, Git actions over SSH results in the following error:
```shell
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
```
#### Configure host keys
Ordinarily we would manually copy the contents (primary and public keys) of `/etc/ssh/` on the primary application server to `/etc/ssh` on all secondary servers. This prevents false man-in-the-middle-attack alerts when accessing servers in your cluster behind a load balancer.
We automate this by creating static host keys as part of our custom AMI. As these host keys are also rotated every time an EC2 instance boots up, "hard coding" them into our custom AMI serves as a workaround.
On your GitLab instance run the following:
```shell
sudo mkdir /etc/ssh_static
sudo cp -R /etc/ssh/* /etc/ssh_static
```
In `/etc/ssh/sshd_config` update the following:
```shell
# HostKeys for protocol version 2
HostKey /etc/ssh_static/ssh_host_rsa_key
HostKey /etc/ssh_static/ssh_host_dsa_key
HostKey /etc/ssh_static/ssh_host_ecdsa_key
HostKey /etc/ssh_static/ssh_host_ed25519_key
```
#### Amazon S3 object storage
Because we're not using NFS for shared storage, we use [Amazon S3](https://aws.amazon.com/s3/) buckets to store backups, artifacts, LFS objects, uploads, merge request diffs, container registry images, and more. Our documentation includes [instructions on how to configure object storage](../../administration/object_storage.md) for each of these data types, and other information about using object storage with GitLab.
{{< alert type="note" >}}
Because we are using the [AWS IAM profile](#create-an-iam-role) we created earlier, be sure to omit the AWS access key and secret access key/value pairs when configuring object storage. Instead, use `'use_iam_profile' => true` in your configuration as shown in the object storage documentation linked previously.
{{< /alert >}}
Remember to run `sudo gitlab-ctl reconfigure` after saving the changes to the `gitlab.rb` file.
---
That concludes the configuration changes for our GitLab instance. Next, we create a custom AMI based on this instance to use for our launch configuration and auto scaling group.
### IP allowlist
We must add [the VPC IP Address Range (CIDR)](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-security-groups.html) of the `gitlab-vpc` we created earlier to the [IP allowlist](../../administration/monitoring/ip_allowlist.md) for the [Health check endpoints](../../administration/monitoring/health_check.md)
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
gitlab_rails['monitoring_whitelist'] = ['127.0.0.0/8', '10.0.0.0/16']
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
### Proxy Protocol
If Proxy protocol is enabled in the [load balancer](#load-balancer) we created earlier, we must also [enable](https://docs.gitlab.com/omnibus/settings/nginx.html#configuring-the-proxy-protocol) this on the `gitlab.rb` file.
1. Edit `/etc/gitlab/gitlab.rb`:
```ruby
nginx['proxy_protocol'] = true
nginx['real_ip_trusted_addresses'] = [ "127.0.0.0/8", "IP_OF_THE_PROXY/32"]
```
1. Reconfigure GitLab:
```shell
sudo gitlab-ctl reconfigure
```
### Sign in for the first time
Using the domain name you used when setting up [DNS for the load balancer](#configure-dns-for-load-balancer), you should now be able to visit GitLab in your browser.
Depending on how you installed GitLab and if you did not change the password by any other means, the default password is either:
- Your instance ID if you used the official GitLab AMI.
- A randomly generated password stored for 24 hours in `/etc/gitlab/initial_root_password`.
To change the default password, sign in as the `root` user with the default password and [change it in the user profile](../../user/profile/user_passwords.md#change-your-password).
When our [auto scaling group](#create-an-auto-scaling-group) spins up new instances, we are able to sign in with username `root` and the newly created password.
### Create custom AMI
On the EC2 dashboard:
1. Select the `GitLab` instance we [created earlier](#install-gitlab).
1. Select **Actions**, scroll down to **Image and templates** and select **Create image**.
1. Give your image a name and description (we use `GitLab-Source` for both).
1. Leave everything else as default and select **Create Image**
Now we have a custom AMI that we use to create our launch configuration the next step.
## Deploy GitLab inside an auto scaling group
### Create a launch template
From the EC2 dashboard:
1. Select **Launch Templates** from the left menu and select **create launch template**.
1. Enter a name for your launch template (we use `gitlab-launch-template`).
1. Select **Launch template contents** and select **My AMIs** tab/
1. Select **Owned by me** and select the `GitLab-Source` custom AMI we created previously.
1. Select an instance type best suited for your needs (at least a `c5.2xlarge`).
1. In the **Key pair** section, select **Create new key pair**.
1. Give the key pair a name (we use `gitlab-launch-template`) and save the `gitlab-launch-template.pem` file for later use.
1. The root volume is 8 GiB by default and should be enough given that we do not store any data there. Select **Configure Security Group**.
1. Check **Select and existing security group** and select the `gitlab-loadbalancer-sec-group` we created earlier.
1. In the **Network settings** section:
1. **Firewall**: Choose **Select existing security group** and select the `gitlab-loadbalancer-sec-group` we created earlier.
1. In the **Advanced details** section:
1. **IAM instance profile**: Select the `GitLabS3Access` role we [created earlier](#create-an-iam-role).
1. Review all your settings and, if you're happy, select **Create launch template**.
### Create an auto scaling group
From the EC2 dashboard:
1. Select **Auto scaling groups** from the left menu and select **Create Auto Scaling group**.
1. Enter a **Group name** (we use `gitlab-auto-scaling-group`).
1. Under **Launch template**, select the launch template we created earlier. Select **Next**
1. In the Network settings section:
1. Under **VPC**, select the `gitlab-vpc` from the dropdown list.
1. Under **Availability Zones and subnets**, select the private [subnets we created earlier](#subnets) (`gitlab-private-10.0.1.0` and `gitlab-private-10.0.3.0`).
1. Select **Next**.
1. In the Load Balancing settings section:
1. Select **Attach to an existing load balancer**.
1. Select the target groups we created earlier in the **Existing load balancer target groups** dropdown list.
1. For **Health Check Type**, check the **Turn on Elastic Load Balancing health checks** option. We leave our **Health Check Grace Period** as the default `300` seconds.
1. Select **Next**.
1. For **Group size**, set **Desired capacity** to `2`.
1. In the Scaling settings section:
1. Select **No scaling policies**. The policies are configured later one.
1. **Min desired capacity**: Set to `2`.
1. **Max desired capacity**: Set to `4`.
1. Select **Next**.
1. Finally, configure notifications and tags as you see fit, review your changes, and create the
auto scaling group.
1. After the auto scaling group is created, we need to create a scale up and down policy in [Cloudwatch](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html) and assign them.
1. Create an alarm for the `CPUUtilization` for metrics from **EC2** instances **By Auto Scaling Group** we created earlier.
1. Create a [scale up policy](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html#step-scaling-create-scale-out-policy) using the following conditions:
1. **Add** `1` capacity unit when `CPUUtilization` is greater than or equal to 60%.
1. Set the **Scaling policy name** to `Scale Up Policy`.

1. Create a [scale down policy](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html#step-scaling-create-scale-in-policy) using the following conditions:
1. **Remove** `1` capacity unit when `CPUUtilization` is less than or equal to 45%.
1. Set the **Scaling policy name** to `Scale Down Policy`.

1. Assign the new dynamic scaling policy to the auto scaling group we created earlier.
As the auto scaling group is created, you see your new instances spinning up in your EC2 dashboard. You also see the new instances added to your load balancer. After the instances pass the heath check, they are ready to start receiving traffic from the load balancer.
Because our instances are created by the auto scaling group, go back to your instances and terminate the [instance we previously created manually](#install-gitlab). We only needed this instance to create our custom AMI.
## Health check and monitoring with Prometheus
Apart from Amazon CloudWatch, which you can enable on various services,
GitLab provides its own integrated monitoring solution based on Prometheus.
For more information about how to set it up, see
[GitLab Prometheus](../../administration/monitoring/prometheus/_index.md).
GitLab also has various [health check endpoints](../../administration/monitoring/health_check.md)
that you can ping and get reports.
## GitLab Runner
If you want to take advantage of [GitLab CI/CD](../../ci/_index.md), you have to
set up at least one [runner](https://docs.gitlab.com/runner/).
Read more on configuring an
[autoscaling GitLab Runner on AWS](https://docs.gitlab.com/runner/configuration/runner_autoscale_aws/).
## Backup and restore
GitLab provides [a tool to back up](../../administration/backup_restore/_index.md)
and restore its Git data, database, attachments, LFS objects, and so on.
Some important things to know:
- The backup/restore tool **does not** store some configuration files, like secrets; you
must [configure this yourself](../../administration/backup_restore/backup_gitlab.md#storing-configuration-files).
- By default, the backup files are stored locally, but you can
[backup GitLab using S3](../../administration/backup_restore/backup_gitlab.md#using-amazon-s3).
- You can [exclude specific directories form the backup](../../administration/backup_restore/backup_gitlab.md#excluding-specific-data-from-the-backup).
### Backing up GitLab
To back up GitLab:
1. SSH into your instance.
1. Take a backup:
```shell
sudo gitlab-backup create
```
### Restoring GitLab from a backup
To restore GitLab, first review the [restore documentation](../../administration/backup_restore/_index.md#restore-gitlab),
and primarily the restore prerequisites. Then, follow the steps under the
[Linux package installations section](../../administration/backup_restore/restore_gitlab.md#restore-for-linux-package-installations).
## Updating GitLab
GitLab releases a new version every month on the [release date](https://about.gitlab.com/releases/). Whenever a new version is
released, you can update your GitLab instance:
1. SSH into your instance
1. Take a backup:
```shell
sudo gitlab-backup create
```
1. Update the repositories and install GitLab:
```shell
sudo apt update
sudo apt install gitlab-ee
```
After a few minutes, the new version should be up and running.
## Find official GitLab-created AMI IDs on AWS
Read more on how to use [GitLab releases as AMIs](../../solutions/cloud/aws/gitlab_single_box_on_aws.md#official-gitlab-releases-as-amis).
## Conclusion
In this guide, we went mostly through scaling and some redundancy options,
your mileage may vary.
Keep in mind that all solutions come with a trade-off between
cost/complexity and uptime. The more uptime you want, the more complex the solution.
And the more complex the solution, the more work is involved in setting up and
maintaining it.
Have a read through these other resources and feel free to
[open an issue](https://gitlab.com/gitlab-org/gitlab/-/issues/new)
to request additional material:
- [Scaling GitLab](../../administration/reference_architectures/_index.md):
GitLab supports several different types of clustering.
- [Geo replication](../../administration/geo/_index.md):
Geo is the solution for widely distributed development teams.
- [Linux package](https://docs.gitlab.com/omnibus/) - Everything you must know
about administering your GitLab instance.
- [Add a license](../../administration/license.md):
Activate all GitLab Enterprise Edition functionality with a license.
- [Pricing](https://about.gitlab.com/pricing/): Pricing for the different tiers.
## Troubleshooting
### Instances are failing health checks
If your instances are failing the load balancer's health checks, verify that they are returning a status `200` from the health check endpoint we configured earlier. Any other status, including redirects like status `302`, causes the health check to fail.
You may have to set a password on the `root` user to prevent automatic redirects on the sign-in endpoint before health checks pass.
### "The change you requested was rejected (422)"
If you see this page when trying to set a password via the web interface, make sure `external_url` in `gitlab.rb` matches the domain you are making a request from, and run `sudo gitlab-ctl reconfigure` after making any changes to it.
### Some job logs are not uploaded to object storage
When the GitLab deployment is scaled up to more than one node, some job logs may not be uploaded to [object storage](../../administration/object_storage.md) properly. [Incremental logging is required](../../administration/object_storage.md#alternatives-to-file-system-storage) for CI to use object storage.
Enable [incremental logging](../../administration/cicd/job_logs.md#incremental-logging) if it has not already been enabled.
|
https://docs.gitlab.com/install/google_cloud_platform
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/_index.md
|
2025-08-13
|
doc/install/google_cloud_platform
|
[
"doc",
"install",
"google_cloud_platform"
] |
_index.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Installing GitLab on Google Cloud Platform
|
Learn how to install a GitLab instance on Google Cloud Platform.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can install GitLab on a [Google Cloud Platform (GCP)](https://cloud.google.com/) using the official Linux package. You should customize it to accommodate your needs.
{{< alert type="note" >}}
To deploy production-ready GitLab on
Google Kubernetes Engine,
you can follow Google Cloud Platform's
[`Click to Deploy` steps](https://github.com/GoogleCloudPlatform/click-to-deploy/blob/master/k8s/gitlab/README.md)
It's an alternative to using a GCP VM, and uses
the [Cloud native GitLab Helm chart](https://docs.gitlab.com/charts/).
{{< /alert >}}
## Prerequisites
There are two prerequisites to install GitLab on GCP:
1. You must have a Google account.
1. You must sign up for the GCP program. If this is your first time, Google
gives you [$300 credit for free](https://console.cloud.google.com/freetrial) to consume over a 60-day period.
After you have performed those two steps, you can [create a VM](#creating-the-vm).
## Creating the VM
To deploy GitLab on GCP you must create a virtual machine:
1. Go to <https://console.cloud.google.com/compute/instances> and sign in with your Google credentials.
1. Select **Create**

1. On the next page, you can select the type of VM as well as the
estimated costs. Provide the name of the instance, desired data center, and machine type.
Note our [hardware requirements for different user base sizes](../requirements.md).

1. To select the size, type, and desired [operating system](../../administration/package_information/supported_os.md),
select **Change** under `Boot disk`. select **Select** when finished.
1. As a last step allow HTTP and HTTPS traffic, then select **Create**. The process finishes in a few seconds.
## Installing GitLab
After a few seconds, the instance is created and available to sign in. The next step is to install GitLab onto the instance.

1. Make a note of the external IP address of the instance, as you will need that in a later step. <!-- using future tense is okay here -->
1. Select **SSH** under the connect column to connect to the instance.
1. A new window appears, with you logged into the instance.

1. Next, follow the instructions for installing GitLab for the operating system you choose, at <https://about.gitlab.com/install/>. You can use the external IP address you noted before as the hostname.
1. Congratulations! GitLab is now installed and you can access it via your browser. To finish installation, open the URL in your browser and provide the initial administrator password. The username for this account is `root`.

## Next steps
These are the most important next steps to take after you installed GitLab for
the first time.
### Assigning a static IP
By default, Google assigns an ephemeral IP to your instance. If you use GitLab in a production
environment with a domain name, you should assign a static IP.
For more information, see [Promote an ephemeral external IP address](https://cloud.google.com/vpc/docs/reserve-static-external-ip-address#promote_ephemeral_ip).
### Using a domain name
Assuming you have a domain name in your possession and you have correctly
set up DNS to point to the static IP you configured in the previous step,
here's how you configure GitLab to be aware of the change:
1. SSH into the VM. You can select **SSH** in the Google console
and a new window pops up.

In the future you might want to set up [connecting with an SSH key](https://cloud.google.com/compute/docs/connect/standard-ssh)
instead.
1. Edit the configuration file of the Linux package using your favorite text editor:
```shell
sudo vim /etc/gitlab/gitlab.rb
```
1. Set the `external_url` value to the domain name you wish GitLab to have
**without** `https`:
```ruby
external_url 'http://gitlab.example.com'
```
We will set up HTTPS in the next step, no need to do this now. <!-- using future tense is okay here -->
1. Reconfigure GitLab for the changes to take effect:
```shell
sudo gitlab-ctl reconfigure
```
1. You can now visit GitLab using the domain name.
### Configuring HTTPS with the domain name
Although not needed, it's strongly recommended to secure GitLab with a
[TLS certificate](https://docs.gitlab.com/omnibus/settings/ssl/).
### Configuring the email SMTP settings
You must configure the email SMTP settings correctly otherwise GitLab cannot send notification emails, like comments, and password changes.
Check the [Linux package documentation](https://docs.gitlab.com/omnibus/settings/smtp.html#smtp-settings) how to do so.
## Further reading
GitLab can be configured to authenticate with other OAuth providers, like LDAP,
SAML, and Kerberos. Here are some documents you might be interested in reading:
- [Linux package documentation](https://docs.gitlab.com/omnibus/)
- [Integration documentation](../../integration/_index.md)
- [GitLab Pages configuration](../../administration/pages/_index.md)
- [GitLab container registry configuration](../../administration/packages/container_registry.md)
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Learn how to install a GitLab instance on Google Cloud Platform.
title: Installing GitLab on Google Cloud Platform
breadcrumbs:
- doc
- install
- google_cloud_platform
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can install GitLab on a [Google Cloud Platform (GCP)](https://cloud.google.com/) using the official Linux package. You should customize it to accommodate your needs.
{{< alert type="note" >}}
To deploy production-ready GitLab on
Google Kubernetes Engine,
you can follow Google Cloud Platform's
[`Click to Deploy` steps](https://github.com/GoogleCloudPlatform/click-to-deploy/blob/master/k8s/gitlab/README.md)
It's an alternative to using a GCP VM, and uses
the [Cloud native GitLab Helm chart](https://docs.gitlab.com/charts/).
{{< /alert >}}
## Prerequisites
There are two prerequisites to install GitLab on GCP:
1. You must have a Google account.
1. You must sign up for the GCP program. If this is your first time, Google
gives you [$300 credit for free](https://console.cloud.google.com/freetrial) to consume over a 60-day period.
After you have performed those two steps, you can [create a VM](#creating-the-vm).
## Creating the VM
To deploy GitLab on GCP you must create a virtual machine:
1. Go to <https://console.cloud.google.com/compute/instances> and sign in with your Google credentials.
1. Select **Create**

1. On the next page, you can select the type of VM as well as the
estimated costs. Provide the name of the instance, desired data center, and machine type.
Note our [hardware requirements for different user base sizes](../requirements.md).

1. To select the size, type, and desired [operating system](../../administration/package_information/supported_os.md),
select **Change** under `Boot disk`. select **Select** when finished.
1. As a last step allow HTTP and HTTPS traffic, then select **Create**. The process finishes in a few seconds.
## Installing GitLab
After a few seconds, the instance is created and available to sign in. The next step is to install GitLab onto the instance.

1. Make a note of the external IP address of the instance, as you will need that in a later step. <!-- using future tense is okay here -->
1. Select **SSH** under the connect column to connect to the instance.
1. A new window appears, with you logged into the instance.

1. Next, follow the instructions for installing GitLab for the operating system you choose, at <https://about.gitlab.com/install/>. You can use the external IP address you noted before as the hostname.
1. Congratulations! GitLab is now installed and you can access it via your browser. To finish installation, open the URL in your browser and provide the initial administrator password. The username for this account is `root`.

## Next steps
These are the most important next steps to take after you installed GitLab for
the first time.
### Assigning a static IP
By default, Google assigns an ephemeral IP to your instance. If you use GitLab in a production
environment with a domain name, you should assign a static IP.
For more information, see [Promote an ephemeral external IP address](https://cloud.google.com/vpc/docs/reserve-static-external-ip-address#promote_ephemeral_ip).
### Using a domain name
Assuming you have a domain name in your possession and you have correctly
set up DNS to point to the static IP you configured in the previous step,
here's how you configure GitLab to be aware of the change:
1. SSH into the VM. You can select **SSH** in the Google console
and a new window pops up.

In the future you might want to set up [connecting with an SSH key](https://cloud.google.com/compute/docs/connect/standard-ssh)
instead.
1. Edit the configuration file of the Linux package using your favorite text editor:
```shell
sudo vim /etc/gitlab/gitlab.rb
```
1. Set the `external_url` value to the domain name you wish GitLab to have
**without** `https`:
```ruby
external_url 'http://gitlab.example.com'
```
We will set up HTTPS in the next step, no need to do this now. <!-- using future tense is okay here -->
1. Reconfigure GitLab for the changes to take effect:
```shell
sudo gitlab-ctl reconfigure
```
1. You can now visit GitLab using the domain name.
### Configuring HTTPS with the domain name
Although not needed, it's strongly recommended to secure GitLab with a
[TLS certificate](https://docs.gitlab.com/omnibus/settings/ssl/).
### Configuring the email SMTP settings
You must configure the email SMTP settings correctly otherwise GitLab cannot send notification emails, like comments, and password changes.
Check the [Linux package documentation](https://docs.gitlab.com/omnibus/settings/smtp.html#smtp-settings) how to do so.
## Further reading
GitLab can be configured to authenticate with other OAuth providers, like LDAP,
SAML, and Kerberos. Here are some documents you might be interested in reading:
- [Linux package documentation](https://docs.gitlab.com/omnibus/)
- [Integration documentation](../../integration/_index.md)
- [GitLab Pages configuration](../../administration/pages/_index.md)
- [GitLab container registry configuration](../../administration/packages/container_registry.md)
|
https://docs.gitlab.com/install/azure
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/_index.md
|
2025-08-13
|
doc/install/azure
|
[
"doc",
"install",
"azure"
] |
_index.md
|
Systems
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install GitLab on Microsoft Azure
|
Learn how to spin up a pre-configured GitLab VM on Microsoft Azure.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
For users of the Microsoft Azure business cloud, GitLab has a pre-configured offering in
the [Azure Marketplace](https://azuremarketplace.microsoft.com/en-us/marketplace/).
This tutorial describes installing GitLab
Enterprise Edition in a single Virtual Machine (VM).
## Prerequisite
You need an account on Azure. Use of the following methods to obtain an account:
- If you or your company already have an account with a subscription, use that account.
If not, you can [create a free account](https://azure.microsoft.com/en-us/free/), which grants you a $200 credit to explore Azure for 30 days. For more information, see [Azure free account](https://azure.microsoft.com/en-us/pricing/offers/ms-azr-0044p/).
- If you have an MSDN subscription, you can activate your Azure subscriber benefits. Your MSDN
subscription gives you recurring Azure credits every month, so you can use
those credits and try out GitLab.
## Deploy and configure GitLab
Because GitLab is already installed in a pre-configured image, all you have to do is
create a new VM:
1. [Visit the GitLab offering in the marketplace](https://azuremarketplace.microsoft.com/en-us/marketplace/apps/gitlabinc1586447921813.gitlabee?tab=Overview)
1. Select **Get it now** and the **Create this app in Azure** window opens.
Select **Continue**.
1. Select one of the following options from the Azure portal:
- Select **Create** to create a VM from scratch.
- Select **Start with a pre-set configuration** to get started with some
pre-configured options. You can modify these configurations at any time.
For the sake of this guide, let's create the VM from scratch, so
select **Create**.
{{< alert type="note" >}}
Be aware that Azure incurs compute charges whenever your VM is
active (known as "allocated"), even if you're using free trial
credits.
[how to properly shutdown an Azure VM to save money](https://build5nines.com/properly-shutdown-azure-vm-to-save-money/).
See the [Azure pricing calculator](https://azure.microsoft.com/en-us/pricing/calculator/)
to learn how much resources can cost.
{{< /alert >}}
After you create the virtual machine, use the information in the following
sections to configure it.
### Configure the Basics tab
The first items you need to configure are the basic settings of the underlying virtual machine:
1. Select the subscription model and a resource group (create a new one if it
doesn't exist).
1. Enter a name for the VM, for example `GitLab`.
1. Select a region.
1. In **Availability options**, select **Availability zone** and set it to `1`.
Read more about the [availability zones](https://learn.microsoft.com/en-us/azure/virtual-machines/availability).
1. Ensure the selected image is set to **GitLab - Gen1**.
1. Select the VM size based on the [hardware requirements](../requirements.md).
Because the minimum system requirements to run a GitLab environment for up to 500 users
is covered by the `D4s_v3` size, select that option.
1. Set the authentication type to **SSH public key**.
1. Enter a user name or leave the one that is automatically created. This is
the user Azure uses to connect to the VM through SSH. By default, the user
has root access.
1. Determine if you want to provide your own SSH key or let Azure create one for you.
For more information about how to set up SSH
public keys, see [SSH](../../user/ssh.md).
Review your entered settings, and then proceed to the Disks tab.
### Configure the Disks tab
For the disks:
1. For the OS disk type, select **Premium SSD**.
1. Select the default encryption.
[Read more about the types of disks](https://learn.microsoft.com/en-us/azure/virtual-machines/managed-disks-overview) that Azure provides.
Review your settings, and then proceed to the Networking tab.
### Configure the Networking tab
Use this tab to define the network connectivity for your
virtual machine, by configuring network interface card (NIC) settings.
You can leave them at their default settings.
Azure creates a security group by default and the VM is assigned to it.
The GitLab image in the marketplace has the following ports open by default:
| Port | Description |
|------|-------------|
| 80 | Enable the VM to respond to HTTP requests, allowing public access. |
| 443 | Enable our VM to respond to HTTPS requests, allowing public access. |
| 22 | Enable our VM to respond to SSH connection requests, allowing public access (with authentication) to remote terminal sessions. |
If you want to change the ports or add any rules, you can do it
after the VM is created by selecting Networking settings in the left sidebar,
while in the VM dashboard.
### Configure the Management tab
Use this tab to configure monitoring and management options
for your VM. You don't need to change the default settings.
### Configure the Advanced tab
Use this tab to add additional configuration, agents, scripts
or applications through virtual machine extensions or `cloud-init`. You don't
need to change the default settings.
### Configure the Tags tab
Use this tab to add name/value pairs that enable you to categorize
resources. You don't need to change the default settings.
### Review and create the VM
The final tab presents you with all of your selected options,
where you can review and modify your choices from the
previous steps. Azure runs validation tests in the background,
and if you provided all of the required settings, you can
create the VM.
After you select **Create**, if you had opted for Azure to create an SSH key pair
for you, a prompt appears to download the private SSH key. Download the key, as it's
needed to SSH into the VM.
After you download the key, the deployment begins.
### Finish deployment
At this point, Azure begins to deploy your new VM. The deployment process
takes a few minutes to complete. After it's complete, the new VM and its
associated resources are displayed on the Azure Dashboard.
Select **Go to resource** to visit the dashboard of the VM.
GitLab is now deployed and ready to be used. Before doing so, however,
you need to set up the domain name and configure GitLab to use it.
### Set up a domain name
The VM has a public IP address (static by default), but Azure allows you
to assign a descriptive DNS name to the VM:
1. From the VM dashboard, select **Configure** under **DNS name**.
1. Enter a descriptive DNS name for your instance in the **DNS name label** field,
for example `gitlab-prod`. This makes the VM accessible at
`gitlab-prod.eastus.cloudapp.azure.com`.
1. Select **Save**.
Eventually, most users want to use their own domain name. For you to do this, you need to add a DNS `A` record
with your domain registrar that points to the public IP address of your Azure VM.
You can use the [Azure DNS](https://learn.microsoft.com/en-us/azure/dns/dns-delegate-domain-azure-dns)
or some [other registrar](https://docs.gitlab.com/omnibus/settings/dns.html).
### Change the GitLab external URL
GitLab uses `external_url` in its configuration file to set up the domain name.
If you don't set this up, when you visit the Azure friendly name, the browser will
redirect you to the public IP.
To set up the GitLab external URL:
1. Connect to GitLab through SSH by going to **Settings > Connect** from the VM
dashboard, and follow the instructions. Remember to sign in with the username
and SSH key you specified when you [created the VM](#configure-the-basics-tab).
The Azure VM domain name is the one you
[set up previously](#set-up-a-domain-name). If you didn't set up a domain name for
your VM, you can use the IP address in its place.
In the case of our example:
```shell
ssh -i <private key path> gitlab-azure@gitlab-prod.eastus.cloudapp.azure.com
```
{{< alert type="note" >}}
If you need to reset your credentials, read
[how to reset SSH credentials for a user on an Azure VM](https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/linux/troubleshoot-ssh-connection#reset-ssh-credentials-for-a-user).
{{< /alert >}}
1. Open `/etc/gitlab/gitlab.rb` with your editor.
1. Find `external_url` and replace it with your own domain name. For the sake
of this example, use the default domain name Azure sets up.
Using `https` in the URL
[automatically enables](https://docs.gitlab.com/omnibus/settings/ssl/#lets-encrypt-integration),
Let's Encrypt, and sets HTTPS by default:
```ruby
external_url 'https://gitlab-prod.eastus.cloudapp.azure.com'
```
1. Find the following settings and comment them out, so that GitLab doesn't
pick up the wrong certificates:
```ruby
# nginx['redirect_http_to_https'] = true
# nginx['ssl_certificate'] = "/etc/gitlab/ssl/server.crt"
# nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/server.key"
```
1. Reconfigure GitLab for the changes to take effect. Run the
following command every time you make changes to `/etc/gitlab/gitlab.rb`:
```shell
sudo gitlab-ctl reconfigure
```
1. To prevent the domain name from
[resetting after a reboot](https://docs.bitnami.com/aws/apps/gitlab/configuration/change-default-address/),
rename the utility that Bitnami uses:
```shell
sudo mv /opt/bitnami/apps/gitlab/bnconfig /opt/bitnami/apps/gitlab/bnconfig.bak
```
You can now visit GitLab with your browser at the new external URL.
### Visit GitLab for the first time
Use the domain name you set up earlier to visit your new GitLab instance
in your browser. In this example, it's `https://gitlab-prod.eastus.cloudapp.azure.com`.
The first thing that appears is the sign-in page. GitLab creates an administrator user by default.
The credentials are:
- Username: `root`
- Password: the password is automatically created, and there are
[two ways to find it](https://docs.bitnami.com/azure/faq/get-started/find-credentials/).
After signing in, be sure to immediately [change the password](../../user/profile/user_passwords.md#change-your-password).
## Maintain your GitLab instance
It's important to keep your GitLab environment up-to-date. The GitLab team is constantly making
enhancements and occasionally you may need to update for security reasons. Use the information
in this section whenever you need to update GitLab.
### Check the current version
To determine the version of GitLab you're currently running:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Overview > Dashboard**.
1. Find the version under the **Components** table.
If there's a newer available version of GitLab that contains one or more
security fixes, GitLab displays an **Update asap** notification message that
encourages you to [update](#update-gitlab).
### Update GitLab
To update GitLab to the latest version:
1. Connect to the VM through SSH.
1. Update GitLab:
```shell
sudo apt update
sudo apt install gitlab-ee
```
This command updates GitLab and its associated components to the latest versions,
and can take time to complete. During this time, the terminal shows various update tasks being
completed in your terminal.
{{< alert type="note" >}}
If you get an error like
`E: The repository 'https://packages.gitlab.com/gitlab/gitlab-ee/debian buster InRelease' is not signed.`,
see the [troubleshooting section](#update-the-gpg-key-for-the-gitlab-repositories).
{{< /alert >}}
1. After the update process is complete, a message like the
following appears:
```plaintext
Upgrade complete! If your GitLab server is misbehaving try running
sudo gitlab-ctl restart
before anything else.
```
Refresh your GitLab instance in the browser and go to the **Admin** area. You should now have an
up-to-date GitLab instance.
## Next steps and further configuration
Now that you have a functional GitLab instance, follow the
[next steps](../next_steps.md) to learn what more you can do with your
new installation.
## Troubleshooting
This section describes common errors you can encounter.
### Update the GPG key for the GitLab repositories
{{< alert type="note" >}}
This is a temporary fix until the GitLab image is updated with the new
GPG key.
{{< /alert >}}
The pre-configured GitLab image in Azure (provided by Bitnami) uses
a GPG key [deprecated in April 2020](https://about.gitlab.com/blog/2020/03/30/gpg-key-for-gitlab-package-repositories-metadata-changing/).
If you try to update the repositories, the system returns the following error:
```plaintext
[ 21.023494] apt-setup[1198]: W: GPG error: https://packages.gitlab.com/gitlab/gitlab-ee/debian buster InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 3F01618A51312F3F
[ 21.024033] apt-setup[1198]: E: The repository 'https://packages.gitlab.com/gitlab/gitlab-ee/debian buster InRelease' is not signed.
```
To fix this, fetch the new GPG key:
```shell
sudo apt install gpg-agent
curl "https://gitlab-org.gitlab.io/omnibus-gitlab/gitlab_new_gpg.key" \
--output /tmp/omnibus_gitlab_gpg.key
sudo apt-key add /tmp/omnibus_gitlab_gpg.key
```
You can now [update GitLab](#update-gitlab). For more information, read about the
[packages signatures](https://docs.gitlab.com/omnibus/update/package_signatures.html).
|
---
stage: Systems
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Learn how to spin up a pre-configured GitLab VM on Microsoft Azure.
title: Install GitLab on Microsoft Azure
breadcrumbs:
- doc
- install
- azure
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
For users of the Microsoft Azure business cloud, GitLab has a pre-configured offering in
the [Azure Marketplace](https://azuremarketplace.microsoft.com/en-us/marketplace/).
This tutorial describes installing GitLab
Enterprise Edition in a single Virtual Machine (VM).
## Prerequisite
You need an account on Azure. Use of the following methods to obtain an account:
- If you or your company already have an account with a subscription, use that account.
If not, you can [create a free account](https://azure.microsoft.com/en-us/free/), which grants you a $200 credit to explore Azure for 30 days. For more information, see [Azure free account](https://azure.microsoft.com/en-us/pricing/offers/ms-azr-0044p/).
- If you have an MSDN subscription, you can activate your Azure subscriber benefits. Your MSDN
subscription gives you recurring Azure credits every month, so you can use
those credits and try out GitLab.
## Deploy and configure GitLab
Because GitLab is already installed in a pre-configured image, all you have to do is
create a new VM:
1. [Visit the GitLab offering in the marketplace](https://azuremarketplace.microsoft.com/en-us/marketplace/apps/gitlabinc1586447921813.gitlabee?tab=Overview)
1. Select **Get it now** and the **Create this app in Azure** window opens.
Select **Continue**.
1. Select one of the following options from the Azure portal:
- Select **Create** to create a VM from scratch.
- Select **Start with a pre-set configuration** to get started with some
pre-configured options. You can modify these configurations at any time.
For the sake of this guide, let's create the VM from scratch, so
select **Create**.
{{< alert type="note" >}}
Be aware that Azure incurs compute charges whenever your VM is
active (known as "allocated"), even if you're using free trial
credits.
[how to properly shutdown an Azure VM to save money](https://build5nines.com/properly-shutdown-azure-vm-to-save-money/).
See the [Azure pricing calculator](https://azure.microsoft.com/en-us/pricing/calculator/)
to learn how much resources can cost.
{{< /alert >}}
After you create the virtual machine, use the information in the following
sections to configure it.
### Configure the Basics tab
The first items you need to configure are the basic settings of the underlying virtual machine:
1. Select the subscription model and a resource group (create a new one if it
doesn't exist).
1. Enter a name for the VM, for example `GitLab`.
1. Select a region.
1. In **Availability options**, select **Availability zone** and set it to `1`.
Read more about the [availability zones](https://learn.microsoft.com/en-us/azure/virtual-machines/availability).
1. Ensure the selected image is set to **GitLab - Gen1**.
1. Select the VM size based on the [hardware requirements](../requirements.md).
Because the minimum system requirements to run a GitLab environment for up to 500 users
is covered by the `D4s_v3` size, select that option.
1. Set the authentication type to **SSH public key**.
1. Enter a user name or leave the one that is automatically created. This is
the user Azure uses to connect to the VM through SSH. By default, the user
has root access.
1. Determine if you want to provide your own SSH key or let Azure create one for you.
For more information about how to set up SSH
public keys, see [SSH](../../user/ssh.md).
Review your entered settings, and then proceed to the Disks tab.
### Configure the Disks tab
For the disks:
1. For the OS disk type, select **Premium SSD**.
1. Select the default encryption.
[Read more about the types of disks](https://learn.microsoft.com/en-us/azure/virtual-machines/managed-disks-overview) that Azure provides.
Review your settings, and then proceed to the Networking tab.
### Configure the Networking tab
Use this tab to define the network connectivity for your
virtual machine, by configuring network interface card (NIC) settings.
You can leave them at their default settings.
Azure creates a security group by default and the VM is assigned to it.
The GitLab image in the marketplace has the following ports open by default:
| Port | Description |
|------|-------------|
| 80 | Enable the VM to respond to HTTP requests, allowing public access. |
| 443 | Enable our VM to respond to HTTPS requests, allowing public access. |
| 22 | Enable our VM to respond to SSH connection requests, allowing public access (with authentication) to remote terminal sessions. |
If you want to change the ports or add any rules, you can do it
after the VM is created by selecting Networking settings in the left sidebar,
while in the VM dashboard.
### Configure the Management tab
Use this tab to configure monitoring and management options
for your VM. You don't need to change the default settings.
### Configure the Advanced tab
Use this tab to add additional configuration, agents, scripts
or applications through virtual machine extensions or `cloud-init`. You don't
need to change the default settings.
### Configure the Tags tab
Use this tab to add name/value pairs that enable you to categorize
resources. You don't need to change the default settings.
### Review and create the VM
The final tab presents you with all of your selected options,
where you can review and modify your choices from the
previous steps. Azure runs validation tests in the background,
and if you provided all of the required settings, you can
create the VM.
After you select **Create**, if you had opted for Azure to create an SSH key pair
for you, a prompt appears to download the private SSH key. Download the key, as it's
needed to SSH into the VM.
After you download the key, the deployment begins.
### Finish deployment
At this point, Azure begins to deploy your new VM. The deployment process
takes a few minutes to complete. After it's complete, the new VM and its
associated resources are displayed on the Azure Dashboard.
Select **Go to resource** to visit the dashboard of the VM.
GitLab is now deployed and ready to be used. Before doing so, however,
you need to set up the domain name and configure GitLab to use it.
### Set up a domain name
The VM has a public IP address (static by default), but Azure allows you
to assign a descriptive DNS name to the VM:
1. From the VM dashboard, select **Configure** under **DNS name**.
1. Enter a descriptive DNS name for your instance in the **DNS name label** field,
for example `gitlab-prod`. This makes the VM accessible at
`gitlab-prod.eastus.cloudapp.azure.com`.
1. Select **Save**.
Eventually, most users want to use their own domain name. For you to do this, you need to add a DNS `A` record
with your domain registrar that points to the public IP address of your Azure VM.
You can use the [Azure DNS](https://learn.microsoft.com/en-us/azure/dns/dns-delegate-domain-azure-dns)
or some [other registrar](https://docs.gitlab.com/omnibus/settings/dns.html).
### Change the GitLab external URL
GitLab uses `external_url` in its configuration file to set up the domain name.
If you don't set this up, when you visit the Azure friendly name, the browser will
redirect you to the public IP.
To set up the GitLab external URL:
1. Connect to GitLab through SSH by going to **Settings > Connect** from the VM
dashboard, and follow the instructions. Remember to sign in with the username
and SSH key you specified when you [created the VM](#configure-the-basics-tab).
The Azure VM domain name is the one you
[set up previously](#set-up-a-domain-name). If you didn't set up a domain name for
your VM, you can use the IP address in its place.
In the case of our example:
```shell
ssh -i <private key path> gitlab-azure@gitlab-prod.eastus.cloudapp.azure.com
```
{{< alert type="note" >}}
If you need to reset your credentials, read
[how to reset SSH credentials for a user on an Azure VM](https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/linux/troubleshoot-ssh-connection#reset-ssh-credentials-for-a-user).
{{< /alert >}}
1. Open `/etc/gitlab/gitlab.rb` with your editor.
1. Find `external_url` and replace it with your own domain name. For the sake
of this example, use the default domain name Azure sets up.
Using `https` in the URL
[automatically enables](https://docs.gitlab.com/omnibus/settings/ssl/#lets-encrypt-integration),
Let's Encrypt, and sets HTTPS by default:
```ruby
external_url 'https://gitlab-prod.eastus.cloudapp.azure.com'
```
1. Find the following settings and comment them out, so that GitLab doesn't
pick up the wrong certificates:
```ruby
# nginx['redirect_http_to_https'] = true
# nginx['ssl_certificate'] = "/etc/gitlab/ssl/server.crt"
# nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/server.key"
```
1. Reconfigure GitLab for the changes to take effect. Run the
following command every time you make changes to `/etc/gitlab/gitlab.rb`:
```shell
sudo gitlab-ctl reconfigure
```
1. To prevent the domain name from
[resetting after a reboot](https://docs.bitnami.com/aws/apps/gitlab/configuration/change-default-address/),
rename the utility that Bitnami uses:
```shell
sudo mv /opt/bitnami/apps/gitlab/bnconfig /opt/bitnami/apps/gitlab/bnconfig.bak
```
You can now visit GitLab with your browser at the new external URL.
### Visit GitLab for the first time
Use the domain name you set up earlier to visit your new GitLab instance
in your browser. In this example, it's `https://gitlab-prod.eastus.cloudapp.azure.com`.
The first thing that appears is the sign-in page. GitLab creates an administrator user by default.
The credentials are:
- Username: `root`
- Password: the password is automatically created, and there are
[two ways to find it](https://docs.bitnami.com/azure/faq/get-started/find-credentials/).
After signing in, be sure to immediately [change the password](../../user/profile/user_passwords.md#change-your-password).
## Maintain your GitLab instance
It's important to keep your GitLab environment up-to-date. The GitLab team is constantly making
enhancements and occasionally you may need to update for security reasons. Use the information
in this section whenever you need to update GitLab.
### Check the current version
To determine the version of GitLab you're currently running:
1. On the left sidebar, at the bottom, select **Admin**.
1. Select **Overview > Dashboard**.
1. Find the version under the **Components** table.
If there's a newer available version of GitLab that contains one or more
security fixes, GitLab displays an **Update asap** notification message that
encourages you to [update](#update-gitlab).
### Update GitLab
To update GitLab to the latest version:
1. Connect to the VM through SSH.
1. Update GitLab:
```shell
sudo apt update
sudo apt install gitlab-ee
```
This command updates GitLab and its associated components to the latest versions,
and can take time to complete. During this time, the terminal shows various update tasks being
completed in your terminal.
{{< alert type="note" >}}
If you get an error like
`E: The repository 'https://packages.gitlab.com/gitlab/gitlab-ee/debian buster InRelease' is not signed.`,
see the [troubleshooting section](#update-the-gpg-key-for-the-gitlab-repositories).
{{< /alert >}}
1. After the update process is complete, a message like the
following appears:
```plaintext
Upgrade complete! If your GitLab server is misbehaving try running
sudo gitlab-ctl restart
before anything else.
```
Refresh your GitLab instance in the browser and go to the **Admin** area. You should now have an
up-to-date GitLab instance.
## Next steps and further configuration
Now that you have a functional GitLab instance, follow the
[next steps](../next_steps.md) to learn what more you can do with your
new installation.
## Troubleshooting
This section describes common errors you can encounter.
### Update the GPG key for the GitLab repositories
{{< alert type="note" >}}
This is a temporary fix until the GitLab image is updated with the new
GPG key.
{{< /alert >}}
The pre-configured GitLab image in Azure (provided by Bitnami) uses
a GPG key [deprecated in April 2020](https://about.gitlab.com/blog/2020/03/30/gpg-key-for-gitlab-package-repositories-metadata-changing/).
If you try to update the repositories, the system returns the following error:
```plaintext
[ 21.023494] apt-setup[1198]: W: GPG error: https://packages.gitlab.com/gitlab/gitlab-ee/debian buster InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 3F01618A51312F3F
[ 21.024033] apt-setup[1198]: E: The repository 'https://packages.gitlab.com/gitlab/gitlab-ee/debian buster InRelease' is not signed.
```
To fix this, fetch the new GPG key:
```shell
sudo apt install gpg-agent
curl "https://gitlab-org.gitlab.io/omnibus-gitlab/gitlab_new_gpg.key" \
--output /tmp/omnibus_gitlab_gpg.key
sudo apt-key add /tmp/omnibus_gitlab_gpg.key
```
You can now [update GitLab](#update-gitlab). For more information, read about the
[packages signatures](https://docs.gitlab.com/omnibus/update/package_signatures.html).
|
https://docs.gitlab.com/install/configuration
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/configuration.md
|
2025-08-13
|
doc/install/docker
|
[
"doc",
"install",
"docker"
] |
configuration.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Configure GitLab running in a Docker container
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This container uses the official Linux package, so you can use
the unique configuration file `/etc/gitlab/gitlab.rb` to configure the instance.
## Edit the configuration file
To access the GitLab configuration file, you can start a shell session in the
context of a running container.
1. Start the session:
```shell
sudo docker exec -it gitlab /bin/bash
```
Alternatively, you can open `/etc/gitlab/gitlab.rb` in an editor directly:
```shell
sudo docker exec -it gitlab editor /etc/gitlab/gitlab.rb
```
1. In your preferred text editor, open `/etc/gitlab/gitlab.rb` and update the following fields:
1. Set the `external_url` field to
a valid URL for your GitLab instance.
1. To receive emails from GitLab, configure the
[SMTP settings](https://docs.gitlab.com/omnibus/settings/smtp.html). The GitLab Docker image
doesn't have an SMTP server pre-installed.
1. If desired [enable HTTPS](https://docs.gitlab.com/omnibus/settings/ssl/).
1. Save the file and restart the container to reconfigure GitLab:
```shell
sudo docker restart gitlab
```
GitLab reconfigures itself each time the container starts.
For more configuration options in GitLab, see the
[configuration documentation](https://docs.gitlab.com/omnibus/settings/configuration.html).
## Pre-configure Docker container
You can pre-configure the GitLab Docker image by adding the environment variable
`GITLAB_OMNIBUS_CONFIG` to the Docker run command. This variable can contain any
`gitlab.rb` setting and is evaluated before the loading of the container's
`gitlab.rb` file. This behavior allows you to configure the external GitLab URL,
and make database configuration or any other option from the
[Linux package template](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/files/gitlab-config-template/gitlab.rb.template).
The settings contained in `GITLAB_OMNIBUS_CONFIG` aren't written to the
`gitlab.rb` configuration file, and are evaluated on load. To provide multiple
settings, separate them with a colon (`;`).
The following example sets the external URL, enables LFS, and starts
the container with a [minimal shm size required for Prometheus](troubleshooting.md#devshm-mount-not-having-enough-space-in-docker-container):
```shell
sudo docker run --detach \
--hostname gitlab.example.com \
--env GITLAB_OMNIBUS_CONFIG="external_url 'http://gitlab.example.com'; gitlab_rails['lfs_enabled'] = true;" \
--publish 443:443 --publish 80:80 --publish 22:22 \
--name gitlab \
--restart always \
--volume $GITLAB_HOME/config:/etc/gitlab \
--volume $GITLAB_HOME/logs:/var/log/gitlab \
--volume $GITLAB_HOME/data:/var/opt/gitlab \
--shm-size 256m \
gitlab/gitlab-ee:<version>-ee.0
```
Every time you execute a `docker run` command, you need to provide
the `GITLAB_OMNIBUS_CONFIG` option. The content of `GITLAB_OMNIBUS_CONFIG` is
_not_ preserved between subsequent runs.
### Run GitLab on a public IP address
You can make Docker to use your IP address and forward all traffic to the
GitLab container by modifying the `--publish` flag.
To expose GitLab on IP `198.51.100.1`:
```shell
sudo docker run --detach \
--hostname gitlab.example.com \
--env GITLAB_OMNIBUS_CONFIG="external_url 'http://gitlab.example.com'" \
--publish 198.51.100.1:443:443 \
--publish 198.51.100.1:80:80 \
--publish 198.51.100.1:22:22 \
--name gitlab \
--restart always \
--volume $GITLAB_HOME/config:/etc/gitlab \
--volume $GITLAB_HOME/logs:/var/log/gitlab \
--volume $GITLAB_HOME/data:/var/opt/gitlab \
--shm-size 256m \
gitlab/gitlab-ee:<version>-ee.0
```
You can then access your GitLab instance at `http://198.51.100.1/` and `https://198.51.100.1/`.
## Expose GitLab on different ports
GitLab occupies [specific ports](../../administration/package_information/defaults.md)
inside the container.
If you want to use different host ports from the default ports `80` (HTTP), `443` (HTTPS), or `22` (SSH),
you need to add a separate `--publish` directive to the `docker run` command.
For example, to expose the web interface on the host's port `8929`, and the SSH service on
port `2424`:
1. Use the following `docker run` command:
```shell
sudo docker run --detach \
--hostname gitlab.example.com \
--env GITLAB_OMNIBUS_CONFIG="external_url 'http://gitlab.example.com:8929'; gitlab_rails['gitlab_shell_ssh_port'] = 2424" \
--publish 8929:8929 --publish 2424:22 \
--name gitlab \
--restart always \
--volume $GITLAB_HOME/config:/etc/gitlab \
--volume $GITLAB_HOME/logs:/var/log/gitlab \
--volume $GITLAB_HOME/data:/var/opt/gitlab \
--shm-size 256m \
gitlab/gitlab-ee:<version>-ee.0
```
{{< alert type="note" >}}
The format to publish ports is `hostPort:containerPort`. Read more in the
Docker documentation about
[exposing incoming ports](https://docs.docker.com/network/#published-ports).
{{< /alert >}}
1. Enter the running container:
```shell
sudo docker exec -it gitlab /bin/bash
```
1. Open `/etc/gitlab/gitlab.rb` with your editor and set `external_url`:
```ruby
# For HTTP
external_url "http://gitlab.example.com:8929"
or
# For HTTPS (notice the https)
external_url "https://gitlab.example.com:8929"
```
The port specified in this URL must match the port published to the host by Docker.
Additionally, if the NGINX listen port is not explicitly set in
`nginx['listen_port']`, the `external_url` is used instead.
For more information, see the [NGINX documentation](https://docs.gitlab.com/omnibus/settings/nginx.html).
1. Set the SSH port:
```ruby
gitlab_rails['gitlab_shell_ssh_port'] = 2424
```
1. Finally, reconfigure GitLab:
```shell
gitlab-ctl reconfigure
```
Following the previous example, your web browser can reach your GitLab instance
at `<hostIP>:8929` and push over SSH on port `2424`.
You can see a `docker-compose.yml` example that uses different ports in the
[Docker compose](installation.md#install-gitlab-by-using-docker-compose) section.
## Configure multiple database connections
Starting in [GitLab 16.0](https://gitlab.com/gitlab-org/omnibus-gitlab/-/merge_requests/6850),
GitLab defaults to using two database connections that point to the same PostgreSQL database.
If, for any reason, you wish to switch back to single database connection:
1. Edit `/etc/gitlab/gitlab.rb` inside the container:
```shell
sudo docker exec -it gitlab editor /etc/gitlab/gitlab.rb
```
1. Add the following line:
```ruby
gitlab_rails['databases']['ci']['enable'] = false
```
1. Restart the container:
```shell
sudo docker restart gitlab
```
## Next steps
After you configure your installation, consider taking the
[recommended next steps](../next_steps.md), including authentication options
and sign-up restrictions.
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Configure GitLab running in a Docker container
breadcrumbs:
- doc
- install
- docker
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This container uses the official Linux package, so you can use
the unique configuration file `/etc/gitlab/gitlab.rb` to configure the instance.
## Edit the configuration file
To access the GitLab configuration file, you can start a shell session in the
context of a running container.
1. Start the session:
```shell
sudo docker exec -it gitlab /bin/bash
```
Alternatively, you can open `/etc/gitlab/gitlab.rb` in an editor directly:
```shell
sudo docker exec -it gitlab editor /etc/gitlab/gitlab.rb
```
1. In your preferred text editor, open `/etc/gitlab/gitlab.rb` and update the following fields:
1. Set the `external_url` field to
a valid URL for your GitLab instance.
1. To receive emails from GitLab, configure the
[SMTP settings](https://docs.gitlab.com/omnibus/settings/smtp.html). The GitLab Docker image
doesn't have an SMTP server pre-installed.
1. If desired [enable HTTPS](https://docs.gitlab.com/omnibus/settings/ssl/).
1. Save the file and restart the container to reconfigure GitLab:
```shell
sudo docker restart gitlab
```
GitLab reconfigures itself each time the container starts.
For more configuration options in GitLab, see the
[configuration documentation](https://docs.gitlab.com/omnibus/settings/configuration.html).
## Pre-configure Docker container
You can pre-configure the GitLab Docker image by adding the environment variable
`GITLAB_OMNIBUS_CONFIG` to the Docker run command. This variable can contain any
`gitlab.rb` setting and is evaluated before the loading of the container's
`gitlab.rb` file. This behavior allows you to configure the external GitLab URL,
and make database configuration or any other option from the
[Linux package template](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/files/gitlab-config-template/gitlab.rb.template).
The settings contained in `GITLAB_OMNIBUS_CONFIG` aren't written to the
`gitlab.rb` configuration file, and are evaluated on load. To provide multiple
settings, separate them with a colon (`;`).
The following example sets the external URL, enables LFS, and starts
the container with a [minimal shm size required for Prometheus](troubleshooting.md#devshm-mount-not-having-enough-space-in-docker-container):
```shell
sudo docker run --detach \
--hostname gitlab.example.com \
--env GITLAB_OMNIBUS_CONFIG="external_url 'http://gitlab.example.com'; gitlab_rails['lfs_enabled'] = true;" \
--publish 443:443 --publish 80:80 --publish 22:22 \
--name gitlab \
--restart always \
--volume $GITLAB_HOME/config:/etc/gitlab \
--volume $GITLAB_HOME/logs:/var/log/gitlab \
--volume $GITLAB_HOME/data:/var/opt/gitlab \
--shm-size 256m \
gitlab/gitlab-ee:<version>-ee.0
```
Every time you execute a `docker run` command, you need to provide
the `GITLAB_OMNIBUS_CONFIG` option. The content of `GITLAB_OMNIBUS_CONFIG` is
_not_ preserved between subsequent runs.
### Run GitLab on a public IP address
You can make Docker to use your IP address and forward all traffic to the
GitLab container by modifying the `--publish` flag.
To expose GitLab on IP `198.51.100.1`:
```shell
sudo docker run --detach \
--hostname gitlab.example.com \
--env GITLAB_OMNIBUS_CONFIG="external_url 'http://gitlab.example.com'" \
--publish 198.51.100.1:443:443 \
--publish 198.51.100.1:80:80 \
--publish 198.51.100.1:22:22 \
--name gitlab \
--restart always \
--volume $GITLAB_HOME/config:/etc/gitlab \
--volume $GITLAB_HOME/logs:/var/log/gitlab \
--volume $GITLAB_HOME/data:/var/opt/gitlab \
--shm-size 256m \
gitlab/gitlab-ee:<version>-ee.0
```
You can then access your GitLab instance at `http://198.51.100.1/` and `https://198.51.100.1/`.
## Expose GitLab on different ports
GitLab occupies [specific ports](../../administration/package_information/defaults.md)
inside the container.
If you want to use different host ports from the default ports `80` (HTTP), `443` (HTTPS), or `22` (SSH),
you need to add a separate `--publish` directive to the `docker run` command.
For example, to expose the web interface on the host's port `8929`, and the SSH service on
port `2424`:
1. Use the following `docker run` command:
```shell
sudo docker run --detach \
--hostname gitlab.example.com \
--env GITLAB_OMNIBUS_CONFIG="external_url 'http://gitlab.example.com:8929'; gitlab_rails['gitlab_shell_ssh_port'] = 2424" \
--publish 8929:8929 --publish 2424:22 \
--name gitlab \
--restart always \
--volume $GITLAB_HOME/config:/etc/gitlab \
--volume $GITLAB_HOME/logs:/var/log/gitlab \
--volume $GITLAB_HOME/data:/var/opt/gitlab \
--shm-size 256m \
gitlab/gitlab-ee:<version>-ee.0
```
{{< alert type="note" >}}
The format to publish ports is `hostPort:containerPort`. Read more in the
Docker documentation about
[exposing incoming ports](https://docs.docker.com/network/#published-ports).
{{< /alert >}}
1. Enter the running container:
```shell
sudo docker exec -it gitlab /bin/bash
```
1. Open `/etc/gitlab/gitlab.rb` with your editor and set `external_url`:
```ruby
# For HTTP
external_url "http://gitlab.example.com:8929"
or
# For HTTPS (notice the https)
external_url "https://gitlab.example.com:8929"
```
The port specified in this URL must match the port published to the host by Docker.
Additionally, if the NGINX listen port is not explicitly set in
`nginx['listen_port']`, the `external_url` is used instead.
For more information, see the [NGINX documentation](https://docs.gitlab.com/omnibus/settings/nginx.html).
1. Set the SSH port:
```ruby
gitlab_rails['gitlab_shell_ssh_port'] = 2424
```
1. Finally, reconfigure GitLab:
```shell
gitlab-ctl reconfigure
```
Following the previous example, your web browser can reach your GitLab instance
at `<hostIP>:8929` and push over SSH on port `2424`.
You can see a `docker-compose.yml` example that uses different ports in the
[Docker compose](installation.md#install-gitlab-by-using-docker-compose) section.
## Configure multiple database connections
Starting in [GitLab 16.0](https://gitlab.com/gitlab-org/omnibus-gitlab/-/merge_requests/6850),
GitLab defaults to using two database connections that point to the same PostgreSQL database.
If, for any reason, you wish to switch back to single database connection:
1. Edit `/etc/gitlab/gitlab.rb` inside the container:
```shell
sudo docker exec -it gitlab editor /etc/gitlab/gitlab.rb
```
1. Add the following line:
```ruby
gitlab_rails['databases']['ci']['enable'] = false
```
1. Restart the container:
```shell
sudo docker restart gitlab
```
## Next steps
After you configure your installation, consider taking the
[recommended next steps](../next_steps.md), including authentication options
and sign-up restrictions.
|
https://docs.gitlab.com/install/upgrade
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/upgrade.md
|
2025-08-13
|
doc/install/docker
|
[
"doc",
"install",
"docker"
] |
upgrade.md
| null | null | null | null | null |
<!-- markdownlint-disable -->
This document was moved to [another location](../../update/docker/_index.md).
<!-- This redirect file can be deleted after <2025-11-08>. -->
<!-- Redirects that point to other docs in the same project expire in three months. -->
<!-- Redirects that point to docs in a different project or site (for example, link is not relative and starts with `https:`) expire in one year. -->
<!-- Before deletion, see: https://docs.gitlab.com/development/documentation/redirects -->
|
---
redirect_to: ../../update/docker/_index.md
remove_date: '2025-11-08'
breadcrumbs:
- doc
- install
- docker
---
<!-- markdownlint-disable -->
This document was moved to [another location](../../update/docker/_index.md).
<!-- This redirect file can be deleted after <2025-11-08>. -->
<!-- Redirects that point to other docs in the same project expire in three months. -->
<!-- Redirects that point to docs in a different project or site (for example, link is not relative and starts with `https:`) expire in one year. -->
<!-- Before deletion, see: https://docs.gitlab.com/development/documentation/redirects -->
|
https://docs.gitlab.com/install/docker
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/_index.md
|
2025-08-13
|
doc/install/docker
|
[
"doc",
"install",
"docker"
] |
_index.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install GitLab in a Docker container
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To run GitLab in a Docker container, use a GitLab image, which contains all of the
necessary services in a single container.
Find the GitLab official Docker images at:
- [GitLab Docker images in Docker Hub](https://hub.docker.com/r/gitlab/gitlab-ee/)
## Related topics
- [Install GitLab in a Docker container](installation.md)
- [Configure GitLab running in a Docker container](configuration.md)
- [Back up GitLab running in a Docker container](backup.md)
- [Upgrade GitLab running in a Docker container](../../update/docker/_index.md)
- [Troubleshooting GitLab running in a Docker container](troubleshooting.md)
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Install GitLab in a Docker container
breadcrumbs:
- doc
- install
- docker
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To run GitLab in a Docker container, use a GitLab image, which contains all of the
necessary services in a single container.
Find the GitLab official Docker images at:
- [GitLab Docker images in Docker Hub](https://hub.docker.com/r/gitlab/gitlab-ee/)
## Related topics
- [Install GitLab in a Docker container](installation.md)
- [Configure GitLab running in a Docker container](configuration.md)
- [Back up GitLab running in a Docker container](backup.md)
- [Upgrade GitLab running in a Docker container](../../update/docker/_index.md)
- [Troubleshooting GitLab running in a Docker container](troubleshooting.md)
|
https://docs.gitlab.com/install/troubleshooting
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/troubleshooting.md
|
2025-08-13
|
doc/install/docker
|
[
"doc",
"install",
"docker"
] |
troubleshooting.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Troubleshooting GitLab running in a Docker container
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
When installing GitLab in a Docker container, you might encounter the following problems.
## Diagnose potential problems
The following commands are useful when troubleshooting your GitLab instance in a Docker container:
Read container logs:
```shell
sudo docker logs gitlab
```
Enter running container:
```shell
sudo docker exec -it gitlab /bin/bash
```
You can administer the GitLab container from within the container as you would
administer a [Linux package installation](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/README.md).
## 500 Internal Error
When updating the Docker image, you may encounter an issue where all paths
display a `500` page. If this occurs, restart the container:
```shell
sudo docker restart gitlab
```
## Permission problems
When updating from older GitLab Docker images, you might encounter permission
problems. This happens when user permissions in previous images were not
preserved correctly. There's a script that fixes permissions for all files.
To fix your container, execute `update-permissions` and restart the
container afterwards:
```shell
sudo docker exec gitlab update-permissions
sudo docker restart gitlab
```
## Error executing action run on resource `ruby_block`
This error occurs when using Docker Toolbox with Oracle VirtualBox on Windows or Mac,
and making use of Docker volumes:
```plaintext
Error executing action run on resource ruby_block[directory resource: /data/GitLab]
```
The `/c/Users` volume is mounted as a
VirtualBox Shared Folder, and does not support all POSIX file system features.
The directory ownership and permissions cannot be changed without remounting, and
GitLab fails.
Switch to using the native Docker install for your
platform, instead of using Docker Toolbox.
If you cannot use the native Docker install (Windows 10 Home Edition, or Windows 7/8),
an alternative solution is to set up NFS mounts instead of VirtualBox shares for
the Docker Toolbox Boot2docker.
## Linux ACL issues
If you are using file ACLs on the Docker host, the `docker` group requires full access to the volumes in order for GitLab to work:
```shell
getfacl $GITLAB_HOME
# file: $GITLAB_HOME
# owner: XXXX
# group: XXXX
user::rwx
group::rwx
group:docker:rwx
mask::rwx
default:user::rwx
default:group::rwx
default:group:docker:rwx
default:mask::rwx
default:other::r-x
```
If these values are not correct, set them with:
```shell
sudo setfacl -mR default:group:docker:rwx $GITLAB_HOME
```
The default group is named `docker`. If you changed the group name, you need to adjust the
command.
## `/dev/shm` mount not having enough space in Docker container
GitLab comes with a Prometheus metrics endpoint at `/-/metrics` to expose
statistics about the health and performance of GitLab. The files
required for this are written to a temporary file system (like `/run` or
`/dev/shm`).
By default, Docker allocates 64 MB to the shared memory directory (mounted at
`/dev/shm`). This is insufficient to hold all the Prometheus metrics related
files generated, and will generate error logs like the following:
```plaintext
writing value to /dev/shm/gitlab/sidekiq/gauge_all_sidekiq_0-1.db failed with unmapped file
writing value to /dev/shm/gitlab/sidekiq/gauge_all_sidekiq_0-1.db failed with unmapped file
writing value to /dev/shm/gitlab/sidekiq/gauge_all_sidekiq_0-1.db failed with unmapped file
writing value to /dev/shm/gitlab/sidekiq/histogram_sidekiq_0-0.db failed with unmapped file
writing value to /dev/shm/gitlab/sidekiq/histogram_sidekiq_0-0.db failed with unmapped file
writing value to /dev/shm/gitlab/sidekiq/histogram_sidekiq_0-0.db failed with unmapped file
writing value to /dev/shm/gitlab/sidekiq/histogram_sidekiq_0-0.db failed with unmapped file
```
While you can turn off the Prometheus Metrics in the **Admin** area, the recommended
solution to fix this problem is to
[install](configuration.md#pre-configure-docker-container) with shared memory set to at least 256 MB.
If you use `docker run`, you can pass the flag `--shm-size 256m`.
If you use a `docker-compose.yml` file, you can set the `shm_size` key.
## Docker containers exhausts space due to the `json-file`
Docker uses the [`json-file` default logging driver](https://docs.docker.com/config/containers/logging/configure/#configure-the-default-logging-driver), which performs no log rotation by default. As a result of this lack of rotation, log files stored by the `json-file` driver can consume a significant amount of disk space for containers that generate a lot of output. This can lead to disk space exhaustion. To address this, use [`journald`](https://docs.docker.com/config/containers/logging/journald/) as the logging driver when available, or [another supported driver](https://docs.docker.com/config/containers/logging/configure/#supported-logging-drivers) with native rotation support.
## Buffer overflow error when starting Docker
If you receive this buffer overflow error, you should purge old log files in
`/var/log/gitlab`:
```plaintext
buffer overflow detected : terminated
xargs: tail: terminated by signal 6
```
Removing old log files helps fix the error, and ensures a clean startup of the instance.
## ThreadError can't create Thread Operation not permitted
```plaintext
can't create Thread: Operation not permitted
```
This error occurs when running a container built with newer `glibc` versions on a
[host that doesn't support the clone3 function](https://github.com/moby/moby/issues/42680). In GitLab 16.0 and later, the container image includes
the Ubuntu 22.04 Linux package, which is built with newer `glibc` versions.
This problem does not occur in newer container runtime tools like [Docker 20.10.10](https://github.com/moby/moby/pull/42836).
To resolve this issue, update Docker to version 20.10.10 or later.
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Troubleshooting GitLab running in a Docker container
breadcrumbs:
- doc
- install
- docker
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
When installing GitLab in a Docker container, you might encounter the following problems.
## Diagnose potential problems
The following commands are useful when troubleshooting your GitLab instance in a Docker container:
Read container logs:
```shell
sudo docker logs gitlab
```
Enter running container:
```shell
sudo docker exec -it gitlab /bin/bash
```
You can administer the GitLab container from within the container as you would
administer a [Linux package installation](https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/README.md).
## 500 Internal Error
When updating the Docker image, you may encounter an issue where all paths
display a `500` page. If this occurs, restart the container:
```shell
sudo docker restart gitlab
```
## Permission problems
When updating from older GitLab Docker images, you might encounter permission
problems. This happens when user permissions in previous images were not
preserved correctly. There's a script that fixes permissions for all files.
To fix your container, execute `update-permissions` and restart the
container afterwards:
```shell
sudo docker exec gitlab update-permissions
sudo docker restart gitlab
```
## Error executing action run on resource `ruby_block`
This error occurs when using Docker Toolbox with Oracle VirtualBox on Windows or Mac,
and making use of Docker volumes:
```plaintext
Error executing action run on resource ruby_block[directory resource: /data/GitLab]
```
The `/c/Users` volume is mounted as a
VirtualBox Shared Folder, and does not support all POSIX file system features.
The directory ownership and permissions cannot be changed without remounting, and
GitLab fails.
Switch to using the native Docker install for your
platform, instead of using Docker Toolbox.
If you cannot use the native Docker install (Windows 10 Home Edition, or Windows 7/8),
an alternative solution is to set up NFS mounts instead of VirtualBox shares for
the Docker Toolbox Boot2docker.
## Linux ACL issues
If you are using file ACLs on the Docker host, the `docker` group requires full access to the volumes in order for GitLab to work:
```shell
getfacl $GITLAB_HOME
# file: $GITLAB_HOME
# owner: XXXX
# group: XXXX
user::rwx
group::rwx
group:docker:rwx
mask::rwx
default:user::rwx
default:group::rwx
default:group:docker:rwx
default:mask::rwx
default:other::r-x
```
If these values are not correct, set them with:
```shell
sudo setfacl -mR default:group:docker:rwx $GITLAB_HOME
```
The default group is named `docker`. If you changed the group name, you need to adjust the
command.
## `/dev/shm` mount not having enough space in Docker container
GitLab comes with a Prometheus metrics endpoint at `/-/metrics` to expose
statistics about the health and performance of GitLab. The files
required for this are written to a temporary file system (like `/run` or
`/dev/shm`).
By default, Docker allocates 64 MB to the shared memory directory (mounted at
`/dev/shm`). This is insufficient to hold all the Prometheus metrics related
files generated, and will generate error logs like the following:
```plaintext
writing value to /dev/shm/gitlab/sidekiq/gauge_all_sidekiq_0-1.db failed with unmapped file
writing value to /dev/shm/gitlab/sidekiq/gauge_all_sidekiq_0-1.db failed with unmapped file
writing value to /dev/shm/gitlab/sidekiq/gauge_all_sidekiq_0-1.db failed with unmapped file
writing value to /dev/shm/gitlab/sidekiq/histogram_sidekiq_0-0.db failed with unmapped file
writing value to /dev/shm/gitlab/sidekiq/histogram_sidekiq_0-0.db failed with unmapped file
writing value to /dev/shm/gitlab/sidekiq/histogram_sidekiq_0-0.db failed with unmapped file
writing value to /dev/shm/gitlab/sidekiq/histogram_sidekiq_0-0.db failed with unmapped file
```
While you can turn off the Prometheus Metrics in the **Admin** area, the recommended
solution to fix this problem is to
[install](configuration.md#pre-configure-docker-container) with shared memory set to at least 256 MB.
If you use `docker run`, you can pass the flag `--shm-size 256m`.
If you use a `docker-compose.yml` file, you can set the `shm_size` key.
## Docker containers exhausts space due to the `json-file`
Docker uses the [`json-file` default logging driver](https://docs.docker.com/config/containers/logging/configure/#configure-the-default-logging-driver), which performs no log rotation by default. As a result of this lack of rotation, log files stored by the `json-file` driver can consume a significant amount of disk space for containers that generate a lot of output. This can lead to disk space exhaustion. To address this, use [`journald`](https://docs.docker.com/config/containers/logging/journald/) as the logging driver when available, or [another supported driver](https://docs.docker.com/config/containers/logging/configure/#supported-logging-drivers) with native rotation support.
## Buffer overflow error when starting Docker
If you receive this buffer overflow error, you should purge old log files in
`/var/log/gitlab`:
```plaintext
buffer overflow detected : terminated
xargs: tail: terminated by signal 6
```
Removing old log files helps fix the error, and ensures a clean startup of the instance.
## ThreadError can't create Thread Operation not permitted
```plaintext
can't create Thread: Operation not permitted
```
This error occurs when running a container built with newer `glibc` versions on a
[host that doesn't support the clone3 function](https://github.com/moby/moby/issues/42680). In GitLab 16.0 and later, the container image includes
the Ubuntu 22.04 Linux package, which is built with newer `glibc` versions.
This problem does not occur in newer container runtime tools like [Docker 20.10.10](https://github.com/moby/moby/pull/42836).
To resolve this issue, update Docker to version 20.10.10 or later.
|
https://docs.gitlab.com/install/backup
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/backup.md
|
2025-08-13
|
doc/install/docker
|
[
"doc",
"install",
"docker"
] |
backup.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Back up GitLab running in a Docker container
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can create a GitLab backup with:
```shell
docker exec -t <container name> gitlab-backup create
```
For more information, see [Back up and restore GitLab](../../administration/backup_restore/_index.md).
{{< alert type="note" >}}
If your GitLab configuration is provided entirely using the `GITLAB_OMNIBUS_CONFIG` environment variable
(by using the ["Pre-configure Docker Container"](configuration.md#pre-configure-docker-container) steps),
the configuration settings are not stored in the `gitlab.rb` file so you do not need
to back up the `gitlab.rb` file.
{{< /alert >}}
{{< alert type="warning" >}}
To avoid [complicated steps](../../administration/backup_restore/troubleshooting_backup_gitlab.md#when-the-secrets-file-is-lost) when recovering
GitLab from a backup, you should also follow the instructions in
[Backing up the GitLab secrets file](../../administration/backup_restore/backup_gitlab.md#storing-configuration-files).
The secrets file is stored either in the `/etc/gitlab/gitlab-secrets.json` file inside the container or in the
`$GITLAB_HOME/config/gitlab-secrets.json` file [on the container host](installation.md#create-a-directory-for-the-volumes).
{{< /alert >}}
## Create a database backup
Before you upgrade GitLab, create a database-only backup. If you encounter issues during the GitLab upgrade, you can restore the database backup to roll back the upgrade. To create a database backup, run this command:
```shell
docker exec -t <container name> gitlab-backup create SKIP=artifacts,repositories,registry,uploads,builds,pages,lfs,packages,terraform_state
```
The backup is written to `/var/opt/gitlab/backups` which should be on a
[volume mounted by Docker](installation.md#create-a-directory-for-the-volumes).
For more information on using the backup to roll back an upgrade, see [Downgrade GitLab](../../update/docker/_index.md#downgrade-gitlab).
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Back up GitLab running in a Docker container
breadcrumbs:
- doc
- install
- docker
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
You can create a GitLab backup with:
```shell
docker exec -t <container name> gitlab-backup create
```
For more information, see [Back up and restore GitLab](../../administration/backup_restore/_index.md).
{{< alert type="note" >}}
If your GitLab configuration is provided entirely using the `GITLAB_OMNIBUS_CONFIG` environment variable
(by using the ["Pre-configure Docker Container"](configuration.md#pre-configure-docker-container) steps),
the configuration settings are not stored in the `gitlab.rb` file so you do not need
to back up the `gitlab.rb` file.
{{< /alert >}}
{{< alert type="warning" >}}
To avoid [complicated steps](../../administration/backup_restore/troubleshooting_backup_gitlab.md#when-the-secrets-file-is-lost) when recovering
GitLab from a backup, you should also follow the instructions in
[Backing up the GitLab secrets file](../../administration/backup_restore/backup_gitlab.md#storing-configuration-files).
The secrets file is stored either in the `/etc/gitlab/gitlab-secrets.json` file inside the container or in the
`$GITLAB_HOME/config/gitlab-secrets.json` file [on the container host](installation.md#create-a-directory-for-the-volumes).
{{< /alert >}}
## Create a database backup
Before you upgrade GitLab, create a database-only backup. If you encounter issues during the GitLab upgrade, you can restore the database backup to roll back the upgrade. To create a database backup, run this command:
```shell
docker exec -t <container name> gitlab-backup create SKIP=artifacts,repositories,registry,uploads,builds,pages,lfs,packages,terraform_state
```
The backup is written to `/var/opt/gitlab/backups` which should be on a
[volume mounted by Docker](installation.md#create-a-directory-for-the-volumes).
For more information on using the backup to roll back an upgrade, see [Downgrade GitLab](../../update/docker/_index.md#downgrade-gitlab).
|
https://docs.gitlab.com/install/installation
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/installation.md
|
2025-08-13
|
doc/install/docker
|
[
"doc",
"install",
"docker"
] |
installation.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Install GitLab in a Docker container
|
Learn about the prerequisites, strategies, and steps for installing GitLab in a Docker container.
|
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To install GitLab in a Docker container, use Docker Compose, Docker Engine, or Docker Swarm mode.
Prerequisites:
- You must have a working [Docker installation](https://docs.docker.com/engine/install/#server) that is not Docker for Windows.
Docker for Windows is not officially supported as the images have known compatibility issues with volume
permissions and potentially other unknown issues. If you are trying to run on Docker
for Windows, see the [getting help page](https://about.gitlab.com/get-help/). This page
contains links to community resources (like IRC or forums) where you can seek help
from other users.
- You must have a mail transport agent (MTA), such as Postfix or Sendmail. The GitLab images don't include an MTA. You can
install an MTA in a separate container. While you can install an MTA in the same container as GitLab, you might need to
reinstall the MTA after every upgrade or restart.
- You should not plan to deploy the GitLab Docker image in Kubernetes as it creates a
single point of failure. If you want to deploy GitLab in Kubernetes, use the
[GitLab Helm Chart](https://docs.gitlab.com/charts/) or [GitLab Operator](https://docs.gitlab.com/operator/)
instead.
- You must have a valid, externally accessible hostname for your Docker installation. Do not use `localhost`.
## Configure the SSH port
By default, GitLab uses port `22` to interact with Git over SSH.
To use port `22`, skip this section.
To use a different port, you can either:
- Change the server's SSH port now (recommended). Then the SSH clone URLs don't need the new port number:
```plaintext
ssh://git@gitlab.example.com/user/project.git
```
- [Change the GitLab Shell SSH port](configuration.md#expose-gitlab-on-different-ports) after installation. Then the SSH clone URLs include the configured port number:
```plaintext
ssh://git@gitlab.example.com:<portNumber>/user/project.git
```
To change the server's SSH port:
1. Open `/etc/ssh/sshd_config` with your editor, and change the SSH port:
```conf
Port = 2424
```
1. Save the file and restart the SSH service:
```shell
sudo systemctl restart ssh
```
1. Verify that you can connect over SSH. Open a new terminal session and SSH to the server using
the new port.
## Create a directory for the volumes
{{< alert type="warning" >}}
Specific recommendations exist for volumes hosting Gitaly data. NFS-based filesystems can
cause performance issues and so [EFS is not recommended](../aws/_index.md#elastic-file-system-efs).
{{< /alert >}}
Create a directory for the configuration files, logs,
and data files. The directory can be in your user's home directory (for example
`~/gitlab-docker`), or in a directory like `/srv/gitlab`.
1. Create the directory:
```shell
sudo mkdir -p /srv/gitlab
```
1. If you're running Docker with a user other than `root`, grant the appropriate
permissions to the user for the new directory.
1. Configure a new environment variable `$GITLAB_HOME` that sets the path to the
directory you created:
```shell
export GITLAB_HOME=/srv/gitlab
```
1. Optionally, you can append the `GITLAB_HOME` environment variable to your shell's
profile so it is applied on all future terminal sessions:
- Bash: `~/.bash_profile`
- ZSH: `~/.zshrc`
The GitLab container uses host-mounted volumes to store persistent data:
| Local location | Container location | Usage |
|----------------------|--------------------|---------------------------------------------|
| `$GITLAB_HOME/data` | `/var/opt/gitlab` | Stores application data. |
| `$GITLAB_HOME/logs` | `/var/log/gitlab` | Stores logs. |
| `$GITLAB_HOME/config`| `/etc/gitlab` | Stores the GitLab configuration files. |
## Find the GitLab version and edition to use
In a production environment, you should pin your deployment to a specific
GitLab version. Review the available versions and choose the version you want to use in the
Docker tags page:
- [GitLab Enterprise Edition tags](https://hub.docker.com/r/gitlab/gitlab-ee/tags/)
- [GitLab Community Edition tags](https://hub.docker.com/r/gitlab/gitlab-ce/tags/)
The tag name consists of the following:
```plaintext
gitlab/gitlab-ee:<version>-ee.0
```
Where `<version>` is the GitLab version, for example `16.5.3`. The version always includes
`<major>.<minor>.<patch>` in its name.
For testing purposes, you can use the `latest` tag, such as `gitlab/gitlab-ee:latest`,
which points to the latest stable release.
The following examples use a stable Enterprise Edition version.
If you want to use the Release Candidate (RC) or nightly image, use
`gitlab/gitlab-ee:rc` or `gitlab/gitlab-ee:nightly` instead.
To install the Community Edition, replace `ee` with `ce`.
## Installation
You can run the GitLab Docker images by using:
- [Docker Compose](#install-gitlab-by-using-docker-compose) (recommended)
- [Docker Engine](#install-gitlab-by-using-docker-engine)
- [Docker Swarm mode](#install-gitlab-by-using-docker-swarm-mode)
### Install GitLab by using Docker Compose
With [Docker Compose](https://docs.docker.com/compose/) you can configure,
install, and upgrade your Docker-based GitLab installation:
1. [Install Docker Compose](https://docs.docker.com/compose/install/linux/).
1. Create a `docker-compose.yml` file. For example:
```yaml
services:
gitlab:
image: gitlab/gitlab-ee:<version>-ee.0
container_name: gitlab
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
# Add any other gitlab.rb configuration here, each on its own line
external_url 'https://gitlab.example.com'
ports:
- '80:80'
- '443:443'
- '22:22'
volumes:
- '$GITLAB_HOME/config:/etc/gitlab'
- '$GITLAB_HOME/logs:/var/log/gitlab'
- '$GITLAB_HOME/data:/var/opt/gitlab'
shm_size: '256m'
```
{{< alert type="note" >}}
Read the [Pre-configure Docker container](configuration.md#pre-configure-docker-container) section
to see how the `GITLAB_OMNIBUS_CONFIG` variable works.
{{< /alert >}}
Here is another `docker-compose.yml` example with GitLab running on a custom
HTTP and SSH port. Notice that the `GITLAB_OMNIBUS_CONFIG` variables match the
`ports` section:
```yaml
services:
gitlab:
image: gitlab/gitlab-ee:<version>-ee.0
container_name: gitlab
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
external_url 'http://gitlab.example.com:8929'
gitlab_rails['gitlab_shell_ssh_port'] = 2424
ports:
- '8929:8929'
- '443:443'
- '2424:22'
volumes:
- '$GITLAB_HOME/config:/etc/gitlab'
- '$GITLAB_HOME/logs:/var/log/gitlab'
- '$GITLAB_HOME/data:/var/opt/gitlab'
shm_size: '256m'
```
This configuration is the same as using `--publish 8929:8929 --publish 2424:22`.
1. In the same directory as `docker-compose.yml`, start GitLab:
```shell
docker compose up -d
```
### Install GitLab by using Docker Engine
Alternatively, you can install GitLab using Docker Engine.
1. If you've set up the `GITLAB_HOME` variable, adjust the directories to meet your requirements
and run the image:
- If you are not on SELinux, run this command:
```shell
sudo docker run --detach \
--hostname gitlab.example.com \
--env GITLAB_OMNIBUS_CONFIG="external_url 'http://gitlab.example.com'" \
--publish 443:443 --publish 80:80 --publish 22:22 \
--name gitlab \
--restart always \
--volume $GITLAB_HOME/config:/etc/gitlab \
--volume $GITLAB_HOME/logs:/var/log/gitlab \
--volume $GITLAB_HOME/data:/var/opt/gitlab \
--shm-size 256m \
gitlab/gitlab-ee:<version>-ee.0
```
This command downloads and starts a GitLab container, and
[publishes ports](https://docs.docker.com/network/#published-ports) needed to
access SSH, HTTP and HTTPS. All GitLab data are stored as subdirectories of
`$GITLAB_HOME`. The container automatically restarts after a system reboot.
- If you are on SELinux, then run this instead:
```shell
sudo docker run --detach \
--hostname gitlab.example.com \
--env GITLAB_OMNIBUS_CONFIG="external_url 'http://gitlab.example.com'" \
--publish 443:443 --publish 80:80 --publish 22:22 \
--name gitlab \
--restart always \
--volume $GITLAB_HOME/config:/etc/gitlab:Z \
--volume $GITLAB_HOME/logs:/var/log/gitlab:Z \
--volume $GITLAB_HOME/data:/var/opt/gitlab:Z \
--shm-size 256m \
gitlab/gitlab-ee:<version>-ee.0
```
This command ensures that the Docker process has enough permissions to create the configuration
files in the mounted volumes.
1. If you're using the [Kerberos integration](../../integration/kerberos.md),
you must also publish your Kerberos port (for example, `--publish 8443:8443`).
Failing to do so prevents Git operations with Kerberos.
The initialization process may take a long time. You can track this
process with:
```shell
sudo docker logs -f gitlab
```
After starting the container, you can visit `gitlab.example.com`. It might take
a while before the Docker container starts to respond to queries.
1. Visit the GitLab URL, and sign in with the username `root`
and the password from the following command:
```shell
sudo docker exec -it gitlab grep 'Password:' /etc/gitlab/initial_root_password
```
{{< alert type="note" >}}
The password file is automatically deleted in the first container restart after 24 hours.
{{< /alert >}}
### Install GitLab by using Docker Swarm mode
With [Docker Swarm mode](https://docs.docker.com/engine/swarm/), you can
configure and deploy your GitLab installation with Docker in a swarm cluster.
In swarm mode, you can leverage [Docker secrets](https://docs.docker.com/engine/swarm/secrets/)
and [Docker configurations](https://docs.docker.com/engine/swarm/configs/) to efficiently and securely deploy your GitLab instance.
Secrets can be used to securely pass your initial root password without exposing it as an environment variable.
Configurations can help you to keep your GitLab image as generic as possible.
Here's an example that deploys GitLab with four runners as a [stack](https://docs.docker.com/get-started/swarm-deploy/#describe-apps-using-stack-files), using secrets and configurations:
1. [Set up a Docker swarm](https://docs.docker.com/engine/swarm/swarm-tutorial/).
1. Create a `docker-compose.yml` file:
```yaml
services:
gitlab:
image: gitlab/gitlab-ee:<version>-ee.0
container_name: gitlab
restart: always
hostname: 'gitlab.example.com'
ports:
- "22:22"
- "80:80"
- "443:443"
volumes:
- $GITLAB_HOME/data:/var/opt/gitlab
- $GITLAB_HOME/logs:/var/log/gitlab
- $GITLAB_HOME/config:/etc/gitlab
shm_size: '256m'
environment:
GITLAB_OMNIBUS_CONFIG: "from_file('/omnibus_config.rb')"
configs:
- source: gitlab
target: /omnibus_config.rb
secrets:
- gitlab_root_password
gitlab-runner:
image: gitlab/gitlab-runner:alpine
deploy:
mode: replicated
replicas: 4
configs:
gitlab:
file: ./gitlab.rb
secrets:
gitlab_root_password:
file: ./root_password.txt
```
To reduce complexity, the previous example excludes the `network` configuration.
You can find more information in the official [Compose file reference](https://docs.docker.com/compose/compose-file/).
1. Create a `gitlab.rb` file:
```ruby
external_url 'https://my.domain.com/'
gitlab_rails['initial_root_password'] = File.read('/run/secrets/gitlab_root_password').gsub("\n", "")
```
1. Create a file called `root_password.txt` containing the password:
```plaintext
MySuperSecretAndSecurePassw0rd!
```
1. Make sure you are in the same directory as `docker-compose.yml` and run:
```shell
docker stack deploy --compose-file docker-compose.yml mystack
```
After you've installed Docker, you need to [configure your GitLab instance](configuration.md).
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
description: Learn about the prerequisites, strategies, and steps for installing GitLab
in a Docker container.
title: Install GitLab in a Docker container
breadcrumbs:
- doc
- install
- docker
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
To install GitLab in a Docker container, use Docker Compose, Docker Engine, or Docker Swarm mode.
Prerequisites:
- You must have a working [Docker installation](https://docs.docker.com/engine/install/#server) that is not Docker for Windows.
Docker for Windows is not officially supported as the images have known compatibility issues with volume
permissions and potentially other unknown issues. If you are trying to run on Docker
for Windows, see the [getting help page](https://about.gitlab.com/get-help/). This page
contains links to community resources (like IRC or forums) where you can seek help
from other users.
- You must have a mail transport agent (MTA), such as Postfix or Sendmail. The GitLab images don't include an MTA. You can
install an MTA in a separate container. While you can install an MTA in the same container as GitLab, you might need to
reinstall the MTA after every upgrade or restart.
- You should not plan to deploy the GitLab Docker image in Kubernetes as it creates a
single point of failure. If you want to deploy GitLab in Kubernetes, use the
[GitLab Helm Chart](https://docs.gitlab.com/charts/) or [GitLab Operator](https://docs.gitlab.com/operator/)
instead.
- You must have a valid, externally accessible hostname for your Docker installation. Do not use `localhost`.
## Configure the SSH port
By default, GitLab uses port `22` to interact with Git over SSH.
To use port `22`, skip this section.
To use a different port, you can either:
- Change the server's SSH port now (recommended). Then the SSH clone URLs don't need the new port number:
```plaintext
ssh://git@gitlab.example.com/user/project.git
```
- [Change the GitLab Shell SSH port](configuration.md#expose-gitlab-on-different-ports) after installation. Then the SSH clone URLs include the configured port number:
```plaintext
ssh://git@gitlab.example.com:<portNumber>/user/project.git
```
To change the server's SSH port:
1. Open `/etc/ssh/sshd_config` with your editor, and change the SSH port:
```conf
Port = 2424
```
1. Save the file and restart the SSH service:
```shell
sudo systemctl restart ssh
```
1. Verify that you can connect over SSH. Open a new terminal session and SSH to the server using
the new port.
## Create a directory for the volumes
{{< alert type="warning" >}}
Specific recommendations exist for volumes hosting Gitaly data. NFS-based filesystems can
cause performance issues and so [EFS is not recommended](../aws/_index.md#elastic-file-system-efs).
{{< /alert >}}
Create a directory for the configuration files, logs,
and data files. The directory can be in your user's home directory (for example
`~/gitlab-docker`), or in a directory like `/srv/gitlab`.
1. Create the directory:
```shell
sudo mkdir -p /srv/gitlab
```
1. If you're running Docker with a user other than `root`, grant the appropriate
permissions to the user for the new directory.
1. Configure a new environment variable `$GITLAB_HOME` that sets the path to the
directory you created:
```shell
export GITLAB_HOME=/srv/gitlab
```
1. Optionally, you can append the `GITLAB_HOME` environment variable to your shell's
profile so it is applied on all future terminal sessions:
- Bash: `~/.bash_profile`
- ZSH: `~/.zshrc`
The GitLab container uses host-mounted volumes to store persistent data:
| Local location | Container location | Usage |
|----------------------|--------------------|---------------------------------------------|
| `$GITLAB_HOME/data` | `/var/opt/gitlab` | Stores application data. |
| `$GITLAB_HOME/logs` | `/var/log/gitlab` | Stores logs. |
| `$GITLAB_HOME/config`| `/etc/gitlab` | Stores the GitLab configuration files. |
## Find the GitLab version and edition to use
In a production environment, you should pin your deployment to a specific
GitLab version. Review the available versions and choose the version you want to use in the
Docker tags page:
- [GitLab Enterprise Edition tags](https://hub.docker.com/r/gitlab/gitlab-ee/tags/)
- [GitLab Community Edition tags](https://hub.docker.com/r/gitlab/gitlab-ce/tags/)
The tag name consists of the following:
```plaintext
gitlab/gitlab-ee:<version>-ee.0
```
Where `<version>` is the GitLab version, for example `16.5.3`. The version always includes
`<major>.<minor>.<patch>` in its name.
For testing purposes, you can use the `latest` tag, such as `gitlab/gitlab-ee:latest`,
which points to the latest stable release.
The following examples use a stable Enterprise Edition version.
If you want to use the Release Candidate (RC) or nightly image, use
`gitlab/gitlab-ee:rc` or `gitlab/gitlab-ee:nightly` instead.
To install the Community Edition, replace `ee` with `ce`.
## Installation
You can run the GitLab Docker images by using:
- [Docker Compose](#install-gitlab-by-using-docker-compose) (recommended)
- [Docker Engine](#install-gitlab-by-using-docker-engine)
- [Docker Swarm mode](#install-gitlab-by-using-docker-swarm-mode)
### Install GitLab by using Docker Compose
With [Docker Compose](https://docs.docker.com/compose/) you can configure,
install, and upgrade your Docker-based GitLab installation:
1. [Install Docker Compose](https://docs.docker.com/compose/install/linux/).
1. Create a `docker-compose.yml` file. For example:
```yaml
services:
gitlab:
image: gitlab/gitlab-ee:<version>-ee.0
container_name: gitlab
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
# Add any other gitlab.rb configuration here, each on its own line
external_url 'https://gitlab.example.com'
ports:
- '80:80'
- '443:443'
- '22:22'
volumes:
- '$GITLAB_HOME/config:/etc/gitlab'
- '$GITLAB_HOME/logs:/var/log/gitlab'
- '$GITLAB_HOME/data:/var/opt/gitlab'
shm_size: '256m'
```
{{< alert type="note" >}}
Read the [Pre-configure Docker container](configuration.md#pre-configure-docker-container) section
to see how the `GITLAB_OMNIBUS_CONFIG` variable works.
{{< /alert >}}
Here is another `docker-compose.yml` example with GitLab running on a custom
HTTP and SSH port. Notice that the `GITLAB_OMNIBUS_CONFIG` variables match the
`ports` section:
```yaml
services:
gitlab:
image: gitlab/gitlab-ee:<version>-ee.0
container_name: gitlab
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
external_url 'http://gitlab.example.com:8929'
gitlab_rails['gitlab_shell_ssh_port'] = 2424
ports:
- '8929:8929'
- '443:443'
- '2424:22'
volumes:
- '$GITLAB_HOME/config:/etc/gitlab'
- '$GITLAB_HOME/logs:/var/log/gitlab'
- '$GITLAB_HOME/data:/var/opt/gitlab'
shm_size: '256m'
```
This configuration is the same as using `--publish 8929:8929 --publish 2424:22`.
1. In the same directory as `docker-compose.yml`, start GitLab:
```shell
docker compose up -d
```
### Install GitLab by using Docker Engine
Alternatively, you can install GitLab using Docker Engine.
1. If you've set up the `GITLAB_HOME` variable, adjust the directories to meet your requirements
and run the image:
- If you are not on SELinux, run this command:
```shell
sudo docker run --detach \
--hostname gitlab.example.com \
--env GITLAB_OMNIBUS_CONFIG="external_url 'http://gitlab.example.com'" \
--publish 443:443 --publish 80:80 --publish 22:22 \
--name gitlab \
--restart always \
--volume $GITLAB_HOME/config:/etc/gitlab \
--volume $GITLAB_HOME/logs:/var/log/gitlab \
--volume $GITLAB_HOME/data:/var/opt/gitlab \
--shm-size 256m \
gitlab/gitlab-ee:<version>-ee.0
```
This command downloads and starts a GitLab container, and
[publishes ports](https://docs.docker.com/network/#published-ports) needed to
access SSH, HTTP and HTTPS. All GitLab data are stored as subdirectories of
`$GITLAB_HOME`. The container automatically restarts after a system reboot.
- If you are on SELinux, then run this instead:
```shell
sudo docker run --detach \
--hostname gitlab.example.com \
--env GITLAB_OMNIBUS_CONFIG="external_url 'http://gitlab.example.com'" \
--publish 443:443 --publish 80:80 --publish 22:22 \
--name gitlab \
--restart always \
--volume $GITLAB_HOME/config:/etc/gitlab:Z \
--volume $GITLAB_HOME/logs:/var/log/gitlab:Z \
--volume $GITLAB_HOME/data:/var/opt/gitlab:Z \
--shm-size 256m \
gitlab/gitlab-ee:<version>-ee.0
```
This command ensures that the Docker process has enough permissions to create the configuration
files in the mounted volumes.
1. If you're using the [Kerberos integration](../../integration/kerberos.md),
you must also publish your Kerberos port (for example, `--publish 8443:8443`).
Failing to do so prevents Git operations with Kerberos.
The initialization process may take a long time. You can track this
process with:
```shell
sudo docker logs -f gitlab
```
After starting the container, you can visit `gitlab.example.com`. It might take
a while before the Docker container starts to respond to queries.
1. Visit the GitLab URL, and sign in with the username `root`
and the password from the following command:
```shell
sudo docker exec -it gitlab grep 'Password:' /etc/gitlab/initial_root_password
```
{{< alert type="note" >}}
The password file is automatically deleted in the first container restart after 24 hours.
{{< /alert >}}
### Install GitLab by using Docker Swarm mode
With [Docker Swarm mode](https://docs.docker.com/engine/swarm/), you can
configure and deploy your GitLab installation with Docker in a swarm cluster.
In swarm mode, you can leverage [Docker secrets](https://docs.docker.com/engine/swarm/secrets/)
and [Docker configurations](https://docs.docker.com/engine/swarm/configs/) to efficiently and securely deploy your GitLab instance.
Secrets can be used to securely pass your initial root password without exposing it as an environment variable.
Configurations can help you to keep your GitLab image as generic as possible.
Here's an example that deploys GitLab with four runners as a [stack](https://docs.docker.com/get-started/swarm-deploy/#describe-apps-using-stack-files), using secrets and configurations:
1. [Set up a Docker swarm](https://docs.docker.com/engine/swarm/swarm-tutorial/).
1. Create a `docker-compose.yml` file:
```yaml
services:
gitlab:
image: gitlab/gitlab-ee:<version>-ee.0
container_name: gitlab
restart: always
hostname: 'gitlab.example.com'
ports:
- "22:22"
- "80:80"
- "443:443"
volumes:
- $GITLAB_HOME/data:/var/opt/gitlab
- $GITLAB_HOME/logs:/var/log/gitlab
- $GITLAB_HOME/config:/etc/gitlab
shm_size: '256m'
environment:
GITLAB_OMNIBUS_CONFIG: "from_file('/omnibus_config.rb')"
configs:
- source: gitlab
target: /omnibus_config.rb
secrets:
- gitlab_root_password
gitlab-runner:
image: gitlab/gitlab-runner:alpine
deploy:
mode: replicated
replicas: 4
configs:
gitlab:
file: ./gitlab.rb
secrets:
gitlab_root_password:
file: ./root_password.txt
```
To reduce complexity, the previous example excludes the `network` configuration.
You can find more information in the official [Compose file reference](https://docs.docker.com/compose/compose-file/).
1. Create a `gitlab.rb` file:
```ruby
external_url 'https://my.domain.com/'
gitlab_rails['initial_root_password'] = File.read('/run/secrets/gitlab_root_password').gsub("\n", "")
```
1. Create a file called `root_password.txt` containing the password:
```plaintext
MySuperSecretAndSecurePassw0rd!
```
1. Make sure you are in the same directory as `docker-compose.yml` and run:
```shell
docker stack deploy --compose-file docker-compose.yml mystack
```
After you've installed Docker, you need to [configure your GitLab instance](configuration.md).
|
https://docs.gitlab.com/install/self_compiled
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/install/_index.md
|
2025-08-13
|
doc/install/self_compiled
|
[
"doc",
"install",
"self_compiled"
] |
_index.md
|
GitLab Delivery
|
Self Managed
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Self-compiled installation
| null |
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This is the official installation guide to set up a production GitLab server
using the source files. It was created for and tested on **Debian/Ubuntu** operating systems.
Read [requirements.md](../requirements.md) for hardware and operating system requirements.
If you want to install on RHEL/CentOS, you should use the [Linux packages](https://about.gitlab.com/install/).
For many other installation options, see the [main installation page](_index.md).
This guide is long because it covers many cases and includes all commands you
need. The following steps have been known to work. **Use caution when you deviate**
from this guide. Make sure you don't violate any assumptions GitLab makes about
its environment. For example, many people run into permission problems because
they changed the location of directories or run services as the wrong user.
If you find a bug/error in this guide, **submit a merge request**
following the
[contributing guide](https://gitlab.com/gitlab-org/gitlab/-/blob/master/CONTRIBUTING.md).
## Consider the Linux package installation
Because a self-compiled installation is a lot of work and error prone, we strongly recommend the fast and reliable [Linux package installation](https://about.gitlab.com/install/) (deb/rpm).
One reason the Linux package is more reliable is its use of runit to restart any of the GitLab processes in case one crashes.
On heavily used GitLab instances the memory usage of the Sidekiq background worker grows over time.
The Linux packages solve this by [letting the Sidekiq terminate gracefully](../../administration/sidekiq/sidekiq_memory_killer.md) if it uses too much memory.
After this termination runit detects Sidekiq is not running and starts it.
Because self-compiled installations don't use runit for process supervision, Sidekiq
can't be terminated and its memory usage grows over time.
## Select a version to install
Make sure you view [this installation guide](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/install/self_compiled/_index.md) from the branch (version) of GitLab you would like to install (for example, `16-0-stable`).
You can select the branch in the version dropdown list in the upper-left corner of GitLab (below the menu bar).
If the highest number stable branch is unclear, check the [GitLab blog](https://about.gitlab.com/blog/) for installation guide links by version.
## Software requirements
| Software | Minimum version | Notes |
|:------------------------|:----------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [Ruby](#2-ruby) | `3.2.x` | From GitLab 16.7 to 17.4, Ruby 3.1 is required. In GitLab 17.5 and later, Ruby 3.2 is required. You must use the standard MRI implementation of Ruby. We love [JRuby](https://www.jruby.org/) and [Rubinius](https://github.com/rubinius/rubinius#the-rubinius-language-platform), but GitLab needs several Gems that have native extensions. |
| [RubyGems](#3-rubygems) | `3.5.x` | A specific RubyGems version is not required, but you should update to benefit from some known performance improvements. |
| [Go](#4-go) | `1.22.x` | In GitLab 17.1 and later, Go 1.22 or later is required. |
| [Git](#git) | `2.47.x` | In GitLab 17.7 and later, Git 2.47.x and later is required. You should use the [Git version provided by Gitaly](#git). |
| [Node.js](#5-node) | `20.13.x` | In GitLab 17.0 and later, Node.js 20.13 or later is required. |
| [PostgreSQL](#7-database) | `16.x` | In GitLab 18.0 and later, PostgreSQL 16 or later is required. |
## GitLab directory structure
The following directories are created as you go through the installation steps:
```plaintext
|-- home
| |-- git
| |-- .ssh
| |-- gitlab
| |-- gitlab-shell
| |-- repositories
```
- `/home/git/.ssh` - Contains OpenSSH settings. Specifically, the `authorized_keys`
file managed by GitLab Shell.
- `/home/git/gitlab` - GitLab core software.
- `/home/git/gitlab-shell` - Core add-on component of GitLab. Maintains SSH
cloning and other functionality.
- `/home/git/repositories` - Bare repositories for all projects organized by
namespace. This directory is where the Git repositories which are pushed/pulled are
maintained for all projects. **This area contains critical data for projects.
[Keep a backup](../../administration/backup_restore/_index.md)**.
The default locations for repositories can be configured in `config/gitlab.yml`
of GitLab and `config.yml` of GitLab Shell.
It is not necessary to create these directories manually now, and doing so can cause errors later in the installation.
## Installation workflow
The GitLab installation consists of setting up the following components:
1. [Packages and dependencies](#1-packages-and-dependencies).
1. [Ruby](#2-ruby).
1. [RubyGems](#3-rubygems).
1. [Go](#4-go).
1. [Node](#5-node).
1. [System users](#6-system-users).
1. [Database](#7-database).
1. [Redis](#8-redis).
1. [GitLab](#9-gitlab).
1. [NGINX](#10-nginx).
## 1. Packages and dependencies
### sudo
`sudo` is not installed on Debian by default. Make sure your system is
up-to-date and install it.
```shell
# run as root!
apt-get update -y
apt-get upgrade -y
apt-get install sudo -y
```
### Build dependencies
Install the required packages (needed to compile Ruby and native extensions to Ruby gems):
```shell
sudo apt-get install -y build-essential zlib1g-dev libyaml-dev libssl-dev libgdbm-dev libre2-dev \
libreadline-dev libncurses5-dev libffi-dev curl openssh-server libxml2-dev libxslt-dev \
libcurl4-openssl-dev libicu-dev libkrb5-dev logrotate rsync python3-docutils pkg-config cmake \
runit-systemd
```
{{< alert type="note" >}}
GitLab requires OpenSSL version 1.1. If your Linux distribution includes a different version of OpenSSL,
you might have to install 1.1 manually.
{{< /alert >}}
### Git
You should use the
[Git version provided by Gitaly](https://gitlab.com/gitlab-org/gitaly/-/issues/2729)
that:
- Is always at the version required by GitLab.
- May contain custom patches required for proper operation.
1. Install the needed dependencies:
```shell
sudo apt-get install -y libcurl4-openssl-dev libexpat1-dev gettext libz-dev libssl-dev libpcre2-dev build-essential git-core
```
1. Clone the Gitaly repository and compile Git. Replace `<X-Y-stable>` with the
stable branch that matches the GitLab version you want to install. For example,
if you want to install GitLab 16.7, use the branch name `16-7-stable`:
```shell
git clone https://gitlab.com/gitlab-org/gitaly.git -b <X-Y-stable> /tmp/gitaly
cd /tmp/gitaly
sudo make git GIT_PREFIX=/usr/local
```
1. Optionally, you can remove the system Git and its dependencies:
```shell
sudo apt remove -y git-core
sudo apt autoremove
```
When [editing `config/gitlab.yml` later](#configure-it), remember to change
the Git path:
- From:
```yaml
git:
bin_path: /usr/bin/git
```
- To:
```yaml
git:
bin_path: /usr/local/bin/git
```
### GraphicsMagick
For the [Custom Favicon](../../administration/appearance.md#customize-the-favicon) to work, GraphicsMagick
must be installed.
```shell
sudo apt-get install -y graphicsmagick
```
### Mail server
To receive mail notifications, make sure to install a mail server.
By default, Debian is shipped with `exim4` but this
[has problems](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/12754) while
Ubuntu does not ship with one. The recommended mail server is `postfix` and you
can install it with:
```shell
sudo apt-get install -y postfix
```
Then select `Internet Site` and press <kbd>Enter</kbd> to confirm the hostname.
### ExifTool
[GitLab Workhorse](https://gitlab.com/gitlab-org/gitlab-workhorse#dependencies)
requires `exiftool` to remove EXIF data from uploaded images.
```shell
sudo apt-get install -y libimage-exiftool-perl
```
## 2. Ruby
The Ruby interpreter is required to run GitLab.
See the [requirements section](#software-requirements) for the minimum
Ruby requirements.
Ruby version managers such as RVM, rbenv, or chruby can cause hard to diagnose problems with GitLab.
You should instead [install Ruby](https://www.ruby-lang.org/en/documentation/installation/)
from the official source code.
## 3. RubyGems
Sometimes, a newer version of RubyGems is required than the one bundled with Ruby.
To update to a specific version:
```shell
gem update --system 3.4.12
```
Or the latest version:
```shell
gem update --system
```
## 4. Go
GitLab has several daemons written in Go. To install
GitLab, you must install a Go compiler. The following instructions assume you use 64-bit
Linux. You can find downloads for other platforms at the
[Go download page](https://go.dev/dl/).
```shell
# Remove former Go installation folder
sudo rm -rf /usr/local/go
curl --remote-name --location --progress-bar "https://go.dev/dl/go1.22.5.linux-amd64.tar.gz"
echo '904b924d435eaea086515bc63235b192ea441bd8c9b198c507e85009e6e4c7f0 go1.22.5.linux-amd64.tar.gz' | shasum -a256 -c - && \
sudo tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz
sudo ln -sf /usr/local/go/bin/{go,gofmt} /usr/local/bin/
rm go1.22.5.linux-amd64.tar.gz
```
## 5. Node
GitLab requires the use of Node to compile JavaScript
assets, and Yarn to manage JavaScript dependencies. The current minimum
requirements for these are:
- `node` 20.x releases (v20.13.0 or later).
[Other LTS versions of Node.js](https://github.com/nodejs/release#release-schedule) might be able to build assets, but we only guarantee Node.js 20.x.
- `yarn` = v1.22.x (Yarn 2 is not supported yet)
In many distributions,
the versions provided by the official package repositories are out of date, so
we must install through the following commands:
```shell
# install node v20.x
curl --location "https://deb.nodesource.com/setup_20.x" | sudo bash -
sudo apt-get install -y nodejs
npm install --global yarn
```
Visit the official websites for [node](https://nodejs.org/en/download) and [yarn](https://classic.yarnpkg.com/en/docs/install/) if you have any trouble with these steps.
## 6. System users
Create a `git` user for GitLab:
```shell
sudo adduser --disabled-login --gecos 'GitLab' git
```
## 7. Database
{{< alert type="note" >}}
Only PostgreSQL is supported.
In GitLab 18.0 and later, we [require PostgreSQL 16+](../requirements.md#postgresql).
{{< /alert >}}
1. Install the database packages.
For Ubuntu 22.04 and later:
```shell
sudo apt install -y postgresql postgresql-client libpq-dev postgresql-contrib
```
For Ubuntu 20.04 and earlier, the available PostgreSQL doesn't meet the minimum
version requirement. You must add PostgreSQL's repository:
```shell
sudo sh -c 'echo "deb https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
sudo apt-get update
sudo apt-get -y install postgresql-16
```
1. Verify the PostgreSQL version you have is supported by the version of GitLab you're
installing:
```shell
psql --version
```
1. Start the PostgreSQL service and confirm that the service is running:
```shell
sudo service postgresql start
sudo service postgresql status
```
1. Create a database user for GitLab:
```shell
sudo -u postgres psql -d template1 -c "CREATE USER git CREATEDB;"
```
1. Create the `pg_trgm` extension:
```shell
sudo -u postgres psql -d template1 -c "CREATE EXTENSION IF NOT EXISTS pg_trgm;"
```
1. Create the `btree_gist` extension:
```shell
sudo -u postgres psql -d template1 -c "CREATE EXTENSION IF NOT EXISTS btree_gist;"
```
1. Create the `plpgsql` extension:
```shell
sudo -u postgres psql -d template1 -c "CREATE EXTENSION IF NOT EXISTS plpgsql;"
```
1. Create the GitLab production database and grant all privileges on the database:
```shell
sudo -u postgres psql -d template1 -c "CREATE DATABASE gitlabhq_production OWNER git;"
```
1. Try connecting to the new database with the new user:
```shell
sudo -u git -H psql -d gitlabhq_production
```
1. Check if the `pg_trgm` extension is enabled:
```sql
SELECT true AS enabled
FROM pg_available_extensions
WHERE name = 'pg_trgm'
AND installed_version IS NOT NULL;
```
If the extension is enabled this produces the following output:
```plaintext
enabled
---------
t
(1 row)
```
1. Check if the `btree_gist` extension is enabled:
```sql
SELECT true AS enabled
FROM pg_available_extensions
WHERE name = 'btree_gist'
AND installed_version IS NOT NULL;
```
If the extension is enabled this produces the following output:
```plaintext
enabled
---------
t
(1 row)
```
1. Check if the `plpgsql` extension is enabled:
```sql
SELECT true AS enabled
FROM pg_available_extensions
WHERE name = 'plpgsql'
AND installed_version IS NOT NULL;
```
If the extension is enabled this produces the following output:
```plaintext
enabled
---------
t
(1 row)
```
1. Quit the database session:
```shell
gitlabhq_production> \q
```
## 8. Redis
See the [requirements page](../requirements.md#redis) for the minimum
Redis requirements.
Install Redis with:
```shell
sudo apt-get install redis-server
```
Once done, you can configure Redis:
```shell
# Configure redis to use sockets
sudo cp /etc/redis/redis.conf /etc/redis/redis.conf.orig
# Disable Redis listening on TCP by setting 'port' to 0
sudo sed 's/^port .*/port 0/' /etc/redis/redis.conf.orig | sudo tee /etc/redis/redis.conf
# Enable Redis socket for default Debian / Ubuntu path
echo 'unixsocket /var/run/redis/redis.sock' | sudo tee -a /etc/redis/redis.conf
# Grant permission to the socket to all members of the redis group
echo 'unixsocketperm 770' | sudo tee -a /etc/redis/redis.conf
# Add git to the redis group
sudo usermod -aG redis git
```
### Supervise Redis with systemd
If your distribution uses systemd init and the output of the following command is `notify`,
you must not make any changes:
```shell
systemctl show --value --property=Type redis-server.service
```
If the output is **not** `notify`, run:
```shell
# Configure Redis to not daemonize, but be supervised by systemd instead and disable the pidfile
sudo sed -i \
-e 's/^daemonize yes$/daemonize no/' \
-e 's/^supervised no$/supervised systemd/' \
-e 's/^pidfile/# pidfile/' /etc/redis/redis.conf
sudo chown redis:redis /etc/redis/redis.conf
# Make the same changes to the systemd unit file
sudo mkdir -p /etc/systemd/system/redis-server.service.d
sudo tee /etc/systemd/system/redis-server.service.d/10fix_type.conf <<EOF
[Service]
Type=notify
PIDFile=
EOF
# Reload the redis service
sudo systemctl daemon-reload
# Activate the changes to redis.conf
sudo systemctl restart redis-server.service
```
### Leave Redis unsupervised
If your system uses SysV init, run these commands:
```shell
# Create the directory which contains the socket
sudo mkdir -p /var/run/redis
sudo chown redis:redis /var/run/redis
sudo chmod 755 /var/run/redis
# Persist the directory which contains the socket, if applicable
if [ -d /etc/tmpfiles.d ]; then
echo 'd /var/run/redis 0755 redis redis 10d -' | sudo tee -a /etc/tmpfiles.d/redis.conf
fi
# Activate the changes to redis.conf
sudo service redis-server restart
```
## 9. GitLab
```shell
# We'll install GitLab into the home directory of the user "git"
cd /home/git
```
### Clone the Source
Clone Community Edition:
```shell
# Clone GitLab repository
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab-foss.git -b <X-Y-stable> gitlab
```
Clone Enterprise Edition:
```shell
# Clone GitLab repository
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab.git -b <X-Y-stable-ee> gitlab
```
Make sure to replace `<X-Y-stable>` with the stable branch that matches the
version you want to install. For example, if you want to install 11.8 you would
use the branch name `11-8-stable`.
{{< alert type="warning" >}}
You can change `<X-Y-stable>` to `master` if you want the "bleeding edge" version, but never install `master` on a production server!
{{< /alert >}}
### Configure It
```shell
# Go to GitLab installation folder
cd /home/git/gitlab
# Copy the example GitLab config
sudo -u git -H cp config/gitlab.yml.example config/gitlab.yml
# Update GitLab config file, follow the directions at top of the file
sudo -u git -H editor config/gitlab.yml
# Copy the example secrets file
sudo -u git -H cp config/secrets.yml.example config/secrets.yml
sudo -u git -H chmod 0600 config/secrets.yml
# Make sure GitLab can write to the log/ and tmp/ directories
sudo chown -R git log/
sudo chown -R git tmp/
sudo chmod -R u+rwX,go-w log/
sudo chmod -R u+rwX tmp/
# Make sure GitLab can write to the tmp/pids/ and tmp/sockets/ directories
sudo chmod -R u+rwX tmp/pids/
sudo chmod -R u+rwX tmp/sockets/
# Create the public/uploads/ directory
sudo -u git -H mkdir -p public/uploads/
# Make sure only the GitLab user has access to the public/uploads/ directory
# now that files in public/uploads are served by gitlab-workhorse
sudo chmod 0700 public/uploads
# Change the permissions of the directory where CI job logs are stored
sudo chmod -R u+rwX builds/
# Change the permissions of the directory where CI artifacts are stored
sudo chmod -R u+rwX shared/artifacts/
# Change the permissions of the directory where GitLab Pages are stored
sudo chmod -R ug+rwX shared/pages/
# Copy the example Puma config
sudo -u git -H cp config/puma.rb.example config/puma.rb
# Refer to https://github.com/puma/puma#configuration for more information.
# You should scale Puma workers and threads based on the number of CPU
# cores you have available. You can get that number via the `nproc` command.
sudo -u git -H editor config/puma.rb
# Configure Redis connection settings
sudo -u git -H cp config/resque.yml.example config/resque.yml
sudo -u git -H cp config/cable.yml.example config/cable.yml
# Change the Redis socket path if you are not using the default Debian / Ubuntu configuration
sudo -u git -H editor config/resque.yml config/cable.yml
```
Make sure to edit both `gitlab.yml` and `puma.rb` to match your setup.
If you want to use HTTPS, see [Using HTTPS](#using-https) for the additional steps.
### Configure GitLab DB Settings
{{< alert type="note" >}}
From [GitLab 15.9](https://gitlab.com/gitlab-org/gitlab/-/issues/387898), `database.yml` with only a section: `main:` is deprecated.
In GitLab 17.0 and later, you must have the two `main:` and `ci:` sections in your `database.yml`.
{{< /alert >}}
```shell
sudo -u git cp config/database.yml.postgresql config/database.yml
# Remove host, username, and password lines from config/database.yml.
# Once modified, the `production` settings will be as follows:
#
# production:
# main:
# adapter: postgresql
# encoding: unicode
# database: gitlabhq_production
# ci:
# adapter: postgresql
# encoding: unicode
# database: gitlabhq_production
# database_tasks: false
#
sudo -u git -H editor config/database.yml
# Remote PostgreSQL only:
# Update username/password in config/database.yml.
# You only need to adapt the production settings (first part).
# If you followed the database guide then please do as follows:
# Change 'secure password' with the value you have given to $password
# You can keep the double quotes around the password
sudo -u git -H editor config/database.yml
# Uncomment the `ci:` sections in config/database.yml.
# Ensure the `database` value in `ci:` matches the database value in `main:`.
# Make config/database.yml readable to git only
sudo -u git -H chmod o-rwx config/database.yml
```
You should have two sections in your `database.yml`: `main:` and `ci:`. The `ci`:
connection [must be to the same database](../../administration/postgresql/_index.md).
### Install Gems
{{< alert type="note" >}}
As of Bundler 1.5.2, you can invoke `bundle install -jN` (where `N` is the number of your processor cores) and enjoy parallel gems installation with measurable difference in completion time (~60% faster). Check the number of your cores with `nproc`. For more information, see this [post](https://thoughtbot.com/blog/parallel-gem-installing-using-bundler).
{{< /alert >}}
Make sure you have `bundle` (run `bundle -v`):
- `>= 1.5.2`, because some [issues](https://devcenter.heroku.com/changelog-items/411) were [fixed](https://github.com/rubygems/bundler/pull/2817) in 1.5.2.
- `< 2.x`.
Install the gems (if you want to use Kerberos for user authentication, omit
`kerberos` in the `--without` option in the following commands):
```shell
sudo -u git -H bundle config set --local deployment 'true'
sudo -u git -H bundle config set --local without 'development test kerberos'
sudo -u git -H bundle config path /home/git/gitlab/vendor/bundle
sudo -u git -H bundle install
```
### Install GitLab Shell
GitLab Shell is an SSH access and repository management software developed specially for GitLab.
```shell
# Run the installation task for gitlab-shell:
sudo -u git -H bundle exec rake gitlab:shell:install RAILS_ENV=production
# By default, the gitlab-shell config is generated from your main GitLab config.
# You can review (and modify) the gitlab-shell config as follows:
sudo -u git -H editor /home/git/gitlab-shell/config.yml
```
If you want to use HTTPS, see [Using HTTPS](#using-https) for the additional steps.
Make sure your hostname can be resolved on the machine itself by either a proper DNS record or an additional line in `/etc/hosts` ("127.0.0.1 hostname"). This might be necessary, for example, if you set up GitLab behind a reverse proxy. If the hostname cannot be resolved, the final installation check fails with `Check GitLab API access: FAILED. code: 401` and pushing commits are rejected with `[remote rejected] master -> master (hook declined)`.
### Install GitLab Workhorse
GitLab-Workhorse uses [GNU Make](https://www.gnu.org/software/make/). The
following command-line installs GitLab-Workhorse in `/home/git/gitlab-workhorse`
which is the recommended location.
```shell
sudo -u git -H bundle exec rake "gitlab:workhorse:install[/home/git/gitlab-workhorse]" RAILS_ENV=production
```
You can specify a different Git repository by providing it as an extra parameter:
```shell
sudo -u git -H bundle exec rake "gitlab:workhorse:install[/home/git/gitlab-workhorse,https://example.com/gitlab-workhorse.git]" RAILS_ENV=production
```
### Install GitLab-Elasticsearch-indexer on Enterprise Edition
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
GitLab-Elasticsearch-Indexer uses [GNU Make](https://www.gnu.org/software/make/). The
following command-line installs GitLab-Elasticsearch-Indexer in `/home/git/gitlab-elasticsearch-indexer`
which is the recommended location.
```shell
sudo -u git -H bundle exec rake "gitlab:indexer:install[/home/git/gitlab-elasticsearch-indexer]" RAILS_ENV=production
```
You can specify a different Git repository by providing it as an extra parameter:
```shell
sudo -u git -H bundle exec rake "gitlab:indexer:install[/home/git/gitlab-elasticsearch-indexer,https://example.com/gitlab-elasticsearch-indexer.git]" RAILS_ENV=production
```
The source code first is fetched to the path specified by the first parameter. Then a binary is built under its `bin` directory.
You must then update `gitlab.yml`'s `production -> elasticsearch -> indexer_path` setting to point to that binary.
### Install GitLab Pages
GitLab Pages uses [GNU Make](https://www.gnu.org/software/make/). This step is optional and only needed if you wish to host static sites from within GitLab. The following commands install GitLab Pages in `/home/git/gitlab-pages`. For additional setup steps, consult the [administration guide](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/pages/source.md) for your version of GitLab as the GitLab Pages daemon can be run several different ways.
```shell
cd /home/git
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab-pages.git
cd gitlab-pages
sudo -u git -H git checkout v$(</home/git/gitlab/GITLAB_PAGES_VERSION)
sudo -u git -H make
```
### Install Gitaly
```shell
# Create and restrict access to the git repository data directory
sudo install -d -o git -m 0700 /home/git/repositories
# Fetch Gitaly source with Git and compile with Go
cd /home/git/gitlab
sudo -u git -H bundle exec rake "gitlab:gitaly:install[/home/git/gitaly,/home/git/repositories]" RAILS_ENV=production
```
You can specify a different Git repository by providing it as an extra parameter:
```shell
sudo -u git -H bundle exec rake "gitlab:gitaly:install[/home/git/gitaly,/home/git/repositories,https://example.com/gitaly.git]" RAILS_ENV=production
```
Next, make sure that Gitaly is configured:
```shell
# Restrict Gitaly socket access
sudo chmod 0700 /home/git/gitlab/tmp/sockets/private
sudo chown git /home/git/gitlab/tmp/sockets/private
# If you are using non-default settings, you need to update config.toml
cd /home/git/gitaly
sudo -u git -H editor config.toml
```
For more information about configuring Gitaly see
[the Gitaly documentation](../../administration/gitaly/_index.md).
### Install the service
GitLab has always supported SysV init scripts, which are widely supported and portable, but now systemd is the standard for service supervision and is used by all major Linux distributions. You should use native systemd services if you can to benefit from automatic restarts, better sandboxing and resource control.
#### Install systemd units
Use these steps if you use systemd as init. Otherwise, follow the [SysV init script steps](#install-sysv-init-script).
Copy the services and run `systemctl daemon-reload` so that systemd picks them up:
```shell
cd /home/git/gitlab
sudo mkdir -p /usr/local/lib/systemd/system
sudo cp lib/support/systemd/* /usr/local/lib/systemd/system/
sudo systemctl daemon-reload
```
The units provided by GitLab make very little assumptions about where you are running Redis and PostgreSQL.
If you installed GitLab in another directory or as a user other than the default, you must change these values in the units as well.
For example, if you're running Redis and PostgreSQL on the same machine as GitLab, you should:
- Edit the Puma service:
```shell
sudo systemctl edit gitlab-puma.service
```
In the editor that opens, add the following and save the file:
```plaintext
[Unit]
Wants=redis-server.service postgresql.service
After=redis-server.service postgresql.service
```
- Edit the Sidekiq service:
```shell
sudo systemctl edit gitlab-sidekiq.service
```
Add the following and save the file:
```plaintext
[Unit]
Wants=redis-server.service postgresql.service
After=redis-server.service postgresql.service
```
`systemctl edit` installs drop-in configuration files at `/etc/systemd/system/<name of the unit>.d/override.conf`, so your local configuration is not overwritten when updating the unit files later. To split up your drop-in configuration files, you can add the previous snippets to `.conf` files under `/etc/systemd/system/<name of the unit>.d/`.
If you manually made changes to the unit files or added drop-in configuration files (without using `systemctl edit`), run the following command for them to take effect:
```shell
sudo systemctl daemon-reload
```
Make GitLab start on boot:
```shell
sudo systemctl enable gitlab.target
```
#### Install SysV init script
Use these steps if you use the SysV init script. If you use systemd, follow the [systemd unit steps](#install-systemd-units).
Download the init script (is `/etc/init.d/gitlab`):
```shell
cd /home/git/gitlab
sudo cp lib/support/init.d/gitlab /etc/init.d/gitlab
```
And if you are installing with a non-default folder or user, copy and edit the defaults file:
```shell
sudo cp lib/support/init.d/gitlab.default.example /etc/default/gitlab
```
If you installed GitLab in another directory or as a user other than the default, you should change these settings in `/etc/default/gitlab`. Do not edit `/etc/init.d/gitlab` as it is changed on upgrade.
Make GitLab start on boot:
```shell
sudo update-rc.d gitlab defaults 21
# or if running this on a machine running systemd
sudo systemctl daemon-reload
sudo systemctl enable gitlab.service
```
### Set up Logrotate
```shell
sudo cp lib/support/logrotate/gitlab /etc/logrotate.d/gitlab
```
### Start Gitaly
Gitaly must be running for the next section.
- To start Gitaly using systemd:
```shell
sudo systemctl start gitlab-gitaly.service
```
- To manually start Gitaly for SysV:
```shell
gitlab_path=/home/git/gitlab
gitaly_path=/home/git/gitaly
sudo -u git -H sh -c "$gitlab_path/bin/daemon_with_pidfile $gitlab_path/tmp/pids/gitaly.pid \
$gitaly_path/_build/bin/gitaly $gitaly_path/config.toml >> $gitlab_path/log/gitaly.log 2>&1 &"
```
### Initialize Database and Activate Advanced Features
```shell
cd /home/git/gitlab
sudo -u git -H bundle exec rake gitlab:setup RAILS_ENV=production
# Type 'yes' to create the database tables.
# or you can skip the question by adding force=yes
sudo -u git -H bundle exec rake gitlab:setup RAILS_ENV=production force=yes
# When done, you see 'Administrator account created:'
```
You can set the Administrator/root password and email by supplying them in environmental variables, `GITLAB_ROOT_PASSWORD` and `GITLAB_ROOT_EMAIL`, as seen in the following command. If you don't set the password (and it is set to the default one), wait to expose GitLab to the public internet until the installation is done and you've logged into the server the first time. During the first login, you are forced to change the default password. An Enterprise Edition subscription may also be activated at this time by supplying the activation code in the `GITLAB_ACTIVATION_CODE` environment variable.
```shell
sudo -u git -H bundle exec rake gitlab:setup RAILS_ENV=production GITLAB_ROOT_PASSWORD=yourpassword GITLAB_ROOT_EMAIL=youremail GITLAB_ACTIVATION_CODE=yourcode
```
### Secure `secrets.yml`
The `secrets.yml` file stores encryption keys for sessions and secure variables.
Backup `secrets.yml` someplace safe, but don't store it in the same place as your database backups.
Otherwise, your secrets are exposed if one of your backups is compromised.
### Check Application Status
Check if GitLab and its environment are configured correctly:
```shell
sudo -u git -H bundle exec rake gitlab:env:info RAILS_ENV=production
```
### Compile Assets
```shell
sudo -u git -H yarn install --production --pure-lockfile
sudo -u git -H bundle exec rake gitlab:assets:compile RAILS_ENV=production NODE_ENV=production
```
If `rake` fails with `JavaScript heap out of memory` error, try to run it with `NODE_OPTIONS` set as follows.
```shell
sudo -u git -H bundle exec rake gitlab:assets:compile RAILS_ENV=production NODE_ENV=production NODE_OPTIONS="--max_old_space_size=4096"
```
### Start Your GitLab Instance
```shell
# For systems running systemd
sudo systemctl start gitlab.target
# For systems running SysV init
sudo service gitlab start
```
## 10. NGINX
NGINX is the officially supported web server for GitLab. If you cannot or do not want to use NGINX as your web server, see [GitLab recipes](https://gitlab.com/gitlab-org/gitlab-recipes/).
### Installation
```shell
sudo apt-get install -y nginx
```
### Site Configuration
Copy the example site configuration:
```shell
sudo cp lib/support/nginx/gitlab /etc/nginx/sites-available/gitlab
sudo ln -s /etc/nginx/sites-available/gitlab /etc/nginx/sites-enabled/gitlab
```
Make sure to edit the configuration file to match your setup. Also, ensure that you match your paths to GitLab, especially if installing for a user other than the `git` user:
```shell
# Change YOUR_SERVER_FQDN to the fully-qualified
# domain name of your host serving GitLab.
#
# Remember to match your paths to GitLab, especially
# if installing for a user other than 'git'.
#
# If using Ubuntu default nginx install:
# either remove the default_server from the listen line
# or else sudo rm -f /etc/nginx/sites-enabled/default
sudo editor /etc/nginx/sites-available/gitlab
```
If you intend to enable GitLab Pages, there is a separate NGINX configuration you need
to use. Read all about the needed configuration at the
[GitLab Pages administration guide](../../administration/pages/_index.md).
If you want to use HTTPS, replace the `gitlab` NGINX configuration with `gitlab-ssl`. See [Using HTTPS](#using-https) for HTTPS configuration details.
For the NGINX to be able to read the GitLab-Workhorse socket, you must make sure, that the `www-data` user can read the socket, which is owned by the GitLab user. This is achieved, if it is world-readable, for example that it has permissions `0755`, which is the default. `www-data` also must be able to list the parent directories.
### Test Configuration
Validate your `gitlab` or `gitlab-ssl` NGINX configuration file with the following command:
```shell
sudo nginx -t
```
You should receive `syntax is okay` and `test is successful` messages. If you
receive error messages, check your `gitlab` or `gitlab-ssl` NGINX configuration
file for typos, as indicated in the provided error message.
Verify that the installed version is greater than 1.12.1:
```shell
nginx -v
```
If it's lower, you may receive the following error:
```plaintext
nginx: [emerg] unknown "start$temp=[filtered]$rest" variable
nginx: configuration file /etc/nginx/nginx.conf test failed
```
### Restart
```shell
# For systems running systemd
sudo systemctl restart nginx.service
# For systems running SysV init
sudo service nginx restart
```
## Post-install
### Double-check Application Status
To make sure you didn't miss anything run a more thorough check with:
```shell
sudo -u git -H bundle exec rake gitlab:check RAILS_ENV=production
```
If all items are green, congratulations on successfully installing GitLab!
{{< alert type="note" >}}
Supply the `SANITIZE=true` environment variable to `gitlab:check` to omit project names from the output of the check command.
{{< /alert >}}
### Initial Login
Visit YOUR_SERVER in your web browser for your first GitLab login.
If you didn't [provide a root password during setup](#initialize-database-and-activate-advanced-features),
you are redirected to a password reset screen to provide the password for the
initial administrator account. Enter your desired password and you are
redirected back to the login screen.
The default account's username is **root**. Provide the password you created
earlier and login. After login, you can change the username if you wish.
**Enjoy!**
To start and stop GitLab when using:
- systemd units: use `sudo systemctl start gitlab.target` or `sudo systemctl stop gitlab.target`.
- The SysV init script: use `sudo service gitlab start` or `sudo service gitlab stop`.
### Recommended next steps
After completing your installation, consider taking the
[recommended next steps](../next_steps.md), including authentication options
and sign-up restrictions.
## Advanced Setup Tips
### Relative URL support
See the [Relative URL documentation](../relative_url.md) for more information on
how to configure GitLab with a relative URL.
### Using HTTPS
To use GitLab with HTTPS:
1. In `gitlab.yml`:
1. Set the `port` option in section 1 to `443`.
1. Set the `https` option in section 1 to `true`.
1. In the `config.yml` of GitLab Shell:
1. Set `gitlab_url` option to the HTTPS endpoint of GitLab (for example, `https://git.example.com`).
1. Set the certificates using either the `ca_file` or `ca_path` option.
1. Use the `gitlab-ssl` NGINX example configuration instead of the `gitlab` configuration.
1. Update `YOUR_SERVER_FQDN`.
1. Update `ssl_certificate` and `ssl_certificate_key`.
1. Review the configuration file and consider applying other security and performance enhancing features.
Using a self-signed certificate is discouraged. If you must use one,
follow the standard directions and generate a self-signed SSL certificate:
```shell
mkdir -p /etc/nginx/ssl/
cd /etc/nginx/ssl/
sudo openssl req -newkey rsa:2048 -x509 -nodes -days 3560 -out gitlab.crt -keyout gitlab.key
sudo chmod o-r gitlab.key
```
### Enable Reply by email
See the ["Reply by email" documentation](../../administration/reply_by_email.md) for more information on how to set this up.
### LDAP Authentication
You can configure LDAP authentication in `config/gitlab.yml`. Restart GitLab after editing this file.
### Using Custom OmniAuth Providers
See the [OmniAuth integration documentation](../../integration/omniauth.md).
### Build your projects
GitLab can build your projects. To enable that feature, you need runners to do that for you.
See the [GitLab Runner section](https://docs.gitlab.com/runner/) to install it.
### Adding your Trusted Proxies
If you are using a reverse proxy on a separate machine, you may want to add the
proxy to the trusted proxies list. Otherwise users appear signed in from the
proxy's IP address.
You can add trusted proxies in `config/gitlab.yml` by customizing the `trusted_proxies`
option in section 1. Save the file and [reconfigure GitLab](../../administration/restart_gitlab.md)
for the changes to take effect.
If you encounter problems with improperly encoded characters in URLs, see
[Error: `404 Not Found` when using a reverse proxy](../../api/rest/troubleshooting.md#error-404-not-found-when-using-a-reverse-proxy).
### Custom Redis Connection
If you'd like to connect to a Redis server on a non-standard port or a different host, you can configure its connection string via the `config/resque.yml` file.
```yaml
# example
production:
url: redis://redis.example.tld:6379
```
If you want to connect the Redis server via socket, use the `unix:` URL scheme and the path to the Redis socket file in the `config/resque.yml` file.
```yaml
# example
production:
url: unix:/path/to/redis/socket
```
Also, you can use environment variables in the `config/resque.yml` file:
```yaml
# example
production:
url: <%= ENV.fetch('GITLAB_REDIS_URL') %>
```
### Custom SSH Connection
If you are running SSH on a non-standard port, you must change the GitLab user's SSH configuration.
```plaintext
# Add to /home/git/.ssh/config
host localhost # Give your setup a name (here: override localhost)
user git # Your remote git user
port 2222 # Your port number
hostname 127.0.0.1; # Your server name or IP
```
You must also change the corresponding options (for example, `ssh_user`, `ssh_host`, `admin_uri`) in the `config/gitlab.yml` file.
### Additional Markup Styles
Apart from the always supported Markdown style, there are other rich text files that GitLab can display. But you might have to install a dependency to do so. See the [`github-markup` gem README](https://github.com/gitlabhq/markup#markups) for more information.
### Prometheus server setup
You can configure the Prometheus server in `config/gitlab.yml`:
```yaml
# example
prometheus:
enabled: true
server_address: '10.1.2.3:9090'
```
## Troubleshooting
### "You appear to have cloned an empty repository."
If you see this message when attempting to clone a repository hosted by GitLab,
this is likely due to an outdated NGINX or Apache configuration, or a missing or
misconfigured GitLab Workhorse instance. Double-check that you've
[installed Go](#4-go), [installed GitLab Workhorse](#install-gitlab-workhorse),
and correctly [configured NGINX](#site-configuration).
### `google-protobuf` "LoadError: /lib/x86_64-linux-gnu/libc.so.6: version 'GLIBC_2.14' not found"
This can happen on some platforms for some versions of the
`google-protobuf` gem. The workaround is to install a source-only
version of this gem.
First, you must find the exact version of `google-protobuf` that your
GitLab installation requires:
```shell
cd /home/git/gitlab
# Only one of the following two commands will print something. It
# will look like: * google-protobuf (3.2.0)
bundle list | grep google-protobuf
bundle check | grep google-protobuf
```
In the following command, `3.2.0` is used as an example. Replace it with the version number
you found prevously:
```shell
cd /home/git/gitlab
sudo -u git -H gem install google-protobuf --version 3.2.0 --platform ruby
```
Finally, you can test whether `google-protobuf` loads correctly. The
following should print `OK`.
```shell
sudo -u git -H bundle exec ruby -rgoogle/protobuf -e 'puts :OK'
```
If the `gem install` command fails, you may need to install the developer
tools of your OS.
On Debian/Ubuntu:
```shell
sudo apt-get install build-essential libgmp-dev
```
On RedHat/CentOS:
```shell
sudo yum groupinstall 'Development Tools'
```
### Error compiling GitLab assets
While compiling assets, you may receive the following error message:
```plaintext
Killed
error Command failed with exit code 137.
```
This can occur when Yarn kills a container that runs out of memory. To fix this:
1. Increase your system's memory to at least 8 GB.
1. Run this command to clean the assets:
```shell
sudo -u git -H bundle exec rake gitlab:assets:clean RAILS_ENV=production NODE_ENV=production
```
1. Run the `yarn` command again to resolve any conflicts:
```shell
sudo -u git -H yarn install --production --pure-lockfile
```
1. Recompile the assets:
```shell
sudo -u git -H bundle exec rake gitlab:assets:compile RAILS_ENV=production NODE_ENV=production
```
|
---
stage: GitLab Delivery
group: Self Managed
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Self-compiled installation
breadcrumbs:
- doc
- install
- self_compiled
---
{{< details >}}
- Tier: Free, Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
This is the official installation guide to set up a production GitLab server
using the source files. It was created for and tested on **Debian/Ubuntu** operating systems.
Read [requirements.md](../requirements.md) for hardware and operating system requirements.
If you want to install on RHEL/CentOS, you should use the [Linux packages](https://about.gitlab.com/install/).
For many other installation options, see the [main installation page](_index.md).
This guide is long because it covers many cases and includes all commands you
need. The following steps have been known to work. **Use caution when you deviate**
from this guide. Make sure you don't violate any assumptions GitLab makes about
its environment. For example, many people run into permission problems because
they changed the location of directories or run services as the wrong user.
If you find a bug/error in this guide, **submit a merge request**
following the
[contributing guide](https://gitlab.com/gitlab-org/gitlab/-/blob/master/CONTRIBUTING.md).
## Consider the Linux package installation
Because a self-compiled installation is a lot of work and error prone, we strongly recommend the fast and reliable [Linux package installation](https://about.gitlab.com/install/) (deb/rpm).
One reason the Linux package is more reliable is its use of runit to restart any of the GitLab processes in case one crashes.
On heavily used GitLab instances the memory usage of the Sidekiq background worker grows over time.
The Linux packages solve this by [letting the Sidekiq terminate gracefully](../../administration/sidekiq/sidekiq_memory_killer.md) if it uses too much memory.
After this termination runit detects Sidekiq is not running and starts it.
Because self-compiled installations don't use runit for process supervision, Sidekiq
can't be terminated and its memory usage grows over time.
## Select a version to install
Make sure you view [this installation guide](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/install/self_compiled/_index.md) from the branch (version) of GitLab you would like to install (for example, `16-0-stable`).
You can select the branch in the version dropdown list in the upper-left corner of GitLab (below the menu bar).
If the highest number stable branch is unclear, check the [GitLab blog](https://about.gitlab.com/blog/) for installation guide links by version.
## Software requirements
| Software | Minimum version | Notes |
|:------------------------|:----------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [Ruby](#2-ruby) | `3.2.x` | From GitLab 16.7 to 17.4, Ruby 3.1 is required. In GitLab 17.5 and later, Ruby 3.2 is required. You must use the standard MRI implementation of Ruby. We love [JRuby](https://www.jruby.org/) and [Rubinius](https://github.com/rubinius/rubinius#the-rubinius-language-platform), but GitLab needs several Gems that have native extensions. |
| [RubyGems](#3-rubygems) | `3.5.x` | A specific RubyGems version is not required, but you should update to benefit from some known performance improvements. |
| [Go](#4-go) | `1.22.x` | In GitLab 17.1 and later, Go 1.22 or later is required. |
| [Git](#git) | `2.47.x` | In GitLab 17.7 and later, Git 2.47.x and later is required. You should use the [Git version provided by Gitaly](#git). |
| [Node.js](#5-node) | `20.13.x` | In GitLab 17.0 and later, Node.js 20.13 or later is required. |
| [PostgreSQL](#7-database) | `16.x` | In GitLab 18.0 and later, PostgreSQL 16 or later is required. |
## GitLab directory structure
The following directories are created as you go through the installation steps:
```plaintext
|-- home
| |-- git
| |-- .ssh
| |-- gitlab
| |-- gitlab-shell
| |-- repositories
```
- `/home/git/.ssh` - Contains OpenSSH settings. Specifically, the `authorized_keys`
file managed by GitLab Shell.
- `/home/git/gitlab` - GitLab core software.
- `/home/git/gitlab-shell` - Core add-on component of GitLab. Maintains SSH
cloning and other functionality.
- `/home/git/repositories` - Bare repositories for all projects organized by
namespace. This directory is where the Git repositories which are pushed/pulled are
maintained for all projects. **This area contains critical data for projects.
[Keep a backup](../../administration/backup_restore/_index.md)**.
The default locations for repositories can be configured in `config/gitlab.yml`
of GitLab and `config.yml` of GitLab Shell.
It is not necessary to create these directories manually now, and doing so can cause errors later in the installation.
## Installation workflow
The GitLab installation consists of setting up the following components:
1. [Packages and dependencies](#1-packages-and-dependencies).
1. [Ruby](#2-ruby).
1. [RubyGems](#3-rubygems).
1. [Go](#4-go).
1. [Node](#5-node).
1. [System users](#6-system-users).
1. [Database](#7-database).
1. [Redis](#8-redis).
1. [GitLab](#9-gitlab).
1. [NGINX](#10-nginx).
## 1. Packages and dependencies
### sudo
`sudo` is not installed on Debian by default. Make sure your system is
up-to-date and install it.
```shell
# run as root!
apt-get update -y
apt-get upgrade -y
apt-get install sudo -y
```
### Build dependencies
Install the required packages (needed to compile Ruby and native extensions to Ruby gems):
```shell
sudo apt-get install -y build-essential zlib1g-dev libyaml-dev libssl-dev libgdbm-dev libre2-dev \
libreadline-dev libncurses5-dev libffi-dev curl openssh-server libxml2-dev libxslt-dev \
libcurl4-openssl-dev libicu-dev libkrb5-dev logrotate rsync python3-docutils pkg-config cmake \
runit-systemd
```
{{< alert type="note" >}}
GitLab requires OpenSSL version 1.1. If your Linux distribution includes a different version of OpenSSL,
you might have to install 1.1 manually.
{{< /alert >}}
### Git
You should use the
[Git version provided by Gitaly](https://gitlab.com/gitlab-org/gitaly/-/issues/2729)
that:
- Is always at the version required by GitLab.
- May contain custom patches required for proper operation.
1. Install the needed dependencies:
```shell
sudo apt-get install -y libcurl4-openssl-dev libexpat1-dev gettext libz-dev libssl-dev libpcre2-dev build-essential git-core
```
1. Clone the Gitaly repository and compile Git. Replace `<X-Y-stable>` with the
stable branch that matches the GitLab version you want to install. For example,
if you want to install GitLab 16.7, use the branch name `16-7-stable`:
```shell
git clone https://gitlab.com/gitlab-org/gitaly.git -b <X-Y-stable> /tmp/gitaly
cd /tmp/gitaly
sudo make git GIT_PREFIX=/usr/local
```
1. Optionally, you can remove the system Git and its dependencies:
```shell
sudo apt remove -y git-core
sudo apt autoremove
```
When [editing `config/gitlab.yml` later](#configure-it), remember to change
the Git path:
- From:
```yaml
git:
bin_path: /usr/bin/git
```
- To:
```yaml
git:
bin_path: /usr/local/bin/git
```
### GraphicsMagick
For the [Custom Favicon](../../administration/appearance.md#customize-the-favicon) to work, GraphicsMagick
must be installed.
```shell
sudo apt-get install -y graphicsmagick
```
### Mail server
To receive mail notifications, make sure to install a mail server.
By default, Debian is shipped with `exim4` but this
[has problems](https://gitlab.com/gitlab-org/gitlab-foss/-/issues/12754) while
Ubuntu does not ship with one. The recommended mail server is `postfix` and you
can install it with:
```shell
sudo apt-get install -y postfix
```
Then select `Internet Site` and press <kbd>Enter</kbd> to confirm the hostname.
### ExifTool
[GitLab Workhorse](https://gitlab.com/gitlab-org/gitlab-workhorse#dependencies)
requires `exiftool` to remove EXIF data from uploaded images.
```shell
sudo apt-get install -y libimage-exiftool-perl
```
## 2. Ruby
The Ruby interpreter is required to run GitLab.
See the [requirements section](#software-requirements) for the minimum
Ruby requirements.
Ruby version managers such as RVM, rbenv, or chruby can cause hard to diagnose problems with GitLab.
You should instead [install Ruby](https://www.ruby-lang.org/en/documentation/installation/)
from the official source code.
## 3. RubyGems
Sometimes, a newer version of RubyGems is required than the one bundled with Ruby.
To update to a specific version:
```shell
gem update --system 3.4.12
```
Or the latest version:
```shell
gem update --system
```
## 4. Go
GitLab has several daemons written in Go. To install
GitLab, you must install a Go compiler. The following instructions assume you use 64-bit
Linux. You can find downloads for other platforms at the
[Go download page](https://go.dev/dl/).
```shell
# Remove former Go installation folder
sudo rm -rf /usr/local/go
curl --remote-name --location --progress-bar "https://go.dev/dl/go1.22.5.linux-amd64.tar.gz"
echo '904b924d435eaea086515bc63235b192ea441bd8c9b198c507e85009e6e4c7f0 go1.22.5.linux-amd64.tar.gz' | shasum -a256 -c - && \
sudo tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz
sudo ln -sf /usr/local/go/bin/{go,gofmt} /usr/local/bin/
rm go1.22.5.linux-amd64.tar.gz
```
## 5. Node
GitLab requires the use of Node to compile JavaScript
assets, and Yarn to manage JavaScript dependencies. The current minimum
requirements for these are:
- `node` 20.x releases (v20.13.0 or later).
[Other LTS versions of Node.js](https://github.com/nodejs/release#release-schedule) might be able to build assets, but we only guarantee Node.js 20.x.
- `yarn` = v1.22.x (Yarn 2 is not supported yet)
In many distributions,
the versions provided by the official package repositories are out of date, so
we must install through the following commands:
```shell
# install node v20.x
curl --location "https://deb.nodesource.com/setup_20.x" | sudo bash -
sudo apt-get install -y nodejs
npm install --global yarn
```
Visit the official websites for [node](https://nodejs.org/en/download) and [yarn](https://classic.yarnpkg.com/en/docs/install/) if you have any trouble with these steps.
## 6. System users
Create a `git` user for GitLab:
```shell
sudo adduser --disabled-login --gecos 'GitLab' git
```
## 7. Database
{{< alert type="note" >}}
Only PostgreSQL is supported.
In GitLab 18.0 and later, we [require PostgreSQL 16+](../requirements.md#postgresql).
{{< /alert >}}
1. Install the database packages.
For Ubuntu 22.04 and later:
```shell
sudo apt install -y postgresql postgresql-client libpq-dev postgresql-contrib
```
For Ubuntu 20.04 and earlier, the available PostgreSQL doesn't meet the minimum
version requirement. You must add PostgreSQL's repository:
```shell
sudo sh -c 'echo "deb https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
sudo apt-get update
sudo apt-get -y install postgresql-16
```
1. Verify the PostgreSQL version you have is supported by the version of GitLab you're
installing:
```shell
psql --version
```
1. Start the PostgreSQL service and confirm that the service is running:
```shell
sudo service postgresql start
sudo service postgresql status
```
1. Create a database user for GitLab:
```shell
sudo -u postgres psql -d template1 -c "CREATE USER git CREATEDB;"
```
1. Create the `pg_trgm` extension:
```shell
sudo -u postgres psql -d template1 -c "CREATE EXTENSION IF NOT EXISTS pg_trgm;"
```
1. Create the `btree_gist` extension:
```shell
sudo -u postgres psql -d template1 -c "CREATE EXTENSION IF NOT EXISTS btree_gist;"
```
1. Create the `plpgsql` extension:
```shell
sudo -u postgres psql -d template1 -c "CREATE EXTENSION IF NOT EXISTS plpgsql;"
```
1. Create the GitLab production database and grant all privileges on the database:
```shell
sudo -u postgres psql -d template1 -c "CREATE DATABASE gitlabhq_production OWNER git;"
```
1. Try connecting to the new database with the new user:
```shell
sudo -u git -H psql -d gitlabhq_production
```
1. Check if the `pg_trgm` extension is enabled:
```sql
SELECT true AS enabled
FROM pg_available_extensions
WHERE name = 'pg_trgm'
AND installed_version IS NOT NULL;
```
If the extension is enabled this produces the following output:
```plaintext
enabled
---------
t
(1 row)
```
1. Check if the `btree_gist` extension is enabled:
```sql
SELECT true AS enabled
FROM pg_available_extensions
WHERE name = 'btree_gist'
AND installed_version IS NOT NULL;
```
If the extension is enabled this produces the following output:
```plaintext
enabled
---------
t
(1 row)
```
1. Check if the `plpgsql` extension is enabled:
```sql
SELECT true AS enabled
FROM pg_available_extensions
WHERE name = 'plpgsql'
AND installed_version IS NOT NULL;
```
If the extension is enabled this produces the following output:
```plaintext
enabled
---------
t
(1 row)
```
1. Quit the database session:
```shell
gitlabhq_production> \q
```
## 8. Redis
See the [requirements page](../requirements.md#redis) for the minimum
Redis requirements.
Install Redis with:
```shell
sudo apt-get install redis-server
```
Once done, you can configure Redis:
```shell
# Configure redis to use sockets
sudo cp /etc/redis/redis.conf /etc/redis/redis.conf.orig
# Disable Redis listening on TCP by setting 'port' to 0
sudo sed 's/^port .*/port 0/' /etc/redis/redis.conf.orig | sudo tee /etc/redis/redis.conf
# Enable Redis socket for default Debian / Ubuntu path
echo 'unixsocket /var/run/redis/redis.sock' | sudo tee -a /etc/redis/redis.conf
# Grant permission to the socket to all members of the redis group
echo 'unixsocketperm 770' | sudo tee -a /etc/redis/redis.conf
# Add git to the redis group
sudo usermod -aG redis git
```
### Supervise Redis with systemd
If your distribution uses systemd init and the output of the following command is `notify`,
you must not make any changes:
```shell
systemctl show --value --property=Type redis-server.service
```
If the output is **not** `notify`, run:
```shell
# Configure Redis to not daemonize, but be supervised by systemd instead and disable the pidfile
sudo sed -i \
-e 's/^daemonize yes$/daemonize no/' \
-e 's/^supervised no$/supervised systemd/' \
-e 's/^pidfile/# pidfile/' /etc/redis/redis.conf
sudo chown redis:redis /etc/redis/redis.conf
# Make the same changes to the systemd unit file
sudo mkdir -p /etc/systemd/system/redis-server.service.d
sudo tee /etc/systemd/system/redis-server.service.d/10fix_type.conf <<EOF
[Service]
Type=notify
PIDFile=
EOF
# Reload the redis service
sudo systemctl daemon-reload
# Activate the changes to redis.conf
sudo systemctl restart redis-server.service
```
### Leave Redis unsupervised
If your system uses SysV init, run these commands:
```shell
# Create the directory which contains the socket
sudo mkdir -p /var/run/redis
sudo chown redis:redis /var/run/redis
sudo chmod 755 /var/run/redis
# Persist the directory which contains the socket, if applicable
if [ -d /etc/tmpfiles.d ]; then
echo 'd /var/run/redis 0755 redis redis 10d -' | sudo tee -a /etc/tmpfiles.d/redis.conf
fi
# Activate the changes to redis.conf
sudo service redis-server restart
```
## 9. GitLab
```shell
# We'll install GitLab into the home directory of the user "git"
cd /home/git
```
### Clone the Source
Clone Community Edition:
```shell
# Clone GitLab repository
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab-foss.git -b <X-Y-stable> gitlab
```
Clone Enterprise Edition:
```shell
# Clone GitLab repository
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab.git -b <X-Y-stable-ee> gitlab
```
Make sure to replace `<X-Y-stable>` with the stable branch that matches the
version you want to install. For example, if you want to install 11.8 you would
use the branch name `11-8-stable`.
{{< alert type="warning" >}}
You can change `<X-Y-stable>` to `master` if you want the "bleeding edge" version, but never install `master` on a production server!
{{< /alert >}}
### Configure It
```shell
# Go to GitLab installation folder
cd /home/git/gitlab
# Copy the example GitLab config
sudo -u git -H cp config/gitlab.yml.example config/gitlab.yml
# Update GitLab config file, follow the directions at top of the file
sudo -u git -H editor config/gitlab.yml
# Copy the example secrets file
sudo -u git -H cp config/secrets.yml.example config/secrets.yml
sudo -u git -H chmod 0600 config/secrets.yml
# Make sure GitLab can write to the log/ and tmp/ directories
sudo chown -R git log/
sudo chown -R git tmp/
sudo chmod -R u+rwX,go-w log/
sudo chmod -R u+rwX tmp/
# Make sure GitLab can write to the tmp/pids/ and tmp/sockets/ directories
sudo chmod -R u+rwX tmp/pids/
sudo chmod -R u+rwX tmp/sockets/
# Create the public/uploads/ directory
sudo -u git -H mkdir -p public/uploads/
# Make sure only the GitLab user has access to the public/uploads/ directory
# now that files in public/uploads are served by gitlab-workhorse
sudo chmod 0700 public/uploads
# Change the permissions of the directory where CI job logs are stored
sudo chmod -R u+rwX builds/
# Change the permissions of the directory where CI artifacts are stored
sudo chmod -R u+rwX shared/artifacts/
# Change the permissions of the directory where GitLab Pages are stored
sudo chmod -R ug+rwX shared/pages/
# Copy the example Puma config
sudo -u git -H cp config/puma.rb.example config/puma.rb
# Refer to https://github.com/puma/puma#configuration for more information.
# You should scale Puma workers and threads based on the number of CPU
# cores you have available. You can get that number via the `nproc` command.
sudo -u git -H editor config/puma.rb
# Configure Redis connection settings
sudo -u git -H cp config/resque.yml.example config/resque.yml
sudo -u git -H cp config/cable.yml.example config/cable.yml
# Change the Redis socket path if you are not using the default Debian / Ubuntu configuration
sudo -u git -H editor config/resque.yml config/cable.yml
```
Make sure to edit both `gitlab.yml` and `puma.rb` to match your setup.
If you want to use HTTPS, see [Using HTTPS](#using-https) for the additional steps.
### Configure GitLab DB Settings
{{< alert type="note" >}}
From [GitLab 15.9](https://gitlab.com/gitlab-org/gitlab/-/issues/387898), `database.yml` with only a section: `main:` is deprecated.
In GitLab 17.0 and later, you must have the two `main:` and `ci:` sections in your `database.yml`.
{{< /alert >}}
```shell
sudo -u git cp config/database.yml.postgresql config/database.yml
# Remove host, username, and password lines from config/database.yml.
# Once modified, the `production` settings will be as follows:
#
# production:
# main:
# adapter: postgresql
# encoding: unicode
# database: gitlabhq_production
# ci:
# adapter: postgresql
# encoding: unicode
# database: gitlabhq_production
# database_tasks: false
#
sudo -u git -H editor config/database.yml
# Remote PostgreSQL only:
# Update username/password in config/database.yml.
# You only need to adapt the production settings (first part).
# If you followed the database guide then please do as follows:
# Change 'secure password' with the value you have given to $password
# You can keep the double quotes around the password
sudo -u git -H editor config/database.yml
# Uncomment the `ci:` sections in config/database.yml.
# Ensure the `database` value in `ci:` matches the database value in `main:`.
# Make config/database.yml readable to git only
sudo -u git -H chmod o-rwx config/database.yml
```
You should have two sections in your `database.yml`: `main:` and `ci:`. The `ci`:
connection [must be to the same database](../../administration/postgresql/_index.md).
### Install Gems
{{< alert type="note" >}}
As of Bundler 1.5.2, you can invoke `bundle install -jN` (where `N` is the number of your processor cores) and enjoy parallel gems installation with measurable difference in completion time (~60% faster). Check the number of your cores with `nproc`. For more information, see this [post](https://thoughtbot.com/blog/parallel-gem-installing-using-bundler).
{{< /alert >}}
Make sure you have `bundle` (run `bundle -v`):
- `>= 1.5.2`, because some [issues](https://devcenter.heroku.com/changelog-items/411) were [fixed](https://github.com/rubygems/bundler/pull/2817) in 1.5.2.
- `< 2.x`.
Install the gems (if you want to use Kerberos for user authentication, omit
`kerberos` in the `--without` option in the following commands):
```shell
sudo -u git -H bundle config set --local deployment 'true'
sudo -u git -H bundle config set --local without 'development test kerberos'
sudo -u git -H bundle config path /home/git/gitlab/vendor/bundle
sudo -u git -H bundle install
```
### Install GitLab Shell
GitLab Shell is an SSH access and repository management software developed specially for GitLab.
```shell
# Run the installation task for gitlab-shell:
sudo -u git -H bundle exec rake gitlab:shell:install RAILS_ENV=production
# By default, the gitlab-shell config is generated from your main GitLab config.
# You can review (and modify) the gitlab-shell config as follows:
sudo -u git -H editor /home/git/gitlab-shell/config.yml
```
If you want to use HTTPS, see [Using HTTPS](#using-https) for the additional steps.
Make sure your hostname can be resolved on the machine itself by either a proper DNS record or an additional line in `/etc/hosts` ("127.0.0.1 hostname"). This might be necessary, for example, if you set up GitLab behind a reverse proxy. If the hostname cannot be resolved, the final installation check fails with `Check GitLab API access: FAILED. code: 401` and pushing commits are rejected with `[remote rejected] master -> master (hook declined)`.
### Install GitLab Workhorse
GitLab-Workhorse uses [GNU Make](https://www.gnu.org/software/make/). The
following command-line installs GitLab-Workhorse in `/home/git/gitlab-workhorse`
which is the recommended location.
```shell
sudo -u git -H bundle exec rake "gitlab:workhorse:install[/home/git/gitlab-workhorse]" RAILS_ENV=production
```
You can specify a different Git repository by providing it as an extra parameter:
```shell
sudo -u git -H bundle exec rake "gitlab:workhorse:install[/home/git/gitlab-workhorse,https://example.com/gitlab-workhorse.git]" RAILS_ENV=production
```
### Install GitLab-Elasticsearch-indexer on Enterprise Edition
{{< details >}}
- Tier: Premium, Ultimate
- Offering: GitLab Self-Managed
{{< /details >}}
GitLab-Elasticsearch-Indexer uses [GNU Make](https://www.gnu.org/software/make/). The
following command-line installs GitLab-Elasticsearch-Indexer in `/home/git/gitlab-elasticsearch-indexer`
which is the recommended location.
```shell
sudo -u git -H bundle exec rake "gitlab:indexer:install[/home/git/gitlab-elasticsearch-indexer]" RAILS_ENV=production
```
You can specify a different Git repository by providing it as an extra parameter:
```shell
sudo -u git -H bundle exec rake "gitlab:indexer:install[/home/git/gitlab-elasticsearch-indexer,https://example.com/gitlab-elasticsearch-indexer.git]" RAILS_ENV=production
```
The source code first is fetched to the path specified by the first parameter. Then a binary is built under its `bin` directory.
You must then update `gitlab.yml`'s `production -> elasticsearch -> indexer_path` setting to point to that binary.
### Install GitLab Pages
GitLab Pages uses [GNU Make](https://www.gnu.org/software/make/). This step is optional and only needed if you wish to host static sites from within GitLab. The following commands install GitLab Pages in `/home/git/gitlab-pages`. For additional setup steps, consult the [administration guide](https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/administration/pages/source.md) for your version of GitLab as the GitLab Pages daemon can be run several different ways.
```shell
cd /home/git
sudo -u git -H git clone https://gitlab.com/gitlab-org/gitlab-pages.git
cd gitlab-pages
sudo -u git -H git checkout v$(</home/git/gitlab/GITLAB_PAGES_VERSION)
sudo -u git -H make
```
### Install Gitaly
```shell
# Create and restrict access to the git repository data directory
sudo install -d -o git -m 0700 /home/git/repositories
# Fetch Gitaly source with Git and compile with Go
cd /home/git/gitlab
sudo -u git -H bundle exec rake "gitlab:gitaly:install[/home/git/gitaly,/home/git/repositories]" RAILS_ENV=production
```
You can specify a different Git repository by providing it as an extra parameter:
```shell
sudo -u git -H bundle exec rake "gitlab:gitaly:install[/home/git/gitaly,/home/git/repositories,https://example.com/gitaly.git]" RAILS_ENV=production
```
Next, make sure that Gitaly is configured:
```shell
# Restrict Gitaly socket access
sudo chmod 0700 /home/git/gitlab/tmp/sockets/private
sudo chown git /home/git/gitlab/tmp/sockets/private
# If you are using non-default settings, you need to update config.toml
cd /home/git/gitaly
sudo -u git -H editor config.toml
```
For more information about configuring Gitaly see
[the Gitaly documentation](../../administration/gitaly/_index.md).
### Install the service
GitLab has always supported SysV init scripts, which are widely supported and portable, but now systemd is the standard for service supervision and is used by all major Linux distributions. You should use native systemd services if you can to benefit from automatic restarts, better sandboxing and resource control.
#### Install systemd units
Use these steps if you use systemd as init. Otherwise, follow the [SysV init script steps](#install-sysv-init-script).
Copy the services and run `systemctl daemon-reload` so that systemd picks them up:
```shell
cd /home/git/gitlab
sudo mkdir -p /usr/local/lib/systemd/system
sudo cp lib/support/systemd/* /usr/local/lib/systemd/system/
sudo systemctl daemon-reload
```
The units provided by GitLab make very little assumptions about where you are running Redis and PostgreSQL.
If you installed GitLab in another directory or as a user other than the default, you must change these values in the units as well.
For example, if you're running Redis and PostgreSQL on the same machine as GitLab, you should:
- Edit the Puma service:
```shell
sudo systemctl edit gitlab-puma.service
```
In the editor that opens, add the following and save the file:
```plaintext
[Unit]
Wants=redis-server.service postgresql.service
After=redis-server.service postgresql.service
```
- Edit the Sidekiq service:
```shell
sudo systemctl edit gitlab-sidekiq.service
```
Add the following and save the file:
```plaintext
[Unit]
Wants=redis-server.service postgresql.service
After=redis-server.service postgresql.service
```
`systemctl edit` installs drop-in configuration files at `/etc/systemd/system/<name of the unit>.d/override.conf`, so your local configuration is not overwritten when updating the unit files later. To split up your drop-in configuration files, you can add the previous snippets to `.conf` files under `/etc/systemd/system/<name of the unit>.d/`.
If you manually made changes to the unit files or added drop-in configuration files (without using `systemctl edit`), run the following command for them to take effect:
```shell
sudo systemctl daemon-reload
```
Make GitLab start on boot:
```shell
sudo systemctl enable gitlab.target
```
#### Install SysV init script
Use these steps if you use the SysV init script. If you use systemd, follow the [systemd unit steps](#install-systemd-units).
Download the init script (is `/etc/init.d/gitlab`):
```shell
cd /home/git/gitlab
sudo cp lib/support/init.d/gitlab /etc/init.d/gitlab
```
And if you are installing with a non-default folder or user, copy and edit the defaults file:
```shell
sudo cp lib/support/init.d/gitlab.default.example /etc/default/gitlab
```
If you installed GitLab in another directory or as a user other than the default, you should change these settings in `/etc/default/gitlab`. Do not edit `/etc/init.d/gitlab` as it is changed on upgrade.
Make GitLab start on boot:
```shell
sudo update-rc.d gitlab defaults 21
# or if running this on a machine running systemd
sudo systemctl daemon-reload
sudo systemctl enable gitlab.service
```
### Set up Logrotate
```shell
sudo cp lib/support/logrotate/gitlab /etc/logrotate.d/gitlab
```
### Start Gitaly
Gitaly must be running for the next section.
- To start Gitaly using systemd:
```shell
sudo systemctl start gitlab-gitaly.service
```
- To manually start Gitaly for SysV:
```shell
gitlab_path=/home/git/gitlab
gitaly_path=/home/git/gitaly
sudo -u git -H sh -c "$gitlab_path/bin/daemon_with_pidfile $gitlab_path/tmp/pids/gitaly.pid \
$gitaly_path/_build/bin/gitaly $gitaly_path/config.toml >> $gitlab_path/log/gitaly.log 2>&1 &"
```
### Initialize Database and Activate Advanced Features
```shell
cd /home/git/gitlab
sudo -u git -H bundle exec rake gitlab:setup RAILS_ENV=production
# Type 'yes' to create the database tables.
# or you can skip the question by adding force=yes
sudo -u git -H bundle exec rake gitlab:setup RAILS_ENV=production force=yes
# When done, you see 'Administrator account created:'
```
You can set the Administrator/root password and email by supplying them in environmental variables, `GITLAB_ROOT_PASSWORD` and `GITLAB_ROOT_EMAIL`, as seen in the following command. If you don't set the password (and it is set to the default one), wait to expose GitLab to the public internet until the installation is done and you've logged into the server the first time. During the first login, you are forced to change the default password. An Enterprise Edition subscription may also be activated at this time by supplying the activation code in the `GITLAB_ACTIVATION_CODE` environment variable.
```shell
sudo -u git -H bundle exec rake gitlab:setup RAILS_ENV=production GITLAB_ROOT_PASSWORD=yourpassword GITLAB_ROOT_EMAIL=youremail GITLAB_ACTIVATION_CODE=yourcode
```
### Secure `secrets.yml`
The `secrets.yml` file stores encryption keys for sessions and secure variables.
Backup `secrets.yml` someplace safe, but don't store it in the same place as your database backups.
Otherwise, your secrets are exposed if one of your backups is compromised.
### Check Application Status
Check if GitLab and its environment are configured correctly:
```shell
sudo -u git -H bundle exec rake gitlab:env:info RAILS_ENV=production
```
### Compile Assets
```shell
sudo -u git -H yarn install --production --pure-lockfile
sudo -u git -H bundle exec rake gitlab:assets:compile RAILS_ENV=production NODE_ENV=production
```
If `rake` fails with `JavaScript heap out of memory` error, try to run it with `NODE_OPTIONS` set as follows.
```shell
sudo -u git -H bundle exec rake gitlab:assets:compile RAILS_ENV=production NODE_ENV=production NODE_OPTIONS="--max_old_space_size=4096"
```
### Start Your GitLab Instance
```shell
# For systems running systemd
sudo systemctl start gitlab.target
# For systems running SysV init
sudo service gitlab start
```
## 10. NGINX
NGINX is the officially supported web server for GitLab. If you cannot or do not want to use NGINX as your web server, see [GitLab recipes](https://gitlab.com/gitlab-org/gitlab-recipes/).
### Installation
```shell
sudo apt-get install -y nginx
```
### Site Configuration
Copy the example site configuration:
```shell
sudo cp lib/support/nginx/gitlab /etc/nginx/sites-available/gitlab
sudo ln -s /etc/nginx/sites-available/gitlab /etc/nginx/sites-enabled/gitlab
```
Make sure to edit the configuration file to match your setup. Also, ensure that you match your paths to GitLab, especially if installing for a user other than the `git` user:
```shell
# Change YOUR_SERVER_FQDN to the fully-qualified
# domain name of your host serving GitLab.
#
# Remember to match your paths to GitLab, especially
# if installing for a user other than 'git'.
#
# If using Ubuntu default nginx install:
# either remove the default_server from the listen line
# or else sudo rm -f /etc/nginx/sites-enabled/default
sudo editor /etc/nginx/sites-available/gitlab
```
If you intend to enable GitLab Pages, there is a separate NGINX configuration you need
to use. Read all about the needed configuration at the
[GitLab Pages administration guide](../../administration/pages/_index.md).
If you want to use HTTPS, replace the `gitlab` NGINX configuration with `gitlab-ssl`. See [Using HTTPS](#using-https) for HTTPS configuration details.
For the NGINX to be able to read the GitLab-Workhorse socket, you must make sure, that the `www-data` user can read the socket, which is owned by the GitLab user. This is achieved, if it is world-readable, for example that it has permissions `0755`, which is the default. `www-data` also must be able to list the parent directories.
### Test Configuration
Validate your `gitlab` or `gitlab-ssl` NGINX configuration file with the following command:
```shell
sudo nginx -t
```
You should receive `syntax is okay` and `test is successful` messages. If you
receive error messages, check your `gitlab` or `gitlab-ssl` NGINX configuration
file for typos, as indicated in the provided error message.
Verify that the installed version is greater than 1.12.1:
```shell
nginx -v
```
If it's lower, you may receive the following error:
```plaintext
nginx: [emerg] unknown "start$temp=[filtered]$rest" variable
nginx: configuration file /etc/nginx/nginx.conf test failed
```
### Restart
```shell
# For systems running systemd
sudo systemctl restart nginx.service
# For systems running SysV init
sudo service nginx restart
```
## Post-install
### Double-check Application Status
To make sure you didn't miss anything run a more thorough check with:
```shell
sudo -u git -H bundle exec rake gitlab:check RAILS_ENV=production
```
If all items are green, congratulations on successfully installing GitLab!
{{< alert type="note" >}}
Supply the `SANITIZE=true` environment variable to `gitlab:check` to omit project names from the output of the check command.
{{< /alert >}}
### Initial Login
Visit YOUR_SERVER in your web browser for your first GitLab login.
If you didn't [provide a root password during setup](#initialize-database-and-activate-advanced-features),
you are redirected to a password reset screen to provide the password for the
initial administrator account. Enter your desired password and you are
redirected back to the login screen.
The default account's username is **root**. Provide the password you created
earlier and login. After login, you can change the username if you wish.
**Enjoy!**
To start and stop GitLab when using:
- systemd units: use `sudo systemctl start gitlab.target` or `sudo systemctl stop gitlab.target`.
- The SysV init script: use `sudo service gitlab start` or `sudo service gitlab stop`.
### Recommended next steps
After completing your installation, consider taking the
[recommended next steps](../next_steps.md), including authentication options
and sign-up restrictions.
## Advanced Setup Tips
### Relative URL support
See the [Relative URL documentation](../relative_url.md) for more information on
how to configure GitLab with a relative URL.
### Using HTTPS
To use GitLab with HTTPS:
1. In `gitlab.yml`:
1. Set the `port` option in section 1 to `443`.
1. Set the `https` option in section 1 to `true`.
1. In the `config.yml` of GitLab Shell:
1. Set `gitlab_url` option to the HTTPS endpoint of GitLab (for example, `https://git.example.com`).
1. Set the certificates using either the `ca_file` or `ca_path` option.
1. Use the `gitlab-ssl` NGINX example configuration instead of the `gitlab` configuration.
1. Update `YOUR_SERVER_FQDN`.
1. Update `ssl_certificate` and `ssl_certificate_key`.
1. Review the configuration file and consider applying other security and performance enhancing features.
Using a self-signed certificate is discouraged. If you must use one,
follow the standard directions and generate a self-signed SSL certificate:
```shell
mkdir -p /etc/nginx/ssl/
cd /etc/nginx/ssl/
sudo openssl req -newkey rsa:2048 -x509 -nodes -days 3560 -out gitlab.crt -keyout gitlab.key
sudo chmod o-r gitlab.key
```
### Enable Reply by email
See the ["Reply by email" documentation](../../administration/reply_by_email.md) for more information on how to set this up.
### LDAP Authentication
You can configure LDAP authentication in `config/gitlab.yml`. Restart GitLab after editing this file.
### Using Custom OmniAuth Providers
See the [OmniAuth integration documentation](../../integration/omniauth.md).
### Build your projects
GitLab can build your projects. To enable that feature, you need runners to do that for you.
See the [GitLab Runner section](https://docs.gitlab.com/runner/) to install it.
### Adding your Trusted Proxies
If you are using a reverse proxy on a separate machine, you may want to add the
proxy to the trusted proxies list. Otherwise users appear signed in from the
proxy's IP address.
You can add trusted proxies in `config/gitlab.yml` by customizing the `trusted_proxies`
option in section 1. Save the file and [reconfigure GitLab](../../administration/restart_gitlab.md)
for the changes to take effect.
If you encounter problems with improperly encoded characters in URLs, see
[Error: `404 Not Found` when using a reverse proxy](../../api/rest/troubleshooting.md#error-404-not-found-when-using-a-reverse-proxy).
### Custom Redis Connection
If you'd like to connect to a Redis server on a non-standard port or a different host, you can configure its connection string via the `config/resque.yml` file.
```yaml
# example
production:
url: redis://redis.example.tld:6379
```
If you want to connect the Redis server via socket, use the `unix:` URL scheme and the path to the Redis socket file in the `config/resque.yml` file.
```yaml
# example
production:
url: unix:/path/to/redis/socket
```
Also, you can use environment variables in the `config/resque.yml` file:
```yaml
# example
production:
url: <%= ENV.fetch('GITLAB_REDIS_URL') %>
```
### Custom SSH Connection
If you are running SSH on a non-standard port, you must change the GitLab user's SSH configuration.
```plaintext
# Add to /home/git/.ssh/config
host localhost # Give your setup a name (here: override localhost)
user git # Your remote git user
port 2222 # Your port number
hostname 127.0.0.1; # Your server name or IP
```
You must also change the corresponding options (for example, `ssh_user`, `ssh_host`, `admin_uri`) in the `config/gitlab.yml` file.
### Additional Markup Styles
Apart from the always supported Markdown style, there are other rich text files that GitLab can display. But you might have to install a dependency to do so. See the [`github-markup` gem README](https://github.com/gitlabhq/markup#markups) for more information.
### Prometheus server setup
You can configure the Prometheus server in `config/gitlab.yml`:
```yaml
# example
prometheus:
enabled: true
server_address: '10.1.2.3:9090'
```
## Troubleshooting
### "You appear to have cloned an empty repository."
If you see this message when attempting to clone a repository hosted by GitLab,
this is likely due to an outdated NGINX or Apache configuration, or a missing or
misconfigured GitLab Workhorse instance. Double-check that you've
[installed Go](#4-go), [installed GitLab Workhorse](#install-gitlab-workhorse),
and correctly [configured NGINX](#site-configuration).
### `google-protobuf` "LoadError: /lib/x86_64-linux-gnu/libc.so.6: version 'GLIBC_2.14' not found"
This can happen on some platforms for some versions of the
`google-protobuf` gem. The workaround is to install a source-only
version of this gem.
First, you must find the exact version of `google-protobuf` that your
GitLab installation requires:
```shell
cd /home/git/gitlab
# Only one of the following two commands will print something. It
# will look like: * google-protobuf (3.2.0)
bundle list | grep google-protobuf
bundle check | grep google-protobuf
```
In the following command, `3.2.0` is used as an example. Replace it with the version number
you found prevously:
```shell
cd /home/git/gitlab
sudo -u git -H gem install google-protobuf --version 3.2.0 --platform ruby
```
Finally, you can test whether `google-protobuf` loads correctly. The
following should print `OK`.
```shell
sudo -u git -H bundle exec ruby -rgoogle/protobuf -e 'puts :OK'
```
If the `gem install` command fails, you may need to install the developer
tools of your OS.
On Debian/Ubuntu:
```shell
sudo apt-get install build-essential libgmp-dev
```
On RedHat/CentOS:
```shell
sudo yum groupinstall 'Development Tools'
```
### Error compiling GitLab assets
While compiling assets, you may receive the following error message:
```plaintext
Killed
error Command failed with exit code 137.
```
This can occur when Yarn kills a container that runs out of memory. To fix this:
1. Increase your system's memory to at least 8 GB.
1. Run this command to clean the assets:
```shell
sudo -u git -H bundle exec rake gitlab:assets:clean RAILS_ENV=production NODE_ENV=production
```
1. Run the `yarn` command again to resolve any conflicts:
```shell
sudo -u git -H yarn install --production --pure-lockfile
```
1. Recompile the assets:
```shell
sudo -u git -H bundle exec rake gitlab:assets:compile RAILS_ENV=production NODE_ENV=production
```
|
https://docs.gitlab.com/corporate_contributor_license_agreement
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/corporate_contributor_license_agreement.md
|
2025-08-13
|
doc/legal
|
[
"doc",
"legal"
] |
corporate_contributor_license_agreement.md
|
none
|
unassigned
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Corporate contributor license agreement
| null |
<!-- vale off -->
You accept and agree to the following terms and conditions for Your present and
future Contributions submitted to GitLab Inc. Except for the license granted
herein to GitLab Inc. and recipients of software distributed by GitLab Inc., You
reserve all right, title, and interest in and to Your Contributions.
"1." **Definitions:**
"You" (or "Your") shall mean the copyright owner or legal entity authorized by
the copyright owner that is making this Agreement with GitLab Inc. For legal
entities, the entity making a Contribution and all other entities that
control, are controlled by, or are under common control with that entity are
considered to be a single Contributor. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the direction or
management of such entity, whether by contract or otherwise, or (ii) ownership
of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial
ownership of such entity.
"Contribution" shall mean the code, documentation or other original works of
authorship, including any modifications or additions to an existing work, that
is submitted by You to GitLab Inc. for inclusion in, or documentation of, any
of the products owned or managed by GitLab Inc. (the "Work"). For the purposes
of this definition, "submitted" means any form of electronic, verbal, or
written communication sent to GitLab Inc. or its representatives, including
but not limited to communication on electronic mailing lists, source code
control systems, and issue tracking systems that are managed by, or on behalf
of, GitLab Inc. for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise designated
in writing by You as "Not a Contribution."
"2." **Grant of Copyright License:**
Subject to the terms and conditions of this Agreement, You hereby grant to
GitLab Inc. and to recipients of software distributed by GitLab Inc. a
perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare derivative works of, publicly display,
publicly perform, sublicense, and distribute Your Contributions and such
derivative works.
"3." **Grant of Patent License:**
Subject to the terms and conditions of this Agreement, You hereby grant to
GitLab Inc. and to recipients of software distributed by GitLab Inc. a
perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made, use,
offer to sell, sell, import, and otherwise transfer the Work, where such
license applies only to those patent claims licensable by You that are
necessarily infringed by Your Contribution(s) alone or by combination of Your
Contribution(s) with the Work to which such Contribution(s) was submitted. If
any entity institutes patent litigation against You or any other entity
(including a cross-claim or counterclaim in a lawsuit) alleging that your
Contribution, or the Work to which you have contributed, constitutes direct or
contributory patent infringement, then any patent licenses granted to that
entity under this Agreement for that Contribution or Work shall terminate as
of the date such litigation is filed.
You represent that You are legally entitled to grant the above license. You
represent further that each of Your employees is authorized to submit
Contributions on Your behalf, but excluding employees that are designated in
writing by You as "Not authorized to submit Contributions on behalf of (name
of Your corporation here)." Such designations of exclusion for unauthorized
employees are to be submitted via email to `legal@gitlab.com`. It is Your
responsibility to notify GitLab Inc. when any change is required to the list
of designated employees excluded from submitting Contributions on Your behalf.
Such notification should also be sent via email to `legal@gitlab.com`.
"4." **Contributions:**
You represent that each of Your Contributions is Your original creation.
Should You wish to submit work that is not Your original creation, You may
submit it to GitLab Inc. separately from any Contribution, identifying the
complete details of its source and of any license or other restriction
(including, but not limited to, related patents, trademarks, and license
agreements) of which you are personally aware, and conspicuously marking the
work as "Submitted on behalf of a third-party: (named here)".
You are not expected to provide support for Your Contributions, except to the
extent You desire to provide support. You may provide support for free, for a
fee, or not at all. Unless required by applicable law or agreed to in writing,
You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied, including, without
limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT,
MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
This text is licensed under the
[Creative Commons Attribution 3.0 License](https://creativecommons.org/licenses/by/3.0/)
and the original source is the Google Open Source Programs Office.
|
---
stage: none
group: unassigned
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Corporate contributor license agreement
breadcrumbs:
- doc
- legal
---
<!-- vale off -->
You accept and agree to the following terms and conditions for Your present and
future Contributions submitted to GitLab Inc. Except for the license granted
herein to GitLab Inc. and recipients of software distributed by GitLab Inc., You
reserve all right, title, and interest in and to Your Contributions.
"1." **Definitions:**
"You" (or "Your") shall mean the copyright owner or legal entity authorized by
the copyright owner that is making this Agreement with GitLab Inc. For legal
entities, the entity making a Contribution and all other entities that
control, are controlled by, or are under common control with that entity are
considered to be a single Contributor. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the direction or
management of such entity, whether by contract or otherwise, or (ii) ownership
of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial
ownership of such entity.
"Contribution" shall mean the code, documentation or other original works of
authorship, including any modifications or additions to an existing work, that
is submitted by You to GitLab Inc. for inclusion in, or documentation of, any
of the products owned or managed by GitLab Inc. (the "Work"). For the purposes
of this definition, "submitted" means any form of electronic, verbal, or
written communication sent to GitLab Inc. or its representatives, including
but not limited to communication on electronic mailing lists, source code
control systems, and issue tracking systems that are managed by, or on behalf
of, GitLab Inc. for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise designated
in writing by You as "Not a Contribution."
"2." **Grant of Copyright License:**
Subject to the terms and conditions of this Agreement, You hereby grant to
GitLab Inc. and to recipients of software distributed by GitLab Inc. a
perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare derivative works of, publicly display,
publicly perform, sublicense, and distribute Your Contributions and such
derivative works.
"3." **Grant of Patent License:**
Subject to the terms and conditions of this Agreement, You hereby grant to
GitLab Inc. and to recipients of software distributed by GitLab Inc. a
perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made, use,
offer to sell, sell, import, and otherwise transfer the Work, where such
license applies only to those patent claims licensable by You that are
necessarily infringed by Your Contribution(s) alone or by combination of Your
Contribution(s) with the Work to which such Contribution(s) was submitted. If
any entity institutes patent litigation against You or any other entity
(including a cross-claim or counterclaim in a lawsuit) alleging that your
Contribution, or the Work to which you have contributed, constitutes direct or
contributory patent infringement, then any patent licenses granted to that
entity under this Agreement for that Contribution or Work shall terminate as
of the date such litigation is filed.
You represent that You are legally entitled to grant the above license. You
represent further that each of Your employees is authorized to submit
Contributions on Your behalf, but excluding employees that are designated in
writing by You as "Not authorized to submit Contributions on behalf of (name
of Your corporation here)." Such designations of exclusion for unauthorized
employees are to be submitted via email to `legal@gitlab.com`. It is Your
responsibility to notify GitLab Inc. when any change is required to the list
of designated employees excluded from submitting Contributions on Your behalf.
Such notification should also be sent via email to `legal@gitlab.com`.
"4." **Contributions:**
You represent that each of Your Contributions is Your original creation.
Should You wish to submit work that is not Your original creation, You may
submit it to GitLab Inc. separately from any Contribution, identifying the
complete details of its source and of any license or other restriction
(including, but not limited to, related patents, trademarks, and license
agreements) of which you are personally aware, and conspicuously marking the
work as "Submitted on behalf of a third-party: (named here)".
You are not expected to provide support for Your Contributions, except to the
extent You desire to provide support. You may provide support for free, for a
fee, or not at all. Unless required by applicable law or agreed to in writing,
You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied, including, without
limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT,
MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
This text is licensed under the
[Creative Commons Attribution 3.0 License](https://creativecommons.org/licenses/by/3.0/)
and the original source is the Google Open Source Programs Office.
|
https://docs.gitlab.com/use_generative_ai
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/use_generative_ai.md
|
2025-08-13
|
doc/legal
|
[
"doc",
"legal"
] |
use_generative_ai.md
|
none
|
unassigned
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Use of generative AI
| null |
Some content on `docs.gitlab.com` was created with the assistance of generative AI tools.
All content, AI-generated or human-created, is reviewed for accuracy and readability by a GitLab team member.
For more information about making AI-generated contributions to GitLab documentation, see our [DCO or our CLA terms](https://about.gitlab.com/community/contribute/dco-cla/).
|
---
stage: none
group: unassigned
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Use of generative AI
breadcrumbs:
- doc
- legal
---
Some content on `docs.gitlab.com` was created with the assistance of generative AI tools.
All content, AI-generated or human-created, is reviewed for accuracy and readability by a GitLab team member.
For more information about making AI-generated contributions to GitLab documentation, see our [DCO or our CLA terms](https://about.gitlab.com/community/contribute/dco-cla/).
|
https://docs.gitlab.com/individual_contributor_license_agreement
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/individual_contributor_license_agreement.md
|
2025-08-13
|
doc/legal
|
[
"doc",
"legal"
] |
individual_contributor_license_agreement.md
|
none
|
unassigned
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Individual contributor license agreement
| null |
<!-- vale off -->
You accept and agree to the following terms and conditions for Your present and
future Contributions submitted to GitLab Inc. Except for the license granted
herein to GitLab Inc. and recipients of software distributed by GitLab Inc., You
reserve all right, title, and interest in and to Your Contributions.
"1." **Definitions:**
"You" (or "Your") shall mean the copyright owner or legal entity authorized by
the copyright owner that is making this Agreement with GitLab Inc. For legal
entities, the entity making a Contribution and all other entities that
control, are controlled by, or are under common control with that entity are
considered to be a single Contributor. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the direction or
management of such entity, whether by contract or otherwise, or (ii) ownership
of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial
ownership of such entity.
"Contribution" shall mean any original work of authorship, including any
modifications or additions to an existing work, that is intentionally
submitted by You to GitLab Inc. for inclusion in, or documentation of, any of
the products owned or managed by GitLab Inc. (the "Work"). For the purposes of
this definition, "submitted" means any form of electronic, verbal, or written
communication sent to GitLab Inc. or its representatives, including but not
limited to communication on electronic mailing lists, source code control
systems, and issue tracking systems that are managed by, or on behalf of,
GitLab Inc. for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise designated
in writing by You as "Not a Contribution."
"2." **Grant of Copyright License:**
Subject to the terms and conditions of this Agreement, You hereby grant to
GitLab Inc. and to recipients of software distributed by GitLab Inc. a
perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare derivative works of, publicly display,
publicly perform, sublicense, and distribute Your Contributions and such
derivative works.
"3." **Grant of Patent License:**
Subject to the terms and conditions of this Agreement, You hereby grant to
GitLab Inc. and to recipients of software distributed by GitLab Inc. a
perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made, use,
offer to sell, sell, import, and otherwise transfer the Work, where such
license applies only to those patent claims licensable by You that are
necessarily infringed by Your Contribution(s) alone or by combination of Your
Contribution(s) with the Work to which such Contribution(s) was submitted. If
any entity institutes patent litigation against You or any other entity
(including a cross-claim or counterclaim in a lawsuit) alleging that your
Contribution, or the Work to which you have contributed, constitutes direct or
contributory patent infringement, then any patent licenses granted to that
entity under this Agreement for that Contribution or Work shall terminate as
of the date such litigation is filed.
You represent that you are legally entitled to grant the above license. If
your employer(s) has rights to intellectual property that you create that
includes your Contributions, you represent that you have received permission
to make Contributions on behalf of that employer, that your employer has
waived such rights for your Contributions to GitLab Inc., or that your
employer has executed a separate Corporate CLA with GitLab Inc.
"4." **Contributions:**
You represent that each of Your Contributions is Your original creation. You
represent that Your Contribution submissions include complete details of any
third-party license or other restriction (including, but not limited to,
related patents and trademarks) of which you are personally aware and which
are associated with any part of Your Contributions.
Should You wish to submit work that is not Your original creation, You may
submit it to GitLab Inc. separately from any Contribution, identifying the
complete details of its source and of any license or other restriction
(including, but not limited to, related patents, trademarks, and license
agreements) of which you are personally aware, and conspicuously marking the
work as "Submitted on behalf of a third-party: (insert_name_here)".
You are not expected to provide support for Your Contributions, except to the
extent You desire to provide support. You may provide support for free, for a
fee, or not at all. Unless required by applicable law or agreed to in writing,
You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied, including, without
limitation, any warranties or conditions of TITLE, NON- INFRINGEMENT,
MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
You agree to notify GitLab Inc. of any facts or circumstances of which you
become aware that would make these representations inaccurate in any respect.
This text is licensed under the
[Creative Commons Attribution 3.0 License](https://creativecommons.org/licenses/by/3.0/)
and the original source is the Google Open Source Programs Office.
|
---
stage: none
group: unassigned
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Individual contributor license agreement
breadcrumbs:
- doc
- legal
---
<!-- vale off -->
You accept and agree to the following terms and conditions for Your present and
future Contributions submitted to GitLab Inc. Except for the license granted
herein to GitLab Inc. and recipients of software distributed by GitLab Inc., You
reserve all right, title, and interest in and to Your Contributions.
"1." **Definitions:**
"You" (or "Your") shall mean the copyright owner or legal entity authorized by
the copyright owner that is making this Agreement with GitLab Inc. For legal
entities, the entity making a Contribution and all other entities that
control, are controlled by, or are under common control with that entity are
considered to be a single Contributor. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the direction or
management of such entity, whether by contract or otherwise, or (ii) ownership
of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial
ownership of such entity.
"Contribution" shall mean any original work of authorship, including any
modifications or additions to an existing work, that is intentionally
submitted by You to GitLab Inc. for inclusion in, or documentation of, any of
the products owned or managed by GitLab Inc. (the "Work"). For the purposes of
this definition, "submitted" means any form of electronic, verbal, or written
communication sent to GitLab Inc. or its representatives, including but not
limited to communication on electronic mailing lists, source code control
systems, and issue tracking systems that are managed by, or on behalf of,
GitLab Inc. for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise designated
in writing by You as "Not a Contribution."
"2." **Grant of Copyright License:**
Subject to the terms and conditions of this Agreement, You hereby grant to
GitLab Inc. and to recipients of software distributed by GitLab Inc. a
perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare derivative works of, publicly display,
publicly perform, sublicense, and distribute Your Contributions and such
derivative works.
"3." **Grant of Patent License:**
Subject to the terms and conditions of this Agreement, You hereby grant to
GitLab Inc. and to recipients of software distributed by GitLab Inc. a
perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made, use,
offer to sell, sell, import, and otherwise transfer the Work, where such
license applies only to those patent claims licensable by You that are
necessarily infringed by Your Contribution(s) alone or by combination of Your
Contribution(s) with the Work to which such Contribution(s) was submitted. If
any entity institutes patent litigation against You or any other entity
(including a cross-claim or counterclaim in a lawsuit) alleging that your
Contribution, or the Work to which you have contributed, constitutes direct or
contributory patent infringement, then any patent licenses granted to that
entity under this Agreement for that Contribution or Work shall terminate as
of the date such litigation is filed.
You represent that you are legally entitled to grant the above license. If
your employer(s) has rights to intellectual property that you create that
includes your Contributions, you represent that you have received permission
to make Contributions on behalf of that employer, that your employer has
waived such rights for your Contributions to GitLab Inc., or that your
employer has executed a separate Corporate CLA with GitLab Inc.
"4." **Contributions:**
You represent that each of Your Contributions is Your original creation. You
represent that Your Contribution submissions include complete details of any
third-party license or other restriction (including, but not limited to,
related patents and trademarks) of which you are personally aware and which
are associated with any part of Your Contributions.
Should You wish to submit work that is not Your original creation, You may
submit it to GitLab Inc. separately from any Contribution, identifying the
complete details of its source and of any license or other restriction
(including, but not limited to, related patents, trademarks, and license
agreements) of which you are personally aware, and conspicuously marking the
work as "Submitted on behalf of a third-party: (insert_name_here)".
You are not expected to provide support for Your Contributions, except to the
extent You desire to provide support. You may provide support for free, for a
fee, or not at all. Unless required by applicable law or agreed to in writing,
You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied, including, without
limitation, any warranties or conditions of TITLE, NON- INFRINGEMENT,
MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
You agree to notify GitLab Inc. of any facts or circumstances of which you
become aware that would make these representations inaccurate in any respect.
This text is licensed under the
[Creative Commons Attribution 3.0 License](https://creativecommons.org/licenses/by/3.0/)
and the original source is the Google Open Source Programs Office.
|
https://docs.gitlab.com/developer_certificate_of_origin
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/developer_certificate_of_origin.md
|
2025-08-13
|
doc/legal
|
[
"doc",
"legal"
] |
developer_certificate_of_origin.md
|
none
|
unassigned
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Developer Certificate of Origin Version 1.1
| null |
<!-- vale off -->
Copyright (C) 2004, 2006 The Linux Foundation and its contributors, 1 Letterman Drive, Suite D4700, San Francisco, CA 94129, USA
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or
(b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or
(c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it.
(d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved.
## License
All documentation content is licensed to this project under [Creative Commons: CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/legalcode).
All contributions to this project are licensed under the following license:
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
---
stage: none
group: unassigned
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Developer Certificate of Origin Version 1.1
breadcrumbs:
- doc
- legal
---
<!-- vale off -->
Copyright (C) 2004, 2006 The Linux Foundation and its contributors, 1 Letterman Drive, Suite D4700, San Francisco, CA 94129, USA
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or
(b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or
(c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it.
(d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved.
## License
All documentation content is licensed to this project under [Creative Commons: CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/legalcode).
All contributions to this project are licensed under the following license:
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
https://docs.gitlab.com/legal
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/_index.md
|
2025-08-13
|
doc/legal
|
[
"doc",
"legal"
] |
_index.md
|
none
|
unassigned
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Legal
| null |
Please read through the [GitLab License Agreement](https://gitlab.com/gitlab-org/gitlab/-/blob/master/CONTRIBUTING.md).
|
---
stage: none
group: unassigned
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Legal
breadcrumbs:
- doc
- legal
---
Please read through the [GitLab License Agreement](https://gitlab.com/gitlab-org/gitlab/-/blob/master/CONTRIBUTING.md).
|
https://docs.gitlab.com/licensing_policy
|
https://gitlab.com/gitlab-org/gitlab/-/tree/master/doc/licensing_policy.md
|
2025-08-13
|
doc/legal
|
[
"doc",
"legal"
] |
licensing_policy.md
|
none
|
unassigned
|
To determine the technical writer assigned to the Stage/Group associated with this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
|
Acceptable Use of User Licenses
| null |
## User Licenses and Affiliates
### Affiliated companies' ability to separately purchase user licenses under one master agreement
Affiliated companies may each purchase user licenses directly from GitLab under one master agreement,
subject to the terms of an applicable transaction document between GitLab and the specific company.
A customer may also purchase user licenses and deploy those licenses to an affiliated company, subject to the requirements below.
### Customers' ability to purchase user licenses and deploy those licenses to an affiliated company
With some exceptions, a customer may purchase user licenses and deploy those licenses to an affiliated entity.
GitLab can accommodate affiliated companies' internal procurement requirements and billing policies,
provided these requirements are clearly communicated in advance of purchase and prior to billing.
GitLab is a global company and may use region-specific pricing. If a customer wants to deploy user licenses outside of
the Geographical Region (defined below) where the customer purchased the licenses, including to an affiliated company,
GitLab may require the customer or affiliated company to accept alternate pricing and conditions.
### Distinct geographical region: definition
The "Geographical Region" is defined as within 4,000 miles, or 6,437 kilometers, of the "Sold To" address set forth in the quote provided by GitLab.
Any use, access, or distribution of the licenses outside the Geographical Region is strictly prohibited unless approved by GitLab in writing.
## Use of Multiple Tiers
GitLab offers three tiers of its Software: (1) Free, (2) Premium, and (3) Ultimate. See <https://about.gitlab.com/pricing/feature-comparison/>.
Customers may use multiple tiers of the software, subject to the requirements in this section, Use of Multiple Tiers, and the section below, Use of Multiple Instances.
### Customers' ability use different tiers of GitLab Software
With some exceptions, a customer may use different tiers of GitLab Software. This requires multiple instances
(see below, Use of Multiple Instances). For example, a customer may have distinct business units or
affiliated companies that each require varying features of the GitLab Software. That customer may desire to deploy a Premium instance for
one business unit and an Ultimate instance for another business unit.
Customers should ensure that use of such multiple instances is kept separate and distinct to avoid prohibited commingling of features, as further discussed below in this section.
<!-- markdownlint-disable MD013 -->
### Customers' (or a customer's business unit or affiliates) ability to use features from its Premium (or Ultimate) instance with code developed in a Free instance
This is a prohibited commingling of features. While there are times a customer may legitimately require multiple instances of
different tiers of GitLab Software, customers are limited to the features of the specific tier of the instance in question.
In this case, while a customer may have a legitimate need for a Free and Premium (or Ultimate) instance, that customer is prohibited from
using features from the Premium (or Ultimate) instance with code developed in the Free instance.
<!-- markdownlint-enable MD013 -->
### Customers' ability to use features from an Ultimate instance with code developed in a Premium instance
This is a prohibited commingling of features. While there are times a customer may legitimately require multiple instances and
different tiers of GitLab Software, customers are limited to the features of the specific tier of the instance in question.
In this case, while a customer may have a legitimate need for a Premium and Ultimate instance, that customer is prohibited from
using features from the Ultimate instance (such as security scanning) with code developed in the Premium instance.
## Use of Multiple Instances
### Customers' ability to have multiple instances
Some customers may desire to have multiple, distinct GitLab instances for different teams, subsidiary companies, etc.
At times, customers may desire to have multiple GitLab instances with the same users on each instance.
Depending on their specific use case, this may require one or multiple subscriptions to accommodate.
Use of multiple instances is also subject to the restrictions above regarding Use of Multiple Tiers.
### Customers' ability to have multiple instances of Free tier (GitLab.com or self-managed)
Customers may have multiple instances of Free tier, subject to some exceptions.
For the Free tier of GitLab.com, [there is a five-user maximum on a top-level namespace with private visibility](../user/free_user_limit.md) per customer or entity.
This five-user maximum is in the aggregate of any Free tier instances. So, for example, if a customer has one Free tier instance with five users,
that customer is prohibited from activating an additional Free tier instance of any user level because the five-user maximum has been met.
For the Free tier of self-managed, there is no five-user maximum.
### Customers' ability to have multiple instances of GitLab.com or Dedicated
Customers may have multiple instances of GitLab.com or Dedicated, provided that the customer purchases a subscription for each of the desired instances.
### Customers' ability to have multiple instances of self-managed with the same Users
This is technically possible, subject to certain conditions:
Subject to the terms of a written agreement between customer and GitLab, one Cloud Licensing activation code (or license key) may
be applied to multiple GitLab Self-Managed instances provided that the users on the instances:
- Are the same, or
- Are a subset of the customer's licensed production instance.
For example, if the customer has a licensed production instance of GitLab, and the customer has other instances with the same list of users,
the production activation code (or license key) will apply. Even if these users are configured in different groups and projects,
as long as the user list is the same, the activation code (or license key) will apply.
However, if either of the conditions above are not met, customer will need to purchase an additional subscription for a separate instance for those users.
## Use of multiple GitLab Self-Managed instances with a single license key or activation code
### Validating when one license or activation code is applied to multiple instances
GitLab requires a written agreement with its customers regarding its right to audit and verify customer compliance with the terms of this Documentation.
### Calculating billable users when one license key or activation code is applied to multiple instances
When a single license file or activation code is applied to more than one instance, GitLab checks across all of the instances associated with
the subscription to identify the instance with the **highest billable user count**. This will be the instance used for calculating values such as
`billable users` and `max users`, and will be used for Quarterly Subscription Reconciliation and Auto-renewal (if enabled).
With this approach, GitLab makes the assumption that all other lower user count instances contain the same or a subset of users of this main instance.
<!-- markdownlint-disable MD013 -->
### Visibility into latest usage data, and how to identify which of the customer's instances the data is for
GitLab Self-Managed usage data shared is stored in CustomersDot under `License seat links`. Data is recorded daily for customers on
Cloud Licensing and whenever customers on Offline licenses share their usage data via email (requested monthly).
To view this data, the customer can search by `Company` name or `Subscription` name. Also recorded with this data is `Hostname` and `Instance identifier` ID,
which can help to indicate if the data is from a production or development instance.
In GitLab 18.1 and later, the `Unique instance` ID field can also be used to identify a customer's GitLab Self-Managed instance.
<!-- markdownlint-enable MD013 -->
### Ability to have some instances using Cloud Licensing, and others air-gapped or offline
If any of the customer's instances require a legacy or offline license file, the customer will need to request a [Cloud Licensing opt out](https://docs.google.com/presentation/d/1gbdHGCLTc0yis0VFyBBZkriMomNo8audr0u8XXTY2iI/edit#slide=id.g137e73c15b5_0_298) during quoting for VP approval.
This will provide the customer with the relevant license file, but also with an activation code that the customer can apply to the Cloud Licensing-eligible instances. In this scenario, GitLab will receive a seat count data only for the Cloud Licensing instance, and this will be used for calculating overages.
### Scenarios when one or more of the instances are a dev environment
Customers are welcome to apply their production license key or activation code to a development environment. The same user restrictions will apply.
### Using a single subscription for a GitLab.com, Dedicated, and GitLab Self-Managed instance
If the customer wants to have GitLab.com, Dedicated, and GitLab Self-Managed instances, the customer will need to purchase separate subscriptions for each instance.
### Example Scenarios
The following scenarios reflect questions a customer may ask related to multiple instances.
#### Example 1
- Q: I want to buy a license for 50 total users, but want to split these users into two instances. Can I do this?
- A: Yes, provided it is for two GitLab Self-Managed instances, you can apply one Cloud Licensing activation code (or license key) to multiple GitLab Self-Managed instances,
provided that the users on the instances are the same, or are a subset of the total users. In this case, because there are 50 total or unique users, you may split
those users into two subset instances.
#### Example 2
- Q: I have 2 different groups, 20 users and 30 users, who will each need their own instance. Can I buy a subscription for 30 users?
- A: No. In this scenario, the customer should purchase two unique subscriptions, for 20 seats and 30 seats so overages in each instance can be managed separately.
A second option would be for the customer to buy a single subscription for 50 users and apply it to both instances.
#### Example 3
- Q: I have 30 users that require a Free GitLab.com instance. Can I activate a Free GitLab.com instance for all 30 users?
- A. No. The Free tier of GitLab.com is limited to five maximum users in the aggregate for each customer. Please contact your account representative to start a trial or evaluation period.
#### Example 4
- Q: I purchased 100 licenses in India but only need to deploy 75. Can I deploy the remaining 25 licenses to my team in California, USA?
- A: No. California is outside of the Geographical Region of India, so you are unable to deploy the remaining 25 licenses in this manner.
#### Example 5
- Q: I have an Ultimate instance with five users and a Premium instance with 100 users. Can I leverage Ultimate features on the code developed in my Premium instance?
- A: No. This is a prohibited commingling of features.
|
---
stage: none
group: unassigned
info: To determine the technical writer assigned to the Stage/Group associated with
this page, see https://handbook.gitlab.com/handbook/product/ux/technical-writing/#assignments
title: Acceptable Use of User Licenses
breadcrumbs:
- doc
- legal
---
## User Licenses and Affiliates
### Affiliated companies' ability to separately purchase user licenses under one master agreement
Affiliated companies may each purchase user licenses directly from GitLab under one master agreement,
subject to the terms of an applicable transaction document between GitLab and the specific company.
A customer may also purchase user licenses and deploy those licenses to an affiliated company, subject to the requirements below.
### Customers' ability to purchase user licenses and deploy those licenses to an affiliated company
With some exceptions, a customer may purchase user licenses and deploy those licenses to an affiliated entity.
GitLab can accommodate affiliated companies' internal procurement requirements and billing policies,
provided these requirements are clearly communicated in advance of purchase and prior to billing.
GitLab is a global company and may use region-specific pricing. If a customer wants to deploy user licenses outside of
the Geographical Region (defined below) where the customer purchased the licenses, including to an affiliated company,
GitLab may require the customer or affiliated company to accept alternate pricing and conditions.
### Distinct geographical region: definition
The "Geographical Region" is defined as within 4,000 miles, or 6,437 kilometers, of the "Sold To" address set forth in the quote provided by GitLab.
Any use, access, or distribution of the licenses outside the Geographical Region is strictly prohibited unless approved by GitLab in writing.
## Use of Multiple Tiers
GitLab offers three tiers of its Software: (1) Free, (2) Premium, and (3) Ultimate. See <https://about.gitlab.com/pricing/feature-comparison/>.
Customers may use multiple tiers of the software, subject to the requirements in this section, Use of Multiple Tiers, and the section below, Use of Multiple Instances.
### Customers' ability use different tiers of GitLab Software
With some exceptions, a customer may use different tiers of GitLab Software. This requires multiple instances
(see below, Use of Multiple Instances). For example, a customer may have distinct business units or
affiliated companies that each require varying features of the GitLab Software. That customer may desire to deploy a Premium instance for
one business unit and an Ultimate instance for another business unit.
Customers should ensure that use of such multiple instances is kept separate and distinct to avoid prohibited commingling of features, as further discussed below in this section.
<!-- markdownlint-disable MD013 -->
### Customers' (or a customer's business unit or affiliates) ability to use features from its Premium (or Ultimate) instance with code developed in a Free instance
This is a prohibited commingling of features. While there are times a customer may legitimately require multiple instances of
different tiers of GitLab Software, customers are limited to the features of the specific tier of the instance in question.
In this case, while a customer may have a legitimate need for a Free and Premium (or Ultimate) instance, that customer is prohibited from
using features from the Premium (or Ultimate) instance with code developed in the Free instance.
<!-- markdownlint-enable MD013 -->
### Customers' ability to use features from an Ultimate instance with code developed in a Premium instance
This is a prohibited commingling of features. While there are times a customer may legitimately require multiple instances and
different tiers of GitLab Software, customers are limited to the features of the specific tier of the instance in question.
In this case, while a customer may have a legitimate need for a Premium and Ultimate instance, that customer is prohibited from
using features from the Ultimate instance (such as security scanning) with code developed in the Premium instance.
## Use of Multiple Instances
### Customers' ability to have multiple instances
Some customers may desire to have multiple, distinct GitLab instances for different teams, subsidiary companies, etc.
At times, customers may desire to have multiple GitLab instances with the same users on each instance.
Depending on their specific use case, this may require one or multiple subscriptions to accommodate.
Use of multiple instances is also subject to the restrictions above regarding Use of Multiple Tiers.
### Customers' ability to have multiple instances of Free tier (GitLab.com or self-managed)
Customers may have multiple instances of Free tier, subject to some exceptions.
For the Free tier of GitLab.com, [there is a five-user maximum on a top-level namespace with private visibility](../user/free_user_limit.md) per customer or entity.
This five-user maximum is in the aggregate of any Free tier instances. So, for example, if a customer has one Free tier instance with five users,
that customer is prohibited from activating an additional Free tier instance of any user level because the five-user maximum has been met.
For the Free tier of self-managed, there is no five-user maximum.
### Customers' ability to have multiple instances of GitLab.com or Dedicated
Customers may have multiple instances of GitLab.com or Dedicated, provided that the customer purchases a subscription for each of the desired instances.
### Customers' ability to have multiple instances of self-managed with the same Users
This is technically possible, subject to certain conditions:
Subject to the terms of a written agreement between customer and GitLab, one Cloud Licensing activation code (or license key) may
be applied to multiple GitLab Self-Managed instances provided that the users on the instances:
- Are the same, or
- Are a subset of the customer's licensed production instance.
For example, if the customer has a licensed production instance of GitLab, and the customer has other instances with the same list of users,
the production activation code (or license key) will apply. Even if these users are configured in different groups and projects,
as long as the user list is the same, the activation code (or license key) will apply.
However, if either of the conditions above are not met, customer will need to purchase an additional subscription for a separate instance for those users.
## Use of multiple GitLab Self-Managed instances with a single license key or activation code
### Validating when one license or activation code is applied to multiple instances
GitLab requires a written agreement with its customers regarding its right to audit and verify customer compliance with the terms of this Documentation.
### Calculating billable users when one license key or activation code is applied to multiple instances
When a single license file or activation code is applied to more than one instance, GitLab checks across all of the instances associated with
the subscription to identify the instance with the **highest billable user count**. This will be the instance used for calculating values such as
`billable users` and `max users`, and will be used for Quarterly Subscription Reconciliation and Auto-renewal (if enabled).
With this approach, GitLab makes the assumption that all other lower user count instances contain the same or a subset of users of this main instance.
<!-- markdownlint-disable MD013 -->
### Visibility into latest usage data, and how to identify which of the customer's instances the data is for
GitLab Self-Managed usage data shared is stored in CustomersDot under `License seat links`. Data is recorded daily for customers on
Cloud Licensing and whenever customers on Offline licenses share their usage data via email (requested monthly).
To view this data, the customer can search by `Company` name or `Subscription` name. Also recorded with this data is `Hostname` and `Instance identifier` ID,
which can help to indicate if the data is from a production or development instance.
In GitLab 18.1 and later, the `Unique instance` ID field can also be used to identify a customer's GitLab Self-Managed instance.
<!-- markdownlint-enable MD013 -->
### Ability to have some instances using Cloud Licensing, and others air-gapped or offline
If any of the customer's instances require a legacy or offline license file, the customer will need to request a [Cloud Licensing opt out](https://docs.google.com/presentation/d/1gbdHGCLTc0yis0VFyBBZkriMomNo8audr0u8XXTY2iI/edit#slide=id.g137e73c15b5_0_298) during quoting for VP approval.
This will provide the customer with the relevant license file, but also with an activation code that the customer can apply to the Cloud Licensing-eligible instances. In this scenario, GitLab will receive a seat count data only for the Cloud Licensing instance, and this will be used for calculating overages.
### Scenarios when one or more of the instances are a dev environment
Customers are welcome to apply their production license key or activation code to a development environment. The same user restrictions will apply.
### Using a single subscription for a GitLab.com, Dedicated, and GitLab Self-Managed instance
If the customer wants to have GitLab.com, Dedicated, and GitLab Self-Managed instances, the customer will need to purchase separate subscriptions for each instance.
### Example Scenarios
The following scenarios reflect questions a customer may ask related to multiple instances.
#### Example 1
- Q: I want to buy a license for 50 total users, but want to split these users into two instances. Can I do this?
- A: Yes, provided it is for two GitLab Self-Managed instances, you can apply one Cloud Licensing activation code (or license key) to multiple GitLab Self-Managed instances,
provided that the users on the instances are the same, or are a subset of the total users. In this case, because there are 50 total or unique users, you may split
those users into two subset instances.
#### Example 2
- Q: I have 2 different groups, 20 users and 30 users, who will each need their own instance. Can I buy a subscription for 30 users?
- A: No. In this scenario, the customer should purchase two unique subscriptions, for 20 seats and 30 seats so overages in each instance can be managed separately.
A second option would be for the customer to buy a single subscription for 50 users and apply it to both instances.
#### Example 3
- Q: I have 30 users that require a Free GitLab.com instance. Can I activate a Free GitLab.com instance for all 30 users?
- A. No. The Free tier of GitLab.com is limited to five maximum users in the aggregate for each customer. Please contact your account representative to start a trial or evaluation period.
#### Example 4
- Q: I purchased 100 licenses in India but only need to deploy 75. Can I deploy the remaining 25 licenses to my team in California, USA?
- A: No. California is outside of the Geographical Region of India, so you are unable to deploy the remaining 25 licenses in this manner.
#### Example 5
- Q: I have an Ultimate instance with five users and a Premium instance with 100 users. Can I leverage Ultimate features on the code developed in my Premium instance?
- A: No. This is a prohibited commingling of features.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.