Search code examples
dockergitlab-cigitlab-ci-runner

How to remember a build number in gitlab-ci script?


In my gitlab-ci.yaml I have multiple jobs like:

  • assembleDebug
  • assembleRelease
  • uploadToStore
  • release

In each of these jobs I retrieve the build number by calling following before_script:

.get_build_number: &get_build_number
  - apt update
  - apt install -y git
  - git checkout ${BUILD_BRANCH}
  - BUILD_VERSION=`cat buildVersion`
  - git checkout main

Since this is contained in every job, is it possible to calculate it in the first job and then remember the number and provide it to the following jobs, since this number should not increase in the meanwhile?


Solution

  • You can use artifacts:reports:dotenv: to pass environment variables to subsequent jobs by artifact.

    set-variables:
      stage: .pre # guaranteed to be the first stage in all pipelines
      script:
        - !reference [.get_build_number]
        - echo "BUILD_VERSION=${BUILD_VERSION}" > version.env
      artifacts:
        reports:
          dotenv: version.env
    
    build:
      # subsequent jobs will have the variable set by the dotenv artifact 
      script:
        - echo "build version is ${BUILD_VERSION}"