官方文档地址:https://docs.gitlab.com/ee/ci/variables/index.html#pass-an-environment-variable-to-another-job

对gitlab版本有要求:14.6及其以上版本才可以

You can pass environment variables from one job to another job in a later stage through variable inheritance. These variables cannot be used as CI/CD variables to configure a pipeline, but they can be used in job scripts.

In the job script, save the variable as a .env file.
    The format of the file must be one variable definition per line.
    Each defined line must be of the form VARIABLE_NAME=ANY VALUE HERE.
    Values can be wrapped in quotes, but cannot contain newline characters. 
Save the .env file as an artifacts:reports:dotenv artifact.
Jobs in later stages can then use the variable in scripts. 

Inherited variables take precedence over certain types of new variable definitions such as job defined variables.

job之间传递自定义变量的写法

build:
  stage: build
  script:
    - echo "BUILD_VARIABLE=value_from_build_job" >> build.env
  artifacts:
    reports:
      dotenv: build.env

deploy:
  stage: deploy
  variables:
    BUILD_VARIABLE: value_from_deploy_job
  script:
    - echo "$BUILD_VARIABLE"  # Output is: 'value_from_build_job' due to precedence
build:
  stage: build
  script:
    - echo "BUILD_VERSION=hello" >> build.env
  artifacts:
    reports:
      dotenv: build.env

deploy_one:
  stage: deploy
  script:
    - echo "$BUILD_VERSION"  # Output is: 'hello'
  dependencies:
    - build

deploy_two:
  stage: deploy
  script:
    - echo "$BUILD_VERSION"  # Output is empty
  dependencies: []

deploy_three:
  stage: deploy
  script:
    - echo "$BUILD_VERSION"  # Output is: 'hello'
  needs:
    - build

deploy_four:
  stage: deploy
  script:
    - echo "$BUILD_VERSION"  # Output is: 'hello'
  needs:
    job: build
    artifacts: true

deploy_five:
  stage: deploy
  script:
    - echo "$BUILD_VERSION"  # Output is empty
  needs:
    job: build
    artifacts: false

以下写法经实践无法使用

...
variables:
  VARIABLES_FILE: ./variables.txt  # "." is required for image that have sh not bash

...

get-version:
  stage: prepare
  image: ...
  script:
    - APP_VERSION=...
    - echo "export APP_VERSION=$APP_VERSION" > $VARIABLES_FILE
  artifacts:
    paths:
      - $VARIABLES_FILE
...
package:
  stage: package
  image: ...
  script:
    - source $VARIABLES_FILE
    - echo "Use env var APP_VERSION here as you like ..."

相关文章: