GitLab CI:在 before_script 构建作业中导出变量

Sim*_*iel 9 continuous-integration gitlab gitlab-ci gitlab-ci-runner

我尝试根据 CI 脚本是否为标记分支运行来实现条件版本控制。但是版本变量尚未解决。相反,它被打印为字符串。

GitLab CI脚本的相关工作:

# build template
.build_base_template: &build_base_template
  image: registry.gitlab.com/xxxxxxx/npm:latest
  tags:
    - docker
  stage: LintBuildTest
  script:
    - export CUR_VERSION='$(cat ./version.txt)$BUILD_VERSION_SUFFIX'
    - npm ci
    - npm run build
  artifacts:
    expire_in: 1 week
    paths:
      - dist/

# default build job
build:
  before_script:
    - export BUILD_VERSION_SUFFIX='-$CI_COMMIT_REF_SLUG-SNAPSHOT-$CI_COMMIT_SHORT_SHA'
  <<: *build_base_template
  except:
    refs:
      - tags
  only:
    variables:
      - $FEATURE_NAME == null

# specific build job for tagged versions
build_tag:
  before_script:
    - export BUILD_VERSION_SUFFIX=''
  <<: *build_base_template
  only:
    refs:
      - tags
Run Code Online (Sandbox Code Playgroud)

mr.*_*lle 13

在before_script中导出的变量在script中可见。

before:
  before_script:
    - export HELLOWELT="hi martin"
  script:
    - echo $HELLOWELT  # prints "hi martin"
Run Code Online (Sandbox Code Playgroud)

  • 但[不在 after_script 中](https://docs.gitlab.com/ee/ci/variables/where_variables_can_be_used.html#execution-shell-environment) (2认同)

Mik*_*rev 5

一般来说,您不能将变量从子进程导出到父进程。

作为解决方法,您可以使用文本文件写入/读取变量值。也许还可以通过 yaml 模板传递变量。