gitlab:作业中的 before 脚本有什么用

San*_*idi 6 gitlab gitlab-ci

before_script我觉得在工作中需要用到什么。script它可以在自身内部组合在一起

deploy-to-stage:
  stage: deploy
  before_script:
    - "which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )"
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - echo "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
    - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN registry.gitlab.com
  script:
    -   *** some code here ***
Run Code Online (Sandbox Code Playgroud)

如果他们要一个接一个地跑

我可以理解before_script所有工作都有共同点,因为它节省了一些样板文件

Haw*_*ker 0

除了丹尼尔的回答之外,before_script工作中定义的另一个用途是覆盖default before_script,如果您想要before_script特定工作的不同内容,甚至什么都不包含。以下内容是从此文档中复制/粘贴的:https://docs.gitlab.com/ee/ci/yaml/script.html#set-a-default-before_script-or-after_script-for-all-jobs

您可以将before_scriptandafter_script与 一起使用default

使用before_scriptwithdefault定义默认命令数组,这些命令应在所有作业中的脚本命令之前运行。与 default 一起使用after_script来定义作业完成后应运行的默认命令数组。您可以通过在作业中定义不同的默认值来覆盖默认值。要忽略默认使用before_script: []after_script: []

default:
  before_script:
    - echo "Execute this `before_script` in all jobs by default."
  after_script:
    - echo "Execute this `after_script` in all jobs by default."

job1:
  script:
    - echo "These script commands execute after the default `before_script`,"
    - echo "and before the default `after_script`."

job2:
  before_script:
    - echo "Execute this script instead of the default `before_script`."
  script:
    - echo "This script executes after the job's `before_script`,"
    - echo "but the job does not use the default `after_script`."
  after_script: []
Run Code Online (Sandbox Code Playgroud)