Skip to content

Set variables through before_script

Description

It would be helpful if there was a way to set the variables of a job or many jobs through a script run in a before_script attribute. The exported variables from this script can then be immediately available to the configuration of all build jobs covered by the particular before_script attribute.

My current use case is that I have a project that contains many Dockerfiles. These Dockerfiles are used for some images that we build our software application with. Thus, these Dockerfiles are used in the image attributes of our .gitlab-ci.yml file. We use environment variables to control the versions/tags of these Docker images. So, we have a versions.sh that exports the tags' values into environment variables. We need this versions.sh script for other shell scripts that build and push the Docker images. We also need to set the same exact variable in our .gitlab-ci.yml because the tags of our image values for our build jobs depend on the variables.

I would much prefer to maintain these variable in one single location instead of two places. Reduces code maintenance complexity.

Proposal

Given that I have a shell script in my project like so:

# versions.sh
export FOO_BAR_VERSION=0.0.1

Then, I am able to resolve the variable inside of my build job definitions in .gitlab-ci.yml:

# NOTE: No more need for the below two lines:
# variables:
#  FOO_BAR_VERSION: 0.0.1

before_script:
  - ./versions.sh

my_build_job:
  - image: "my_image_repo:$(FOO_BAR_VERSION)"
  - script:
    - "echo "FOO_BAR_VERSION = $(FOO_BAR_VERSION)"