Search code examples
continuous-integrationgitlabgitlab-cigitlab-ci-runner

GitLab CI: Export variable in before_script build job


I try to implement a conditional versioning depending on if the CI script runs for a tagged branch or not. However the version var is not resolved. Instead it is printed as a string.

The relevant jobs of the GitLab CI script:

# 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

Solution

  • in general you can't export variables from child to parent processes.

    As workaround you can use text file to write/read variable value. Also maybe it's possible to pass variable via yaml template.