gitlab-ci.yml有个方便的功能称为Anchors 中文是"锚"的意思,它可以让你轻松的在文档中复制内容。Anchors可用于复制/继承属性,并且是使用hidden keys来提供模版的完美示例。
下面这个例子使用了anchors和map merging。它将会创建两个jobs,test1 和test2 ,该jobs将集成.job_template 的参数,每个job都自定义脚本:
案例一:
.job_template: &job_definition
image: ruby:2.1
services:
- postgres
- redis
test1:
<<: *job_definition
script:
- test1 project
test2:
<<: *job_definition
script:
- test2 project
& 在anchor的名称(job_definition )前设置,<< 表示"merge the given hash into the current one",* 包括命名的anchor(job_definition )。扩展版本如下:
.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
案例二:
.build_base: &build_base
stage: build
image: monachus/hugo
artifacts:
paths:
- public
script:
- export
- hugo --baseURL ${BASE_URL}
build:production:
<<: *build_base
variables:
<<: *production_variables
GIT_SUBMODULE_STRATEGY: recursive
only:
- master
build:staging:
<<: *build_base
variables:
<<: *staging_variables
GIT_SUBMODULE_STRATEGY: recursive
only:
- dev
.deploy_base: &deploy_base
stage: deploy
image: monachus/hugo
script:
- hugo --baseURL ${BASE_URL}
deploy:production:
<<: *deploy_base
variables:
<<: *production_variables
dependencies:
- build:production
only:
- master
deploy:staging:
<<: *deploy_base
variables:
<<: *staging_variables
dependencies:
- build:staging
only:
- dev
案例三:
使用anchors来定义两个服务。两个服务会创建两个job,test:postgres 和test:mysql ,他们会在.job_template 中共享定义的script 指令,以及分别在.postgres_services 和.mysql_services 中定义的service 指令:
.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
扩展版本如下:
.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
可以看到hidden keys被方便的用作模版。
|