- 導入
- 設定パラメータ
- グローバルパラメータ
- パラメータの詳細
-
variables
- Special YAML features
- Skip Pipeline
- Processing Git pushes
- Deprecated parameters
GitLab CI/CD パイプライン設定リファレンス
GitLab CI/CD パイプラインは、各プロジェクト内の .gitlab-ci.yml
というYAMLファイルを使って設定します。
.gitlab-ci.yml
ファイルはパイプラインの構造と順序を定義し、以下のことを決めます。
- GitLab Runnerを使って実行する内容。
- 特定の状況において、どのような判断をするか。例えば、処理が成功した場合と失敗した場合。
このトピックでは、CI/CDパイプラインの設定について説明します。その他のCI/CDの設定については、以下を参照してください。
- GitLab CI/CDの変数、パイプラインの実行環境を設定するための内容です。
- GitLab Runnerの高度な設定、GitLab Runnerを設定するための内容です。
パイプラインの完全な設定例を以下で紹介しています。
- GitLab CI/CDの入門には、クイックスタートガイドをご覧ください。
- サンプル集については、GitLab CI/CDの使用例を参照してください。
- 企業で使われる大規模な
.gitlab-ci.yml
ファイルのサンプルとして、GitLab
の開発で使われている.gitlab-ci.yml
ファイルを参照してください。
GitLab CI/CDについての追加情報はこちらをご覧ください。
- CI/CDの簡単な設定の動画をご覧ください。
- あなたの組織におけるCI/CDの事例を作るウェブキャストを見て、CI/CDの利点とCI/CDによる自動化の結果を測定する方法を学ぶ。
- GitLabを使用して、[Verizonがリビルドを30日間から8時間以内に短縮した方法を学ぶ。
導入
パイプラインの設定はジョブから始まります。ジョブは .gitlab-ci.yml
ファイルの最も基本的な要素です。
ジョブは以下のようなものです。
- どのような条件で実行されるべきかを示す制約とともに定義されます。
- 任意の名前を持つトップレベル要素で、少なくとも
script
句を含んでいます。 - 定義できる数に制限はありません。
使用例。
job1:
script: "execute-script-for-job1"
job2:
script: "execute-script-for-job2"
上記の例は2つのジョブを別々に実行し、それぞれのジョブが異なるコマンドを実行する、最もシンプルなCI/CDの設定です。
もちろんコマンドは直接コードを実行したり(./configure;make;make install
)、リポジトリ内のスクリプトを実行したり(test.sh
)することができます。
ジョブはRunnerによってピックアップされ、Runnerの環境内で実行されます。重要なのは、それぞれのジョブが独立して実行されることです。
.gitlab-ci.yml
を検証する
GitLab CI/CDの各インスタンスにはLintと呼ばれるデバッグツールが組み込まれており、.gitlab-ci.yml
ファイルの内容を検証するために使用できます。Lintはプロジェクト名前空間のci/lint
ページの下にあります。例えば、https://gitlab.example.com/gitlab-org/project-123/-/ci/lint
です。
ジョブで利用できない名前
各ジョブは一意の名前を持たなければなりませんが、ジョブ名として使用できないの予約されたキーワード
がいくつかあります。
image
services
stages
types
before_script
after_script
variables
cache
include
予約語の使用
特定の値(例えば、true
やfalse
など)を使用しているときにバリデーションエラーが発生する場合は、以下を試してみてください。
- それらを「”」で囲む。
- それらを別の形に変更する。例えば、
/bin/true
。
設定パラメータ
ジョブは、ジョブの動作を定義するパラメータのリストとして定義されます。
次の表は、ジョブで使用可能なパラメータの一覧です。
キーワード | 説明 |
---|---|
script
| Runnerで実行されるシェルスクリプトです。 |
image
| Dockerイメージを使用します。image:name 、image:entrypoint も利用可能です。
|
services
| Dockerサービスのイメージを使用します。services:name 、services:alias 、services:entrypoint 、services:command も利用可能です。
|
before_script
| ジョブの前に実行されるコマンドを上書きします。 |
after_script
| ジョブの後に実行されるコマンドを上書きします。 |
stage
| ジョブのステージを定義します(デフォルトは test )。
|
only
| どのような場合にジョブが作成されるかを制限します。only:refs 、only:kubernetes 、only:variables 、only:changes も利用可能です。
|
except
| どのような場合にジョブが作成されないかを制限します。except:refs 、except:kubernetes 、except:variables 、except:changes も利用可能です。
|
rules
| ジョブを作成する、または作成しないかどうかを判断するために評価する条件の一覧です。only /except と一緒に使用できません。
|
tags
| Runnerを選択する際に使用するタグの一覧です。 |
allow_failure
| ジョブの失敗を許可します。ジョブが失敗しても、パイプラインのステータスには影響しません。 |
when
| いつジョブを実行するかを決めます。when:manual 、when:delayed も利用可能です。
|
environment
| ジョブをデプロイする環境の名前です。environment:name 、environment:url 、environment:on_stop 、environment:auto_stop_in 、environment:action も利用可能です。
|
cache
| 後続の処理でキャッシュされるべきファイルのリストです。。cache:paths 、cache:key 、cache:untracked 、cache:policy も利用可能です。
|
artifacts
| 成功した場合にジョブに添付するファイルとディレクトリのリストです。artifacts:paths 、artifacts:exclude 、artifacts:expose_as 、artifacts:name 、artifacts:untracked 、artifacts:when 、artifacts:expire_in 、artifacts:reports 、artifacts:reports:junit 、artifacts:reports:cobertura 、artifacts:reports:terraform 。GitLabエンタープライズエディションでは、 artifacts:reports:codequality 、artifacts:reports:sast 、artifacts:reports:dependency_scanning 、artifacts:reports:container_scanning 、artifacts:reports:dast 、artifacts:reports:license_scanning 、artifacts:reports:license_management (removed in GitLab 13.0)、artifacts:reports:performance 、artifacts:reports:load_performance artifacts:reports:metrics も利用可能です。
|
dependencies
| アーティファクトを取得するジョブのリストを与えることで、アーティファクトが渡されるジョブを制限します。 |
coverage
| ジョブのコードカバレッジを設定します。 |
retry
| ジョブが失敗した場合に、ジョブをいつ、何回自動リトライするかを設定します。 |
timeout
| プロジェクト全体の設定よりも優先される、ジョブレベルのタイムアウトを定義します。 |
parallel
| ジョブを並列に実行するインスタンス数を定義します。 |
trigger
| ダウンストリームのパイプライントリガーを定義します。 |
include
| このジョブが外部YAMLファイルを含むことを許可します。include:local 、include:file 、include:template 、include:remote も利用可能です。
|
extends
| このジョブが継承する項目を設定します。 |
pages
| GitLab Pagesで使用するために、ジョブの結果をアップロードします。 |
variables
| ジョブレベルでジョブ変数を定義します。 |
interruptible
| 新しいジョブによって、冗長なジョブをキャンセルできるかどうかを定義します。 |
resource_group
| ジョブの同時実行を制限します。 |
release
| Runnerにリリースオブジェクトを生成するよう指示します。 |
グローバルパラメータ
一部のパラメータはグローバルレベルで定義する必要があり、パイプライン内のすべてのジョブに影響を与えます。
グローバルデフォルト
いくつかのパラメータは、default:
キーワードを使用して、すべてのジョブのデフォルトとしてグローバルに設定することができます。デフォルトのパラメータは、ジョブ固有の設定で上書きすることができます。
以下のジョブパラメータは、default:
ブロック内で定義することができます。
以下の例では、ruby:2.5
イメージをデフォルトとして設定されており、すべてのジョブで使用されます。ただし、rspec 2.6
ジョブだけはruby:2.6
イメージを使用しています。
default:
image: ruby:2.5
rspec:
script: bundle exec rspec
rspec 2.6:
image: ruby:2.6
script: bundle exec rspec
inherit
GitLab 12.9で導入されました。
グローバルに定義されたデフォルトや変数の継承を無効にするには、inherit:
パラメータを使用します。
すべてのvariables:
またはdefault:
パラメータの継承を有効または無効にするには、以下の形式を使用します。
-
default: true
またはdefault: false
-
variables: true
またはvariables: false
default:
パラメータまたは variables:
のサブセットのみを継承するには、継承したいもの一覧を指定してください。一覧にないものは継承されません。以下のいずれかの形式を使用してください。
inherit:
default: [parameter1, parameter2]
variables: [VARIABLE1, VARIABLE2]
または:
inherit:
default:
- parameter1
- parameter2
variables:
- VARIABLE1
- VARIABLE2
下の例では:
-
rubocop
:- 継承する: なし。
-
rspec
:- 継承する: デフォルトの
image
、WEBHOOK_URL
変数。 - 継承しない: デフォルトの
before_script
、DOMAIN
変数。
- 継承する: デフォルトの
-
capybara
:- 継承する: デフォルトの
before_script
、デフォルトのimage
。 - 継承しない:
DOMAIN
変数とWEBHOOK_URL
変数。
- 継承する: デフォルトの
-
karma
:- 継承する: デフォルトの
image
、デフォルトのbefore_script
、DOMAIN
変数。 - 継承しない:
WEBHOOK_URL
変数。
- 継承する: デフォルトの
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
stages
stages
は、ジョブを含有するステージを定義するために使用され、パイプラインに対してグローバルに定義されます。
stage
の仕様により、柔軟な多段パイプラインを構築できます。
stages
の要素の順序が、ジョブの実行順序を定義します。
- 同じステージのジョブは並列に実行されます。
- 次のステージのジョブは、前のステージのジョブが正常に終了した後に実行されます。
3つのステージを定義した次の例を考えてみましょう。
stages:
- build
- test
- deploy
- はじめに、
build
のジョブがすべて並列に実行されます。 -
build
のすべてのジョブが成功した場合、test
のジョブが並列に実行されます。 -
test
のすべてのジョブが成功した場合、deploy
のジョブが並列に実行されます。 -
deploy
のすべてのジョブが成功した場合、コミットは成功
とマークされます。 - 前のジョブのいずれかが失敗した場合、コミットは
失敗
とマークされ、それ以降のステージのジョブは実行されません。
また、特筆すべきエッジケースが2つあります。
-
.gitlab-ci.yml
にstages
が定義されていない場合、デフォルトではbuild
、test
、deploy
がジョブのステージとして使用されます。 - ジョブで
stage
を指定していない場合、ジョブにはtest
ステージが割り当てられます。
workflow:rules
GitLab 12.5で導入されました
トップレベルの workflow:
キーは、パイプラインの全体に適用され、パイプラインが作成されるかどうかを決定します。現在、ジョブ内で定義されたrules:
と同様に動作するように、単一のrules:
キーを受け入れます。これは、パイプラインの動的な設定を可能にするためです。
GitLab CI/CDとworkflow: rules
を初めて使う方には、workflow:rules
のテンプレートが役立ちます。
独自の workflow: rules
を定義するのに、現在利用可能な設定オプションは以下の通りです。
if
ルールのリストは、1つが一致するまで評価されます。一致するものがない場合は、最後のwhen
が使用されます。
workflow:
rules:
- if: $CI_COMMIT_REF_NAME =~ /-wip$/
when: never
- if: $CI_COMMIT_TAG
when: never
- when: always
workflow:rules
のテンプレート
GitLab 13.0で導入されました。
一般的なシナリオのためにworkflow: rules
を設定するパイプラインで使用するためのテンプレートをあらかじめ用意しています。これらを使用することで、物事がより簡単になり、重複したパイプラインの実行を防ぐことができます。
Branch-Pipelines
テンプレートは、ブランチとタグのためにパイプラインを実行するようにします。
ブランチパイプラインのステータスは、そのブランチをソースとして使用するマージリクエスト内に表示されます。しかし、このパイプラインタイプは マージリクエストパイプライン、マージ結果のパイプラインやマージトレインのいかなる機能もサポートしません。 これらの機能を意図的に避けている場合は、このテンプレートを使用してください。
以下のようにincludedします。
include:
- template: 'Workflows/Branch-Pipelines.gitlab-ci.yml'
MergeRequest-Pipelines
テンプレートは、デフォルトブランチ(通常はmaster
)、タグ、およびすべてのタイプのマージリクエストパイプラインを実行します。上記で述べたマージリクエストパイプラインの機能 のいずれかを使用する場合は、このテンプレートを使用してください。
以下のようにincludedします。
include:
- template: 'Workflows/MergeRequest-Pipelines.gitlab-ci.yml'
include
- GitLab Premium 10.5 で導入されました。
- 10.6からStarter、Premium、Ultimateで利用可能になりました。
- 11.4でGitLab Coreに移動しました。
include
キーワードを使用すると、外部のYAMLファイルを含有することができます。これにより、CI/CDの設定を複数のファイルに分解し、長い設定ファイルの可読性を高めることができます。
また、テンプレートファイルを中央のリポジトリに保存し、プロジェクトにその設定ファイルを含めることも可能です。これは、すべてのプロジェクトのグローバルデフォルト変数など、設定の重複を避けるのに役立ちます。
include
は外部のYAMLファイルが拡張子.yml
か.yaml
を持っている必要があり、そうでなければ外部ファイルはインクルードされません。
include
は以下のインクルード方法をサポートしています。
方法 | 説明 |
---|---|
local
| ローカルのプロジェクトリポジトリからファイルをインクルードします。 |
file
| 別のプロジェクトリポジトリからのファイルをインクルードします。 |
remote
| リモートURLからのファイルをインクルードします。公開されている必要があります。 |
template
| GitLabが提供しているテンプレートをインクルードします。 |
include
メソッドは変数展開をサポートしていません。
.gitlab-ci.yml
の設定は、パイプラインの作成時に評価されます。
設定は時間的にスナップショットであり、データベースに永続化されています。参照された .gitlab-ci.yml
の設定を変更しても、次のパイプラインが作成されるまで GitLab には反映されません。インクルード
で定義されたファイルは
-
.gitlab-ci.yml
にあるものをディープマージされます。 - キーワード
include
の位置にかかわらず、常に最初に評価され、.gitlab-ci.yml
の内容とマージされます。
.gitlab-ci.yml
内のローカル定義は、インクルードされた定義を上書きします。include
によってソースされた異なるYAMLファイル間で使用することはサポートされていません。同一ファイル内のアンカーのみを参照する必要があります。YAMLアンカーを使う代わりに、extends
キーワードを使うことができます。
include:local
include:local
は .gitlab-ci.yml
と同じリポジトリのファイルをインクルードします。
ルートディレクトリ(/)
からの相対的なフルパスを使用して参照されます。
設定ファイルと同じブランチにある、すでにGitで管理されているファイルしか使えません。つまり、include:local
を使う場合は、.gitlab-ci.yml
とローカルファイルの両方が同じブランチにあることを確認してください。
すべてのネストされたインクルードは同じプロジェクトのスコープ内で実行されるので、ローカルインクルード、プロジェクトインクルード、リモートインクルード、テンプレートインクルードを使用することができます。
使用例:
include:
- local: '/templates/.gitlab-ci-template.yml'
これは、短いローカルインクルードとして定義することができます。
include: '.gitlab-ci-production.yml'
include:file
GitLab 11.7 で導入されました。
同じ GitLab インスタンスの下にある別のプライベートプロジェクトのファイルをインクルードするには、include:file
を使用します。このファイルは、ルートディレクトリ(/
)からの相対的なフルパスを使って参照されます。使用例:
include:
- project: 'my-group/my-project'
file: '/templates/.gitlab-ci-template.yml'
ref
も指定できますが、デフォルトはプロジェクトのHEAD
です。
include:
- project: 'my-group/my-project'
ref: master
file: '/templates/.gitlab-ci-template.yml'
- project: 'my-group/my-project'
ref: v1.0.0
file: '/templates/.gitlab-ci-template.yml'
- project: 'my-group/my-project'
ref: 787123b47f14b552955ca2786bc9542ae66fee5b # Git SHA
file: '/templates/.gitlab-ci-template.yml'
すべてのネストされたインクルードはターゲットプロジェクトのスコープ内で実行されるので、ローカル(ターゲットプロジェクトからの相対的な)インクルード、プロジェクトインクルード、リモートインクルード、テンプレートインクルードを使用することができます。
include:remote
include:remote
を使用すると、別の場所からのファイルをインクルードすることができます。
HTTP/HTTPS を使用して、完全な URL を使用して参照されます。リモートURLの認証スキーマはサポートされていないため、リモートファイルは単純なGETリクエストで公開されなければなりません。使用例:
include:
- remote: 'https://gitlab.com/awesome-project/raw/master/.gitlab-ci-template.yml'
すべてのネストされたインクルードは、パブリックユーザとしてコンテキストなしで実行されるので、別のリモートまたはパブリックプロジェクト、またはテンプレートのみが許可されます。
include:template
GitLab 11.7 で導入されました。
include:template
を使うと、GitLabに同梱されている.gitlab-ci.yml
のテンプレートをインクルードすることができます。
使用例。
# File sourced from GitLab's template collection
include:
- template: Auto-DevOps.gitlab-ci.yml
複数ファイルのinclude:template
:
include:
- template: Android-Fastlane.gitlab-ci.yml
- template: Auto-DevOps.gitlab-ci.yml
すべてのネストされたインクルードは、ユーザーの許可を得てのみ実行されるので、プロジェクトインクルード、リモートインクルード、テンプレートインクルードを使用することができます。
ネストされたインクルード
GitLab 11.9 で導入されました。
入れ子になったインクルードでは、インクルードのセットを構成することができます。
合計100個のインクルードは許可されていますが、重複したインクルードは設定エラーとみなされます。
GitLab 12.4以降、すべてのファイルを解決するための制限時間は30秒となっています。
追加のincludes
の使用例
こちらから追加のincludes
の使用例利用できます。
パラメータの詳細
CI/CDパイプラインを設定するためのパラメータについて詳しく説明します。
image
ジョブで使用するDockerイメージを指定するために使用します。
使用例:
- 簡単な定義例は、
.gitlab-ci.yml
からのimage
とservices
の定義を参照してください。 - 詳しい使用方法については、Dockerインテグレーションのドキュメントを参照してください。
image:name
詳しくは、「image
の利用可能な設定」を参照してください。
image:entrypoint
詳しくは、「image
の利用可能な設定」を参照してください。
services
image
で指定したベースイメージにリンクしたサービスのDockerイメージを指定するために使用します。
使用例:
- 簡単な定義例は、
.gitlab-ci.yml
からのimage
とservices
の定義を参照してください。 - 詳しい使用方法については、Dockerインテグレーションのドキュメントを参照してください。
- サービスの使用例としては、GitLab CI/CDのサービスを参照してください。
services:name
詳細については、「services
で利用可能な設定」を参照してください。
services:alias
詳細については、「services
で利用可能な設定」を参照してください。
services:entrypoint
詳細については、「services
で利用可能な設定」を参照してください。
services:command
詳細については、「services
で利用可能な設定」を参照してください。
script
スクリプトは
、ジョブが必要とする唯一の必須キーワードです。Runnerが実行するシェルスクリプトです。使用例:
job:
script: "bundle exec rspec"
スクリプト用のYAMLアンカーが利用可能です。
このパラメータには、配列を使用して複数のコマンドを含めることもできます。
job:
script:
- uname -a
- bundle exec rspec
script
コマンドを一重引用符や二重引用符で囲む必要がある場合があります。
例えば、コロン (:
) を含むコマンドは、YAMLパーサーが “key: value” のペアではなく文字列として解釈するために、引用符で囲む必要があります。特殊文字の使用には注意してください。
:
, {
, }
, [
, ]
, ,
, &
, *
, #
, ?
, |
, -
, <
, >
, =
, !
, %
, @
, `
。スクリプトコマンドのいずれかがゼロ以外の終了コードを返した場合、ジョブは失敗し、それ以降のコマンドは実行されません。この動作は、終了コードを変数に格納することで回避できます。
job:
script:
- false || exit_code=$?
- if [ $exit_code -ne 0 ]; then echo "Previous command failed"; fi;
before_script
とafter_script
GitLab 8.7 で導入され、GitLab Runner v1.2 が必要です。
before_script
は、デプロイジョブを含む各ジョブの前に実行されるべきコマンドを定義するために使用されますが、任意のアーティファクトの復元後に実行されるべきコマンドを定義するために使用されます。
これは配列でなければなりません。
before_script
で指定されたスクリプトは、メインのscript
で指定されたスクリプトと結合され、単一のシェル内で一緒に実行されます。
after_script
は、失敗したものも含めて、各ジョブの後に実行されるコマンドを定義するために使用されます。これは配列でなければなりません。
after_script
で指定されたスクリプトは、before_script
やscript
のスクリプトとは別に、新しいシェルで実行されます。その結果として:
- 現在の作業ディレクトリをデフォルトに戻します。
-
before_script
で定義されたスクリプトやscript
で行われた変更にはアクセスできません。-
script
のスクリプトでエクスポートされた変数やコマンドのエイリアス。 -
before_script
やscript
のスクリプトによってインストールされたソフトウェアのように、(RunnerのExecutorに依存する)作業ツリー外の変更。
-
- 5分にハードコードされた別のタイムアウトを持っています。詳細は関連する課題を参照してください。
- ジョブの終了コードに影響を与えないようにしてください。
script
セクションが成功し、after_script
がタイムアウトするか失敗した場合、コード0
(成功
)でジョブは終了します。
グローバルに定義されたbefore_script
やafter_script
をジョブごとに設定すれば、上書きすることができます。
default:
before_script:
- global before script
job:
before_script:
- execute this instead of global before script
script:
- my command
after_script:
- execute this after my script
before_script
とafter_script
ではYAMLアンカーを利用できます。
スクリプトの出力を色付け
スクリプトの出力は、ANSI エスケープコードを使って色をつけるか、ANSI エスケープコードを出力するコマンドやプログラムを実行することで色をつけることができます。
以下は、Bashでカラーコードを使用する例です。
job:
script:
- echo -e "\e[31mThis text is red,\e[0m but this text isn't\e[31m however this text is red again."
カラーコードをシェル変数で定義したり、カスタム環境変数でも定義することができるので、コマンドが読みやすく再利用しやすいです。
以下は、上記と同じ例で、before_script
で定義した変数を使用しています。
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"
以下は、PowerShellでカラーコードを使用する例です。
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"
複数行のコマンド
|
(リテラル)と>
(折り返し)のYAMLマルチラインブロックスカラ指標を使用して、長いコマンドを複数行のコマンドに分割して可読性を向上させることができます。
script:
項目として実行したり、必要に応じてexit 1
コマンドをコマンド文字列に適宜追加したりすることができます。|
(リテラル) YAMLマルチラインブロックスカラーインジケータを使用して、ジョブディスクリプションのscript
セクションに複数行に渡ってコマンドを書くことができます。
各行は別のコマンドとして扱われます。
ジョブログでは最初のコマンドだけが繰り返されますが、追加のコマンドはまだ実行されています。
job:
script:
- |
echo "First command line."
echo "Second command line."
echo "Third command line."
上記の例では、ジョブログに以下のように表示されます。
$ echo First command line # collapsed multi-line command
First command line
Second command line.
Third command line.
>
(folded) YAML マルチラインブロックスカラーインジケータは、セクション間の空行を新しいコマンドの開始として扱います。
job:
script:
- >
echo "First command line
is split over two lines."
echo "Second command line."
これは、>
または|
ブロック・スカラー・インジケータを使用せずに、マルチライン・コマンドを書くのと同じように動作します。
job:
script:
- echo "First command line
is split over two lines."
echo "Second command line."
上記の両方の例は、ジョブログに以下のように表示されます。
$ echo First command line is split over two lines. # collapsed multi-line command
First command line is split over two lines.
Second command line.
>
や|
ブロックのスカラ指標が省略されている場合、GitLabは空ではない行を連結してコマンドを形成するので、連結したときに実行できることを確認してください。
シェルのヒアドキュメントを|
演算子や>
演算子と一緒に使用できます。 以下の例では、小文字を大文字に変換しています。
job:
script:
- |
tr a-z A-Z << END_TEXT
one two three
four five six
END_TEXT
以下の結果になります。
$ tr a-z A-Z << END_TEXT # collapsed multi-line command
ONE TWO THREE
FOUR FIVE SIX
stage
stage
はジョブごとに定義され、グローバルで定義したstages
に依存します。 これは、ジョブを異なるステージにグループ化し、同じステージ
のジョブを(一定の条件のもとで)並列に実行することを可能にします。 例えば、以下のような場合には、ジョブを複数のステージにグループ化することができます。
stages:
- build
- test
- deploy
job 0:
stage: .pre
script: make something useful before build stage
job 1:
stage: build
script: make build dependencies
job 2:
stage: build
script: make build artifacts
job 3:
stage: test
script: make test
job 4:
stage: deploy
script: make deploy
job 5:
stage: .post
script: make something useful at the end of pipeline
独自のRunnerを使用する
独自のRunnerを使用している場合、GitLab Runner はデフォルトで一度に1つのジョブしか実行しません (詳細は Runner グローバル設定のconcurrent
フラグを参照してください)。
以下の場合に限り、ジョブは独自のRunner上で並列に実行されます。
- 別々のRunnerで実行される場合。
- Runnerの
cuncurrent
設定を変更した場合。
.pre
と .post
GitLab 12.4で導入されました。
以下のステージは、すべてのパイプラインで利用可能です。
-
.pre
は、常にパイプラインの最初のステージであることが保証されています。 -
.post
は、常にパイプラインの最後のステージであることが保証されています。
ユーザー定義のステージは、.pre
の後と.post
の前に実行されます。
.gitlab-ci.yml
で順番がずれて定義されていても、.pre
と.post
の順番を変えることはできません。
-
順番通りに定義されている例:
stages: - .pre - a - b - .post
-
順番がずれて定義されている例:
stages: - a - .pre - b - .post
-
明示的に定義されていない例:
stages: - a - b
.pre
または .post
のステージのジョブのみが含まれている場合には作成されません。
extends
GitLab 11.3 で導入されました。
extends
は extends
を使用するジョブが適用されるエントリ名を定義します。
これはYAMLアンカーを使う代替案で、もう少し柔軟で読みやすいです。
.tests:
script: rake test
stage: test
only:
refs:
- branches
rspec:
extends: .tests
script: rake rspec
only:
variables:
- $RSPEC
上の例では、rspec
ジョブは.tests
テンプレートジョブを継承しています。 GitLabはキーに基づいて逆ディープマージを実行します。GitLabは以下を行ないます。
-
rspec
の内容を再帰的に.tests
にマージします。 - キーの値はマージしません。
その結果、以下のようなrspec
ジョブになります。
rspec:
script: rake rspec
stage: test
only:
refs:
- branches
variables:
- $RSPEC
script: rake test
は script: rake rspec
で上書きされていることに注意してください。rake test
を含めたい場合は、before_script
とafter_script
を参照してください。
この例の.tests
は隠しジョブですが、通常のジョブを継承することも可能です。
extends
は複数レベルの継承をサポートしていますが、3つ以上のレベルを使用することは推奨されていません。 サポートされている最大ネスティングレベルは10です。
.tests:
only:
- pushes
.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
GitLab 12.0 以降では、複数の親をextends
することも可能です。
マージの詳細
extends
はハッシュをマージできますが、配列をマージできません。マージで使用されるアルゴリズムは「最も近いスコープを優先」であり、最後のメンバーからのキーは、常に他のレベルで定義されたものを上書きします。 例えば、次のようになります。
.only-important:
variables:
URL: "http://my-url.internal"
IMPORTANT_VAR: "the details"
only:
- master
- 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
その結果、以下のようなrspec
ジョブになります。
rspec:
variables:
URL: "http://docker-url.internal"
IMPORTANT_VAR: "the details"
GITLAB: "is-awesome"
only:
- master
- stable
tags:
- docker
image: alpine
script:
- rake rspec
上の例では、以下に注意してください。
-
variables
セクションはマージされましたが、URL: "http://my-url.internal
” はURL: "http://docker-url.internal"
で上書きされています。 -
tags: ['production']
はtags: ['docker']
で上書きされています。 -
script
はマージされず、script: ['echo "Hello world!"]
はscript: ['rake rspec']
で上書きされています。 YAMLアンカーを使って配列を結合することができます。
extends
と include
を一緒に使用する
extends
はinclude
と組み合わせて、設定ファイル全体で動作します。
例えば、ローカルに以下のようなinclude.yml
ファイルがある場合:
.template:
script:
- echo Hello!
.gitlab-ci.yml
の中では、次のように使用できます。
include: included.yml
useTemplate:
image: alpine
extends: .template
これにより、useTemplate
というジョブが実行され、.template
ジョブで定義されているように echo Hello!
を実行し、ローカルジョブで定義されているようにalpine
Dockerイメージを使用します。
rules
GitLab 12.3 で導入されました。
rules
キーワードは、パイプラインにジョブを追加するかどうかを決定するジョブポリシーを設定する方法です。
一致するまで、個々のルール句のリストを順番に評価します。 一致した場合、設定に応じて、そのジョブはパイプラインに含まれるか、パイプラインから除外されます。 含まれる場合、ジョブには特定の属性が追加されます。
rules
は、only/except
と組み合わせて使用できません。 これを実行しようとすると、linterは「key may not be used with rules
」というエラーを返します。ルール属性
rules
で許可されるジョブ属性は、次の通りです。
-
when
: 定義されていない場合のデフォルトはwhen: on_success
です。-
when:delayed
として使用する場合は、start_in
も必要です。
-
-
allow_failure
:定義されていない場合のデフォルトはallow_failure: false
です。
ルールがtrueと評価され、かつ when
に never
以外の値がある場合、そのジョブはパイプラインに含まれます。
使用例。
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: '$CI_COMMIT_BRANCH == "master"'
when: delayed
start_in: '3 hours'
allow_failure: true
将来的には、ルールに追加のジョブ設定が追加される可能性があります。 有用なものが利用できない場合は、課題を開いてください。
ルールで使える条件句
利用可能なルールの条件句は以下の通りです。
条件句 | 説明 |
---|---|
if
|
if 文を評価することで、パイプラインからジョブを追加または除外します。 only:variables と似ています。
|
changes
| 変更されたファイルに基づいて、パイプラインからジョブを追加または除外します。 only:changes と似ています。
|
exists
| 特定のファイルの存在に基づいて、パイプラインからジョブを追加または除外します。 |
一致するルールが見つかるまで、ルールは順番に評価されます。 一致するルールが見つかった場合は、パイプラインにジョブを追加するかどうかの属性がチェックされます。 属性が定義されていない場合は、デフォルトでは以下のようになります。
when: on_success
allow_failure: false
ジョブがパイプラインに追加される場合:
- ルールがマッチし、
when: on_success
、when:delayed
、when: always
を持つ場合。 - ルールが一致しないが、最後の句が(ルールのない)
when: on_success
、when: delayed
、when: always
の場合。
ジョブはパイプラインに追加されない場合:
- ルールが一致せず、独立したwhen
: on_success
、when: delayed
、when: always
が存在しない場合。 - ルールがマッチし、属性として
when: never
を持つ場合。
例えば、if
句を使用してジョブの実行条件を厳密に制限します。
job:
script: "echo Hello, Rules!"
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
when: manual
allow_failure: true
- if: '$CI_PIPELINE_SOURCE == "schedule"'
この例では:
- パイプラインがマージリクエストのためのものである場合、最初のルールが一致します。そのため、ジョブがマージリクエストパイプラインに追加され、その属性は次のようになります。
-
when: manual
(手動ジョブ) -
allow_failure: true
(手動ジョブが実行されていない場合でもパイプラインの実行を継続します)
-
- パイプラインがマージリクエストのためのものではない場合、最初のルールがマッチせず、2番目のルールが評価されます。
- パイプラインがスケジュールされたパイプラインであれば、2 番目のルールが一致し、ジョブはスケジュールされたパイプラインに追加されます。 属性が定義されていないので、ジョブの属性は次のようになります。
-
when: on_success
(デフォルト) -
allow_failure: false
(デフォルト)
-
- それ以外のすべての場合、ルールが一致しないため、ジョブは他のパイプラインに追加されません。
次のように、いくつかのケースではジョブを除外し、それ以外のケースではすべてのジョブを実行するようにルールを定義することもできます。
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
- パイプラインがマージリクエストのためのものである場合、ジョブはパイプラインに追加されません。
- パイプラインがスケジューリングされたパイプラインの場合、ジョブはパイプラインに追加されません。
-
それ以外のすべての場合、
when: on_success
により、ジョブはパイプラインに追加されます。
when: on_success
、always
、delayed
を使用すると、2 つのパイプラインが同時に開始されることがあります。 プッシュパイプラインとマージリクエストパイプラインは、同じイベント (オープンしているマージリクエストのソースブランチへのプッシュ) によって開始されることがあります。
rules
とonly
/except
の違い
only/except
で定義されたジョブは、デフォルトではマージリクエストパイプラインを起動しません。明示的にonly: merge_requests
を追加する必要があります。
rules
で定義されたジョブは、すべてのタイプのパイプラインを起動することができます。
使用例。
job:
script: "echo This creates double pipelines!"
rules:
- if: '$CUSTOM_VARIABLE == "false"'
when: never
- when: always
このジョブは $CUSTOM_VARIABLE
が false の場合には実行されませんが、プッシュ (ブランチ) とマージリクエストの両方のパイプラインを含む他のすべてのパイプラインで実行されます。 この設定では、オープンしているマージリクエストのソースブランチへのすべてのプッシュはパイプラインの重複を引き起こします。 同じジョブでプッシュとマージリクエストの両方のパイプラインを明示的に許可することで、同じ効果を得ることができます。
実行するパイプラインのタイプを制限するために、workflow: rules
のご利用をお勧めします。 マージリクエストパイプラインのみを許可したり、ブランチパイプラインのみを許可したりすることで、重複したパイプラインを排除することができます。 あるいは、ルールをよりシンプルに書き換えたり、最終的な when
句(always
、on_success
、delayed
) を使用しないようにすることもできます。
また、同じパイプライン内でonly/except
ジョブとrules
ジョブを混在させることはお勧めしません。YAMLエラーは発生しないかもしれませんが、only/except
とrules
のデフォルトの動作が異なるため、正確な実行動作のデバッグは複雑になります。
rules:if
rules:if
句は、単純なif
文を評価することで、ジョブをパイプラインに追加するかどうかを決定します。 if
文がtrueであれば、ジョブはパイプラインに含まれるか、パイプラインから除外されるかのどちらかになります。 わかりやすく言えば、if
ルールは次のいずれかのように解釈することができます。
- 「このルールがtrueと評価された場合、ジョブを追加します。」(デフォルト)
- (
when: never
を追加することで)「このルールがtrueと評価される場合は、ジョブを追加しません。」
rules:if
は only:variables
とは少し異なり、ルールごとに1つの式の文字列のみを受け付ける点が異なります。 評価される式の集合は、&&
または ||
を使用して1つの式に結合することができ、変数にマッチする構文を使用します。
if:
句は、定義済みの環境変数やカスタム環境変数の値に基づいて評価されます。
使用例。
job:
script: "echo Hello, Rules!"
rules:
- if: '$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/ && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master"'
when: always
- if: '$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/'
when: manual
allow_failure: true
- if: '$CI_MERGE_REQUEST_SOURCE_BRANCH_NAME' # Checking for the presence of a variable is possible
ジョブのwhen
のロジックについて、いくつか詳細をご紹介します。
- 提供されたルールがどれも一致しない場合、ジョブは
when: never
に設定され、パイプラインには含まれません。 - 条件句のないルール、例えば
if
やchanges
のないwhen
やallow_failurerule
のようなルールは、常にマッチし、到達した場合には常に使用されます。 - ルールがマッチし、
when
が定義されていない場合、ルールはジョブのデフォルトのwhen
としてon_success
を使用します。 -
when
はルールごとに1回、またはジョブレベルで1回定義して、すべてのルールに適用することができます。 ジョブレベルでのwhen
とルール内でのwhen
を混在させることはできません。
$CI_PIPELINE_SOURCE
変数の値をチェックすることで、only
/except
キーワードと同様の動作をすることができます。
値 | 説明 |
---|---|
push
| ブランチやタグを含む、git push イベントで起動されるパイプラインのためのものです。
|
web
| プロジェクトのCI/CD > パイプラインメニューから、GitLab UIのパイプライン実行ボタンを使って作成したパイプラインの場合。 |
trigger
| トリガートークンを使用して作成されたパイプラインの場合。 |
schedule
| スケジュールパイプラインの場合。 |
api
| パイプラインAPIで起動されたパイプラインの場合。 |
external
| GitLab以外のCIサービスを利用する場合。 |
pipelines
|
CI_JOB_TOKEN でAPIを使用して作成したマルチプロジェクトパイプラインの場合。
|
chat
| GitLab ChatOps コマンドを使用して作成したパイプラインの場合。 |
webide
| WebIDEを使用して作成したパイプラインの場合。 |
merge_request_event
| マージリクエストが作成または更新されたときに作成されるパイプライン用。 マージリクエストパイプライン、マージ結果パイプライン、マージトレインを有効にするために必要です。 |
external_pull_request_event
| GitHub 上の外部プルリクエストが作成または更新されたとき。 詳細は外部プルリクエスト用のパイプラインを参照してください。 |
parent_pipeline
|
rules の親子パイプラインによってトリガーされるパイプラインの場合、子パイプラインの設定でこれを使用して、親パイプラインによってトリガーされるようにします。
|
使用例。
job:
script: "echo Hello, Rules!"
rules:
- if: '$CI_PIPELINE_SOURCE == "schedule"'
when: manual
allow_failure: true
- if: '$CI_PIPELINE_SOURCE == "push"'
この例では、スケジュールされたパイプラインで手動ジョブとして、または(ブランチやタグへの)プッシュパイプラインで(デフォルトの)when: on_success
を指定して、ジョブを実行します。 他のパイプラインタイプにジョブを追加することはありません。
他の使用例:
job:
script: "echo Hello, Rules!"
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
- if: '$CI_PIPELINE_SOURCE == "schedule"'
この例では、マージリクエストパイプラインおよびスケジュールパイプラインで、 when: on_success
としてジョブを実行します。 他の種類のパイプラインでは実行されません。
if
句で使用するその他の一般的な変数:
-
if: $CI_COMMIT_TAG
: タグに対して変更がプッシュされた場合。 -
if: $CI_COMMIT_BRANCH
: 変更が任意のブランチにプッシュされた場合。 -
if: '$CI_COMMIT_BRANCH == "master":
変更がmaster
にプッシュされた場合。 -
if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH':
変更がデフォルトブランチ(通常はmaster
)にプッシュされた場合。 デフォルトブランチが異なる可能性のある複数のプロジェクトで同じ設定を再利用する場合に便利です。 -
if: '$CI_COMMIT_BRANCH =~ /regex-expression/':
コミットブランチが正規表現にマッチした場合。 -
if: '$CUSTOM_VARIABLE !~ /regex-expression/':
カスタム変数のCUSTOM_VARIABLE
が正規表現と一致しない場合。 -
if: '$CUSTOM_VARIABLE == "value1":
カスタム変数のCUSTOM_VARIABLE
がvalue1
と正確に一致する場合。
rules:changes
パイプラインにジョブを追加するかどうかを判断するために、rules: changes
句で Git プッシュイベントで変更されたファイルを確認します。
rules: changes
は only: changes
や except: changes
と全く同じように動作し、パスの配列を受け付けます。 同様に、Gitプッシュイベントがない場合は常に「true」を返します。 これはブランチパイプラインやマージリクエストパイプラインでのみ使用してください。
使用例。
workflow:
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- changes:
- Dockerfile
when: manual
allow_failure: true
この例では:
-
workflow: rules
は、すべてのジョブのマージリクエストパイプラインのみを許可します。 -
Dockerfile
が変更された場合は、手動ジョブとしてパイプラインに追加し、(allow_failure: true
により)ジョブが起動されていなくてもパイプラインの実行を継続できるようにします。 -
Dockerfileが
変更されていない場合は、(when: never
と同じように)どのパイプラインにもジョブを追加しません。
rules:exists
GitLab 12.4で導入されました。
exists
はパスの配列を受け取り、これらのパスがリポジトリ内にファイルとして存在するかどうかを判定します。
使用例。
job:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- exists:
- Dockerfile
また、グロブパターンを使用して、リポジトリ内の任意のディレクトリにある複数のファイルをマッチさせることもできます。
使用例。
job:
script: bundle exec rspec
rules:
- exists:
- spec/**.rb
exists
の使用は 10000 回のチェックに制限されています。 10000 回目のチェック後、パターン付きのグロブを持つルールは常に「true」と判定されます。
rules:allow_failure
GitLab 12.8 で導入されました。
以下のように allow_failure: true
により、rules:
内であるジョブの失敗を許可したり、手動ジョブがパイプラインの実行を止めないようにできます。 rules:
を使用するすべてのジョブで、allow_failure:
が定義されていない場合のデフォルトは allow_failure: false
です。
ルールレベルの rules:allow_failure
オプションで、ジョブレベルのallow_failure
オプションを上書きでき、特定のルールによってジョブが起動された場合にのみ適用されます。
job:
script: "echo Hello, Rules!"
rules:
- if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master"'
when: manual
allow_failure: true
この例では、最初のルールが一致する場合、ジョブはwhen: manual
とallow_failure: true
を持つことになります。
複雑なルール句
if
句、change
句、exists
句をANDで結合するには、これらを同じルールで使用します。
以下の例をご覧くだい。
-
Dockerfile
またはdocker/scripts/
内のファイルが変更され、かつ$VAR == "string value"
の場合は、手動ジョブが実行されます。 - そうでなければ、ジョブはパイプラインに含まれません。
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
rules:
- if: '$VAR == "string value"'
changes: # Will include the job and set to when:manual if any of the follow paths match a modified file.
- Dockerfile
- docker/scripts/*
when: manual
# - when: never would be redundant here, this is implied any time rules are listed.
現在only
/except
で利用可能なbranches
やrefs
などのキーワードは、その使い方や振る舞いを個別に検討しているため、rules
ではまだ利用できません。 今後のキーワードの改善については、rules
改善のためのエピックで議論されており、誰でも提案やリクエストができるようになっています。
only
/except
(基本)
rules
構文は、ジョブがいつ実行されるべきか、あるいは実行されないべきかを定義するための改良された、より強力な解決方法です。 パイプラインを最大限に活用するために、only/except
ではなく、rules
を使用することを検討してください。only
とexcept
はジョブが作成されるタイミングを制限するためにジョブポリシーを設定する2つのパラメータです。
-
only
は、ジョブが実行されるブランチとタグの名前を定義します。 -
except
は、ジョブが実行されないブランチとタグの名前を定義します。
ジョブポリシーの使い方には、いくつかのルールがあります。
-
only
とexcept
は一緒に使用できます。only
とexcept
の両方がジョブで定義されている場合、参照(ブランチやタグ)はonly
とexcept
でフィルタリングされます。 -
only
とexcept
では、正規表現を使用できます(サポートされている正規表現構文)。 -
only
とexcept
では、リポジトリのパスを指定して、フォーク先でのジョブの実行を制限できます。
また、only
と except
では、以下の特殊なキーワード使用できます。
値 | 説明 |
---|---|
branches
| パイプラインのGit参照がブランチの場合。 |
tags
| パイプラインのGit参照がタグの場合。 |
api
| パイプラインAPIで起動されたパイプラインの場合。 |
external
| GitLab以外のCIサービスを利用する場合。 |
pipelines
|
CI_JOB_TOKEN でAPIを使用して作成したマルチプロジェクトパイプラインの場合。
|
pushes
| ブランチやタグを含む、git push イベントで起動されるパイプラインのためのものです。
|
schedules
| スケジュールパイプラインの場合。 |
triggers
| トリガートークンを使用して作成されたパイプラインの場合。 |
web
| プロジェクトのCI/CD > パイプラインメニューから、GitLab UIのパイプライン実行ボタンを使って作成したパイプラインの場合。 |
merge_requests
| マージリクエストが作成または更新されたときに作成されるパイプライン用です。マージリクエストパイプライン、マージ結果パイプライン、マージトレインを有効にします。 |
external_pull_requests
| GitHub上の外部プルリクエストが作成または更新されたとき(詳細は外部プルリクエスト用のパイプラインを参照してください)。 |
chat
| GitLab ChatOps コマンドを使用して作成したパイプラインの場合。 |
以下の例では、issue-で
始まるブランチに対してのみジョブ
が実行され、それ以外のブランチではスキップされます。
job:
# use regexp
only:
- /^issue-.*$/
# use special keyword
except:
- branches
パターンマッチングはデフォルトで大文字小文字を区別します。 パターンの大文字小文字を区別しないようにするには、/pattern/i
のようにi
フラグ修飾子を使用します。
job:
# use regexp
only:
- /^issue-.*$/i
# use special keyword
except:
- branches
以下の例では、タグがプッシュされた場合、trigger APIでビルドが明示的にリクエストされた場合、スケジュールパイプラインの場合にジョブ
が実行されます。
job:
# use special keywords
only:
- tags
- triggers
- schedules
リポジトリのパスを使用して、親リポジトリに対してのみジョブを実行させ、フォークされたリポジトリに対しては実行させないようにできます。
job:
only:
- branches@gitlab-org/gitlab
except:
- master@gitlab-org/gitlab
- /^release/.*$/@gitlab-org/gitlab
上記の例では、master
と release/
で始まる名前のブランチを除いて、gitlab-org/gitlab
上のすべてのブランチに対してジョブを
実行します。
ジョブがonly
ルールを持っていない場合には、only: ['branches', 'tags']
がデフォルトで設定されます。 except
ルールを持っていない場合には、空の設定になります。
例えば、
job:
script: echo 'test'
は以下のように解釈されます。
job:
script: echo 'test'
only: ['branches', 'tags']
正規表現
@
は参照(ブランチまたはタグ)のリポジトリパスの先頭を示すために使用されるので、正規表現で@
文字を含む参照名にマッチするには、16進数の文字コード\x40
を使用する必要があります
タグやブランチ名だけが正規表現でマッチできます。リポジトリのパスが与えられている場合は、文字列としてのみマッチします。
タグ名やブランチ名に正規表現を使用してマッチさせる場合、参照名の全体が正規表現にマッチする必要があり、正規表現は/
で囲まれていなければなりません(正規表現のフラグは終わりの/
の後ろに追加してください)。そのため、issue-/. */
はissue
-で始まるタグ名やブランチ名にはマッチしません。
^
と$
アンカーを使用できます。例えば、/issue/
だけの場合はsevere-issues
というブランチ名にマッチしますが、(/^issue-.*$/
と同等の)/^issue-/
はマッチしません。
only
/except
でサポートされる正規表現
GitLab 11.9.4から、only
とexcept
で使用されている正規表現を、内部的に RE2で変換するようになりました。
これはRuby正規表現のサブセットのみを利用できることを意味します。RE2では計算の複雑さから利用できる機能が制限されており、否定の先読みのように、GitLab 11.9.4から利用できなくなった機能もあります。
GitLab 11.9.7 から GitLab 12.0 までのバージョンでは、GitLab は管理者が有効にすることができる機能フラグを提供しています。 これにより、以前に許可されていた構文のバージョンとの互換性を保持することができ、ユーザーは新しい構文への移行をスムーズに行うことができます。
Feature.enable(:allow_unsafe_ruby_regexp)
only
/except
(上級)
GitLabは単純な設定と複雑な設定の両方をサポートしているので、配列やハッシュのスキームを利用することができます。
以下の4つのキーが利用可能です。
refs
variables
changes
kubernetes
only
やexcept
で複数のキーを使用した場合、キーは結合された単一式として評価されます。 つまり:
-
only:
は「すべての条件が一致する場合にこのジョブを含める」ことを意味します。 -
except:
は「いずれかの条件が一致する場合はこのジョブを除外する」ことを意味します。
以下のように、only
では、個々のキーは論理的にANDで結合されます。
(any of refs) AND (any of variables) AND (any of changes) AND (if Kubernetes is active)
次の例では、以下のすべてが「true」の場合にのみ
test
ジョブが作成されます。
-
スケジュールされているパイプライン、または
master
で実行されているパイプライン。 -
変数
キーワードがマッチしている。 - プロジェクトの
kubernetes
サービスがアクティブである。
test:
script: npm run test
only:
refs:
- master
- schedules
variables:
- $CI_COMMIT_MESSAGE =~ /run-end-to-end-tests/
kubernetes: active
except
はこの評価式全体の否定として実装されています。
NOT((any of refs) AND (any of variables) AND (any of changes) AND (if Kubernetes is active))
この関係式は、ORを使用して、次のように表現できます。
(any of refs) OR (any of variables) OR (any of changes) OR (if Kubernetes is active)
次の例では、以下のいずれかが「true」の場合、test
ジョブは作成されません。
-
master
で実行されているパイプライン。 - リポジトリのルートにある
README.md
ファイルに変更がされている。
test:
script: npm run test
except:
refs:
- master
changes:
- "README.md"
only:refs
/except:refs
refs
ポリシーは、GitLab 10.0 で導入されました。
refs
キーは、単純なonly/except設定と同じ値を取ることができます。
以下の例では、deploy
ジョブはパイプラインがスケジュールされているか、master
ブランチので実行されている場合にのみ作成されます。
deploy:
only:
refs:
- master
- schedules
only:kubernetes
/except:kubernetes
kubernetes
ポリシーは、GitLab 10.0で導入されました。
kubernetes
キーは、active
キーワードのみを受け付けます。
以下の例では、プロジェクト内でKubernetesサービスがアクティブな場合にのみdeploy
ジョブが作成されます。
deploy:
only:
kubernetes: active
only:variables
/except:variables
variables
ポリシーは、GitLab 10.7 で導入されました。
variables
キーワードは、変数の評価式を定義するために使われます。 つまり、定義済みの変数、プロジェクト変数、グループ変数、環境スコープ変数を使って、GitLabがジョブを作成するかどうかを判断するための評価式を定義することができます。
変数の評価式の使用例:
deploy:
script: cap staging deploy
only:
refs:
- branches
variables:
- $RELEASE == "staging"
- $STAGING
もう1つの使用例では、コミットメッセージによってジョブを除外しています。
end-to-end:
script: rake test:end-to-end
except:
variables:
- $CI_COMMIT_MESSAGE =~ /skip-end-to-end-tests/
変数の評価式の詳細はこちらをご覧ください。
only:changes
/except:changes
changes
ポリシーは、GitLab 11.4 で導入されました。
only
や except
でchanges
キーワードを指定すると、Gitプッシュで変更されたファイルに基づいて、ジョブを作成するかどうかを定義することができます。
つまり、only:changes
ポリシーは、以下のパイプラインの場合に有用です。
$CI_PIPELINE_SOURCE == 'push'
$CI_PIPELINE_SOURCE == 'merge_request_event'
$CI_PIPELINE_SOURCE == 'external_pull_request_event'
上記の3つ以外のソースのパイプラインのように、Gitプッシュイベントがない場合は、指定したファイルが新しいのか古いのか変更
を判断することができず、常に「true」を返します。
以下は、only: changes
を使用した基本的な例です。
docker build:
script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
only:
changes:
- Dockerfile
- docker/scripts/*
- dockerfiles/**/*
- more_scripts/*.{rb,py,sh}
上記のシナリオでは、GitLab の既存のブランチにコミットをプッシュすると、docker build
ジョブが作成されます。ただし、プッシュされたコミットの1つで、以下のファイルのいずれかが変更されている必要があります。
-
Dockerfile
ファイル。 -
docker/scripts/
ディレクトリ内の任意のファイル。 -
dockerfiles
ディレクトリとそのサブディレクトリ内の任意のファイル。 -
more_scripts
ディレクトリ内のrb
、py
、sh
の拡張子を持つファイル。
only:changes
を使用していると、only:merge_requests
も使用していないと望ましくない動作が発生する可能性があります。また、グロブパターンを使って、リポジトリのルートディレクトリやリポジトリ内の_任意の_ディレクトリにある複数のファイルをマッチさせることもできます。しかし、それらを二重引用符で囲まないと、.gitlab-ci.yml
のパースに失敗します。例えば、次のようになります。
test:
script: npm run test
only:
changes:
- "*.json"
- "**/*.sql"
以下の例では、リポジトリのルートディレクトリ内の拡張子が.md
のファイルに変更が検出された場合、build
ジョブをスキップします。
build:
script: npm run build
except:
changes:
- "*.md"
CAUTION:Waring:この機能をマージリクエストパイプラインで使用せず、新しいブランチやタグで使用する際には、注意すべき点がいくつかあります。
マージリクエストパイプラインで only:changes
を使用する
マージリクエストパイプラインを使用すると、マージリクエストで変更されたファイルに基づいて作成されるジョブを定義することができます。
ソースブランチの正しいベースSHAを推論するために、このキーワードを only: [merge_requests]
と組み合わせて使用することをお勧めします。 このようにすると、ファイルの差分がそれ以降のコミットから正しく計算され、マージリクエストのすべての変更がパイプラインで正しくテストされます。
使用例。
docker build service one:
script: docker build -t my-service-one-image:$CI_COMMIT_REF_SLUG .
only:
refs:
- merge_requests
changes:
- Dockerfile
- service-one/**/*
上記のシナリオでは、マージリクエストでservice-one
ディレクトリ内のファイルやDockerfile
ファイルが変更されると、GitLabはdocker build service one
ジョブを実行します。
マージリクエストパイプラインとonly: [change]
を組み合わせても、only: [merge_requests] を
省略した場合は、望ましくない動作が発生する可能性があることに注意してください。
使用例。
docker build service one:
script: docker build -t my-service-one-image:$CI_COMMIT_REF_SLUG .
only:
changes:
- Dockerfile
- service-one/**/*
上の例では、service-one/**/*
内のファイルへの変更が原因でパイプラインが失敗する可能性があります。 その後、このファイルへの変更を含まず、Dockerfile
への変更を含むコミットがプッシュされる可能性がありますが、このパイプラインは Dockerfile
への変更をテストしているだけなので成功する可能性があります。 GitLab は成功した最新のパイプラインをチェックして、まだ修正されていない変更が原因で以前のパイプラインが失敗したにもかかわらず、マージリクエストをマージ可能と表示します。
この設定では、最新のパイプラインが以前のパイプラインで発生した失敗を適切に修正しているかどうかを確認する必要があります。
マージリクエストパイプライン以外で only:changes
を使用する
マージリクエストパイプライン以外では、パイプラインはマージリクエストと関連づけられていないブランチやタグ上で実行されます。この場合、直近の SHA を用いて差分が計算されます。これは git diff HEAD~
と同等です。これは、次のように想定外の動作を引き起こす可能性があります。
- 新しいブランチや新しいタグを GitLab にプッシュする際には、このポリシーは常に「true」と評価されます。
- 新しいコミットをプッシュすると、直近のコミットをベースSHAとして、変更されたファイルが計算されます。
スケジュールパイプラインで only:changes
の使用する
スケジュールパイプラインでは、only:changes
は常に「true」として評価されます。
needs
needs:
キーワードにより、.gitlab-ci.yml
で有効非巡回グラフ(DAG)を実装でき、ジョブの実行順を柔軟にできます。
これにより、いくつかのジョブを他のジョブを待たずに実行することができ、ステージの順番を無視して複数のステージを同時に実行することができます。
次の例を考えてみましょう。
linux:build:
stage: build
mac:build:
stage: build
lint:
stage: test
needs: []
linux:rspec:
stage: test
needs: ["linux:build"]
linux:rubocop:
stage: test
needs: ["linux:build"]
mac:rspec:
stage: test
needs: ["mac:build"]
mac:rubocop:
stage: test
needs: ["mac:build"]
production:
stage: deploy
この例では、4つの実行パスを作成します。
-
Linter:
lint
ジョブはneedsがない(needs: []
)ので、build
ステージが完了するのを待たずにすぐに実行されます。 -
Linuxパス:
linux:rspec
とlinux:rubocop
ジョブは、linux:build
ジョブが終了するとすぐに実行され、mac:build
が終了するのを待たずに実行されます。 -
macOS パス:
mac:rspec
とmac:rubocop
ジョブはmac:build
ジョブが終了するとすぐに実行され、linux:build
が終了するのを待たずに実行されます。 -
production
ジョブは前のジョブが終了するとすぐに実行されます。この場合は、linux:build
、linux:rspec
、linux:rubocop
、mac:build
、mac:rspec
、mac:rubocop
が前のジョブに該当します。
要件と制限
-
needs:
がonly/except
ルールのために作成されていないジョブやそもそも存在しないジョブを指すように設定されている場合は、YAML エラーのパイプラインが作成されます。 -
needs:
配列で1つのジョブが必要とするジョブの最大数は制限されています。- GitLab.com の場合、制限は 10 です。 詳細については、インフラの課題を参照してください。
- セルフマネージド型インスタンスの場合、以下の制限があります。
-
ci_dag_limit_needs
機能フラグが有効な場合(デフォルト)の制限は10です。 -
ci_dag_limit_needs
機能フラグが無効な場合の制限は50です。
-
-
needs
の参照するジョブがparallel:
としてマークされている場合は、そのジョブの実行は、すべての並列ジョブに依存します。 - 前のステージのジョブを使う必要がある点で、
needs:
とdependencies:
は似ています。つまり、循環的な依存関係を作ることはできません。 今のところ、同じステージのジョブに依存できませんが、サポートの予定があります。 - 上記と関連して、キーワード
needs:
を持つまたは参照されるすべてのジョブで、明示的にstageを定義する必要があります。
needs:
ジョブの制限を変更する
needs:
内で定義できる最大ジョブ数のデフォルトは10ですが、フィーチャーフラグを使って50に変更することができます。 50に変更するには、Railsコンソールセッションを起動して、以下を実行します。
Feature::disable(:ci_dag_limit_needs)
10に戻すには、反対に次のコマンドを実行します。
Feature::enable(:ci_dag_limit_needs)
needs:
でアーティファクトのダウンロード
GitLab 12.6 で導入されました。
needs
を使用する場合、アーティファクトのダウンロードは、artifacts: true
(デフォルト)またはartifacts: false
で制御されます。
GitLab 12.6以降、ジョブでアーティファクトのダウンロードを制御するために、dependencies
キーワードとneeds
を組み合わせて使用できません。needs
を使用しないジョブでは、dependencies
は有効なキーワードとして使用できます。
以下の例では、rspec
ジョブではbuild_job
のアーティファクトをダウンロードしますが、rubocop
ジョブではダウンロードしません。
build_job:
stage: build
artifacts:
paths:
- binaries/
rspec:
stage: test
needs:
- job: build_job
artifacts: true
rubocop:
stage: test
needs:
- job: build_job
artifacts: false
さらに以下の3つの構文例のartifacts
は、build_job_1
ではtrue、build_job_2
とbuild_job_3
では両方ともデフォルトのtrueとなります。そのため、rspec
は3つのすべてのビルドジョブ
のアーティファクトをダウンロードします。
rspec:
needs:
- job: build_job_1
artifacts: true
- job: build_job_2
- build_job_3
needs
を使用してクロスプロジェクトのアーティファクトをダウンロード
GitLab 12.7 で導入されました。
needs
は、同じプロジェクト内の他の参照(ブランチまたはタグ)、または異なるプロジェクトのパイプラインの最大5つのジョブからアーティファクトをダウンロードするために使用することができます。
build_job:
stage: build
script:
- ls -lhR
needs:
- project: group/project-name
job: build-1
ref: master
artifacts: true
build_job
は、group/project-name
プロジェクトのmaster
ブランチにある最新の成功したbuild-1
ジョブからアーティファクトをダウンロードします。
同一プロジェクト内のパイプライン間でのアーティファクトのダウンロード
needs
は、project
キーワードとして現在のプロジェクトを指定することで、現在のプロジェクトの他のパイプラインのアーティファクトをダウンロードするために使用できます。また、ダウンロード先の参照を指定することもできます。次の例では、build_job
は、最新の成功したbuild-1
ジョブのアーティファクトを、other-ref
を指定してダウンロードします。
build_job:
stage: build
script:
- ls -lhR
needs:
- project: group/same-project-name
job: build-1
ref: other-ref
artifacts: true
parallel:
で実行されているジョブからのアーティファクトのダウンロードはサポートされていません。
tags
tags
は、このプロジェクトの利用可能なすべてのRunnerから特定のRunnerを選択するために使用されます。
Runnerを登録する際に、Runnerのタグを指定することができます。
tags
を使用すると、指定されたタグが割り当てられたRunnerでジョブを実行することができます。
job:
tags:
- ruby
- postgres
上記の設定では、ruby
とpostgres
の両方のタグが定義されているRunnerによってジョブ
がビルドされます。
タグは、複数のプラットフォームで異なるジョブを実行するためにも使用できます。例えば、OS X Runnerに osx
というタグを付け、Windows Runnerにwindows
というタグを付けた場合、以下のようなジョブがそれぞれのプラットフォーム上で実行されます。
windows job:
stage:
- build
tags:
- windows
script:
- echo Hello, %USERNAME%!
osx job:
stage:
- build
tags:
- osx
script:
- echo "Hello, $USER!"
allow_failure
allow_failure
を使用すると、ジョブの失敗がパイプラインの他の部分に影響しないようにできます。when: manual
構文を使用する手動ジョブを除いて、allow_failureのデフォルト値はfalse
です。rules
構文で使用する場合は、when: manual
ジョブを含めて、allow_failureのデフォルト値はfaseです。
allow_failureを有効にしてジョブが失敗した場合、ジョブはUI上でオレンジ色の警告を表示しますが、パイプラインの論理フローはジョブが成功したとみなし、ブロックされません。
他のすべてのジョブが成功したと仮定すると、ジョブのステージとそのパイプラインは同じオレンジ色の警告を表示します。 しかし、関連するコミットは警告なしで「成功」とマークされます。
以下の例では、job1
とjob2
は並列に実行されます。job1
はallow_failure: true
とマークされているため、たとえ失敗しても、次のステージの実行が停止することはありません。
job1:
stage: test
script:
- execute_script_that_will_fail
allow_failure: true
job2:
stage: test
script:
- execute_script_that_will_succeed
job3:
stage: deploy
script:
- deploy_to_staging
when
when
はジョブが失敗した場合や失敗したにもかかわらず実行されるジョブを制御するために使用されます。
when
は、以下のいずれかの値を設定することができます。
-
on_success
- 前のステージのすべてのジョブが成功した(あるいは、allow_failure
とマークされているため成功したとみなされる)場合にのみジョブを実行します 。 これがデフォルトです。 -
on_failure
- 前のステージの少なくとも1つのジョブが失敗した場合にのみジョブを実行します。 -
always
- 前のステージのジョブのステータスと関係なくジョブを実行します。 -
manual
- ジョブを手動で実行します (GitLab 8.10 で追加されました)。 詳細は、以下のマニュアルアクションを参照してください。 -
delayed
- 一定期間後にジョブを実行します (GitLab 11.14 で追加されました)。詳細は、以下の遅延アクションを参照してください。
使用例。
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
cleanup_job:
stage: cleanup
script:
- cleanup after jobs
when: always
上記のスクリプトは:
-
build_job
が失敗した場合のみ、cleanup_build_job
を実行します。 - 成功・失敗に関わらず、常にパイプラインの最後のステップとして
cleanup_job
を実行します。 - GitLabのUIから
deploy_job
を手動で実行できるようにします。
when:manual
- GitLab 8.10 で導入されました。
- 手動アクションのブロッキングがGitLab 9.0で導入されました。
- 保護アクションがGitLab 9.2で導入されました。
手動アクションは、自動的に実行されるのではなく、ユーザーが明示的に起動する必要がある特殊なタイプのジョブです。 手動アクションの使用例としては、本番環境へのデプロイが挙げられます。 手動アクションは、パイプライン、ジョブ、環境、デプロイの各画面から起動することができます。 詳細については、環境のドキュメントを参照してください。
手動アクションの動作として、オプションとブロックがあります。 手動アクションをブロックすると、そのアクションが定義されたステージでパイプラインの実行がブロックされます。 ブロックされた手動アクションを実行した人が_Play_ボタンをクリックすると、パイプラインの実行を再開することができます。
パイプラインがブロックされていると、「パイプラインが成功した時にマージ」が設定されている場合はマージされません。 ブロックされたパイプラインには _manual_と呼ばれる特別なステータスを持ちます。 when:manual
構文を使用すると、手動アクションはデフォルトではブロックしない動作になります。 手動アクションをブロッキする動作にしたい場合は、.gitlab-ci.yml
でジョブの定義にallow_failure: false
を追加する必要があります。
オプションの手動アクションはデフォルトで allow_failure: true
が設定されており、その成否はパイプライン全体のステータスには寄与しません。 つまり、たとえ手動アクションが失敗しても、パイプラインは成功と判定されます。
手動アクションは書き込みアクションとみなされるので、ユーザーがアクションを起動する際は、保護ブランチのパーミッションが使用されます。言い換えると、パイプラインの手動アクションを起動するには、そのブランチをマージする権限が必要です。保護環境を利用して、不正なユーザーによって実行されないように、より厳密に手動デプロイを保護することが可能です。
when:manual
と trigger
を一緒に使用すると、jobs:#{job-name} when
should be on_success, on_failure or always
というエラーになります。これは、when:manual
はtriggerの使用を妨げるためです。手動ジョブを保護する
保護環境を使用して、手動ジョブの実行を許可されたユーザーを定義することができます。 保護環境に関連付けられたユーザーのみが手動ジョブを実行することを許可することで、以下のようないくつかの特別なユースケースを実装することが可能です。
- より正確に誰が環境にデプロイできるかを制限します。
- 承認されたユーザーが「承認」するまでパイプラインをブロックできるようにします。
このためには:
-
ジョブに
environment
を追加します。 例えば:deploy_prod: stage: deploy script: - echo "Deploy to production server" environment: name: production url: https://example.com when: manual only: - master
-
保護環境の設定で、環境(上の例では
production
環境) を選択し、手動ジョブの実行を許可するユーザー、ロール、グループを Allowed to Deploy リストに追加します。 このリストに含まれるユーザーのみが手動ジョブを実行することができます。
さらに、allow_failure: false
を追加してブロックする手動ジョブとして定義した場合、手動ジョブが実行されるまでパイプラインの次のステージは実行されません。 これは、ブロックする手動ジョブを実行することで、後のパイプラインステージの実行を「承認」することを許可されたユーザーのリストを定義するために使用できます。
when:delayed
GitLab 11.4で導入されました。
遅延ジョブは、一定期間後にスクリプトを実行するためのものです。これは、すぐにジョブが実行待ち
状態になるのを避けたい場合に便利です。
start_in
キーで期間を設定できます。start_in
キーの値は、単位が指定されていない限り、経過時間を秒単位で表します。start_inキーは1週間以内でなければなりません。有効な値の例としては、以下のようなものがあります。
'5'
10 seconds
30 minutes
1 day
1 week
ステージ内に遅延ジョブがある場合、遅延ジョブが終了するまでパイプラインは進行しません。つまり、このキーワードは、異なるステージ間に遅延を挿入する場合にも使用できます。
遅延ジョブのタイマーは、前のステージが終了した直後に開始されます。 他のタイプのジョブと同様に、遅延ジョブのタイマーは前のステージが成功しない限り開始しません。
次の例では、前のステージが完了してから30分後に実行されるtimed rollout 10%
という名前のジョブを作成します。
timed rollout 10%:
stage: deploy
script: echo 'Rolling out 10% ...'
when: delayed
start_in: 30 minutes
(Unschedule) ボタンをクリックすることで、遅延ジョブのタイマーを停止することができます。 このジョブは、手動でジョブを実行しない限り実行されることはありません。
Playボタンをクリックすると、遅延ジョブをすぐに開始することができます。GitLab Runnerがすぐにジョブをピックアップして、ジョブを開始します。
environment
- GitLab 8.9 で導入されました。
- 環境についてのドキュメントでは、環境についての詳細と、多くの例を見つけることができます。
environment
は、特定の環境にデプロイするためのジョブを定義するために使用されます。
envitonment
が指定され、その名前の環境が存在しない場合、自動的に新しい環境が作成されます。
environmnet
キーワードを定義する、最も単純な例は次のようなものです。
deploy to production:
stage: deploy
script: git push production HEAD:master
environment: production
上記の例では、deploy to production
ジョブはproduction
環境へデプロイするためのジョブとしてマークされます。
environment:name
- GitLab 8.11 で導入されました。
- GitLab 8.11 より前のバージョンでは、環境名は
environment: production
のような文字列で定義することができました。 現在は、name
キーワードで定義することが推奨されています。name
パラメータは、定義されたCI変数のいずれかを使用することができます。事前定義済み変数、セキュア変数、.gitlab-ci.yml
のvariables
などがあります。しかし、script
で定義された変数を使うことはできません。
environment
の名前には以下を使用できます:
- 半角英字
- 半角数字
- スペース
-
_
/
$
{
}
一般的な名前は、qa
、staging
、production
ですが、ワークフローに適した任意の名前を使用することができます。
environment
キーワードの直後に環境名を定義するのではなく、別の値として定義することも可能です。 その場合は、environment
の下にある name
キーワードを使用します。
deploy to production:
stage: deploy
script: git push production HEAD:master
environment:
name: production
environment:url
- GitLab 8.11 で導入されました。
- GitLab 8.11以前はGitLabのUIでのみURLを追加することができましたが、現在は
.gitlab-ci.yml
で定義することが推奨されています。url
パラメータは、定義されたCI変数のいずれかを使用することができます。事前定義済み変数、セキュア変数、.gitlab-ci.yml
のvariables
などがあります。しかし、script
で定義された変数を使うことはできません。
これはオプションの値で、設定すると GitLab のさまざまな場所にボタンが表示され、クリックすると定義された URL に移動します。
以下の例では、ジョブが正常に終了すると、マージリクエストと環境/デプロイメントページに https://prod.example.com
を指すボタンが作成されます。
deploy to production:
stage: deploy
script: git push production HEAD:master
environment:
name: production
url: https://prod.example.com
environment:on_stop
- GitLab 8.13 で導入されました。
- GitLab 8.14 以降では、ストップアクションが定義されている環境では、関連するブランチが削除されたときに自動的にストップアクションが実行されます。
環境を閉じる (停止する) には、environment
の下で定義されている on_stop
キーワードを使用します。 これは、環境を閉じるために実行する別のジョブを宣言します。
例としてenvironment:action
のセクションを参照してください。
environment:action
GitLab 8.13 で導入されました。
action
キーワードは on_stop
と一緒に使用され、環境を閉じるために呼び出されるジョブで定義されます。
使用例:
review_app:
stage: deploy
script: make deploy-app
environment:
name: review/$CI_COMMIT_REF_NAME
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_NAME
action: stop
上記の例では、review
環境にデプロイするために review_app
ジョブを定義し、on_stop
の下に stop_review_app
ジョブを定義しました。
review_app
ジョブが正常に終了すると、when
で定義した設定に基づいて stop_review_app
ジョブを起動します。この場合はmanual
に設定しているので、実行するにはGitLabのWeb UIからの手動操作が必要になります。
また、この例では、GIT_STRATEGY
を none
に設定しています。これにより、ブランチの削除後にstop_review_appjob
が自動的に開始されたときに、 GitLab Runner がコードをチェックアウトしようとしないようにしています。
GIT_STRATEGY
を設定する際にアンカー変数を使用することで、グローバル変数を上書きせずに変更することができます。stop_review_app
ジョブのは、以下のキーワードが定義されている必要があります。
-
when
- 参照 environment:name
environment:action
さらに、両方のジョブは rules
または only/except
の設定を一致させる必要がありあます。上の例で、設定が一致していない場合は、review_app
ジョブを含むパイプラインにstop_review_app
ジョブが含まれていない可能性があります。その場合は、環境を自動的に停止させるためにaction: stop
を開始できません。
environment:auto_stop_in
GitLab 12.8 で導入されました。
auto_stop_in
キーワードは、環境の有効期限を指定するためのキーワードで、期限が切れるとGitLabが自動的に環境を停止します。
例えば、
review_app:
script: deploy-review-app
environment:
name: review/$CI_COMMIT_REF_NAME
auto_stop_in: 1 day
review_app
ジョブを実行してレビューアプリを作成した場合、環境の有効期限は1日
に設定されます。
詳細については、環境の自動停止に関するドキュメントを参照してください。
environment:kubernetes
GitLab 12.6 で導入されました。
kubernetes
ブロックは、プロジェクトに関連付けられたKubernetesクラスタへのデプロイを設定するために使用されます。
使用例。
deploy:
stage: deploy
script: make deploy-app
environment:
name: production
kubernetes:
namespace: production
これは、production
というKubernetesの名前空間を使用して、production
環境にデプロイするためのdeploy
ジョブを設定します。
詳細については、「Kubernetes
で利用可能な設定」を参照してください。
動的な環境
使用例。
deploy as review app:
stage: deploy
script: make deploy
environment:
name: review/$CI_COMMIT_REF_NAME
url: https://$CI_ENVIRONMENT_SLUG.example.com/
Deploy as revew app
ジョブは、review/$CI_COMMIT_REF_NAME
という名前の環境を動的に作成します。この$CI_COMMIT_REF_NAME
はRunnerによって設定される環境変数です。また、環境名に基づいて設定される、$CI_ENVIRONMENT_SLUG
変数は、URLに含めるのに適しています。 例えば、レビューアプリのデプロイが pow
という名前のブランチで実行された場合、この環境には https://review-pow.example.com/
のような URL でアクセスできます。
もちろん、これはアプリケーションをホストするサーバが適切に設定されていることが前提となります。
一般的なユースケースは、ブランチごとに動的な環境を作成して、それをレビューアプリとして使用することです。レビューアプリを使用した簡単な例は、以下で見ることができます。https://gitlab.com/gitlab-examples/review-apps-nginx/
cache
- GitLab Runner v0.7.0 で導入されました。
cache
はグローバルにもジョブごとにも設定できます。- GitLab 9.0 からは、デフォルトでパイプラインとジョブ間でキャッシュが有効になり、共有されるようになりました。
- GitLab 9.2からは、アーティファクトより先にキャッシュが復元されるようになりました。
cache
は、ジョブ間でキャッシュする、ファイルとディレクトリのリストを指定するために使用します。ローカルの作業コピーのパスのみを使用できます。
cache
が特定のジョブの外側で定義されている場合、それはグローバルに設定されていることを意味し、すべてのジョブでそのキャッシュを使用できます。
cache:paths
キャッシュするファイルやディレクトリを指定するには、paths
ディレクティブを使用します。パスはプロジェクトディレクトリ($CI_PROJECT_DIR
) からの相対パスで指定してください。以下のように、ワイルドカードのグロブパターンを使用できます。
-
GitLab Runner 13.0 以降では、
doublestar.Glob
を使用できます。 - GitLab Runner 12.10 以前のバージョンでは、
filepath.Math
を使用できます。
以下の例では、binaries
フォルダの.apk
で終わるファイルと.config
というファイルをキャッシュします。
rspec:
script: test
cache:
paths:
- binaries/*.apk
- .config
ジョブで定義したキャッシュはグローバルで定義したキャッシュを上書きします。 以下のrspec
ジョブでは、binaries/
フォルダのみをキャッシュします。
cache:
paths:
- my/files
rspec:
script: test
cache:
key: rspec
paths:
- binaries/
キャッシュは異なるジョブ間で共有されるので、想定しない内容でキャッシュが上書きされる可能性があります。異なるcache:keyを設定することで、ジョブごとに異なるキャッシュを持つことができます。
cache:key
GitLab Runner v1.0.0 で導入されました。
キャッシュはジョブ間で共有されるので、異なるジョブで異なるパスをキャッシュする場合は、異なるcache:key
を設定する必要があります。そうでない場合は、想定しない内容でキャッシュが上書きされる可能性があります。
key
ディレクティブを使用すると、ジョブ間のキャッシュの範囲を定義できます。つまり、すべてのジョブで単一のキャッシュ、ジョブごとに異なるキャッシュ、ブランチごとに異なるキャッシュなど、ワークフローに合わせた方法で柔軟にファイルをキャッシュできます。
cache:key
として、すべての定義済み変数を使用できます。設定されていない場合のデフォルト値は、文字列のdefault
になります。つまり、すべてのジョブ間でキャッシュが共有されます。
cache:key
には /
やそれをURIエンコードした %2F
を含めることはできません。また、ドットのみ(.
、%2E
)の値も禁止されています。以下は、ブランチごとのキャッシュを有効にする例です。
cache:
key: "$CI_COMMIT_REF_SLUG"
paths:
- binaries/
Windows バッチファイルでシェルスクリプトを実行する場合は、以下のように$
を%
で置き換えてください。
cache:
key: "%CI_COMMIT_REF_SLUG%"
paths:
- binaries/
cache:key:files
GitLab v12.5 で導入されました。
cache:key:files
キーワードは、cache:key
の機能を拡張し、いくつかのケースでキャッシュの再利用を容易にします。これにより、再ビルドの頻度を減らすことができ 、後続のパイプラインランを高速化します。
cache:key:files
を使用するには、キャッシュキーを生成するために使用するファイルを指定しなければなりません。
キャッシュkey
は、指定したファイルを変更した直近のコミットから計算された SHA チェックサムになります (2 つのファイルがリストアップされている場合は最大 2 つまで)。どちらのファイルもコミットで変更されていない場合の、フォールバックキーはdefault
です。
cache:
key:
files:
- Gemfile.lock
- package.json
paths:
- vendor/ruby
- node_modules
この例では、Gemfile.lock
と package.json
ファイルに関連付けられた Ruby と Node.js の依存関係のキャッシュを作成しています。これらのファイルが変更されるたびに、新しいキャッシュキーが計算され、新しいキャッシュが作成されます。つまり、cache:key:files
で同じ Gemfile.lock
と package.json
を指定して実行するジョブには、同じキャッシュが使用されます。
cache:key:prefix
GitLab v12.5 で導入されました。
prefix
を使用すると、指定のプレフィックス
と cache:key:files
で計算された SHA を組み合わせてキャッシュキーを構成できます。
例えば test
というプレフィックス
を追加すると、 test-feef9576d21ee9b6a32e30c5c79d0a0ceb68d1e5
のようなキャッシュキーになります。
指定したファイルがコミットで変更されていない場合のキャッシュキーは、プレフィックスにdefault
を追加したものになります。この例では test-default
になります。
cache:key
と同様に、prefix
は任意の定義済み変数を使用することができますが、以下を使用できません。
-
/
(またはそれをURIエンコードした%2F
) -
.
のみ (またはそれをURIエンコードした%2E
)
cache:
key:
files:
- Gemfile.lock
prefix: ${CI_JOB_NAME}
paths:
- vendor/ruby
rspec:
script:
- bundle exec rspec
例えば、$CI_JOB_NAME
というプレフィックス
を追加すると、キャッシュキーはrspec-feef9576d21ee9b6a32e30c5c79d0a0ceb68d1e5
のようになります。そしてジョブキャッシュは異なるブランチ間で共有されます。ブランチで Gemfile.lock
を変更した場合、そのブランチの cache:key:files
は別の SHA チェックサムを持つようになります。その結果、新しいキャッシュキーが生成され、そのキー用の新しいキャッシュが作成されます。Gemfile.lock
が見つからない場合は、default
というキーにプレフィックスが追加されるので、この例のキーは rspec-default
になります。
cache:untracked
untracked: true
に設定すると、Gitで追跡されていないファイルをすべてキャッシュします。
rspec:
script: test
cache:
untracked: true
以下は、Git で追跡されていないファイルとbinaries
内のファイルをすべてキャッシュする例です。
rspec:
script: test
cache:
untracked: true
paths:
- binaries/
cache:policy
GitLab 9.4 で導入されました。
キャッシュ処理のデフォルトの動作は、ジョブの開始時にファイルをダウンロードし、終了時に再アップロードすることです。 これにより、ジョブによって行われた変更を将来の実行で再利用することができます。これは、pull-push
キャッシュポリシーと呼ばれます。
ジョブがキャッシュファイルを変更しないことが分かっている場合は、そのジョブでpolicy: pull
を使用することでアップロードをスキップすることができます。 一般的に、キャッシュを確実に更新するために、より早いステージで通常のキャッシュジョブを使用します。
stages:
- setup
- test
prepare:
stage: setup
cache:
key: gems
paths:
- vendor/bundle
script:
- bundle install --deployment
rspec:
stage: test
cache:
key: gems
paths:
- vendor/bundle
policy: pull
script:
- bundle exec rspec ...
これにより、特に多数のキャッシュを使用するジョブが並列に実行されている場合には、ジョブの実行を高速化し、キャッシュサーバの負荷を軽減することができます。
さらに、以前のコンテンツを参照せずに無条件にキャッシュを再作成するジョブがある場合は、そのジョブで policy: push
を使用してダウンロードをスキップすることができます。
artifacts
- Windows以外のGitLab Runner v0.7.0 で導入されました。
- GitLab Runner v.1.0.0でWindowsに対応しました。
- GitLab 9.2からは、アーティファクトの前にキャッシュが復元されるようになりました。
- すべてのExecutorに対応しているわけではありません。
- ジョブのアーティファクトは、デフォルトでは成功したジョブに対してのみ収集されます。
artifacts
は、ジョブがsuccess、failure、alwaysの場合に、そのジョブに添付するファイルとディレクトリのリストを指定するために使用します。
ジョブの終了後、アーティファクトはGitLabに送られ、UIからダウンロードできます。
artifacts:paths
パスにはプロジェクトディレクトリ($CI_PROJECT_DIR
) からの相対パスを使用し、直接外部にリンクできません。 globパターンと filepath.Match
をワイルドカードとして使用できます。
アーティファクトを取得できるジョブを制限するには、dependenciesを参照してください。
binaries
内のすべてのファイルと.config
ファイルをアーティファクトとして送信する例:
artifacts:
paths:
- binaries/
- .config
他のジョブでのアーティファクトの取得を無効にするには、dependenciesを空にして定義します。
job:
stage: build
script: make build
dependencies: []
一時的なビルドのアーティファクトでビルドサーバーのストレージがいっぱいにならないように、タグ付けされたリリースだけでアーティファクトを作成したい場合があります。
以下は、タグに対してのみアーティファクトを作成する(default-job
ではアーティファクトを作成しない)例です。
default-job:
script:
- mvn test -U
except:
- tags
release-job:
script:
- mvn package -U
artifacts:
paths:
- target/*.war
only:
- tags
ディレクトリにもワイルドカードを使用することができます。 以下は、xyz
で終わるディレクトリ内のすべてのファイルをアーティファクトに指定する例です。
job:
artifacts:
paths:
- path/*xyz/*
artifacts:exclude
- GitLab 13.1 で導入されました。
- GitLab Runner 13.1 が必要です。
exclude
を使用すると、ファイルがアーティファクトに追加されないようにできます。
artifacts:paths
と同様に、 exclude
パスはプロジェクトディレクトリからの相対パスです。ワイルドカードは、globパターンと filepath.Match
に従ったものを使うことができます。
拡張子が*.o
のファイルを除く、binaries/
以下のすべてのファイルを保存する例:
artifacts:
paths:
- binaries/
exclude:
- binaries/**/*.o
artifacts:untracked
でマッチしたファイルを、artifacts:exclude
を使って除外することもできます。
artifacts:expose_as
GitLab 12.5で導入されました。
expose_as
キーワードを使用すると、マージリクエスト 画面でジョブのアーティファクトを公開することができます。
1つのファイルにマッチする例:
test:
script: [ "echo 'test' > file.txt" ]
artifacts:
expose_as: 'artifact 1'
paths: ['file.txt']
この設定では、GitLabは file.txt
を指すartifact 1というリンクをマージリクエストに追加します。
ディレクトリ全体にマッチする例:
test:
script: [ "mkdir test && echo 'test' > test/file.txt" ]
artifacts:
expose_as: 'artifact 1'
paths: ['test/']
以下に注意してください。
- 変数を使用して
artifacts:path
を定義すると、マージリクエスト画面にアーティファクトが表示されません。 - マージリクエストごとに公開できるアーティファクトは最大10個です。
- Globパターンはサポートされていません。
- ディレクトリが指定された場合で、ディレクトリ内に複数のファイルがある場合は、ジョブアーティファクトブラウザへのリンクとなります。
-
.html
、.htm
、.txt
、.json
、.xml
、.log
という拡張子の単一ファイルをアーティファクトとして公開し、GitLab Pagesが:- 有効な場合、GitLab Pagesでファイルを表示します。
- 無効な場合、アーティファクトブラウザでファイルを表示します。
artifacts:name
Introduced in GitLab 8.6 and GitLab Runner v1.1.0.
The name
directive allows you to define the name of the created artifacts
archive. That way, you can have a unique name for every archive which could be
useful when you’d like to download the archive from GitLab. The artifacts:name
variable can make use of any of the predefined variables.
The default name is artifacts
, which becomes artifacts.zip
when downloaded.
feature/my-feature
) it’s advised to use $CI_COMMIT_REF_SLUG
instead of $CI_COMMIT_REF_NAME
for proper naming of the artifact.To create an archive with a name of the current job:
job:
artifacts:
name: "$CI_JOB_NAME"
paths:
- binaries/
To create an archive with a name of the current branch or tag including only the binaries directory:
job:
artifacts:
name: "$CI_COMMIT_REF_NAME"
paths:
- binaries/
To create an archive with a name of the current job and the current branch or tag including only the binaries directory:
job:
artifacts:
name: "$CI_JOB_NAME-$CI_COMMIT_REF_NAME"
paths:
- binaries/
To create an archive with a name of the current stage and branch name:
job:
artifacts:
name: "$CI_JOB_STAGE-$CI_COMMIT_REF_NAME"
paths:
- binaries/
Windows バッチファイルでシェルスクリプトを実行する場合は、以下のように$
を%
で置き換えてください。
job:
artifacts:
name: "%CI_JOB_STAGE%-%CI_COMMIT_REF_NAME%"
paths:
- binaries/
If you use Windows PowerShell to run your shell scripts you need to replace
$
with $env:
:
job:
artifacts:
name: "$env:CI_JOB_STAGE-$env:CI_COMMIT_REF_NAME"
paths:
- binaries/
artifacts:untracked
artifacts:untracked
is used to add all Git untracked files as artifacts (along
to the paths defined in artifacts:paths
).
artifacts:untracked
ignores configuration in the repository’s .gitignore
file.Send all Git untracked files:
artifacts:
untracked: true
Send all Git untracked files and files in binaries
:
artifacts:
untracked: true
paths:
- binaries/
Send all untracked files but exclude *.txt
:
artifacts:
untracked: true
exclude:
- *.txt
artifacts:when
Introduced in GitLab 8.9 and GitLab Runner v1.3.0.
artifacts:when
is used to upload artifacts on job failure or despite the
failure.
artifacts:when
can be set to one of the following values:
-
on_success
- upload artifacts only when the job succeeds. This is the default. -
on_failure
- upload artifacts only when the job fails. -
always
- upload artifacts regardless of the job status.
To upload artifacts only when job fails:
job:
artifacts:
when: on_failure
artifacts:expire_in
Introduced in GitLab 8.9 and GitLab Runner v1.3.0.
expire_in
allows you to specify how long artifacts should live before they
expire and are therefore deleted, counting from the time they are uploaded and
stored on GitLab. If the expiry time is not defined, it defaults to the
instance wide setting
(30 days by default).
You can use the Keep button on the job page to override expiration and keep artifacts forever.
After their expiry, artifacts are deleted hourly by default (via a cron job), and are not accessible anymore.
The value of expire_in
is an elapsed time in seconds, unless a unit is
provided. Examples of valid values:
42
3 mins 4 sec
2 hrs 20 min
2h20min
6 mos 1 day
47 yrs 6 mos and 4d
3 weeks and 2 days
To expire artifacts 1 week after being uploaded:
job:
artifacts:
expire_in: 1 week
:keep_latest_artifact_for_ref
and :destroy_only_unlocked_expired_artifacts
feature flags.
artifacts:reports
The artifacts:reports
keyword
is used for collecting test reports, code quality reports, and security reports from jobs.
It also exposes these reports in GitLab’s UI (merge requests, pipeline views, and security dashboards).
These are the available report types:
Parameter | 説明 |
---|---|
artifacts:reports:junit
| The junit report collects JUnit XML files.
|
artifacts:reports:dotenv
| The dotenv report collects a set of environment variables.
|
artifacts:reports:cobertura
| The cobertura report collects Cobertura coverage XML files.
|
artifacts:reports:terraform
| The terraform report collects Terraform tfplan.json files.
|
artifacts:reports:codequality
| The codequality report collects CodeQuality issues.
|
artifacts:reports:sast
| The sast report collects Static Application Security Testing vulnerabilities.
|
artifacts:reports:dependency_scanning
| The dependency_scanning report collects Dependency Scanning vulnerabilities.
|
artifacts:reports:container_scanning
| The container_scanning report collects Container Scanning vulnerabilities.
|
artifacts:reports:dast
| The dast report collects Dynamic Application Security Testing vulnerabilities.
|
artifacts:reports:license_management
| The license_management report collects Licenses (removed from GitLab 13.0).
|
artifacts:reports:license_scanning
| The license_scanning report collects Licenses.
|
artifacts:reports:performance
| The performance report collects Browser Performance metrics.
|
artifacts:reports:load_performance
| The load_performance report collects load performance metrics.
|
artifacts:reports:metrics
| The metrics report collects Metrics.
|
dependencies
Introduced in GitLab 8.6 and GitLab Runner v1.1.1.
By default, all artifacts
from all previous stages
are passed, but you can use the dependencies
parameter to define a limited
list of jobs (or no jobs) to fetch artifacts from.
To use this feature, define dependencies
in context of the job and pass
a list of all previous jobs from which the artifacts should be downloaded.
You can only define jobs from stages that are executed before the current one.
An error will be shown if you define jobs from the current stage or next ones.
Defining an empty array will skip downloading any artifacts for that job.
The status of the previous job is not considered when using dependencies
, so
if it failed or it’s a manual job that was not run, no error occurs.
In the following example, we define two jobs with artifacts, build:osx
and
build:linux
. When the test:osx
is executed, the artifacts from build:osx
will be downloaded and extracted in the context of the build. The same happens
for test:linux
and artifacts from build:linux
.
The job deploy
will download artifacts from all previous jobs because of
the stage precedence:
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
When a dependent job will fail
Introduced in GitLab 10.3.
If the artifacts of the job that is set as a dependency have been expired or erased, then the dependent job will fail.
coverage
Introduced in GitLab 8.17.
coverage
allows you to configure how code coverage will be extracted from the
job output.
Regular expressions are the only valid kind of value expected here. So, using
surrounding /
is mandatory in order to consistently and explicitly represent
a regular expression string. You must escape special characters if you want to
match them literally.
A simple example:
job1:
script: rspec
coverage: '/Code coverage: \d+\.\d+/'
retry
- Introduced in GitLab 9.5.
- Behavior expanded in GitLab 11.5 to control on which failures to retry.
retry
allows you to configure how many times a job is going to be retried in
case of a failure.
When a job fails and has retry
configured, it’s going to be processed again
up to the amount of times specified by the retry
keyword.
If retry
is set to 2, and a job succeeds in a second run (first retry), it won’t be retried
again. retry
value has to be a positive integer, equal or larger than 0, but
lower or equal to 2 (two retries maximum, three runs in total).
A simple example to retry in all failure cases:
test:
script: rspec
retry: 2
By default, a job will be retried on all failure cases. To have a better control
on which failures to retry, retry
can be a hash with the following keys:
-
max
: The maximum number of retries. -
when
: The failure cases to retry.
To retry only runner system failures at maximum two times:
test:
script: rspec
retry:
max: 2
when: runner_system_failure
If there is another failure, other than a runner system failure, the job will not be retried.
To retry on multiple failure cases, when
can also be an array of failures:
test:
script: rspec
retry:
max: 2
when:
- runner_system_failure
- stuck_or_timeout_failure
Possible values for when
are:
-
always
: Retry on any failure (default). -
unknown_failure
: Retry when the failure reason is unknown. -
script_failure
: Retry when the script failed. -
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 was a runner system failure (for example, job setup failed). -
missing_dependency_failure
: Retry if a dependency was missing. -
runner_unsupported
: Retry if the runner was 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 was a structural integrity problem detected.
You can specify the number of retry attempts for certain stages of job execution using variables.
timeout
GitLab 12.3 で導入されました。
timeout
allows you to configure a timeout for a specific job. For example:
build:
script: build.sh
timeout: 3 hours 30 minutes
test:
script: rspec
timeout: 3h 30m
The job-level timeout can exceed the project-level timeout but can’t exceed the Runner-specific timeout.
parallel
Introduced in GitLab 11.5.
parallel
allows you to configure how many instances of a job to run in
parallel. This value has to be greater than or equal to two (2) and less than or equal to 50.
This creates N instances of the same job that run in parallel. They are named
sequentially from job_name 1/N
to job_name N/N
.
For every job, CI_NODE_INDEX
and CI_NODE_TOTAL
environment variables are set.
Marking a job to be run in parallel requires adding parallel
to your configuration
file. For example:
test:
script: rspec
parallel: 5
A simple example using Semaphore Test Boosters and RSpec to run some Ruby tests:
# Gemfile
source 'https://rubygems.org'
gem 'rspec'
gem 'semaphore_test_boosters'
test:
parallel: 3
script:
- bundle
- bundle exec rspec_booster --job $CI_NODE_INDEX/$CI_NODE_TOTAL
You can then navigate to the Jobs tab of a new pipeline build and see your RSpec job split into three separate jobs.
trigger
- Introduced in GitLab Premium 11.8.
- Moved to GitLab Core in 12.8.
trigger
allows you to define downstream pipeline trigger. When a job created
from trigger
definition is started by GitLab, a downstream pipeline gets
created.
This keyword allows the creation of two different types of downstream pipelines:
trigger
with when:manual
together results in the error jobs:#{job-name}
when should be on_success, on_failure or always
, because when:manual
prevents
triggers being used.Simple trigger
syntax for multi-project pipelines
The simplest way to configure a downstream trigger is to use trigger
keyword
with a full path to a downstream project:
rspec:
stage: test
script: bundle exec rspec
staging:
stage: deploy
trigger: my/deployment
Complex trigger
syntax for multi-project pipelines
It’s possible to configure a branch name that GitLab will use to create a downstream pipeline with:
rspec:
stage: test
script: bundle exec rspec
staging:
stage: deploy
trigger:
project: my/deployment
branch: stable
It’s possible to mirror the status from a triggered pipeline:
trigger_job:
trigger:
project: my/project
strategy: depend
It’s possible to mirror the status from an upstream pipeline:
upstream_bridge:
stage: test
needs:
pipeline: other/project
trigger
syntax for child pipeline
GitLab 12.7で導入されました。
To create a child pipeline, specify the path to the YAML file containing the CI config of the child pipeline:
trigger_job:
trigger:
include: path/to/child-pipeline.yml
Similar to multi-project pipelines, it’s possible to mirror the status from a triggered pipeline:
trigger_job:
trigger:
include:
- local: path/to/child-pipeline.yml
strategy: depend
Trigger child pipeline with generated configuration file
GitLab 12.9で導入されました。
You can also trigger a child pipeline from a dynamically generated configuration file:
generate-config:
stage: build
script: generate-ci-config > generated-config.yml
artifacts:
paths:
- generated-config.yml
child-pipeline:
stage: test
trigger:
include:
- artifact: generated-config.yml
job: generate-config
The generated-config.yml
is extracted from the artifacts and used as the configuration
for triggering the child pipeline.
Linking pipelines with trigger:strategy
By default, the trigger
job completes with the success
status
as soon as the downstream pipeline is created.
To force the trigger
job to wait for the downstream (multi-project or child) pipeline to complete, use
strategy: depend
. This will make the trigger job wait with a “running” status until the triggered
pipeline completes. At that point, the trigger
job will complete and display the same status as
the downstream job.
trigger_job:
trigger:
include: path/to/child-pipeline.yml
strategy: depend
This can help keep your pipeline execution linear. In the example above, jobs from subsequent stages will wait for the triggered pipeline to successfully complete before starting, at the cost of reduced parallelization.
Trigger a pipeline by API call
Triggers can be used to force a rebuild of a specific branch, tag or commit, with an API call when a pipeline gets created using a trigger token.
Not to be confused with the trigger
parameter.
Read more in the triggers documentation.
interruptible
GitLab 12.3 で導入されました。
interruptible
is used to indicate that a job should be canceled if made redundant by a newer pipeline run. Defaults to false
.
This value will only be used if the automatic cancellation of redundant pipelines feature
is enabled.
When enabled, a pipeline on the same branch will be canceled when:
- It’s made redundant by a newer pipeline run.
- Either all jobs are set as interruptible, or any uninterruptible jobs haven’t started.
Pending jobs are always considered interruptible.
Here is a simple example:
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 will never be canceled, even though set as interruptible."
interruptible: true
In the example above, a new pipeline run will cause an existing running pipeline to be:
- Canceled, if only
step-1
is running or pending. - Not canceled, once
step-2
starts running.
resource_group
GitLab 12.7で導入されました。
Sometimes running multiples jobs or pipelines at the same time in an environment can lead to errors during the deployment.
To avoid these errors, the resource_group
attribute can be used to ensure that
the Runner won’t run certain jobs simultaneously.
When the resource_group
key is defined for a job in .gitlab-ci.yml
,
job executions are mutually exclusive across different pipelines for the same project.
If multiple jobs belonging to the same resource group are enqueued simultaneously,
only one of the jobs will be picked by the Runner, and the other jobs will wait until the
resource_group
is free.
Here is a simple example:
deploy-to-production:
script: deploy
resource_group: production
In this case, if a deploy-to-production
job is running in a pipeline, and a new
deploy-to-production
job is created in a different pipeline, it won’t run until
the currently running/pending deploy-to-production
job is finished. As a result,
you can ensure that concurrent deployments will never happen to the production environment.
There can be multiple resource_group
s defined per environment. A good use case for this
is when deploying to physical devices. You may have more than one physical device, and each
one can be deployed to, but there can be only one deployment per device at any given time.
-
, _
, /
, $
, {
, }
, .
, and spaces.
It can’t start or end with /
.For more information, see Deployments Safety.
release
Introduced in GitLab 13.2.
release
indicates that the job creates a Release,
and optionally includes URLs for Release assets.
These methods are supported:
tag_name
-
name
(optional) -
description
(optional) -
ref
(optional) -
milestones
(optional) -
released_at
(optional)
The Release is created only if the job processes without error. If the Rails API
returns an error during Release creation, the release
job fails.
release-cli
Docker image
The Docker image to use for the release-cli
must be specified, using the following directive:
image: registry.gitlab.com/gitlab-org/release-cli:latest
Script
All jobs require a script
tag at a minimum. A :release
job can use the output of a
:script
tag, but if this is not necessary, a placeholder script can be used, for example:
script:
- echo 'release job'
An issue exists to remove this requirement in an upcoming version of GitLab.
A pipeline can have multiple release
jobs, for example:
ios-release:
script:
- echo 'iOS release job'
release:
tag_name: v1.0.0-ios
description: 'iOS release v1.0.0'
android-release:
script:
- echo 'Android release job'
release:
tag_name: v1.0.0-android
description: 'Android release v1.0.0'
release:tag_name
The tag_name
must be specified. It can refer to an existing Git tag or can be specified by the user.
When the specified tag doesn’t exist in the repository, a new tag is created from the associated SHA of the pipeline.
For example, when creating a Release from a Git tag:
job:
release:
tag_name: $CI_COMMIT_TAG
description: changelog.txt
It is also possible to create any unique tag, in which case only: tags
is not mandatory.
A semantic versioning example:
job:
release:
tag_name: ${MAJOR}_${MINOR}_${REVISION}
description: changelog.txt
- The 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. - The
release
section executes after thescript
tag and before theafter_script
.
release:name
The Release name. If omitted, it is populated with the value of release: tag_name
.
release:description
Specifies the longer description of the Release.
release:ref
If the release: tag_name
doesn’t exist yet, the release is created from ref
.
ref
can be 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. Defaults to the current date and time if not defined. Expected in ISO 8601 format (2019-03-15T08:00:00Z).
Complete example for release
Combining the individual examples given above for release
results in the following
code snippets. There are two options, depending on how you generate the
tags. These options cannot be used together, so choose one:
-
To create a release when you push a Git tag, or when you add a Git tag in the UI by going to Repository > Tags:
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 release_job' release: name: 'Release $CI_COMMIT_TAG' description: 'Created using the release-cli $EXTRA_DESCRIPTION' # $EXTRA_DESCRIPTION must be defined tag_name: '$CI_COMMIT_TAG' # elsewhere in the pipeline. ref: '$CI_COMMIT_TAG' milestones: - 'm1' - 'm2' - 'm3' released_at: '2020-07-15T08:00:00Z' # Optional, will auto generate if not defined, # or can use a variable.
-
To create a release automatically when changes are pushed to the default branch, using a new Git tag that is defined with variables:
release_job: stage: release image: registry.gitlab.com/gitlab-org/release-cli:latest rules: - if: $CI_COMMIT_TAG when: never # Do not run this job when a tag is created manually - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH # Run this job when the default branch changes script: - echo 'running release_job' release: name: 'Release $CI_COMMIT_SHA' description: 'Created using the release-cli $EXTRA_DESCRIPTION' # $EXTRA_DESCRIPTION and the tag_name tag_name: 'v${MAJOR}.${MINOR}.${REVISION}' # variables must be defined elsewhere ref: '$CI_COMMIT_SHA' # in the pipeline. milestones: - 'm1' - 'm2' - 'm3' released_at: '2020-07-15T08:00:00Z' # Optional, will auto generate if not defined, # or can use a variable.
releaser-cli
command line
The entries under the :release
node are transformed into a bash
command line and sent
to the Docker container, which contains the release-cli.
You can also call the release-cli
directly from a script
entry.
The YAML described above would be translated into a CLI command like this:
release-cli create --name "Release $CI_COMMIT_SHA" --description "Created using the release-cli $EXTRA_DESCRIPTION" --tag-name "v${MAJOR}.${MINOR}.${REVISION}" --ref "$CI_COMMIT_SHA" --released-at "2020-07-15T08:00:00Z" --milestone "m1" --milestone "m2" --milestone "m3"
pages
pages
is a special job that is used to upload static content to GitLab that
can be used to serve your website. It has a special syntax, so the two
requirements below must be met:
- Any static content must be placed under a
public/
directory. -
artifacts
with a path to thepublic/
directory must be defined.
The example below simply moves all files from the root of the project to the
public/
directory. The .public
workaround is so cp
does not also copy
public/
to itself in an infinite loop:
pages:
stage: deploy
script:
- mkdir .public
- cp -r * .public
- mv .public public
artifacts:
paths:
- public
only:
- master
Read more on GitLab Pages user documentation.
variables
Introduced in GitLab Runner v0.5.0.
GitLab CI/CD allows you to define variables inside .gitlab-ci.yml
that are
then passed in the job environment. They can be set globally and per-job.
When the variables
keyword is used on a job level, it will override the global
YAML variables and predefined ones of the same name.
They are stored in the Git repository and are meant to store non-sensitive project configuration, for example:
variables:
DATABASE_URL: "postgres://postgres@postgres/my_database"
These variables can be later used in all executed commands and scripts. The YAML-defined variables are also set to all created service containers, thus allowing to fine tune them.
Except for the user defined variables, there are also the ones set up by the
Runner itself.
One example would be CI_COMMIT_REF_NAME
which has the value of
the branch or tag name for which project is built. Apart from the variables
you can set in .gitlab-ci.yml
, there are also the so called
Variables
which can be set in GitLab’s UI.
YAML anchors for variables are available.
Learn more about variables and their priority.
Git strategy
- Introduced in GitLab 8.9 as an experimental feature.
-
GIT_STRATEGY=none
requires GitLab Runner v1.7+.
You can set the GIT_STRATEGY
used for getting recent application code, either
globally or per-job in the variables
section. If left
unspecified, the default from project settings will be used.
There are three possible values: clone
, fetch
, and none
.
clone
is the slowest option. It clones the repository from scratch for every
job, ensuring that the local working copy is always pristine.
variables:
GIT_STRATEGY: clone
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 since the last job ran.
variables:
GIT_STRATEGY: fetch
none
also re-uses the local working copy, but skips all Git operations
(including GitLab Runner’s pre-clone script, if present). It’s mostly useful
for jobs that operate exclusively on artifacts (for example, deploy
). Git repository
data may be present, but it’s certain to be out of date, so you should only
rely on files brought into the local working copy from cache or artifacts.
variables:
GIT_STRATEGY: none
GIT_STRATEGY
is not supported for
Kubernetes executor,
but may be in the future. See the support Git strategy with Kubernetes executor feature proposal
for updates.Git submodule strategy
Requires GitLab Runner v1.10+.
The GIT_SUBMODULE_STRATEGY
variable is used to control if / how Git
submodules are included when fetching the code before a build. You can set them
globally or per-job in the variables
section.
There are three possible values: none
, normal
, and recursive
:
-
none
means that submodules won’t be included when fetching the project code. This is the default, which matches the pre-v1.10 behavior. -
normal
means that only the top-level submodules will be included. It’s equivalent to:git submodule sync git submodule update --init
-
recursive
means that all submodules (including submodules of submodules) will be 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:git submodule sync --recursive git submodule update --init --recursive
Note that 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 documentation.
Git checkout
Introduced in GitLab Runner 9.3.
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
section.
If set to false
, the Runner will:
- when doing
fetch
- update the repository and leave working copy on the current revision, - when doing
clone
- clone the repository and leave working copy on the default branch.
Having this setting set to true
will mean that for both clone
and fetch
strategies the Runner will checkout the working copy to a revision related
to the CI pipeline:
variables:
GIT_STRATEGY: clone
GIT_CHECKOUT: "false"
script:
- git checkout -B master origin/master
- git merge $CI_COMMIT_SHA
Git clean flags
Introduced in GitLab Runner 11.10
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
section.
GIT_CLEAN_FLAGS
accepts all possible options of the 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.
使用例。
variables:
GIT_CLEAN_FLAGS: -ffdx -e cache/
script:
- ls -al cache/
Git fetch extra flags
Introduced in GitLab Runner 13.1.
The GIT_FETCH_EXTRA_FLAGS
variable is used to control the behavior of
git fetch
. You can set it globally or per-job in the variables
section.
GIT_FETCH_EXTRA_FLAGS
accepts all possible options of the git fetch
command, but please note that GIT_FETCH_EXTRA_FLAGS
flags will be appended after the default flags that can’t be modified.
The default flags are:
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
:
variables:
GIT_FETCH_EXTRA_FLAGS: --prune
script:
- ls -al cache/
The configurtion above will result in git fetch
being called this way:
git fetch origin $REFSPECS --depth 50 --prune
Where $REFSPECS
is a value provided to the Runner internally by GitLab.
Job stages attempts
Introduced in GitLab, it requires GitLab Runner v1.9+.
You can set the number for attempts the running job will try to execute each of the following stages:
Variable | 説明 |
---|---|
GET_SOURCES_ATTEMPTS | Number of attempts to fetch sources running a job |
ARTIFACT_DOWNLOAD_ATTEMPTS | Number of attempts to download artifacts running a job |
RESTORE_CACHE_ATTEMPTS | Number of attempts to restore the cache running a job |
EXECUTOR_JOB_SECTION_ATTEMPTS |
Since GitLab 12.10, the number of attempts to run a section in a job after a No Such Container error (Docker executor only).
|
The default is one single attempt.
使用例:
variables:
GET_SOURCES_ATTEMPTS: 3
You can set them globally or per-job in the variables
section.
Shallow cloning
Introduced in GitLab 8.9 as an experimental feature.
git depth
value of 50
.You can specify the depth of fetching and cloning using GIT_DEPTH
. This allows
shallow cloning of the repository which can significantly speed up cloning for
repositories with a large number of commits or old, large binaries. The value is
passed to git fetch
and git clone
.
Since Git fetching and cloning is based on a ref, such as a branch name, Runners
can’t clone a specific commit SHA. If there are multiple jobs in the queue, or
you’re retrying an old job, the commit to be tested needs to be within the
Git history that is cloned. Setting too small a value for GIT_DEPTH
can make
it impossible to run these old commits. You will see unresolved reference
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 since only part of the Git history is present.
To fetch or clone only the last 3 commits:
variables:
GIT_DEPTH: "3"
You can set it globally or per-job in the variables
section.
Custom build directories
Introduced in GitLab Runner 11.10
custom_build_dir
is enabled in the Runner’s
configuration.
This is the default configuration for docker
and kubernetes
executor.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 in which directory to clone the
repository:
variables:
GIT_CLONE_PATH: $CI_BUILDS_DIR/project-name
test:
script:
- pwd
The GIT_CLONE_PATH
has to always be within $CI_BUILDS_DIR
. The directory set in $CI_BUILDS_DIR
is dependent on executor and configuration of runners.builds_dir
setting.
Handling concurrency
An executor using a concurrency greater than 1
might lead
to failures because multiple jobs might be working on the same directory if the builds_dir
is shared between jobs.
GitLab 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 within $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 within the given executor. -
$CI_CONCURRENT_PROJECT_ID
: Unique ID for all jobs running within 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:
variables:
GIT_CLONE_PATH: $CI_BUILDS_DIR/$CI_CONCURRENT_ID/project-name
test:
script:
- pwd
The $CI_CONCURRENT_PROJECT_ID
should be used in conjunction with $CI_PROJECT_PATH
as the $CI_PROJECT_PATH
provides a path of a repository. That is, group/subgroup/project
. For example:
variables:
GIT_CLONE_PATH: $CI_BUILDS_DIR/$CI_CONCURRENT_ID/$CI_PROJECT_PATH
test:
script:
- pwd
Nested paths
The value of GIT_CLONE_PATH
is expanded once and nesting variables
within is not supported.
For example, you define both the variables below in your
.gitlab-ci.yml
file:
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.
Special YAML features
It’s possible to use special YAML features like anchors (&
), aliases (*
)
and map merging (<<
), which will allow you to greatly reduce the complexity
of .gitlab-ci.yml
.
Read more about the various YAML features.
In most cases, the extends
keyword is more user friendly and should
be used over these special YAML features. YAML anchors may still
need to be used to merge arrays.
Anchors
Introduced in GitLab 8.6 and GitLab Runner v1.1.1.
YAML has a handy feature called ‘anchors’, which lets you easily duplicate content across your document. Anchors can be used to duplicate/inherit properties, and is a perfect example to be used with hidden jobs to provide templates for your jobs. When there is duplicate keys, GitLab will perform a reverse deep merge based on the keys.
The following example uses anchors and map merging. It will create two jobs,
test1
and test2
, that will inherit the parameters of .job_template
, each
having their own custom script
defined:
.job_template: &job_definition # Hidden key that defines an anchor named 'job_definition'
image: ruby:2.6
services:
- postgres
- redis
test1:
<<: *job_definition # Merge the contents of the 'job_definition' alias
script:
- test1 project
test2:
<<: *job_definition # Merge the contents of the 'job_definition' alias
script:
- test2 project
&
sets up the name of the anchor (job_definition
), <<
means “merge the
given hash into the current one”, and *
includes the named anchor
(job_definition
again). The expanded version looks like this:
.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
Let’s see another one example. This time we will use anchors to define two sets
of services. This will create two jobs, test:postgres
and test:mysql
, that
will share the script
directive defined in .job_template
, and the services
directive defined in .postgres_services
and .mysql_services
respectively:
.job_template: &job_definition
script:
- test project
tags:
- dev
.postgres_services:
services: &postgres_definition
- postgres
- ruby
.mysql_services:
services: &mysql_definition
- mysql
- ruby
test:postgres:
<<: *job_definition
services: *postgres_definition
tags:
- postgres
test:mysql:
<<: *job_definition
services: *mysql_definition
The expanded version looks like this:
.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.
tags: [dev]
has been overwritten by tags: [postgres]
.include
feature. Anchors are only valid within the file they were defined in. Instead
of using YAML anchors, you can use the extends
keyword.YAML anchors for before_script
and after_script
GitLab 12.5で導入されました。
You can use YAML anchors with before_script
and after_script
,
which makes it possible to include a predefined list of commands in multiple
jobs.
使用例:
.something_before: &something_before
- echo 'something before'
.something_after: &something_after
- echo 'something after'
- echo 'another thing after'
job_name:
before_script:
- *something_before
script:
- echo 'this is the script'
after_script:
- *something_after
YAML anchors for script
GitLab 12.5で導入されました。
You can use YAML anchors with scripts, which makes it possible to include a predefined list of commands in multiple jobs.
使用例。
.something: &something
- echo 'something'
job_name:
script:
- *something
- echo 'this is the script'
YAML anchors for variables
YAML anchors can be used with variables
, to easily repeat assignment
of variables across multiple jobs. It can also enable more flexibility when a job
requires a specific variables
block that would otherwise override the global variables.
In the example below, we will override the GIT_STRATEGY
variable without affecting
the use of the SAMPLE_VARIABLE
variable:
# global variables
variables: &global-variables
SAMPLE_VARIABLE: sample_variable_value
ANOTHER_SAMPLE_VARIABLE: another_sample_variable_value
# a job that needs to set the GIT_STRATEGY variable, yet depend on global variables
job_no_git_strategy:
stage: cleanup
variables:
<<: *global-variables
GIT_STRATEGY: none
script: echo $SAMPLE_VARIABLE
Hide jobs
Introduced in GitLab 8.6 and GitLab Runner v1.1.1.
If you want to temporarily ‘disable’ a job, rather than commenting out all the lines where the job is defined:
#hidden_job:
# script:
# - run test
You can instead start its name with a dot (.
) and it won’t be processed by
GitLab CI/CD. In the following example, .hidden_job
will be ignored:
.hidden_job:
script:
- run test
Use this feature to ignore jobs, or use the special YAML features and transform the hidden jobs into templates.
Skip Pipeline
If your commit message contains [ci skip]
or [skip ci]
, using any
capitalization, the commit will be created but the pipeline will be skipped.
Alternatively, one can pass the ci.skip
Git push option
if using Git 2.10 or newer.
Processing Git pushes
GitLab will create at most 4 branch and tag pipelines when
pushing multiple changes in single git push
invocation.
This limitation does not affect any of the updated Merge Request pipelines. All updated Merge Requests will have a pipeline created when using pipelines for merge requests.
Deprecated parameters
The following parameters are deprecated.
Globally-defined types
types
is deprecated, and could be removed in a future release.
Use stages
instead.Job-defined type
type
is deprecated, and could be removed in one of the future releases.
Use stage
instead.Globally-defined image
, services
, cache
, before_script
, after_script
Defining image
, services
, cache
, before_script
, and
after_script
globally is deprecated. Support could be removed
from a future release.
Use default:
instead. For example:
default:
image: ruby:2.5
services:
- docker:dind
cache:
paths: [vendor/]
before_script:
- bundle install --path vendor/
after_script:
- rm -rf tmp/