一行行解读.gitlab-ci.yml

2022-03-26  本文已影响0人  说叁两事

【日常】.gitlab-ci.yml解读

# .job: 定义隐藏的任务Job,该任务不会被Gitlab cicd执行
# &template 定义锚点
# 隐藏任务结合锚点,可以提供模板给任务Job复用 —— 不可跨文件使用,跨文件考虑`!reference`API
# .job: &template定义可复用的内容
.script_package_install-deploy: &script_package_install-deploy |
  yarn global add @custom/deploy-tool

# docker 镜像
image: node:latest

# 钩子函数,脚本执行之前需要执行的命令
before_script:
  - npm config set registry https://registry.npm.taobao.org/
  - npm config set cache-folder .cache
  - *script_package_install-deploy

# 定义不同的周期阶段,属于同一周期的任务Job并行执行
stages:
  - build
  - deploy_staging
  - deploy_preview
  - deploy_production

# .job: &template定义可复用的内容
.script_set_env: &script_set_env |
  if [ "$CI_COMMIT_REF_NAME" == "production" ]; then
    if [ "$CI_JOB_STAGE" == "deploy_production" ]; then
      export DEPLOY_ENVIRONMENT=prod
    else
      export DEPLOY_ENVIRONMENT=preview
    fi
  else [ "$CI_COMMIT_REF_NAME" == "staging" ]
    export DEPLOY_ENVIRONMENT=staging
  fi

# .job: &template定义可复用的内容
# 通过*template使用锚点定义的内容
.deploy: &deploy_common
  script:
    - *script_set_env
    - deploy-tool deploy

# 定义任务build
build:
  stage: build  # 所属周期阶段,同周期的并行执行
  cache: # 需要缓存文件
    key: $CI_PROJECT_NAME
    paths:
      - .cache/**/*
      - node_modules/**/*
  script: # 该任务要执行的脚本
    - npm i 
    - *script_set_env  # 通过*template使用锚点定义的内容
    - deploy-tool build
  only: # 执行时机:staging、production分支push后自动执行
    - staging
    - production

# 定义任务deploy_staging
deploy_staging:
  stage: deploy_staging # 所属周期阶段,同周期的并行执行
  <<: *deploy_common  # 通过<<: *template合并锚点定义的内容
  environment: # 定义要部署的环境
    name: staging
  only: # 执行时机:staging分支push后自动执行
    - staging

# 定义任务deploy_preview
deploy_preview:
  stage: deploy_preview # 所属周期阶段,同周期的并行执行
  <<: *deploy_common  # 通过<<: *template合并锚点定义的内容
  environment: # 定义要部署的环境
    name: preview
  only: # 执行时机:production分支push后自动执行
    - production

# 定义任务deploy_preview
deploy_production:
  stage: deploy_production # 所属周期阶段,同周期的并行执行
  <<: *deploy_common # 通过<<: *template合并锚点定义的内容
  environment: # 定义要部署的环境
    name: production
  when: manual # 手动执行
  only: # 因为when的存在,不自动执行了,when默认值on_success
    - production

*template vs. <<: *template

*template:复用的只是任务脚本的其中一个指令
<<: *template:复用的是整个任务脚本

【篇外】如何配置.gitlab-ci.yml

stages:
  - build
  - deploy_staging
  - deploy_preview
  - deploy_production

build:
  stage: build  // 约定所属stage
  cache:
    key: $CI_PROJECT_NAME
    paths:
      - .cache/**/*
      - node_modules/**/*
  script:
    - npm i
    - *script_set_env
  only:
    - tags // 打了tag时触发该任务
    - staging  // 提交staging分支时触发该任务
    - production  // 提交production分支时触发该任务

Job执行时机

variables:
  TEST: "HELLO WORLD"

job1:
  script:
    - echo "$TEST"

复用脚本(锚点)

上一篇 下一篇

猜你喜欢

热点阅读