GitLab 中文文档

使用 .gitlab-ci.yml 配置project's builds

这篇文档讲述了.gitlab-ci.yml的用法,这个文件被 GitLab Runner用来控制project's builds流程。

如果你想快速了解 GitLab CI的介绍,可以阅读 GitLab CI快速入门.


Table of Contents generated with DocToc

  • .gitlab-ci.yml
    • image and services
    • before_script
    • after_script
    • stages
    • types
    • variables
    • cache
      • cache:key
  • Jobs
    • script
    • stage
    • only and except
    • job variables
    • tags
    • allow_failure
    • when
      • Manual actions
    • environment
    • artifacts
      • artifacts:name
      • artifacts:when
      • artifacts:expire_in
    • dependencies
    • before_script and after_script
  • Git Strategy
  • Shallow cloning
  • Hidden jobs
  • Special YAML features
    • Anchors
  • Validate the .gitlab-ci.yml
  • Skipping builds
  • Examples

.gitlab-ci.yml

从7.12版本开始,GitLab CI使用YAML 文件(.gitlab-ci.yml)来配置project's builds。这个文件存放在仓库根目录,它包含了用来 built该project的配置项。

YAML文件使用一些约束条件定义jobs该何时进行工作。jobs 需定义一个top-level元素,并且 通常至少包含一个script的子句。

job1:
  script: "execute-script-for-job1"

job2:
  script: "execute-script-for-job2"

上面的例子是一个拥有两个独立的job的简单可行的CI配置,每个 job会执行不同的命令。

每个job执行的命令可以执行运行系统命令,如(./configure;make;make install) 或者运行仓库目录里面的脚本文件,如(test.sh)。

Jobs用来创建builds,并由已指派给 project的Runners 在该Runner的环境中执行builds。 值得注意的是,每个job都是彼此独立的运行的。

YAML语法允许使用更复杂的规范,例如 下面的例子:

image: ruby:2.1
services:
  - postgres

before_script:
  - bundle install

after_script:
  - rm secrets

stages:
  - build
  - test
  - deploy

job1:
  stage: build
  script:
    - execute-script-for-job1
  only:
    - master
  tags:
    - docker

下面这些关键词 不能 用作job名称:

关键词 必需 描述
image no 使用docker image, 已涵盖在 GitLab CI使用Docker
services no 使用docker services, 已涵盖在 GitLab CI使用Docker
stages no 定义builds阶段
types no stages的别名
before_script no 定义每个job之前执行的脚本
after_script no 定义每个job之后执行的脚本
variables no 定义build变量
cache no 定义与后续job之间应缓存的文件

image and services

这两个关键词允许指定这次build需要使用的自定义的Dokcer images和 Docker services。该功能的配置已涵盖在 GitLab CI与Docker的整合文档中。

before_script

before_script is used to define the command that should be run before all builds, including deploy builds. This can be an array or a multi-line string. before_script 用来定义应该在所有的builds开始之前执行的命令, 它可以是一个数组或者一个multi-line(多行)字符串。

after_script

Note: 该功能自GitLab 8.7引入,并依赖GitLab Runner v1.2。

after_script 用来定义在所有的builds完成之后执行的命令, 它也可以是一个数组或者一个multi-line(多行)字符串。

stages

stages 在jobs中可以用来定义build的各个阶段, stages 的规范允许灵活的使用多个stage pipelines。

stages中各元素的顺序决定了builds的执行顺序:

  1. 同一个stage中的元素将并行Builds。
  2. 下一个stage将在上一个stage中所有元素 成功完成后进行Builds。

我们思考下下面的例子,定义了哪3个stages:

stages:
  - build
  - test
  - deploy
  1. 首先 build 中的jobs将并行执行。
  2. 如果 build 中的jobs都成功执行了, test 中的jobs将并行执行.
  3. 如果 test 中的jobs都成功执行了, deploy 中的jobs将并行执行.
  4. 如果 deploy 中的jobs都成功完成, 该条 commit 将标记为 success.
  5. 如果前面任意一个jobs执行失败,该条 commit 将标记为 failed,并且 下一步的stage中的jobs不会继续下去。

