How to inherit gitlab variables accross projects?

Viewed 449

How can I let gitlab fill a global variable with from CI/CD secret, and then inherit this global variable in other projects?

templates/commons.yml:

variables:
  TEST_VAR: $FILLED_FROM_SECRETS

project/.gitlab_ci.yml.

include:
  - project: '/templates'
    ref: master
    file:
      - 'commons.yml'

test:
  stage: test
  script:
    - echo $TEST_VAR

Result: the variable is never set. Why? (of course the FILLED_FORM_SECRETS variable is set in the commons project)

3 Answers

The problem you have is that include: only brings in the contents on the YAML file, not the project level settings or variables.

As possible alternatives, you can:

  • Set the variable in the template directly (not recommended for sensitive values)
  • Set variables set on your own self-hosted runners (note variables cannot be masked this way)
  • Set instance CI/CD variables
  • Set a required CI configuration to forcibly include a template to all projects (that template can include variables you need) (note variables cannot be masked this way)
  • Set group CI/CD variables (where all your projects live under the common group)
  • Retrieve your secrets using the vault integration or as part of your job script

With the include keyword the included files are merged with the .gitlab-ci.yml and then your .gitlab-ci.yml is executed in the repo where the pipeline is triggered. Therefore, only gobal variables in this repo or inherited variables from any parent groups are known. That's why TEST_VAR is not substituted with the value from the secret as the variable is defined in another repository.

According to the doc, the syntax you used require you provide the whole path for your project (all the part after gitlab.com/group/project).

Assuming your project path is gitlab.com/group/my_project, then you choose one of the following

include:
  - project: 'group/my_project'
    ref: master
    file:
      - 'templates/commons.yml'
# or simply, if 'templates' folder lives in the same project as your gitlab-ci.yml file
  - '/templates/commons.yml'

test:
  stage: test
  script:
    - echo $TEST_VAR

I personally used both ways in my work, but the doc shows other ways to implement this that you can have a look at.

Related