gitlab ci Anchors介绍与实践

gitlab-ci.yml有个方便的功能称为Anchors 中文是"锚"的意思,它可以让你轻松的在文档中复制内容。Anchors可用于复制/继承属性,并且是使用hidden keys来提供模版的完美示例。

下面这个例子使用了anchors和map merging。它将会创建两个jobs,test1test2,该jobs将集成.job_template的参数,每个job都自定义脚本:

案例一:

.job_template: &job_definition  # Hidden key 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

&在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:postgrestest: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被方便的用作模版。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值