还有值得一提的两个边缘情况:

  1. 如未在.gitlab-ci.yml中定义任何stages,默认情况下buildtest and deploy 允许作为预设的任务 stage,即stage名为build,test,deploy.
  2. 如果一个job没有指定stage,该任务会给指派为test stage。

types

与stages同样的功能,是stages的别名。

variables

Note: 该功能自GitLab Runner v0.5.0中引入。

GitLab CI允许在.gitlab-ci.yml里面添加变量以便应用到build环境中。 变量存储在git仓库中并用于存储non-sensitive(非敏感)的project配置, 如下面的例子:

variables:
  DATABASE_URL: "postgres://postgres@postgres/my_database"

这个变量可延迟作用于所有已执行的命令和脚本中。

同事通过YAML定义的变量也会设置所有的服务容器, 因此允许微调这些服务容器。

job level也可以定义变量。

cache

Note: 该功能自GitLab Runner v0.7.0引入。

chche 用来指定需要在 builds 之间进行换成的一组文件、文件夹。

默认情况下per-job和per-branch的缓存都是启用的

如果cache 是在jobs的作用域外面定义的, 那么它就是一个全局的设置,所有的jobs都会使用它的配置。

缓存binaries 目录下的文件和.config文件:

rspec:
  script: test
  cache:
    paths:
    - binaries/
    - .config

缓存所有未被Git跟踪的文件:

rspec:
  script: test
  cache:
    untracked: true

缓存所有未被Git跟踪的文件以及binaries目录下的文件:

rspec:
  script: test
  cache:
    untracked: true
    paths:
    - binaries/

本地作用域定义的cache会覆盖全局的设置, 如下面的例子只会缓存binaries/

cache:
  paths:
  - my/files

rspec:
  script: test
  cache:
    paths:
    - binaries/

cache最大程度的提供缓存功能,所以不要期望每次都能命中缓存, 要查看详细的执行信息,请检车GitLab Runner。

cache:key

Note: 该功能自 GitLab Runner v1.0.0引入。

这个 key 指令允许定义jobs之间缓存的亲和力, 允许所有的jobs只有单个缓存,也可以是每个per-job caching、 per-branch caching,或者其他你认为合适的方法。

key允许你对缓存进行微调, 也允许在不同Jobs设置不同brances之间缓存数据。

cache:key变量可以使用任何预定义变量。


Example configurations

启用 per-job caching:

cache:
  key: "$CI_BUILD_NAME"
  untracked: true

启用 per-branch caching:

cache:
  key: "$CI_BUILD_REF_NAME"
  untracked: true

启用 per-job and per-branch caching:

cache:
  key: "$CI_BUILD_NAME/$CI_BUILD_REF_NAME"
  untracked: true

启用 per-branch and per-stage caching:

cache:
  key: "$CI_BUILD_STAGE/$CI_BUILD_REF_NAME"
  untracked: true

如果你用的是 Windows Batch Windows批处理运行shell scripts, 需要把$替换为%

cache:
  key: "%CI_BUILD_STAGE%/%CI_BUILD_REF_NAME%"
  untracked: true

Jobs

.gitlab-ci.yml allows you to specify an unlimited number of jobs. Each job must have a unique name, which is not one of the Keywords mentioned above. A job is defined by a list of parameters that define the build behavior.

job_name:
  script:
    - rake spec
    - coverage
  stage: test
  only:
    - master
  except:
    - develop
  tags:
    - ruby
    - postgres
  allow_failure: true
