Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gitlab-CI environment variable from Python script to pipeline

How I can get the gitlab-ci environment variable VERSION value from the python script - get_version.py for a gitlab-runners which will work on both OS windows and linux? I need some universal solution so that it works on both OS.

Here is my .gitlab-ci.yml :

stages:
  - versioning

variables:
  VERSION: ""

versioning:
  stage: versioning
  script:
  - echo "[versioning] ..."
  - python ./ci-cd_scripts/get_version.py
  - echo $VERSION

Here is my ./ci-cd_scripts/get_version.py :

import os

refName = os.environ.get("CI_COMMIT_REF_NAME")
piplineID = os.environ.get("CI_PIPELINE_ID")
relVersion = refName + ".0." + piplineID

version = relVersion.replace("rel.", "")
print("current version is", version)

python output in pipeline log

like image 454
Denis Mozhaev Avatar asked Aug 03 '26 15:08

Denis Mozhaev


1 Answers

what I found that works is to save it to a temp file.

import os

refName = os.environ.get("CI_COMMIT_REF_NAME")
piplineID = os.environ.get("CI_PIPELINE_ID")
relVersion = refName + ".0." + piplineID

version = relVersion.replace("rel.", "")
print("current version is", version)
with open('.env', 'w') as writer:
     writer.write(f'export VERSION="{version}"')

and then in the pipeline you just export the variable using the .env file

script:
  - ./ci-cd_scripts/get_version.py
  - source .env
  - echo $VERSION
like image 162
paul Avatar answered Aug 07 '26 21:08

paul