Keyword Required Description
script yes Defines a shell script which is executed by Runner
image no Use docker image, covered in Using Docker Images
services no Use docker services, covered in Using Docker Images
stage no Defines a build stage (default: test)
type no Alias for stage
variables no Define build variables on a job level
only no Defines a list of git refs for which build is created
except no Defines a list of git refs for which build is not created
tags no Defines a list of tags which are used to select Runner
allow_failure no Allow build to fail. Failed build doesn't contribute to commit status
when no Define when to run build. Can beon_success,on_failure,always or manual
dependencies no Define other builds that a build depends on so that you can pass artifacts between them
artifacts no Define list of build artifacts
cache no Define list of files that should be cached between subsequent runs
before_script no Override a set of commands that are executed before build
after_script no Override a set of commands that are executed after build
environment no Defines a name of environment to which deployment is done by this build

script

script is a shell script which is executed by the Runner. For example:

job:
  script: "bundle exec rspec"

This parameter can also contain several commands using an array:

job:
  script:
    - uname -a
    - bundle exec rspec

Sometimes, script commands will need to be wrapped in single or double quotes. For example, commands that contain a colon (:) need to be wrapped in quotes so that the YAML parser knows to interpret the whole thing as a string rather than a "key: value" pair. Be careful when using special characters (:{}[],&*#?|-<>=!%@,`).

stage

stage allows to group build into different stages. Builds of the same stage are executed in parallel. For more info about the use of stage please check stages.

only and except

only and except are two parameters that set a refs policy to limit when jobs are built:

  1. only defines the names of branches and tags for which the job will be built.
  2. except defines the names of branches and tags for which the job will not be built.

There are a few rules that apply to the usage of refs policy:

  • only and except are inclusive. If both only and except are defined in a job specification, the ref is filtered by onlyand except.
  • only and except allow the use of regular expressions.
  • only and except allow the use of special keywords: branchestags, and triggers.
  • only and except allow to specify a repository path to filter jobs for forks.

In the example below, job will run only for refs that start with issue-, whereas all branches will be skipped.

job:
  # use regexp
  only:
    - /^issue-.*$/
  # use special keyword
  except:
    - branches

In this example, job will run only for refs that are tagged, or if a build is explicitly requested via an API trigger.

job:
  # use special keywords
  only:
    - tags
    - triggers

The repository path can be used to have jobs executed only for the parent repository and not forks:

job:
  only:
    - branches@gitlab-org/gitlab-ce
  except:
    - master@gitlab-org/gitlab-ce

The above example will run job for all branches on gitlab-org/gitlab-ce, except master.

job variables

It is possible to define build variables using a variables keyword on a job level. It works basically the same way as its global-level equivalent but allows you to define job-specific build variables.

When the variables keyword is used on a job level, it overrides global YAML build variables and predefined variables.

Build variables priority is defined in variables documentation.

tags

tags is used to select specific Runners from the list of all Runners that are allowed to run this project.

During the registration of a Runner, you can specify the Runner's tags, for example rubypostgresdevelopment.

tags allow you to run builds with Runners that have the specified tags assigned to them:

job:
  tags:
    - ruby
    - postgres

The specification above, will make sure that job is built by a Runner that has both ruby AND postgres tags defined.

allow_failure

allow_failure is used when you want to allow a build to fail without impacting the rest of the CI suite. Failed builds don't contribute to the commit status.

When enabled and the build fails, the pipeline will be successful/green for all intents and purposes, but a "CI build passed with warnings" message will be displayed on the merge request or commit or build page. This is to be used by builds that are allowed to fail, but where failure indicates some other (manual) steps should be taken elsewhere.

In the example below, job1 and job2 will run in parallel, but if job1 fails, it will not stop the next stage from running, since it's marked with 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 is used to implement jobs that are run in case of failure or despite the failure.

when can be set to one of the following values:

  1. on_success - execute build only when all builds from prior stages succeed. This is the default.
  2. on_failure - execute build only when at least one build from prior stages fails.
  3. always - execute build regardless of the status of builds from prior stages.
  4. manual - execute build manually (added in GitLab 8.10). Read about manual actions below.

For example:

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 builds
  when: always

The above script will:

  1. Execute cleanup_build_job only when build_job fails.
  2. Always execute cleanup_job as the last step in pipeline regardless of success or failure.
  3. Allow you to manually execute deploy_job from GitLab's UI.

Manual actions

Note: Introduced in GitLab 8.10.

Manual actions are a special type of job that are not executed automatically; they need to be explicitly started by a user. Manual actions can be started from pipeline, build, environment, and deployment views. You can execute the same manual action multiple times.

An example usage of manual actions is deployment to production.

environment

Note: Introduced in GitLab 8.9.

environment is used to define that a job deploys to a specific environment. This allows easy tracking of all deployments to your environments straight from GitLab.

If environment is specified and no environment under that name exists, a new one will be created automatically.

The environment name must contain only letters, digits, '-' and '_'. Common names are qastaging, and production, but you can use whatever name works with your workflow.


Example configurations

deploy to production:
  stage: deploy
  script: git push production HEAD:master
  environment: production

The deploy to production job will be marked as doing deployment to production environment.

artifacts

**Notes:**

  • Introduced in GitLab Runner v0.7.0 for non-Windows platforms.
  • Windows support was added in GitLab Runner v.1.0.0.
  • Currently not all executors are supported.
  • Build artifacts are only collected for successful builds by default.

artifacts is used to specify a list of files and directories which should be attached to the build after success. To pass artifacts between different builds, see dependencies.

Below are some examples.

Send all files in binaries and .config:

artifacts:
  paths:
  - binaries/
  - .config

Send all Git untracked files:

artifacts:
  untracked: true

Send all Git untracked files and files in binaries:

artifacts:
  untracked: true
  paths:
  - binaries/

You may want to create artifacts only for tagged releases to avoid filling the build server storage with temporary build artifacts.

Create artifacts only for tags (default-job will not create artifacts):

default-job:
  script:
    - mvn test -U
  except:
    - tags

release-job:
  script:
    - mvn package -U
  artifacts:
    paths:
    - target/*.war
  only:
    - tags

The artifacts will be sent to GitLab after a successful build and will be available for download in the GitLab UI.

artifacts:name

Note: 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.


Example configurations

To create an archive with a name of the current build:

job:
  artifacts:
    name: "$CI_BUILD_NAME"

To create an archive with a name of the current branch or tag including only the files that are untracked by Git:

job:
   artifacts:
     name: "$CI_BUILD_REF_NAME"
     untracked: true

To create an archive with a name of the current build and the current branch or tag including only the files that are untracked by Git:

job:
  artifacts:
    name: "${CI_BUILD_NAME}_${CI_BUILD_REF_NAME}"
    untracked: true

To create an archive with a name of the current stage and branch name:

job:
  artifacts:
    name: "${CI_BUILD_STAGE}_${CI_BUILD_REF_NAME}"
    untracked: true

If you use Windows Batch to run your shell scripts you need to replace $ with %:

job:
  artifacts:
    name: "%CI_BUILD_STAGE%_%CI_BUILD_REF_NAME%"
    untracked: true

artifacts:when

Note: Introduced in GitLab 8.9 and GitLab Runner v1.3.0.

artifacts:when is used to upload artifacts on build failure or despite the failure.

artifacts:when can be set to one of the following values:

  1. on_success - upload artifacts only when the build succeeds. This is the default.
  2. on_failure - upload artifacts only when the build fails.
  3. always - upload artifacts regardless of the build status.

Example configurations

To upload artifacts only when build fails.

job:
  artifacts:
    when: on_failure

artifacts:expire_in

Note: Introduced in GitLab 8.9 and GitLab Runner v1.3.0.

artifacts:expire_in is used to delete uploaded artifacts after the specified time. By default, artifacts are stored on GitLab forever. expire_in allows you to specify how long artifacts should live before they expire, counting from the time they are uploaded and stored on GitLab.

You can use the Keep button on the build page to override expiration and keep artifacts forever.

After expiry, artifacts are actually deleted hourly by default (via a cron job), but they are not accessible after expiry.

The value of expire_in is an elapsed time. Examples of parseable values:

  • '3 mins 4 sec'
  • '2 hrs 20 min'
  • '2h20min'
  • '6 mos 1 day'
  • '47 yrs 6 mos and 4d'
  • '3 weeks and 2 days'

Example configurations

To expire artifacts 1 week after being uploaded:

job:
  artifacts:
    expire_in: 1 week

dependencies

Note: Introduced in GitLab 8.6 and GitLab Runner v1.1.1.

This feature should be used in conjunction with artifacts and allows you to define the artifacts to pass between different builds.

Note that artifacts from all previous stages are passed by default.

To use this feature, define dependencies in context of the job and pass a list of all previous builds from which the artifacts should be downloaded. You can only define builds from stages that are executed before the current one. An error will be shown if you define builds from the current stage or next ones. Defining an empty array will skip downloading any artifacts for that job.


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 fortest:linux and artifacts from build:linux.

The job deploy will download artifacts from all previous builds 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

before_script and after_script

It's possible to overwrite globally defined before_script and after_script:

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

Git Strategy

Note: Introduced in GitLab 8.9 as an experimental feature. May change in future releases or be removed completely.

You can set the GIT_STRATEGY used for getting recent application code. clone is slower, but makes sure you have a clean directory before every build. fetch is faster. GIT_STRATEGY can be specified in the global variables section or in thevariables section for individual jobs. If it's not specified, then the default from project settings will be used.

variables:
  GIT_STRATEGY: clone

or

variables:
  GIT_STRATEGY: fetch

Shallow cloning

Note: Introduced in GitLab 8.9 as an experimental feature. May change in future releases or be removed completely.

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.

Note: If you use a depth of 1 and have a queue of builds or retry builds, jobs may fail.

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 builds in the queue, or you are retrying an old build, 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 build logs. You should then reconsider changing GIT_DEPTH to a higher value.

Builds 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"

Hidden jobs

Note: Introduced in GitLab 8.6 and GitLab Runner v1.1.1.

Jobs that start with a dot (.) will be not processed by GitLab CI. You can use this feature to ignore jobs, or use the special YAML features and transform the hidden jobs into templates.

In the following example, .job_name will be ignored:

.job_name:
  script:
    - rake spec

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.

Anchors

Note: Introduced in GitLab 8.6 and GitLab Runner v1.1.1.

YAML also has a handy feature called 'anchors', which let 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.

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 job that defines an anchor named 'job_definition'
  image: ruby:2.1
  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.1
  services:
    - postgres
    - redis

test1:
  image: ruby:2.1
  services:
    - postgres
    - redis
  script:
    - test1 project

test2:
  image: ruby:2.1
  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 servicesdirective defined in .postgres_services and .mysql_services respectively:

.job_template: &job_definition
  script:
    - test project

.postgres_services:
  services: &postgres_definition
    - postgres
    - ruby

.mysql_services:
  services: &mysql_definition
    - mysql
    - ruby

test:postgres:
  <<: *job_definition
  services: *postgres_definition

test:mysql:
  <<: *job_definition
  services: *mysql_definition

The expanded version looks like this:

.job_template:
  script:
    - test project

.postgres_services:
  services:
    - postgres
    - ruby

.mysql_services:
  services:
    - mysql
    - ruby

test:postgres:
  script:
    - test project
  services:
    - postgres
    - ruby

test:mysql:
  script:
    - test project
  services:
    - mysql
    - ruby

You can see that the hidden jobs are conveniently used as templates.

Validate the .gitlab-ci.yml

Each instance of GitLab CI has an embedded debug tool called Lint. You can find the link under /ci/lint of your gitlab instance.

Skipping builds

If your commit message contains [ci skip] or [skip ci], using any capitalization, the commit will be created but the builds will be skipped.

Examples

Visit the examples README to see a list of examples using GitLab CI with various languages.


你可能感兴趣的:(文档类)